LiveInterval.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  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. return llvm::partition_point(*this,
  304. [&](const Segment &X) { return X.end <= Pos; });
  305. }
  306. VNInfo *LiveRange::createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc) {
  307. // Use the segment set, if it is available.
  308. if (segmentSet != nullptr)
  309. return CalcLiveRangeUtilSet(this).createDeadDef(Def, &VNIAlloc, nullptr);
  310. // Otherwise use the segment vector.
  311. return CalcLiveRangeUtilVector(this).createDeadDef(Def, &VNIAlloc, nullptr);
  312. }
  313. VNInfo *LiveRange::createDeadDef(VNInfo *VNI) {
  314. // Use the segment set, if it is available.
  315. if (segmentSet != nullptr)
  316. return CalcLiveRangeUtilSet(this).createDeadDef(VNI->def, nullptr, VNI);
  317. // Otherwise use the segment vector.
  318. return CalcLiveRangeUtilVector(this).createDeadDef(VNI->def, nullptr, VNI);
  319. }
  320. // overlaps - Return true if the intersection of the two live ranges is
  321. // not empty.
  322. //
  323. // An example for overlaps():
  324. //
  325. // 0: A = ...
  326. // 4: B = ...
  327. // 8: C = A + B ;; last use of A
  328. //
  329. // The live ranges should look like:
  330. //
  331. // A = [3, 11)
  332. // B = [7, x)
  333. // C = [11, y)
  334. //
  335. // A->overlaps(C) should return false since we want to be able to join
  336. // A and C.
  337. //
  338. bool LiveRange::overlapsFrom(const LiveRange& other,
  339. const_iterator StartPos) const {
  340. assert(!empty() && "empty range");
  341. const_iterator i = begin();
  342. const_iterator ie = end();
  343. const_iterator j = StartPos;
  344. const_iterator je = other.end();
  345. assert((StartPos->start <= i->start || StartPos == other.begin()) &&
  346. StartPos != other.end() && "Bogus start position hint!");
  347. if (i->start < j->start) {
  348. i = std::upper_bound(i, ie, j->start);
  349. if (i != begin()) --i;
  350. } else if (j->start < i->start) {
  351. ++StartPos;
  352. if (StartPos != other.end() && StartPos->start <= i->start) {
  353. assert(StartPos < other.end() && i < end());
  354. j = std::upper_bound(j, je, i->start);
  355. if (j != other.begin()) --j;
  356. }
  357. } else {
  358. return true;
  359. }
  360. if (j == je) return false;
  361. while (i != ie) {
  362. if (i->start > j->start) {
  363. std::swap(i, j);
  364. std::swap(ie, je);
  365. }
  366. if (i->end > j->start)
  367. return true;
  368. ++i;
  369. }
  370. return false;
  371. }
  372. bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP,
  373. const SlotIndexes &Indexes) const {
  374. assert(!empty() && "empty range");
  375. if (Other.empty())
  376. return false;
  377. // Use binary searches to find initial positions.
  378. const_iterator I = find(Other.beginIndex());
  379. const_iterator IE = end();
  380. if (I == IE)
  381. return false;
  382. const_iterator J = Other.find(I->start);
  383. const_iterator JE = Other.end();
  384. if (J == JE)
  385. return false;
  386. while (true) {
  387. // J has just been advanced to satisfy:
  388. assert(J->end >= I->start);
  389. // Check for an overlap.
  390. if (J->start < I->end) {
  391. // I and J are overlapping. Find the later start.
  392. SlotIndex Def = std::max(I->start, J->start);
  393. // Allow the overlap if Def is a coalescable copy.
  394. if (Def.isBlock() ||
  395. !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
  396. return true;
  397. }
  398. // Advance the iterator that ends first to check for more overlaps.
  399. if (J->end > I->end) {
  400. std::swap(I, J);
  401. std::swap(IE, JE);
  402. }
  403. // Advance J until J->end >= I->start.
  404. do
  405. if (++J == JE)
  406. return false;
  407. while (J->end < I->start);
  408. }
  409. }
  410. /// overlaps - Return true if the live range overlaps an interval specified
  411. /// by [Start, End).
  412. bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const {
  413. assert(Start < End && "Invalid range");
  414. const_iterator I = lower_bound(*this, End);
  415. return I != begin() && (--I)->end > Start;
  416. }
  417. bool LiveRange::covers(const LiveRange &Other) const {
  418. if (empty())
  419. return Other.empty();
  420. const_iterator I = begin();
  421. for (const Segment &O : Other.segments) {
  422. I = advanceTo(I, O.start);
  423. if (I == end() || I->start > O.start)
  424. return false;
  425. // Check adjacent live segments and see if we can get behind O.end.
  426. while (I->end < O.end) {
  427. const_iterator Last = I;
  428. // Get next segment and abort if it was not adjacent.
  429. ++I;
  430. if (I == end() || Last->end != I->start)
  431. return false;
  432. }
  433. }
  434. return true;
  435. }
  436. /// ValNo is dead, remove it. If it is the largest value number, just nuke it
  437. /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
  438. /// it can be nuked later.
  439. void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
  440. if (ValNo->id == getNumValNums()-1) {
  441. do {
  442. valnos.pop_back();
  443. } while (!valnos.empty() && valnos.back()->isUnused());
  444. } else {
  445. ValNo->markUnused();
  446. }
  447. }
  448. /// RenumberValues - Renumber all values in order of appearance and delete the
  449. /// remaining unused values.
  450. void LiveRange::RenumberValues() {
  451. SmallPtrSet<VNInfo*, 8> Seen;
  452. valnos.clear();
  453. for (const Segment &S : segments) {
  454. VNInfo *VNI = S.valno;
  455. if (!Seen.insert(VNI).second)
  456. continue;
  457. assert(!VNI->isUnused() && "Unused valno used by live segment");
  458. VNI->id = (unsigned)valnos.size();
  459. valnos.push_back(VNI);
  460. }
  461. }
  462. void LiveRange::addSegmentToSet(Segment S) {
  463. CalcLiveRangeUtilSet(this).addSegment(S);
  464. }
  465. LiveRange::iterator LiveRange::addSegment(Segment S) {
  466. // Use the segment set, if it is available.
  467. if (segmentSet != nullptr) {
  468. addSegmentToSet(S);
  469. return end();
  470. }
  471. // Otherwise use the segment vector.
  472. return CalcLiveRangeUtilVector(this).addSegment(S);
  473. }
  474. void LiveRange::append(const Segment S) {
  475. // Check that the segment belongs to the back of the list.
  476. assert(segments.empty() || segments.back().end <= S.start);
  477. segments.push_back(S);
  478. }
  479. std::pair<VNInfo*,bool> LiveRange::extendInBlock(ArrayRef<SlotIndex> Undefs,
  480. SlotIndex StartIdx, SlotIndex Kill) {
  481. // Use the segment set, if it is available.
  482. if (segmentSet != nullptr)
  483. return CalcLiveRangeUtilSet(this).extendInBlock(Undefs, StartIdx, Kill);
  484. // Otherwise use the segment vector.
  485. return CalcLiveRangeUtilVector(this).extendInBlock(Undefs, StartIdx, Kill);
  486. }
  487. VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
  488. // Use the segment set, if it is available.
  489. if (segmentSet != nullptr)
  490. return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Kill);
  491. // Otherwise use the segment vector.
  492. return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Kill);
  493. }
  494. /// Remove the specified segment from this range. Note that the segment must
  495. /// be in a single Segment in its entirety.
  496. void LiveRange::removeSegment(SlotIndex Start, SlotIndex End,
  497. bool RemoveDeadValNo) {
  498. // Find the Segment containing this span.
  499. iterator I = find(Start);
  500. assert(I != end() && "Segment is not in range!");
  501. assert(I->containsInterval(Start, End)
  502. && "Segment is not entirely in range!");
  503. // If the span we are removing is at the start of the Segment, adjust it.
  504. VNInfo *ValNo = I->valno;
  505. if (I->start == Start) {
  506. if (I->end == End) {
  507. segments.erase(I); // Removed the whole Segment.
  508. if (RemoveDeadValNo)
  509. removeValNoIfDead(ValNo);
  510. } else
  511. I->start = End;
  512. return;
  513. }
  514. // Otherwise if the span we are removing is at the end of the Segment,
  515. // adjust the other way.
  516. if (I->end == End) {
  517. I->end = Start;
  518. return;
  519. }
  520. // Otherwise, we are splitting the Segment into two pieces.
  521. SlotIndex OldEnd = I->end;
  522. I->end = Start; // Trim the old segment.
  523. // Insert the new one.
  524. segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
  525. }
  526. LiveRange::iterator LiveRange::removeSegment(iterator I, bool RemoveDeadValNo) {
  527. VNInfo *ValNo = I->valno;
  528. I = segments.erase(I);
  529. if (RemoveDeadValNo)
  530. removeValNoIfDead(ValNo);
  531. return I;
  532. }
  533. void LiveRange::removeValNoIfDead(VNInfo *ValNo) {
  534. if (none_of(*this, [=](const Segment &S) { return S.valno == ValNo; }))
  535. markValNoForDeletion(ValNo);
  536. }
  537. /// removeValNo - Remove all the segments defined by the specified value#.
  538. /// Also remove the value# from value# list.
  539. void LiveRange::removeValNo(VNInfo *ValNo) {
  540. if (empty()) return;
  541. llvm::erase_if(segments,
  542. [ValNo](const Segment &S) { return S.valno == ValNo; });
  543. // Now that ValNo is dead, remove it.
  544. markValNoForDeletion(ValNo);
  545. }
  546. void LiveRange::join(LiveRange &Other,
  547. const int *LHSValNoAssignments,
  548. const int *RHSValNoAssignments,
  549. SmallVectorImpl<VNInfo *> &NewVNInfo) {
  550. verify();
  551. // Determine if any of our values are mapped. This is uncommon, so we want
  552. // to avoid the range scan if not.
  553. bool MustMapCurValNos = false;
  554. unsigned NumVals = getNumValNums();
  555. unsigned NumNewVals = NewVNInfo.size();
  556. for (unsigned i = 0; i != NumVals; ++i) {
  557. unsigned LHSValID = LHSValNoAssignments[i];
  558. if (i != LHSValID ||
  559. (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
  560. MustMapCurValNos = true;
  561. break;
  562. }
  563. }
  564. // If we have to apply a mapping to our base range assignment, rewrite it now.
  565. if (MustMapCurValNos && !empty()) {
  566. // Map the first live range.
  567. iterator OutIt = begin();
  568. OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
  569. for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
  570. VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
  571. assert(nextValNo && "Huh?");
  572. // If this live range has the same value # as its immediate predecessor,
  573. // and if they are neighbors, remove one Segment. This happens when we
  574. // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
  575. if (OutIt->valno == nextValNo && OutIt->end == I->start) {
  576. OutIt->end = I->end;
  577. } else {
  578. // Didn't merge. Move OutIt to the next segment,
  579. ++OutIt;
  580. OutIt->valno = nextValNo;
  581. if (OutIt != I) {
  582. OutIt->start = I->start;
  583. OutIt->end = I->end;
  584. }
  585. }
  586. }
  587. // If we merge some segments, chop off the end.
  588. ++OutIt;
  589. segments.erase(OutIt, end());
  590. }
  591. // Rewrite Other values before changing the VNInfo ids.
  592. // This can leave Other in an invalid state because we're not coalescing
  593. // touching segments that now have identical values. That's OK since Other is
  594. // not supposed to be valid after calling join();
  595. for (Segment &S : Other.segments)
  596. S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]];
  597. // Update val# info. Renumber them and make sure they all belong to this
  598. // LiveRange now. Also remove dead val#'s.
  599. unsigned NumValNos = 0;
  600. for (unsigned i = 0; i < NumNewVals; ++i) {
  601. VNInfo *VNI = NewVNInfo[i];
  602. if (VNI) {
  603. if (NumValNos >= NumVals)
  604. valnos.push_back(VNI);
  605. else
  606. valnos[NumValNos] = VNI;
  607. VNI->id = NumValNos++; // Renumber val#.
  608. }
  609. }
  610. if (NumNewVals < NumVals)
  611. valnos.resize(NumNewVals); // shrinkify
  612. // Okay, now insert the RHS live segments into the LHS.
  613. LiveRangeUpdater Updater(this);
  614. for (Segment &S : Other.segments)
  615. Updater.add(S);
  616. }
  617. /// Merge all of the segments in RHS into this live range as the specified
  618. /// value number. The segments in RHS are allowed to overlap with segments in
  619. /// the current range, but only if the overlapping segments have the
  620. /// specified value number.
  621. void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
  622. VNInfo *LHSValNo) {
  623. LiveRangeUpdater Updater(this);
  624. for (const Segment &S : RHS.segments)
  625. Updater.add(S.start, S.end, LHSValNo);
  626. }
  627. /// MergeValueInAsValue - Merge all of the live segments of a specific val#
  628. /// in RHS into this live range as the specified value number.
  629. /// The segments in RHS are allowed to overlap with segments in the
  630. /// current range, it will replace the value numbers of the overlaped
  631. /// segments with the specified value number.
  632. void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
  633. const VNInfo *RHSValNo,
  634. VNInfo *LHSValNo) {
  635. LiveRangeUpdater Updater(this);
  636. for (const Segment &S : RHS.segments)
  637. if (S.valno == RHSValNo)
  638. Updater.add(S.start, S.end, LHSValNo);
  639. }
  640. /// MergeValueNumberInto - This method is called when two value nubmers
  641. /// are found to be equivalent. This eliminates V1, replacing all
  642. /// segments with the V1 value number with the V2 value number. This can
  643. /// cause merging of V1/V2 values numbers and compaction of the value space.
  644. VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
  645. assert(V1 != V2 && "Identical value#'s are always equivalent!");
  646. // This code actually merges the (numerically) larger value number into the
  647. // smaller value number, which is likely to allow us to compactify the value
  648. // space. The only thing we have to be careful of is to preserve the
  649. // instruction that defines the result value.
  650. // Make sure V2 is smaller than V1.
  651. if (V1->id < V2->id) {
  652. V1->copyFrom(*V2);
  653. std::swap(V1, V2);
  654. }
  655. // Merge V1 segments into V2.
  656. for (iterator I = begin(); I != end(); ) {
  657. iterator S = I++;
  658. if (S->valno != V1) continue; // Not a V1 Segment.
  659. // Okay, we found a V1 live range. If it had a previous, touching, V2 live
  660. // range, extend it.
  661. if (S != begin()) {
  662. iterator Prev = S-1;
  663. if (Prev->valno == V2 && Prev->end == S->start) {
  664. Prev->end = S->end;
  665. // Erase this live-range.
  666. segments.erase(S);
  667. I = Prev+1;
  668. S = Prev;
  669. }
  670. }
  671. // Okay, now we have a V1 or V2 live range that is maximally merged forward.
  672. // Ensure that it is a V2 live-range.
  673. S->valno = V2;
  674. // If we can merge it into later V2 segments, do so now. We ignore any
  675. // following V1 segments, as they will be merged in subsequent iterations
  676. // of the loop.
  677. if (I != end()) {
  678. if (I->start == S->end && I->valno == V2) {
  679. S->end = I->end;
  680. segments.erase(I);
  681. I = S+1;
  682. }
  683. }
  684. }
  685. // Now that V1 is dead, remove it.
  686. markValNoForDeletion(V1);
  687. return V2;
  688. }
  689. void LiveRange::flushSegmentSet() {
  690. assert(segmentSet != nullptr && "segment set must have been created");
  691. assert(
  692. segments.empty() &&
  693. "segment set can be used only initially before switching to the array");
  694. segments.append(segmentSet->begin(), segmentSet->end());
  695. segmentSet = nullptr;
  696. verify();
  697. }
  698. bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const {
  699. ArrayRef<SlotIndex>::iterator SlotI = Slots.begin();
  700. ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
  701. // If there are no regmask slots, we have nothing to search.
  702. if (SlotI == SlotE)
  703. return false;
  704. // Start our search at the first segment that ends after the first slot.
  705. const_iterator SegmentI = find(*SlotI);
  706. const_iterator SegmentE = end();
  707. // If there are no segments that end after the first slot, we're done.
  708. if (SegmentI == SegmentE)
  709. return false;
  710. // Look for each slot in the live range.
  711. for ( ; SlotI != SlotE; ++SlotI) {
  712. // Go to the next segment that ends after the current slot.
  713. // The slot may be within a hole in the range.
  714. SegmentI = advanceTo(SegmentI, *SlotI);
  715. if (SegmentI == SegmentE)
  716. return false;
  717. // If this segment contains the slot, we're done.
  718. if (SegmentI->contains(*SlotI))
  719. return true;
  720. // Otherwise, look for the next slot.
  721. }
  722. // We didn't find a segment containing any of the slots.
  723. return false;
  724. }
  725. void LiveInterval::freeSubRange(SubRange *S) {
  726. S->~SubRange();
  727. // Memory was allocated with BumpPtr allocator and is not freed here.
  728. }
  729. void LiveInterval::removeEmptySubRanges() {
  730. SubRange **NextPtr = &SubRanges;
  731. SubRange *I = *NextPtr;
  732. while (I != nullptr) {
  733. if (!I->empty()) {
  734. NextPtr = &I->Next;
  735. I = *NextPtr;
  736. continue;
  737. }
  738. // Skip empty subranges until we find the first nonempty one.
  739. do {
  740. SubRange *Next = I->Next;
  741. freeSubRange(I);
  742. I = Next;
  743. } while (I != nullptr && I->empty());
  744. *NextPtr = I;
  745. }
  746. }
  747. void LiveInterval::clearSubRanges() {
  748. for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) {
  749. Next = I->Next;
  750. freeSubRange(I);
  751. }
  752. SubRanges = nullptr;
  753. }
  754. /// For each VNI in \p SR, check whether or not that value defines part
  755. /// of the mask describe by \p LaneMask and if not, remove that value
  756. /// from \p SR.
  757. static void stripValuesNotDefiningMask(unsigned Reg, LiveInterval::SubRange &SR,
  758. LaneBitmask LaneMask,
  759. const SlotIndexes &Indexes,
  760. const TargetRegisterInfo &TRI,
  761. unsigned ComposeSubRegIdx) {
  762. // Phys reg should not be tracked at subreg level.
  763. // Same for noreg (Reg == 0).
  764. if (!Register::isVirtualRegister(Reg) || !Reg)
  765. return;
  766. // Remove the values that don't define those lanes.
  767. SmallVector<VNInfo *, 8> ToBeRemoved;
  768. for (VNInfo *VNI : SR.valnos) {
  769. if (VNI->isUnused())
  770. continue;
  771. // PHI definitions don't have MI attached, so there is nothing
  772. // we can use to strip the VNI.
  773. if (VNI->isPHIDef())
  774. continue;
  775. const MachineInstr *MI = Indexes.getInstructionFromIndex(VNI->def);
  776. assert(MI && "Cannot find the definition of a value");
  777. bool hasDef = false;
  778. for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
  779. if (!MOI->isReg() || !MOI->isDef())
  780. continue;
  781. if (MOI->getReg() != Reg)
  782. continue;
  783. LaneBitmask OrigMask = TRI.getSubRegIndexLaneMask(MOI->getSubReg());
  784. LaneBitmask ExpectedDefMask =
  785. ComposeSubRegIdx
  786. ? TRI.composeSubRegIndexLaneMask(ComposeSubRegIdx, OrigMask)
  787. : OrigMask;
  788. if ((ExpectedDefMask & LaneMask).none())
  789. continue;
  790. hasDef = true;
  791. break;
  792. }
  793. if (!hasDef)
  794. ToBeRemoved.push_back(VNI);
  795. }
  796. for (VNInfo *VNI : ToBeRemoved)
  797. SR.removeValNo(VNI);
  798. // If the subrange is empty at this point, the MIR is invalid. Do not assert
  799. // and let the verifier catch this case.
  800. }
  801. void LiveInterval::refineSubRanges(
  802. BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
  803. std::function<void(LiveInterval::SubRange &)> Apply,
  804. const SlotIndexes &Indexes, const TargetRegisterInfo &TRI,
  805. unsigned ComposeSubRegIdx) {
  806. LaneBitmask ToApply = LaneMask;
  807. for (SubRange &SR : subranges()) {
  808. LaneBitmask SRMask = SR.LaneMask;
  809. LaneBitmask Matching = SRMask & LaneMask;
  810. if (Matching.none())
  811. continue;
  812. SubRange *MatchingRange;
  813. if (SRMask == Matching) {
  814. // The subrange fits (it does not cover bits outside \p LaneMask).
  815. MatchingRange = &SR;
  816. } else {
  817. // We have to split the subrange into a matching and non-matching part.
  818. // Reduce lanemask of existing lane to non-matching part.
  819. SR.LaneMask = SRMask & ~Matching;
  820. // Create a new subrange for the matching part
  821. MatchingRange = createSubRangeFrom(Allocator, Matching, SR);
  822. // Now that the subrange is split in half, make sure we
  823. // only keep in the subranges the VNIs that touch the related half.
  824. stripValuesNotDefiningMask(reg(), *MatchingRange, Matching, Indexes, TRI,
  825. ComposeSubRegIdx);
  826. stripValuesNotDefiningMask(reg(), SR, SR.LaneMask, Indexes, TRI,
  827. ComposeSubRegIdx);
  828. }
  829. Apply(*MatchingRange);
  830. ToApply &= ~Matching;
  831. }
  832. // Create a new subrange if there are uncovered bits left.
  833. if (ToApply.any()) {
  834. SubRange *NewRange = createSubRange(Allocator, ToApply);
  835. Apply(*NewRange);
  836. }
  837. }
  838. unsigned LiveInterval::getSize() const {
  839. unsigned Sum = 0;
  840. for (const Segment &S : segments)
  841. Sum += S.start.distance(S.end);
  842. return Sum;
  843. }
  844. void LiveInterval::computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
  845. LaneBitmask LaneMask,
  846. const MachineRegisterInfo &MRI,
  847. const SlotIndexes &Indexes) const {
  848. assert(reg().isVirtual());
  849. LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(reg());
  850. assert((VRegMask & LaneMask).any());
  851. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  852. for (const MachineOperand &MO : MRI.def_operands(reg())) {
  853. if (!MO.isUndef())
  854. continue;
  855. unsigned SubReg = MO.getSubReg();
  856. assert(SubReg != 0 && "Undef should only be set on subreg defs");
  857. LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubReg);
  858. LaneBitmask UndefMask = VRegMask & ~DefMask;
  859. if ((UndefMask & LaneMask).any()) {
  860. const MachineInstr &MI = *MO.getParent();
  861. bool EarlyClobber = MO.isEarlyClobber();
  862. SlotIndex Pos = Indexes.getInstructionIndex(MI).getRegSlot(EarlyClobber);
  863. Undefs.push_back(Pos);
  864. }
  865. }
  866. }
  867. raw_ostream& llvm::operator<<(raw_ostream& OS, const LiveRange::Segment &S) {
  868. return OS << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')';
  869. }
  870. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  871. LLVM_DUMP_METHOD void LiveRange::Segment::dump() const {
  872. dbgs() << *this << '\n';
  873. }
  874. #endif
  875. void LiveRange::print(raw_ostream &OS) const {
  876. if (empty())
  877. OS << "EMPTY";
  878. else {
  879. for (const Segment &S : segments) {
  880. OS << S;
  881. assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo");
  882. }
  883. }
  884. // Print value number info.
  885. if (getNumValNums()) {
  886. OS << ' ';
  887. unsigned vnum = 0;
  888. for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
  889. ++i, ++vnum) {
  890. const VNInfo *vni = *i;
  891. if (vnum) OS << ' ';
  892. OS << vnum << '@';
  893. if (vni->isUnused()) {
  894. OS << 'x';
  895. } else {
  896. OS << vni->def;
  897. if (vni->isPHIDef())
  898. OS << "-phi";
  899. }
  900. }
  901. }
  902. }
  903. void LiveInterval::SubRange::print(raw_ostream &OS) const {
  904. OS << " L" << PrintLaneMask(LaneMask) << ' '
  905. << static_cast<const LiveRange &>(*this);
  906. }
  907. void LiveInterval::print(raw_ostream &OS) const {
  908. OS << printReg(reg()) << ' ';
  909. super::print(OS);
  910. // Print subranges
  911. for (const SubRange &SR : subranges())
  912. OS << SR;
  913. OS << " weight:" << Weight;
  914. }
  915. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  916. LLVM_DUMP_METHOD void LiveRange::dump() const {
  917. dbgs() << *this << '\n';
  918. }
  919. LLVM_DUMP_METHOD void LiveInterval::SubRange::dump() const {
  920. dbgs() << *this << '\n';
  921. }
  922. LLVM_DUMP_METHOD void LiveInterval::dump() const {
  923. dbgs() << *this << '\n';
  924. }
  925. #endif
  926. #ifndef NDEBUG
  927. void LiveRange::verify() const {
  928. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  929. assert(I->start.isValid());
  930. assert(I->end.isValid());
  931. assert(I->start < I->end);
  932. assert(I->valno != nullptr);
  933. assert(I->valno->id < valnos.size());
  934. assert(I->valno == valnos[I->valno->id]);
  935. if (std::next(I) != E) {
  936. assert(I->end <= std::next(I)->start);
  937. if (I->end == std::next(I)->start)
  938. assert(I->valno != std::next(I)->valno);
  939. }
  940. }
  941. }
  942. void LiveInterval::verify(const MachineRegisterInfo *MRI) const {
  943. super::verify();
  944. // Make sure SubRanges are fine and LaneMasks are disjunct.
  945. LaneBitmask Mask;
  946. LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg())
  947. : LaneBitmask::getAll();
  948. for (const SubRange &SR : subranges()) {
  949. // Subrange lanemask should be disjunct to any previous subrange masks.
  950. assert((Mask & SR.LaneMask).none());
  951. Mask |= SR.LaneMask;
  952. // subrange mask should not contained in maximum lane mask for the vreg.
  953. assert((Mask & ~MaxMask).none());
  954. // empty subranges must be removed.
  955. assert(!SR.empty());
  956. SR.verify();
  957. // Main liverange should cover subrange.
  958. assert(covers(SR));
  959. }
  960. }
  961. #endif
  962. //===----------------------------------------------------------------------===//
  963. // LiveRangeUpdater class
  964. //===----------------------------------------------------------------------===//
  965. //
  966. // The LiveRangeUpdater class always maintains these invariants:
  967. //
  968. // - When LastStart is invalid, Spills is empty and the iterators are invalid.
  969. // This is the initial state, and the state created by flush().
  970. // In this state, isDirty() returns false.
  971. //
  972. // Otherwise, segments are kept in three separate areas:
  973. //
  974. // 1. [begin; WriteI) at the front of LR.
  975. // 2. [ReadI; end) at the back of LR.
  976. // 3. Spills.
  977. //
  978. // - LR.begin() <= WriteI <= ReadI <= LR.end().
  979. // - Segments in all three areas are fully ordered and coalesced.
  980. // - Segments in area 1 precede and can't coalesce with segments in area 2.
  981. // - Segments in Spills precede and can't coalesce with segments in area 2.
  982. // - No coalescing is possible between segments in Spills and segments in area
  983. // 1, and there are no overlapping segments.
  984. //
  985. // The segments in Spills are not ordered with respect to the segments in area
  986. // 1. They need to be merged.
  987. //
  988. // When they exist, Spills.back().start <= LastStart,
  989. // and WriteI[-1].start <= LastStart.
  990. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  991. void LiveRangeUpdater::print(raw_ostream &OS) const {
  992. if (!isDirty()) {
  993. if (LR)
  994. OS << "Clean updater: " << *LR << '\n';
  995. else
  996. OS << "Null updater.\n";
  997. return;
  998. }
  999. assert(LR && "Can't have null LR in dirty updater.");
  1000. OS << " updater with gap = " << (ReadI - WriteI)
  1001. << ", last start = " << LastStart
  1002. << ":\n Area 1:";
  1003. for (const auto &S : make_range(LR->begin(), WriteI))
  1004. OS << ' ' << S;
  1005. OS << "\n Spills:";
  1006. for (unsigned I = 0, E = Spills.size(); I != E; ++I)
  1007. OS << ' ' << Spills[I];
  1008. OS << "\n Area 2:";
  1009. for (const auto &S : make_range(ReadI, LR->end()))
  1010. OS << ' ' << S;
  1011. OS << '\n';
  1012. }
  1013. LLVM_DUMP_METHOD void LiveRangeUpdater::dump() const {
  1014. print(errs());
  1015. }
  1016. #endif
  1017. // Determine if A and B should be coalesced.
  1018. static inline bool coalescable(const LiveRange::Segment &A,
  1019. const LiveRange::Segment &B) {
  1020. assert(A.start <= B.start && "Unordered live segments.");
  1021. if (A.end == B.start)
  1022. return A.valno == B.valno;
  1023. if (A.end < B.start)
  1024. return false;
  1025. assert(A.valno == B.valno && "Cannot overlap different values");
  1026. return true;
  1027. }
  1028. void LiveRangeUpdater::add(LiveRange::Segment Seg) {
  1029. assert(LR && "Cannot add to a null destination");
  1030. // Fall back to the regular add method if the live range
  1031. // is using the segment set instead of the segment vector.
  1032. if (LR->segmentSet != nullptr) {
  1033. LR->addSegmentToSet(Seg);
  1034. return;
  1035. }
  1036. // Flush the state if Start moves backwards.
  1037. if (!LastStart.isValid() || LastStart > Seg.start) {
  1038. if (isDirty())
  1039. flush();
  1040. // This brings us to an uninitialized state. Reinitialize.
  1041. assert(Spills.empty() && "Leftover spilled segments");
  1042. WriteI = ReadI = LR->begin();
  1043. }
  1044. // Remember start for next time.
  1045. LastStart = Seg.start;
  1046. // Advance ReadI until it ends after Seg.start.
  1047. LiveRange::iterator E = LR->end();
  1048. if (ReadI != E && ReadI->end <= Seg.start) {
  1049. // First try to close the gap between WriteI and ReadI with spills.
  1050. if (ReadI != WriteI)
  1051. mergeSpills();
  1052. // Then advance ReadI.
  1053. if (ReadI == WriteI)
  1054. ReadI = WriteI = LR->find(Seg.start);
  1055. else
  1056. while (ReadI != E && ReadI->end <= Seg.start)
  1057. *WriteI++ = *ReadI++;
  1058. }
  1059. assert(ReadI == E || ReadI->end > Seg.start);
  1060. // Check if the ReadI segment begins early.
  1061. if (ReadI != E && ReadI->start <= Seg.start) {
  1062. assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
  1063. // Bail if Seg is completely contained in ReadI.
  1064. if (ReadI->end >= Seg.end)
  1065. return;
  1066. // Coalesce into Seg.
  1067. Seg.start = ReadI->start;
  1068. ++ReadI;
  1069. }
  1070. // Coalesce as much as possible from ReadI into Seg.
  1071. while (ReadI != E && coalescable(Seg, *ReadI)) {
  1072. Seg.end = std::max(Seg.end, ReadI->end);
  1073. ++ReadI;
  1074. }
  1075. // Try coalescing Spills.back() into Seg.
  1076. if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
  1077. Seg.start = Spills.back().start;
  1078. Seg.end = std::max(Spills.back().end, Seg.end);
  1079. Spills.pop_back();
  1080. }
  1081. // Try coalescing Seg into WriteI[-1].
  1082. if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
  1083. WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
  1084. return;
  1085. }
  1086. // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
  1087. if (WriteI != ReadI) {
  1088. *WriteI++ = Seg;
  1089. return;
  1090. }
  1091. // Finally, append to LR or Spills.
  1092. if (WriteI == E) {
  1093. LR->segments.push_back(Seg);
  1094. WriteI = ReadI = LR->end();
  1095. } else
  1096. Spills.push_back(Seg);
  1097. }
  1098. // Merge as many spilled segments as possible into the gap between WriteI
  1099. // and ReadI. Advance WriteI to reflect the inserted instructions.
  1100. void LiveRangeUpdater::mergeSpills() {
  1101. // Perform a backwards merge of Spills and [SpillI;WriteI).
  1102. size_t GapSize = ReadI - WriteI;
  1103. size_t NumMoved = std::min(Spills.size(), GapSize);
  1104. LiveRange::iterator Src = WriteI;
  1105. LiveRange::iterator Dst = Src + NumMoved;
  1106. LiveRange::iterator SpillSrc = Spills.end();
  1107. LiveRange::iterator B = LR->begin();
  1108. // This is the new WriteI position after merging spills.
  1109. WriteI = Dst;
  1110. // Now merge Src and Spills backwards.
  1111. while (Src != Dst) {
  1112. if (Src != B && Src[-1].start > SpillSrc[-1].start)
  1113. *--Dst = *--Src;
  1114. else
  1115. *--Dst = *--SpillSrc;
  1116. }
  1117. assert(NumMoved == size_t(Spills.end() - SpillSrc));
  1118. Spills.erase(SpillSrc, Spills.end());
  1119. }
  1120. void LiveRangeUpdater::flush() {
  1121. if (!isDirty())
  1122. return;
  1123. // Clear the dirty state.
  1124. LastStart = SlotIndex();
  1125. assert(LR && "Cannot add to a null destination");
  1126. // Nothing to merge?
  1127. if (Spills.empty()) {
  1128. LR->segments.erase(WriteI, ReadI);
  1129. LR->verify();
  1130. return;
  1131. }
  1132. // Resize the WriteI - ReadI gap to match Spills.
  1133. size_t GapSize = ReadI - WriteI;
  1134. if (GapSize < Spills.size()) {
  1135. // The gap is too small. Make some room.
  1136. size_t WritePos = WriteI - LR->begin();
  1137. LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
  1138. // This also invalidated ReadI, but it is recomputed below.
  1139. WriteI = LR->begin() + WritePos;
  1140. } else {
  1141. // Shrink the gap if necessary.
  1142. LR->segments.erase(WriteI + Spills.size(), ReadI);
  1143. }
  1144. ReadI = WriteI + Spills.size();
  1145. mergeSpills();
  1146. LR->verify();
  1147. }
  1148. unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) {
  1149. // Create initial equivalence classes.
  1150. EqClass.clear();
  1151. EqClass.grow(LR.getNumValNums());
  1152. const VNInfo *used = nullptr, *unused = nullptr;
  1153. // Determine connections.
  1154. for (const VNInfo *VNI : LR.valnos) {
  1155. // Group all unused values into one class.
  1156. if (VNI->isUnused()) {
  1157. if (unused)
  1158. EqClass.join(unused->id, VNI->id);
  1159. unused = VNI;
  1160. continue;
  1161. }
  1162. used = VNI;
  1163. if (VNI->isPHIDef()) {
  1164. const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
  1165. assert(MBB && "Phi-def has no defining MBB");
  1166. // Connect to values live out of predecessors.
  1167. for (MachineBasicBlock *Pred : MBB->predecessors())
  1168. if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(Pred)))
  1169. EqClass.join(VNI->id, PVNI->id);
  1170. } else {
  1171. // Normal value defined by an instruction. Check for two-addr redef.
  1172. // FIXME: This could be coincidental. Should we really check for a tied
  1173. // operand constraint?
  1174. // Note that VNI->def may be a use slot for an early clobber def.
  1175. if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def))
  1176. EqClass.join(VNI->id, UVNI->id);
  1177. }
  1178. }
  1179. // Lump all the unused values in with the last used value.
  1180. if (used && unused)
  1181. EqClass.join(used->id, unused->id);
  1182. EqClass.compress();
  1183. return EqClass.getNumClasses();
  1184. }
  1185. void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[],
  1186. MachineRegisterInfo &MRI) {
  1187. // Rewrite instructions.
  1188. for (MachineOperand &MO :
  1189. llvm::make_early_inc_range(MRI.reg_operands(LI.reg()))) {
  1190. MachineInstr *MI = MO.getParent();
  1191. const VNInfo *VNI;
  1192. if (MI->isDebugValue()) {
  1193. // DBG_VALUE instructions don't have slot indexes, so get the index of
  1194. // the instruction before them. The value is defined there too.
  1195. SlotIndex Idx = LIS.getSlotIndexes()->getIndexBefore(*MI);
  1196. VNI = LI.Query(Idx).valueOut();
  1197. } else {
  1198. SlotIndex Idx = LIS.getInstructionIndex(*MI);
  1199. LiveQueryResult LRQ = LI.Query(Idx);
  1200. VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
  1201. }
  1202. // In the case of an <undef> use that isn't tied to any def, VNI will be
  1203. // NULL. If the use is tied to a def, VNI will be the defined value.
  1204. if (!VNI)
  1205. continue;
  1206. if (unsigned EqClass = getEqClass(VNI))
  1207. MO.setReg(LIV[EqClass - 1]->reg());
  1208. }
  1209. // Distribute subregister liveranges.
  1210. if (LI.hasSubRanges()) {
  1211. unsigned NumComponents = EqClass.getNumClasses();
  1212. SmallVector<unsigned, 8> VNIMapping;
  1213. SmallVector<LiveInterval::SubRange*, 8> SubRanges;
  1214. BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
  1215. for (LiveInterval::SubRange &SR : LI.subranges()) {
  1216. // Create new subranges in the split intervals and construct a mapping
  1217. // for the VNInfos in the subrange.
  1218. unsigned NumValNos = SR.valnos.size();
  1219. VNIMapping.clear();
  1220. VNIMapping.reserve(NumValNos);
  1221. SubRanges.clear();
  1222. SubRanges.resize(NumComponents-1, nullptr);
  1223. for (unsigned I = 0; I < NumValNos; ++I) {
  1224. const VNInfo &VNI = *SR.valnos[I];
  1225. unsigned ComponentNum;
  1226. if (VNI.isUnused()) {
  1227. ComponentNum = 0;
  1228. } else {
  1229. const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def);
  1230. assert(MainRangeVNI != nullptr
  1231. && "SubRange def must have corresponding main range def");
  1232. ComponentNum = getEqClass(MainRangeVNI);
  1233. if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) {
  1234. SubRanges[ComponentNum-1]
  1235. = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask);
  1236. }
  1237. }
  1238. VNIMapping.push_back(ComponentNum);
  1239. }
  1240. DistributeRange(SR, SubRanges.data(), VNIMapping);
  1241. }
  1242. LI.removeEmptySubRanges();
  1243. }
  1244. // Distribute main liverange.
  1245. DistributeRange(LI, LIV, EqClass);
  1246. }