LiveInterval.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the LiveRange and LiveInterval classes. Given some
  11. // numbering of each the machine instructions an interval [i, j) is said to be a
  12. // live range for register v if there is no instruction with number j' >= j
  13. // such that v is live at j' and there is no instruction with number i' < i such
  14. // that v is live at i'. In this implementation ranges can have holes,
  15. // i.e. a range might look like [1,20), [50,65), [1000,1001). Each
  16. // individual segment is represented as an instance of LiveRange::Segment,
  17. // and the whole range is represented as an instance of LiveRange.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "llvm/CodeGen/LiveInterval.h"
  21. #include "RegisterCoalescer.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Target/TargetRegisterInfo.h"
  30. #include <algorithm>
  31. using namespace llvm;
  32. LiveRange::iterator LiveRange::find(SlotIndex Pos) {
  33. // This algorithm is basically std::upper_bound.
  34. // Unfortunately, std::upper_bound cannot be used with mixed types until we
  35. // adopt C++0x. Many libraries can do it, but not all.
  36. if (empty() || Pos >= endIndex())
  37. return end();
  38. iterator I = begin();
  39. size_t Len = size();
  40. do {
  41. size_t Mid = Len >> 1;
  42. if (Pos < I[Mid].end)
  43. Len = Mid;
  44. else
  45. I += Mid + 1, Len -= Mid + 1;
  46. } while (Len);
  47. return I;
  48. }
  49. VNInfo *LiveRange::createDeadDef(SlotIndex Def,
  50. VNInfo::Allocator &VNInfoAllocator) {
  51. assert(!Def.isDead() && "Cannot define a value at the dead slot");
  52. iterator I = find(Def);
  53. if (I == end()) {
  54. VNInfo *VNI = getNextValue(Def, VNInfoAllocator);
  55. segments.push_back(Segment(Def, Def.getDeadSlot(), VNI));
  56. return VNI;
  57. }
  58. if (SlotIndex::isSameInstr(Def, I->start)) {
  59. assert(I->valno->def == I->start && "Inconsistent existing value def");
  60. // It is possible to have both normal and early-clobber defs of the same
  61. // register on an instruction. It doesn't make a lot of sense, but it is
  62. // possible to specify in inline assembly.
  63. //
  64. // Just convert everything to early-clobber.
  65. Def = std::min(Def, I->start);
  66. if (Def != I->start)
  67. I->start = I->valno->def = Def;
  68. return I->valno;
  69. }
  70. assert(SlotIndex::isEarlierInstr(Def, I->start) && "Already live at def");
  71. VNInfo *VNI = getNextValue(Def, VNInfoAllocator);
  72. segments.insert(I, Segment(Def, Def.getDeadSlot(), VNI));
  73. return VNI;
  74. }
  75. // overlaps - Return true if the intersection of the two live ranges is
  76. // not empty.
  77. //
  78. // An example for overlaps():
  79. //
  80. // 0: A = ...
  81. // 4: B = ...
  82. // 8: C = A + B ;; last use of A
  83. //
  84. // The live ranges should look like:
  85. //
  86. // A = [3, 11)
  87. // B = [7, x)
  88. // C = [11, y)
  89. //
  90. // A->overlaps(C) should return false since we want to be able to join
  91. // A and C.
  92. //
  93. bool LiveRange::overlapsFrom(const LiveRange& other,
  94. const_iterator StartPos) const {
  95. assert(!empty() && "empty range");
  96. const_iterator i = begin();
  97. const_iterator ie = end();
  98. const_iterator j = StartPos;
  99. const_iterator je = other.end();
  100. assert((StartPos->start <= i->start || StartPos == other.begin()) &&
  101. StartPos != other.end() && "Bogus start position hint!");
  102. if (i->start < j->start) {
  103. i = std::upper_bound(i, ie, j->start);
  104. if (i != begin()) --i;
  105. } else if (j->start < i->start) {
  106. ++StartPos;
  107. if (StartPos != other.end() && StartPos->start <= i->start) {
  108. assert(StartPos < other.end() && i < end());
  109. j = std::upper_bound(j, je, i->start);
  110. if (j != other.begin()) --j;
  111. }
  112. } else {
  113. return true;
  114. }
  115. if (j == je) return false;
  116. while (i != ie) {
  117. if (i->start > j->start) {
  118. std::swap(i, j);
  119. std::swap(ie, je);
  120. }
  121. if (i->end > j->start)
  122. return true;
  123. ++i;
  124. }
  125. return false;
  126. }
  127. bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP,
  128. const SlotIndexes &Indexes) const {
  129. assert(!empty() && "empty range");
  130. if (Other.empty())
  131. return false;
  132. // Use binary searches to find initial positions.
  133. const_iterator I = find(Other.beginIndex());
  134. const_iterator IE = end();
  135. if (I == IE)
  136. return false;
  137. const_iterator J = Other.find(I->start);
  138. const_iterator JE = Other.end();
  139. if (J == JE)
  140. return false;
  141. for (;;) {
  142. // J has just been advanced to satisfy:
  143. assert(J->end >= I->start);
  144. // Check for an overlap.
  145. if (J->start < I->end) {
  146. // I and J are overlapping. Find the later start.
  147. SlotIndex Def = std::max(I->start, J->start);
  148. // Allow the overlap if Def is a coalescable copy.
  149. if (Def.isBlock() ||
  150. !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
  151. return true;
  152. }
  153. // Advance the iterator that ends first to check for more overlaps.
  154. if (J->end > I->end) {
  155. std::swap(I, J);
  156. std::swap(IE, JE);
  157. }
  158. // Advance J until J->end >= I->start.
  159. do
  160. if (++J == JE)
  161. return false;
  162. while (J->end < I->start);
  163. }
  164. }
  165. /// overlaps - Return true if the live range overlaps an interval specified
  166. /// by [Start, End).
  167. bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const {
  168. assert(Start < End && "Invalid range");
  169. const_iterator I = std::lower_bound(begin(), end(), End);
  170. return I != begin() && (--I)->end > Start;
  171. }
  172. /// ValNo is dead, remove it. If it is the largest value number, just nuke it
  173. /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
  174. /// it can be nuked later.
  175. void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
  176. if (ValNo->id == getNumValNums()-1) {
  177. do {
  178. valnos.pop_back();
  179. } while (!valnos.empty() && valnos.back()->isUnused());
  180. } else {
  181. ValNo->markUnused();
  182. }
  183. }
  184. /// RenumberValues - Renumber all values in order of appearance and delete the
  185. /// remaining unused values.
  186. void LiveRange::RenumberValues() {
  187. SmallPtrSet<VNInfo*, 8> Seen;
  188. valnos.clear();
  189. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  190. VNInfo *VNI = I->valno;
  191. if (!Seen.insert(VNI))
  192. continue;
  193. assert(!VNI->isUnused() && "Unused valno used by live segment");
  194. VNI->id = (unsigned)valnos.size();
  195. valnos.push_back(VNI);
  196. }
  197. }
  198. /// This method is used when we want to extend the segment specified by I to end
  199. /// at the specified endpoint. To do this, we should merge and eliminate all
  200. /// segments that this will overlap with. The iterator is not invalidated.
  201. void LiveRange::extendSegmentEndTo(iterator I, SlotIndex NewEnd) {
  202. assert(I != end() && "Not a valid segment!");
  203. VNInfo *ValNo = I->valno;
  204. // Search for the first segment that we can't merge with.
  205. iterator MergeTo = std::next(I);
  206. for (; MergeTo != end() && NewEnd >= MergeTo->end; ++MergeTo) {
  207. assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
  208. }
  209. // If NewEnd was in the middle of a segment, make sure to get its endpoint.
  210. I->end = std::max(NewEnd, std::prev(MergeTo)->end);
  211. // If the newly formed segment now touches the segment after it and if they
  212. // have the same value number, merge the two segments into one segment.
  213. if (MergeTo != end() && MergeTo->start <= I->end &&
  214. MergeTo->valno == ValNo) {
  215. I->end = MergeTo->end;
  216. ++MergeTo;
  217. }
  218. // Erase any dead segments.
  219. segments.erase(std::next(I), MergeTo);
  220. }
  221. /// This method is used when we want to extend the segment specified by I to
  222. /// start at the specified endpoint. To do this, we should merge and eliminate
  223. /// all segments that this will overlap with.
  224. LiveRange::iterator
  225. LiveRange::extendSegmentStartTo(iterator I, SlotIndex NewStart) {
  226. assert(I != end() && "Not a valid segment!");
  227. VNInfo *ValNo = I->valno;
  228. // Search for the first segment that we can't merge with.
  229. iterator MergeTo = I;
  230. do {
  231. if (MergeTo == begin()) {
  232. I->start = NewStart;
  233. segments.erase(MergeTo, I);
  234. return I;
  235. }
  236. assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
  237. --MergeTo;
  238. } while (NewStart <= MergeTo->start);
  239. // If we start in the middle of another segment, just delete a range and
  240. // extend that segment.
  241. if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
  242. MergeTo->end = I->end;
  243. } else {
  244. // Otherwise, extend the segment right after.
  245. ++MergeTo;
  246. MergeTo->start = NewStart;
  247. MergeTo->end = I->end;
  248. }
  249. segments.erase(std::next(MergeTo), std::next(I));
  250. return MergeTo;
  251. }
  252. LiveRange::iterator LiveRange::addSegmentFrom(Segment S, iterator From) {
  253. SlotIndex Start = S.start, End = S.end;
  254. iterator it = std::upper_bound(From, end(), Start);
  255. // If the inserted segment starts in the middle or right at the end of
  256. // another segment, just extend that segment to contain the segment of S.
  257. if (it != begin()) {
  258. iterator B = std::prev(it);
  259. if (S.valno == B->valno) {
  260. if (B->start <= Start && B->end >= Start) {
  261. extendSegmentEndTo(B, End);
  262. return B;
  263. }
  264. } else {
  265. // Check to make sure that we are not overlapping two live segments with
  266. // different valno's.
  267. assert(B->end <= Start &&
  268. "Cannot overlap two segments with differing ValID's"
  269. " (did you def the same reg twice in a MachineInstr?)");
  270. }
  271. }
  272. // Otherwise, if this segment ends in the middle of, or right next to, another
  273. // segment, merge it into that segment.
  274. if (it != end()) {
  275. if (S.valno == it->valno) {
  276. if (it->start <= End) {
  277. it = extendSegmentStartTo(it, Start);
  278. // If S is a complete superset of a segment, we may need to grow its
  279. // endpoint as well.
  280. if (End > it->end)
  281. extendSegmentEndTo(it, End);
  282. return it;
  283. }
  284. } else {
  285. // Check to make sure that we are not overlapping two live segments with
  286. // different valno's.
  287. assert(it->start >= End &&
  288. "Cannot overlap two segments with differing ValID's");
  289. }
  290. }
  291. // Otherwise, this is just a new segment that doesn't interact with anything.
  292. // Insert it.
  293. return segments.insert(it, S);
  294. }
  295. /// extendInBlock - If this range is live before Kill in the basic
  296. /// block that starts at StartIdx, extend it to be live up to Kill and return
  297. /// the value. If there is no live range before Kill, return NULL.
  298. VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
  299. if (empty())
  300. return 0;
  301. iterator I = std::upper_bound(begin(), end(), Kill.getPrevSlot());
  302. if (I == begin())
  303. return 0;
  304. --I;
  305. if (I->end <= StartIdx)
  306. return 0;
  307. if (I->end < Kill)
  308. extendSegmentEndTo(I, Kill);
  309. return I->valno;
  310. }
  311. /// Remove the specified segment from this range. Note that the segment must
  312. /// be in a single Segment in its entirety.
  313. void LiveRange::removeSegment(SlotIndex Start, SlotIndex End,
  314. bool RemoveDeadValNo) {
  315. // Find the Segment containing this span.
  316. iterator I = find(Start);
  317. assert(I != end() && "Segment is not in range!");
  318. assert(I->containsInterval(Start, End)
  319. && "Segment is not entirely in range!");
  320. // If the span we are removing is at the start of the Segment, adjust it.
  321. VNInfo *ValNo = I->valno;
  322. if (I->start == Start) {
  323. if (I->end == End) {
  324. if (RemoveDeadValNo) {
  325. // Check if val# is dead.
  326. bool isDead = true;
  327. for (const_iterator II = begin(), EE = end(); II != EE; ++II)
  328. if (II != I && II->valno == ValNo) {
  329. isDead = false;
  330. break;
  331. }
  332. if (isDead) {
  333. // Now that ValNo is dead, remove it.
  334. markValNoForDeletion(ValNo);
  335. }
  336. }
  337. segments.erase(I); // Removed the whole Segment.
  338. } else
  339. I->start = End;
  340. return;
  341. }
  342. // Otherwise if the span we are removing is at the end of the Segment,
  343. // adjust the other way.
  344. if (I->end == End) {
  345. I->end = Start;
  346. return;
  347. }
  348. // Otherwise, we are splitting the Segment into two pieces.
  349. SlotIndex OldEnd = I->end;
  350. I->end = Start; // Trim the old segment.
  351. // Insert the new one.
  352. segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
  353. }
  354. /// removeValNo - Remove all the segments defined by the specified value#.
  355. /// Also remove the value# from value# list.
  356. void LiveRange::removeValNo(VNInfo *ValNo) {
  357. if (empty()) return;
  358. iterator I = end();
  359. iterator E = begin();
  360. do {
  361. --I;
  362. if (I->valno == ValNo)
  363. segments.erase(I);
  364. } while (I != E);
  365. // Now that ValNo is dead, remove it.
  366. markValNoForDeletion(ValNo);
  367. }
  368. void LiveRange::join(LiveRange &Other,
  369. const int *LHSValNoAssignments,
  370. const int *RHSValNoAssignments,
  371. SmallVectorImpl<VNInfo *> &NewVNInfo) {
  372. verify();
  373. // Determine if any of our values are mapped. This is uncommon, so we want
  374. // to avoid the range scan if not.
  375. bool MustMapCurValNos = false;
  376. unsigned NumVals = getNumValNums();
  377. unsigned NumNewVals = NewVNInfo.size();
  378. for (unsigned i = 0; i != NumVals; ++i) {
  379. unsigned LHSValID = LHSValNoAssignments[i];
  380. if (i != LHSValID ||
  381. (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
  382. MustMapCurValNos = true;
  383. break;
  384. }
  385. }
  386. // If we have to apply a mapping to our base range assignment, rewrite it now.
  387. if (MustMapCurValNos && !empty()) {
  388. // Map the first live range.
  389. iterator OutIt = begin();
  390. OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
  391. for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
  392. VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
  393. assert(nextValNo != 0 && "Huh?");
  394. // If this live range has the same value # as its immediate predecessor,
  395. // and if they are neighbors, remove one Segment. This happens when we
  396. // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
  397. if (OutIt->valno == nextValNo && OutIt->end == I->start) {
  398. OutIt->end = I->end;
  399. } else {
  400. // Didn't merge. Move OutIt to the next segment,
  401. ++OutIt;
  402. OutIt->valno = nextValNo;
  403. if (OutIt != I) {
  404. OutIt->start = I->start;
  405. OutIt->end = I->end;
  406. }
  407. }
  408. }
  409. // If we merge some segments, chop off the end.
  410. ++OutIt;
  411. segments.erase(OutIt, end());
  412. }
  413. // Rewrite Other values before changing the VNInfo ids.
  414. // This can leave Other in an invalid state because we're not coalescing
  415. // touching segments that now have identical values. That's OK since Other is
  416. // not supposed to be valid after calling join();
  417. for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
  418. I->valno = NewVNInfo[RHSValNoAssignments[I->valno->id]];
  419. // Update val# info. Renumber them and make sure they all belong to this
  420. // LiveRange now. Also remove dead val#'s.
  421. unsigned NumValNos = 0;
  422. for (unsigned i = 0; i < NumNewVals; ++i) {
  423. VNInfo *VNI = NewVNInfo[i];
  424. if (VNI) {
  425. if (NumValNos >= NumVals)
  426. valnos.push_back(VNI);
  427. else
  428. valnos[NumValNos] = VNI;
  429. VNI->id = NumValNos++; // Renumber val#.
  430. }
  431. }
  432. if (NumNewVals < NumVals)
  433. valnos.resize(NumNewVals); // shrinkify
  434. // Okay, now insert the RHS live segments into the LHS.
  435. LiveRangeUpdater Updater(this);
  436. for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
  437. Updater.add(*I);
  438. }
  439. /// Merge all of the segments in RHS into this live range as the specified
  440. /// value number. The segments in RHS are allowed to overlap with segments in
  441. /// the current range, but only if the overlapping segments have the
  442. /// specified value number.
  443. void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
  444. VNInfo *LHSValNo) {
  445. LiveRangeUpdater Updater(this);
  446. for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
  447. Updater.add(I->start, I->end, LHSValNo);
  448. }
  449. /// MergeValueInAsValue - Merge all of the live segments of a specific val#
  450. /// in RHS into this live range as the specified value number.
  451. /// The segments in RHS are allowed to overlap with segments in the
  452. /// current range, it will replace the value numbers of the overlaped
  453. /// segments with the specified value number.
  454. void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
  455. const VNInfo *RHSValNo,
  456. VNInfo *LHSValNo) {
  457. LiveRangeUpdater Updater(this);
  458. for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
  459. if (I->valno == RHSValNo)
  460. Updater.add(I->start, I->end, LHSValNo);
  461. }
  462. /// MergeValueNumberInto - This method is called when two value nubmers
  463. /// are found to be equivalent. This eliminates V1, replacing all
  464. /// segments with the V1 value number with the V2 value number. This can
  465. /// cause merging of V1/V2 values numbers and compaction of the value space.
  466. VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
  467. assert(V1 != V2 && "Identical value#'s are always equivalent!");
  468. // This code actually merges the (numerically) larger value number into the
  469. // smaller value number, which is likely to allow us to compactify the value
  470. // space. The only thing we have to be careful of is to preserve the
  471. // instruction that defines the result value.
  472. // Make sure V2 is smaller than V1.
  473. if (V1->id < V2->id) {
  474. V1->copyFrom(*V2);
  475. std::swap(V1, V2);
  476. }
  477. // Merge V1 segments into V2.
  478. for (iterator I = begin(); I != end(); ) {
  479. iterator S = I++;
  480. if (S->valno != V1) continue; // Not a V1 Segment.
  481. // Okay, we found a V1 live range. If it had a previous, touching, V2 live
  482. // range, extend it.
  483. if (S != begin()) {
  484. iterator Prev = S-1;
  485. if (Prev->valno == V2 && Prev->end == S->start) {
  486. Prev->end = S->end;
  487. // Erase this live-range.
  488. segments.erase(S);
  489. I = Prev+1;
  490. S = Prev;
  491. }
  492. }
  493. // Okay, now we have a V1 or V2 live range that is maximally merged forward.
  494. // Ensure that it is a V2 live-range.
  495. S->valno = V2;
  496. // If we can merge it into later V2 segments, do so now. We ignore any
  497. // following V1 segments, as they will be merged in subsequent iterations
  498. // of the loop.
  499. if (I != end()) {
  500. if (I->start == S->end && I->valno == V2) {
  501. S->end = I->end;
  502. segments.erase(I);
  503. I = S+1;
  504. }
  505. }
  506. }
  507. // Now that V1 is dead, remove it.
  508. markValNoForDeletion(V1);
  509. return V2;
  510. }
  511. unsigned LiveInterval::getSize() const {
  512. unsigned Sum = 0;
  513. for (const_iterator I = begin(), E = end(); I != E; ++I)
  514. Sum += I->start.distance(I->end);
  515. return Sum;
  516. }
  517. raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange::Segment &S) {
  518. return os << '[' << S.start << ',' << S.end << ':' << S.valno->id << ")";
  519. }
  520. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  521. void LiveRange::Segment::dump() const {
  522. dbgs() << *this << "\n";
  523. }
  524. #endif
  525. void LiveRange::print(raw_ostream &OS) const {
  526. if (empty())
  527. OS << "EMPTY";
  528. else {
  529. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  530. OS << *I;
  531. assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
  532. }
  533. }
  534. // Print value number info.
  535. if (getNumValNums()) {
  536. OS << " ";
  537. unsigned vnum = 0;
  538. for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
  539. ++i, ++vnum) {
  540. const VNInfo *vni = *i;
  541. if (vnum) OS << " ";
  542. OS << vnum << "@";
  543. if (vni->isUnused()) {
  544. OS << "x";
  545. } else {
  546. OS << vni->def;
  547. if (vni->isPHIDef())
  548. OS << "-phi";
  549. }
  550. }
  551. }
  552. }
  553. void LiveInterval::print(raw_ostream &OS) const {
  554. OS << PrintReg(reg) << ' ';
  555. super::print(OS);
  556. }
  557. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  558. void LiveRange::dump() const {
  559. dbgs() << *this << "\n";
  560. }
  561. void LiveInterval::dump() const {
  562. dbgs() << *this << "\n";
  563. }
  564. #endif
  565. #ifndef NDEBUG
  566. void LiveRange::verify() const {
  567. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  568. assert(I->start.isValid());
  569. assert(I->end.isValid());
  570. assert(I->start < I->end);
  571. assert(I->valno != 0);
  572. assert(I->valno->id < valnos.size());
  573. assert(I->valno == valnos[I->valno->id]);
  574. if (std::next(I) != E) {
  575. assert(I->end <= std::next(I)->start);
  576. if (I->end == std::next(I)->start)
  577. assert(I->valno != std::next(I)->valno);
  578. }
  579. }
  580. }
  581. #endif
  582. //===----------------------------------------------------------------------===//
  583. // LiveRangeUpdater class
  584. //===----------------------------------------------------------------------===//
  585. //
  586. // The LiveRangeUpdater class always maintains these invariants:
  587. //
  588. // - When LastStart is invalid, Spills is empty and the iterators are invalid.
  589. // This is the initial state, and the state created by flush().
  590. // In this state, isDirty() returns false.
  591. //
  592. // Otherwise, segments are kept in three separate areas:
  593. //
  594. // 1. [begin; WriteI) at the front of LR.
  595. // 2. [ReadI; end) at the back of LR.
  596. // 3. Spills.
  597. //
  598. // - LR.begin() <= WriteI <= ReadI <= LR.end().
  599. // - Segments in all three areas are fully ordered and coalesced.
  600. // - Segments in area 1 precede and can't coalesce with segments in area 2.
  601. // - Segments in Spills precede and can't coalesce with segments in area 2.
  602. // - No coalescing is possible between segments in Spills and segments in area
  603. // 1, and there are no overlapping segments.
  604. //
  605. // The segments in Spills are not ordered with respect to the segments in area
  606. // 1. They need to be merged.
  607. //
  608. // When they exist, Spills.back().start <= LastStart,
  609. // and WriteI[-1].start <= LastStart.
  610. void LiveRangeUpdater::print(raw_ostream &OS) const {
  611. if (!isDirty()) {
  612. if (LR)
  613. OS << "Clean updater: " << *LR << '\n';
  614. else
  615. OS << "Null updater.\n";
  616. return;
  617. }
  618. assert(LR && "Can't have null LR in dirty updater.");
  619. OS << " updater with gap = " << (ReadI - WriteI)
  620. << ", last start = " << LastStart
  621. << ":\n Area 1:";
  622. for (LiveRange::const_iterator I = LR->begin(); I != WriteI; ++I)
  623. OS << ' ' << *I;
  624. OS << "\n Spills:";
  625. for (unsigned I = 0, E = Spills.size(); I != E; ++I)
  626. OS << ' ' << Spills[I];
  627. OS << "\n Area 2:";
  628. for (LiveRange::const_iterator I = ReadI, E = LR->end(); I != E; ++I)
  629. OS << ' ' << *I;
  630. OS << '\n';
  631. }
  632. void LiveRangeUpdater::dump() const
  633. {
  634. print(errs());
  635. }
  636. // Determine if A and B should be coalesced.
  637. static inline bool coalescable(const LiveRange::Segment &A,
  638. const LiveRange::Segment &B) {
  639. assert(A.start <= B.start && "Unordered live segments.");
  640. if (A.end == B.start)
  641. return A.valno == B.valno;
  642. if (A.end < B.start)
  643. return false;
  644. assert(A.valno == B.valno && "Cannot overlap different values");
  645. return true;
  646. }
  647. void LiveRangeUpdater::add(LiveRange::Segment Seg) {
  648. assert(LR && "Cannot add to a null destination");
  649. // Flush the state if Start moves backwards.
  650. if (!LastStart.isValid() || LastStart > Seg.start) {
  651. if (isDirty())
  652. flush();
  653. // This brings us to an uninitialized state. Reinitialize.
  654. assert(Spills.empty() && "Leftover spilled segments");
  655. WriteI = ReadI = LR->begin();
  656. }
  657. // Remember start for next time.
  658. LastStart = Seg.start;
  659. // Advance ReadI until it ends after Seg.start.
  660. LiveRange::iterator E = LR->end();
  661. if (ReadI != E && ReadI->end <= Seg.start) {
  662. // First try to close the gap between WriteI and ReadI with spills.
  663. if (ReadI != WriteI)
  664. mergeSpills();
  665. // Then advance ReadI.
  666. if (ReadI == WriteI)
  667. ReadI = WriteI = LR->find(Seg.start);
  668. else
  669. while (ReadI != E && ReadI->end <= Seg.start)
  670. *WriteI++ = *ReadI++;
  671. }
  672. assert(ReadI == E || ReadI->end > Seg.start);
  673. // Check if the ReadI segment begins early.
  674. if (ReadI != E && ReadI->start <= Seg.start) {
  675. assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
  676. // Bail if Seg is completely contained in ReadI.
  677. if (ReadI->end >= Seg.end)
  678. return;
  679. // Coalesce into Seg.
  680. Seg.start = ReadI->start;
  681. ++ReadI;
  682. }
  683. // Coalesce as much as possible from ReadI into Seg.
  684. while (ReadI != E && coalescable(Seg, *ReadI)) {
  685. Seg.end = std::max(Seg.end, ReadI->end);
  686. ++ReadI;
  687. }
  688. // Try coalescing Spills.back() into Seg.
  689. if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
  690. Seg.start = Spills.back().start;
  691. Seg.end = std::max(Spills.back().end, Seg.end);
  692. Spills.pop_back();
  693. }
  694. // Try coalescing Seg into WriteI[-1].
  695. if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
  696. WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
  697. return;
  698. }
  699. // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
  700. if (WriteI != ReadI) {
  701. *WriteI++ = Seg;
  702. return;
  703. }
  704. // Finally, append to LR or Spills.
  705. if (WriteI == E) {
  706. LR->segments.push_back(Seg);
  707. WriteI = ReadI = LR->end();
  708. } else
  709. Spills.push_back(Seg);
  710. }
  711. // Merge as many spilled segments as possible into the gap between WriteI
  712. // and ReadI. Advance WriteI to reflect the inserted instructions.
  713. void LiveRangeUpdater::mergeSpills() {
  714. // Perform a backwards merge of Spills and [SpillI;WriteI).
  715. size_t GapSize = ReadI - WriteI;
  716. size_t NumMoved = std::min(Spills.size(), GapSize);
  717. LiveRange::iterator Src = WriteI;
  718. LiveRange::iterator Dst = Src + NumMoved;
  719. LiveRange::iterator SpillSrc = Spills.end();
  720. LiveRange::iterator B = LR->begin();
  721. // This is the new WriteI position after merging spills.
  722. WriteI = Dst;
  723. // Now merge Src and Spills backwards.
  724. while (Src != Dst) {
  725. if (Src != B && Src[-1].start > SpillSrc[-1].start)
  726. *--Dst = *--Src;
  727. else
  728. *--Dst = *--SpillSrc;
  729. }
  730. assert(NumMoved == size_t(Spills.end() - SpillSrc));
  731. Spills.erase(SpillSrc, Spills.end());
  732. }
  733. void LiveRangeUpdater::flush() {
  734. if (!isDirty())
  735. return;
  736. // Clear the dirty state.
  737. LastStart = SlotIndex();
  738. assert(LR && "Cannot add to a null destination");
  739. // Nothing to merge?
  740. if (Spills.empty()) {
  741. LR->segments.erase(WriteI, ReadI);
  742. LR->verify();
  743. return;
  744. }
  745. // Resize the WriteI - ReadI gap to match Spills.
  746. size_t GapSize = ReadI - WriteI;
  747. if (GapSize < Spills.size()) {
  748. // The gap is too small. Make some room.
  749. size_t WritePos = WriteI - LR->begin();
  750. LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
  751. // This also invalidated ReadI, but it is recomputed below.
  752. WriteI = LR->begin() + WritePos;
  753. } else {
  754. // Shrink the gap if necessary.
  755. LR->segments.erase(WriteI + Spills.size(), ReadI);
  756. }
  757. ReadI = WriteI + Spills.size();
  758. mergeSpills();
  759. LR->verify();
  760. }
  761. unsigned ConnectedVNInfoEqClasses::Classify(const LiveInterval *LI) {
  762. // Create initial equivalence classes.
  763. EqClass.clear();
  764. EqClass.grow(LI->getNumValNums());
  765. const VNInfo *used = 0, *unused = 0;
  766. // Determine connections.
  767. for (LiveInterval::const_vni_iterator I = LI->vni_begin(), E = LI->vni_end();
  768. I != E; ++I) {
  769. const VNInfo *VNI = *I;
  770. // Group all unused values into one class.
  771. if (VNI->isUnused()) {
  772. if (unused)
  773. EqClass.join(unused->id, VNI->id);
  774. unused = VNI;
  775. continue;
  776. }
  777. used = VNI;
  778. if (VNI->isPHIDef()) {
  779. const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
  780. assert(MBB && "Phi-def has no defining MBB");
  781. // Connect to values live out of predecessors.
  782. for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
  783. PE = MBB->pred_end(); PI != PE; ++PI)
  784. if (const VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI)))
  785. EqClass.join(VNI->id, PVNI->id);
  786. } else {
  787. // Normal value defined by an instruction. Check for two-addr redef.
  788. // FIXME: This could be coincidental. Should we really check for a tied
  789. // operand constraint?
  790. // Note that VNI->def may be a use slot for an early clobber def.
  791. if (const VNInfo *UVNI = LI->getVNInfoBefore(VNI->def))
  792. EqClass.join(VNI->id, UVNI->id);
  793. }
  794. }
  795. // Lump all the unused values in with the last used value.
  796. if (used && unused)
  797. EqClass.join(used->id, unused->id);
  798. EqClass.compress();
  799. return EqClass.getNumClasses();
  800. }
  801. void ConnectedVNInfoEqClasses::Distribute(LiveInterval *LIV[],
  802. MachineRegisterInfo &MRI) {
  803. assert(LIV[0] && "LIV[0] must be set");
  804. LiveInterval &LI = *LIV[0];
  805. // Rewrite instructions.
  806. for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg),
  807. RE = MRI.reg_end(); RI != RE;) {
  808. MachineOperand &MO = RI.getOperand();
  809. MachineInstr *MI = MO.getParent();
  810. ++RI;
  811. // DBG_VALUE instructions don't have slot indexes, so get the index of the
  812. // instruction before them.
  813. // Normally, DBG_VALUE instructions are removed before this function is
  814. // called, but it is not a requirement.
  815. SlotIndex Idx;
  816. if (MI->isDebugValue())
  817. Idx = LIS.getSlotIndexes()->getIndexBefore(MI);
  818. else
  819. Idx = LIS.getInstructionIndex(MI);
  820. LiveQueryResult LRQ = LI.Query(Idx);
  821. const VNInfo *VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
  822. // In the case of an <undef> use that isn't tied to any def, VNI will be
  823. // NULL. If the use is tied to a def, VNI will be the defined value.
  824. if (!VNI)
  825. continue;
  826. MO.setReg(LIV[getEqClass(VNI)]->reg);
  827. }
  828. // Move runs to new intervals.
  829. LiveInterval::iterator J = LI.begin(), E = LI.end();
  830. while (J != E && EqClass[J->valno->id] == 0)
  831. ++J;
  832. for (LiveInterval::iterator I = J; I != E; ++I) {
  833. if (unsigned eq = EqClass[I->valno->id]) {
  834. assert((LIV[eq]->empty() || LIV[eq]->expiredAt(I->start)) &&
  835. "New intervals should be empty");
  836. LIV[eq]->segments.push_back(*I);
  837. } else
  838. *J++ = *I;
  839. }
  840. LI.segments.erase(J, E);
  841. // Transfer VNInfos to their new owners and renumber them.
  842. unsigned j = 0, e = LI.getNumValNums();
  843. while (j != e && EqClass[j] == 0)
  844. ++j;
  845. for (unsigned i = j; i != e; ++i) {
  846. VNInfo *VNI = LI.getValNumInfo(i);
  847. if (unsigned eq = EqClass[i]) {
  848. VNI->id = LIV[eq]->getNumValNums();
  849. LIV[eq]->valnos.push_back(VNI);
  850. } else {
  851. VNI->id = j;
  852. LI.valnos[j++] = VNI;
  853. }
  854. }
  855. LI.valnos.resize(j);
  856. }