LiveInterval.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. //===-- llvm/CodeGen/LiveInterval.h - Interval representation ---*- C++ -*-===//
  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. #ifndef LLVM_CODEGEN_LIVEINTERVAL_H
  21. #define LLVM_CODEGEN_LIVEINTERVAL_H
  22. #include "llvm/ADT/IntEqClasses.h"
  23. #include "llvm/CodeGen/SlotIndexes.h"
  24. #include "llvm/Support/AlignOf.h"
  25. #include "llvm/Support/Allocator.h"
  26. #include <cassert>
  27. #include <climits>
  28. #include <set>
  29. namespace llvm {
  30. class CoalescerPair;
  31. class LiveIntervals;
  32. class MachineInstr;
  33. class MachineRegisterInfo;
  34. class TargetRegisterInfo;
  35. class raw_ostream;
  36. template <typename T, unsigned Small> class SmallPtrSet;
  37. /// VNInfo - Value Number Information.
  38. /// This class holds information about a machine level values, including
  39. /// definition and use points.
  40. ///
  41. class VNInfo {
  42. public:
  43. typedef BumpPtrAllocator Allocator;
  44. /// The ID number of this value.
  45. unsigned id;
  46. /// The index of the defining instruction.
  47. SlotIndex def;
  48. /// VNInfo constructor.
  49. VNInfo(unsigned i, SlotIndex d)
  50. : id(i), def(d)
  51. { }
  52. /// VNInfo construtor, copies values from orig, except for the value number.
  53. VNInfo(unsigned i, const VNInfo &orig)
  54. : id(i), def(orig.def)
  55. { }
  56. /// Copy from the parameter into this VNInfo.
  57. void copyFrom(VNInfo &src) {
  58. def = src.def;
  59. }
  60. /// Returns true if this value is defined by a PHI instruction (or was,
  61. /// PHI instructions may have been eliminated).
  62. /// PHI-defs begin at a block boundary, all other defs begin at register or
  63. /// EC slots.
  64. bool isPHIDef() const { return def.isBlock(); }
  65. /// Returns true if this value is unused.
  66. bool isUnused() const { return !def.isValid(); }
  67. /// Mark this value as unused.
  68. void markUnused() { def = SlotIndex(); }
  69. };
  70. /// Result of a LiveRange query. This class hides the implementation details
  71. /// of live ranges, and it should be used as the primary interface for
  72. /// examining live ranges around instructions.
  73. class LiveQueryResult {
  74. VNInfo *const EarlyVal;
  75. VNInfo *const LateVal;
  76. const SlotIndex EndPoint;
  77. const bool Kill;
  78. public:
  79. LiveQueryResult(VNInfo *EarlyVal, VNInfo *LateVal, SlotIndex EndPoint,
  80. bool Kill)
  81. : EarlyVal(EarlyVal), LateVal(LateVal), EndPoint(EndPoint), Kill(Kill)
  82. {}
  83. /// Return the value that is live-in to the instruction. This is the value
  84. /// that will be read by the instruction's use operands. Return NULL if no
  85. /// value is live-in.
  86. VNInfo *valueIn() const {
  87. return EarlyVal;
  88. }
  89. /// Return true if the live-in value is killed by this instruction. This
  90. /// means that either the live range ends at the instruction, or it changes
  91. /// value.
  92. bool isKill() const {
  93. return Kill;
  94. }
  95. /// Return true if this instruction has a dead def.
  96. bool isDeadDef() const {
  97. return EndPoint.isDead();
  98. }
  99. /// Return the value leaving the instruction, if any. This can be a
  100. /// live-through value, or a live def. A dead def returns NULL.
  101. VNInfo *valueOut() const {
  102. return isDeadDef() ? nullptr : LateVal;
  103. }
  104. /// Returns the value alive at the end of the instruction, if any. This can
  105. /// be a live-through value, a live def or a dead def.
  106. VNInfo *valueOutOrDead() const {
  107. return LateVal;
  108. }
  109. /// Return the value defined by this instruction, if any. This includes
  110. /// dead defs, it is the value created by the instruction's def operands.
  111. VNInfo *valueDefined() const {
  112. return EarlyVal == LateVal ? nullptr : LateVal;
  113. }
  114. /// Return the end point of the last live range segment to interact with
  115. /// the instruction, if any.
  116. ///
  117. /// The end point is an invalid SlotIndex only if the live range doesn't
  118. /// intersect the instruction at all.
  119. ///
  120. /// The end point may be at or past the end of the instruction's basic
  121. /// block. That means the value was live out of the block.
  122. SlotIndex endPoint() const {
  123. return EndPoint;
  124. }
  125. };
  126. /// This class represents the liveness of a register, stack slot, etc.
  127. /// It manages an ordered list of Segment objects.
  128. /// The Segments are organized in a static single assignment form: At places
  129. /// where a new value is defined or different values reach a CFG join a new
  130. /// segment with a new value number is used.
  131. class LiveRange {
  132. public:
  133. /// This represents a simple continuous liveness interval for a value.
  134. /// The start point is inclusive, the end point exclusive. These intervals
  135. /// are rendered as [start,end).
  136. struct Segment {
  137. SlotIndex start; // Start point of the interval (inclusive)
  138. SlotIndex end; // End point of the interval (exclusive)
  139. VNInfo *valno; // identifier for the value contained in this segment.
  140. Segment() : valno(nullptr) {}
  141. Segment(SlotIndex S, SlotIndex E, VNInfo *V)
  142. : start(S), end(E), valno(V) {
  143. assert(S < E && "Cannot create empty or backwards segment");
  144. }
  145. /// Return true if the index is covered by this segment.
  146. bool contains(SlotIndex I) const {
  147. return start <= I && I < end;
  148. }
  149. /// Return true if the given interval, [S, E), is covered by this segment.
  150. bool containsInterval(SlotIndex S, SlotIndex E) const {
  151. assert((S < E) && "Backwards interval?");
  152. return (start <= S && S < end) && (start < E && E <= end);
  153. }
  154. bool operator<(const Segment &Other) const {
  155. return std::tie(start, end) < std::tie(Other.start, Other.end);
  156. }
  157. bool operator==(const Segment &Other) const {
  158. return start == Other.start && end == Other.end;
  159. }
  160. void dump() const;
  161. };
  162. typedef SmallVector<Segment,4> Segments;
  163. typedef SmallVector<VNInfo*,4> VNInfoList;
  164. Segments segments; // the liveness segments
  165. VNInfoList valnos; // value#'s
  166. // The segment set is used temporarily to accelerate initial computation
  167. // of live ranges of physical registers in computeRegUnitRange.
  168. // After that the set is flushed to the segment vector and deleted.
  169. typedef std::set<Segment> SegmentSet;
  170. std::unique_ptr<SegmentSet> segmentSet;
  171. typedef Segments::iterator iterator;
  172. iterator begin() { return segments.begin(); }
  173. iterator end() { return segments.end(); }
  174. typedef Segments::const_iterator const_iterator;
  175. const_iterator begin() const { return segments.begin(); }
  176. const_iterator end() const { return segments.end(); }
  177. typedef VNInfoList::iterator vni_iterator;
  178. vni_iterator vni_begin() { return valnos.begin(); }
  179. vni_iterator vni_end() { return valnos.end(); }
  180. typedef VNInfoList::const_iterator const_vni_iterator;
  181. const_vni_iterator vni_begin() const { return valnos.begin(); }
  182. const_vni_iterator vni_end() const { return valnos.end(); }
  183. /// Constructs a new LiveRange object.
  184. LiveRange(bool UseSegmentSet = false)
  185. : segmentSet(UseSegmentSet ? llvm::make_unique<SegmentSet>()
  186. : nullptr) {}
  187. /// Constructs a new LiveRange object by copying segments and valnos from
  188. /// another LiveRange.
  189. LiveRange(const LiveRange &Other, BumpPtrAllocator &Allocator) {
  190. assert(Other.segmentSet == nullptr &&
  191. "Copying of LiveRanges with active SegmentSets is not supported");
  192. // Duplicate valnos.
  193. for (const VNInfo *VNI : Other.valnos) {
  194. createValueCopy(VNI, Allocator);
  195. }
  196. // Now we can copy segments and remap their valnos.
  197. for (const Segment &S : Other.segments) {
  198. segments.push_back(Segment(S.start, S.end, valnos[S.valno->id]));
  199. }
  200. }
  201. /// advanceTo - Advance the specified iterator to point to the Segment
  202. /// containing the specified position, or end() if the position is past the
  203. /// end of the range. If no Segment contains this position, but the
  204. /// position is in a hole, this method returns an iterator pointing to the
  205. /// Segment immediately after the hole.
  206. iterator advanceTo(iterator I, SlotIndex Pos) {
  207. assert(I != end());
  208. if (Pos >= endIndex())
  209. return end();
  210. while (I->end <= Pos) ++I;
  211. return I;
  212. }
  213. const_iterator advanceTo(const_iterator I, SlotIndex Pos) const {
  214. assert(I != end());
  215. if (Pos >= endIndex())
  216. return end();
  217. while (I->end <= Pos) ++I;
  218. return I;
  219. }
  220. /// find - Return an iterator pointing to the first segment that ends after
  221. /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
  222. /// when searching large ranges.
  223. ///
  224. /// If Pos is contained in a Segment, that segment is returned.
  225. /// If Pos is in a hole, the following Segment is returned.
  226. /// If Pos is beyond endIndex, end() is returned.
  227. iterator find(SlotIndex Pos);
  228. const_iterator find(SlotIndex Pos) const {
  229. return const_cast<LiveRange*>(this)->find(Pos);
  230. }
  231. void clear() {
  232. valnos.clear();
  233. segments.clear();
  234. }
  235. size_t size() const {
  236. return segments.size();
  237. }
  238. bool hasAtLeastOneValue() const { return !valnos.empty(); }
  239. bool containsOneValue() const { return valnos.size() == 1; }
  240. unsigned getNumValNums() const { return (unsigned)valnos.size(); }
  241. /// getValNumInfo - Returns pointer to the specified val#.
  242. ///
  243. inline VNInfo *getValNumInfo(unsigned ValNo) {
  244. return valnos[ValNo];
  245. }
  246. inline const VNInfo *getValNumInfo(unsigned ValNo) const {
  247. return valnos[ValNo];
  248. }
  249. /// containsValue - Returns true if VNI belongs to this range.
  250. bool containsValue(const VNInfo *VNI) const {
  251. return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
  252. }
  253. /// getNextValue - Create a new value number and return it. MIIdx specifies
  254. /// the instruction that defines the value number.
  255. VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
  256. VNInfo *VNI =
  257. new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
  258. valnos.push_back(VNI);
  259. return VNI;
  260. }
  261. /// createDeadDef - Make sure the range has a value defined at Def.
  262. /// If one already exists, return it. Otherwise allocate a new value and
  263. /// add liveness for a dead def.
  264. VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
  265. /// Create a copy of the given value. The new value will be identical except
  266. /// for the Value number.
  267. VNInfo *createValueCopy(const VNInfo *orig,
  268. VNInfo::Allocator &VNInfoAllocator) {
  269. VNInfo *VNI =
  270. new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
  271. valnos.push_back(VNI);
  272. return VNI;
  273. }
  274. /// RenumberValues - Renumber all values in order of appearance and remove
  275. /// unused values.
  276. void RenumberValues();
  277. /// MergeValueNumberInto - This method is called when two value numbers
  278. /// are found to be equivalent. This eliminates V1, replacing all
  279. /// segments with the V1 value number with the V2 value number. This can
  280. /// cause merging of V1/V2 values numbers and compaction of the value space.
  281. VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
  282. /// Merge all of the live segments of a specific val# in RHS into this live
  283. /// range as the specified value number. The segments in RHS are allowed
  284. /// to overlap with segments in the current range, it will replace the
  285. /// value numbers of the overlaped live segments with the specified value
  286. /// number.
  287. void MergeSegmentsInAsValue(const LiveRange &RHS, VNInfo *LHSValNo);
  288. /// MergeValueInAsValue - Merge all of the segments of a specific val#
  289. /// in RHS into this live range as the specified value number.
  290. /// The segments in RHS are allowed to overlap with segments in the
  291. /// current range, but only if the overlapping segments have the
  292. /// specified value number.
  293. void MergeValueInAsValue(const LiveRange &RHS,
  294. const VNInfo *RHSValNo, VNInfo *LHSValNo);
  295. bool empty() const { return segments.empty(); }
  296. /// beginIndex - Return the lowest numbered slot covered.
  297. SlotIndex beginIndex() const {
  298. assert(!empty() && "Call to beginIndex() on empty range.");
  299. return segments.front().start;
  300. }
  301. /// endNumber - return the maximum point of the range of the whole,
  302. /// exclusive.
  303. SlotIndex endIndex() const {
  304. assert(!empty() && "Call to endIndex() on empty range.");
  305. return segments.back().end;
  306. }
  307. bool expiredAt(SlotIndex index) const {
  308. return index >= endIndex();
  309. }
  310. bool liveAt(SlotIndex index) const {
  311. const_iterator r = find(index);
  312. return r != end() && r->start <= index;
  313. }
  314. /// Return the segment that contains the specified index, or null if there
  315. /// is none.
  316. const Segment *getSegmentContaining(SlotIndex Idx) const {
  317. const_iterator I = FindSegmentContaining(Idx);
  318. return I == end() ? nullptr : &*I;
  319. }
  320. /// Return the live segment that contains the specified index, or null if
  321. /// there is none.
  322. Segment *getSegmentContaining(SlotIndex Idx) {
  323. iterator I = FindSegmentContaining(Idx);
  324. return I == end() ? nullptr : &*I;
  325. }
  326. /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
  327. VNInfo *getVNInfoAt(SlotIndex Idx) const {
  328. const_iterator I = FindSegmentContaining(Idx);
  329. return I == end() ? nullptr : I->valno;
  330. }
  331. /// getVNInfoBefore - Return the VNInfo that is live up to but not
  332. /// necessarilly including Idx, or NULL. Use this to find the reaching def
  333. /// used by an instruction at this SlotIndex position.
  334. VNInfo *getVNInfoBefore(SlotIndex Idx) const {
  335. const_iterator I = FindSegmentContaining(Idx.getPrevSlot());
  336. return I == end() ? nullptr : I->valno;
  337. }
  338. /// Return an iterator to the segment that contains the specified index, or
  339. /// end() if there is none.
  340. iterator FindSegmentContaining(SlotIndex Idx) {
  341. iterator I = find(Idx);
  342. return I != end() && I->start <= Idx ? I : end();
  343. }
  344. const_iterator FindSegmentContaining(SlotIndex Idx) const {
  345. const_iterator I = find(Idx);
  346. return I != end() && I->start <= Idx ? I : end();
  347. }
  348. /// overlaps - Return true if the intersection of the two live ranges is
  349. /// not empty.
  350. bool overlaps(const LiveRange &other) const {
  351. if (other.empty())
  352. return false;
  353. return overlapsFrom(other, other.begin());
  354. }
  355. /// overlaps - Return true if the two ranges have overlapping segments
  356. /// that are not coalescable according to CP.
  357. ///
  358. /// Overlapping segments where one range is defined by a coalescable
  359. /// copy are allowed.
  360. bool overlaps(const LiveRange &Other, const CoalescerPair &CP,
  361. const SlotIndexes&) const;
  362. /// overlaps - Return true if the live range overlaps an interval specified
  363. /// by [Start, End).
  364. bool overlaps(SlotIndex Start, SlotIndex End) const;
  365. /// overlapsFrom - Return true if the intersection of the two live ranges
  366. /// is not empty. The specified iterator is a hint that we can begin
  367. /// scanning the Other range starting at I.
  368. bool overlapsFrom(const LiveRange &Other, const_iterator I) const;
  369. /// Returns true if all segments of the @p Other live range are completely
  370. /// covered by this live range.
  371. /// Adjacent live ranges do not affect the covering:the liverange
  372. /// [1,5](5,10] covers (3,7].
  373. bool covers(const LiveRange &Other) const;
  374. /// Add the specified Segment to this range, merging segments as
  375. /// appropriate. This returns an iterator to the inserted segment (which
  376. /// may have grown since it was inserted).
  377. iterator addSegment(Segment S);
  378. /// If this range is live before @p Use in the basic block that starts at
  379. /// @p StartIdx, extend it to be live up to @p Use, and return the value. If
  380. /// there is no segment before @p Use, return nullptr.
  381. VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use);
  382. /// join - Join two live ranges (this, and other) together. This applies
  383. /// mappings to the value numbers in the LHS/RHS ranges as specified. If
  384. /// the ranges are not joinable, this aborts.
  385. void join(LiveRange &Other,
  386. const int *ValNoAssignments,
  387. const int *RHSValNoAssignments,
  388. SmallVectorImpl<VNInfo *> &NewVNInfo);
  389. /// True iff this segment is a single segment that lies between the
  390. /// specified boundaries, exclusively. Vregs live across a backedge are not
  391. /// considered local. The boundaries are expected to lie within an extended
  392. /// basic block, so vregs that are not live out should contain no holes.
  393. bool isLocal(SlotIndex Start, SlotIndex End) const {
  394. return beginIndex() > Start.getBaseIndex() &&
  395. endIndex() < End.getBoundaryIndex();
  396. }
  397. /// Remove the specified segment from this range. Note that the segment
  398. /// must be a single Segment in its entirety.
  399. void removeSegment(SlotIndex Start, SlotIndex End,
  400. bool RemoveDeadValNo = false);
  401. void removeSegment(Segment S, bool RemoveDeadValNo = false) {
  402. removeSegment(S.start, S.end, RemoveDeadValNo);
  403. }
  404. /// Remove segment pointed to by iterator @p I from this range. This does
  405. /// not remove dead value numbers.
  406. iterator removeSegment(iterator I) {
  407. return segments.erase(I);
  408. }
  409. /// Query Liveness at Idx.
  410. /// The sub-instruction slot of Idx doesn't matter, only the instruction
  411. /// it refers to is considered.
  412. LiveQueryResult Query(SlotIndex Idx) const {
  413. // Find the segment that enters the instruction.
  414. const_iterator I = find(Idx.getBaseIndex());
  415. const_iterator E = end();
  416. if (I == E)
  417. return LiveQueryResult(nullptr, nullptr, SlotIndex(), false);
  418. // Is this an instruction live-in segment?
  419. // If Idx is the start index of a basic block, include live-in segments
  420. // that start at Idx.getBaseIndex().
  421. VNInfo *EarlyVal = nullptr;
  422. VNInfo *LateVal = nullptr;
  423. SlotIndex EndPoint;
  424. bool Kill = false;
  425. if (I->start <= Idx.getBaseIndex()) {
  426. EarlyVal = I->valno;
  427. EndPoint = I->end;
  428. // Move to the potentially live-out segment.
  429. if (SlotIndex::isSameInstr(Idx, I->end)) {
  430. Kill = true;
  431. if (++I == E)
  432. return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
  433. }
  434. // Special case: A PHIDef value can have its def in the middle of a
  435. // segment if the value happens to be live out of the layout
  436. // predecessor.
  437. // Such a value is not live-in.
  438. if (EarlyVal->def == Idx.getBaseIndex())
  439. EarlyVal = nullptr;
  440. }
  441. // I now points to the segment that may be live-through, or defined by
  442. // this instr. Ignore segments starting after the current instr.
  443. if (!SlotIndex::isEarlierInstr(Idx, I->start)) {
  444. LateVal = I->valno;
  445. EndPoint = I->end;
  446. }
  447. return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
  448. }
  449. /// removeValNo - Remove all the segments defined by the specified value#.
  450. /// Also remove the value# from value# list.
  451. void removeValNo(VNInfo *ValNo);
  452. /// Returns true if the live range is zero length, i.e. no live segments
  453. /// span instructions. It doesn't pay to spill such a range.
  454. bool isZeroLength(SlotIndexes *Indexes) const {
  455. for (const Segment &S : segments)
  456. if (Indexes->getNextNonNullIndex(S.start).getBaseIndex() <
  457. S.end.getBaseIndex())
  458. return false;
  459. return true;
  460. }
  461. bool operator<(const LiveRange& other) const {
  462. const SlotIndex &thisIndex = beginIndex();
  463. const SlotIndex &otherIndex = other.beginIndex();
  464. return thisIndex < otherIndex;
  465. }
  466. /// Flush segment set into the regular segment vector.
  467. /// The method is to be called after the live range
  468. /// has been created, if use of the segment set was
  469. /// activated in the constructor of the live range.
  470. void flushSegmentSet();
  471. void print(raw_ostream &OS) const;
  472. void dump() const;
  473. /// \brief Walk the range and assert if any invariants fail to hold.
  474. ///
  475. /// Note that this is a no-op when asserts are disabled.
  476. #ifdef NDEBUG
  477. void verify() const {}
  478. #else
  479. void verify() const;
  480. #endif
  481. protected:
  482. /// Append a segment to the list of segments.
  483. void append(const LiveRange::Segment S);
  484. private:
  485. friend class LiveRangeUpdater;
  486. void addSegmentToSet(Segment S);
  487. void markValNoForDeletion(VNInfo *V);
  488. };
  489. inline raw_ostream &operator<<(raw_ostream &OS, const LiveRange &LR) {
  490. LR.print(OS);
  491. return OS;
  492. }
  493. /// LiveInterval - This class represents the liveness of a register,
  494. /// or stack slot.
  495. class LiveInterval : public LiveRange {
  496. public:
  497. typedef LiveRange super;
  498. /// A live range for subregisters. The LaneMask specifies which parts of the
  499. /// super register are covered by the interval.
  500. /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
  501. class SubRange : public LiveRange {
  502. public:
  503. SubRange *Next;
  504. unsigned LaneMask;
  505. /// Constructs a new SubRange object.
  506. SubRange(unsigned LaneMask)
  507. : Next(nullptr), LaneMask(LaneMask) {
  508. }
  509. /// Constructs a new SubRange object by copying liveness from @p Other.
  510. SubRange(unsigned LaneMask, const LiveRange &Other,
  511. BumpPtrAllocator &Allocator)
  512. : LiveRange(Other, Allocator), Next(nullptr), LaneMask(LaneMask) {
  513. }
  514. };
  515. private:
  516. SubRange *SubRanges; ///< Single linked list of subregister live ranges.
  517. public:
  518. const unsigned reg; // the register or stack slot of this interval.
  519. float weight; // weight of this interval
  520. LiveInterval(unsigned Reg, float Weight)
  521. : SubRanges(nullptr), reg(Reg), weight(Weight) {}
  522. ~LiveInterval() {
  523. clearSubRanges();
  524. }
  525. template<typename T>
  526. class SingleLinkedListIterator {
  527. T *P;
  528. public:
  529. SingleLinkedListIterator<T>(T *P) : P(P) {}
  530. SingleLinkedListIterator<T> &operator++() {
  531. P = P->Next;
  532. return *this;
  533. }
  534. SingleLinkedListIterator<T> &operator++(int) {
  535. SingleLinkedListIterator res = *this;
  536. ++*this;
  537. return res;
  538. }
  539. bool operator!=(const SingleLinkedListIterator<T> &Other) {
  540. return P != Other.operator->();
  541. }
  542. bool operator==(const SingleLinkedListIterator<T> &Other) {
  543. return P == Other.operator->();
  544. }
  545. T &operator*() const {
  546. return *P;
  547. }
  548. T *operator->() const {
  549. return P;
  550. }
  551. };
  552. typedef SingleLinkedListIterator<SubRange> subrange_iterator;
  553. subrange_iterator subrange_begin() {
  554. return subrange_iterator(SubRanges);
  555. }
  556. subrange_iterator subrange_end() {
  557. return subrange_iterator(nullptr);
  558. }
  559. typedef SingleLinkedListIterator<const SubRange> const_subrange_iterator;
  560. const_subrange_iterator subrange_begin() const {
  561. return const_subrange_iterator(SubRanges);
  562. }
  563. const_subrange_iterator subrange_end() const {
  564. return const_subrange_iterator(nullptr);
  565. }
  566. iterator_range<subrange_iterator> subranges() {
  567. return make_range(subrange_begin(), subrange_end());
  568. }
  569. iterator_range<const_subrange_iterator> subranges() const {
  570. return make_range(subrange_begin(), subrange_end());
  571. }
  572. /// Creates a new empty subregister live range. The range is added at the
  573. /// beginning of the subrange list; subrange iterators stay valid.
  574. SubRange *createSubRange(BumpPtrAllocator &Allocator, unsigned LaneMask) {
  575. SubRange *Range = new (Allocator) SubRange(LaneMask);
  576. appendSubRange(Range);
  577. return Range;
  578. }
  579. /// Like createSubRange() but the new range is filled with a copy of the
  580. /// liveness information in @p CopyFrom.
  581. SubRange *createSubRangeFrom(BumpPtrAllocator &Allocator, unsigned LaneMask,
  582. const LiveRange &CopyFrom) {
  583. SubRange *Range = new (Allocator) SubRange(LaneMask, CopyFrom, Allocator);
  584. appendSubRange(Range);
  585. return Range;
  586. }
  587. /// Returns true if subregister liveness information is available.
  588. bool hasSubRanges() const {
  589. return SubRanges != nullptr;
  590. }
  591. /// Removes all subregister liveness information.
  592. void clearSubRanges();
  593. /// Removes all subranges without any segments (subranges without segments
  594. /// are not considered valid and should only exist temporarily).
  595. void removeEmptySubRanges();
  596. /// Construct main live range by merging the SubRanges of @p LI.
  597. void constructMainRangeFromSubranges(const SlotIndexes &Indexes,
  598. VNInfo::Allocator &VNIAllocator);
  599. /// getSize - Returns the sum of sizes of all the LiveRange's.
  600. ///
  601. unsigned getSize() const;
  602. /// isSpillable - Can this interval be spilled?
  603. bool isSpillable() const {
  604. return weight != llvm::huge_valf;
  605. }
  606. /// markNotSpillable - Mark interval as not spillable
  607. void markNotSpillable() {
  608. weight = llvm::huge_valf;
  609. }
  610. bool operator<(const LiveInterval& other) const {
  611. const SlotIndex &thisIndex = beginIndex();
  612. const SlotIndex &otherIndex = other.beginIndex();
  613. return std::tie(thisIndex, reg) < std::tie(otherIndex, other.reg);
  614. }
  615. void print(raw_ostream &OS) const;
  616. void dump() const;
  617. /// \brief Walks the interval and assert if any invariants fail to hold.
  618. ///
  619. /// Note that this is a no-op when asserts are disabled.
  620. #ifdef NDEBUG
  621. void verify(const MachineRegisterInfo *MRI = nullptr) const {}
  622. #else
  623. void verify(const MachineRegisterInfo *MRI = nullptr) const;
  624. #endif
  625. private:
  626. /// Appends @p Range to SubRanges list.
  627. void appendSubRange(SubRange *Range) {
  628. Range->Next = SubRanges;
  629. SubRanges = Range;
  630. }
  631. /// Free memory held by SubRange.
  632. void freeSubRange(SubRange *S);
  633. };
  634. inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
  635. LI.print(OS);
  636. return OS;
  637. }
  638. raw_ostream &operator<<(raw_ostream &OS, const LiveRange::Segment &S);
  639. inline bool operator<(SlotIndex V, const LiveRange::Segment &S) {
  640. return V < S.start;
  641. }
  642. inline bool operator<(const LiveRange::Segment &S, SlotIndex V) {
  643. return S.start < V;
  644. }
  645. /// Helper class for performant LiveRange bulk updates.
  646. ///
  647. /// Calling LiveRange::addSegment() repeatedly can be expensive on large
  648. /// live ranges because segments after the insertion point may need to be
  649. /// shifted. The LiveRangeUpdater class can defer the shifting when adding
  650. /// many segments in order.
  651. ///
  652. /// The LiveRange will be in an invalid state until flush() is called.
  653. class LiveRangeUpdater {
  654. LiveRange *LR;
  655. SlotIndex LastStart;
  656. LiveRange::iterator WriteI;
  657. LiveRange::iterator ReadI;
  658. SmallVector<LiveRange::Segment, 16> Spills;
  659. void mergeSpills();
  660. public:
  661. /// Create a LiveRangeUpdater for adding segments to LR.
  662. /// LR will temporarily be in an invalid state until flush() is called.
  663. LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
  664. ~LiveRangeUpdater() { flush(); }
  665. /// Add a segment to LR and coalesce when possible, just like
  666. /// LR.addSegment(). Segments should be added in increasing start order for
  667. /// best performance.
  668. void add(LiveRange::Segment);
  669. void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
  670. add(LiveRange::Segment(Start, End, VNI));
  671. }
  672. /// Return true if the LR is currently in an invalid state, and flush()
  673. /// needs to be called.
  674. bool isDirty() const { return LastStart.isValid(); }
  675. /// Flush the updater state to LR so it is valid and contains all added
  676. /// segments.
  677. void flush();
  678. /// Select a different destination live range.
  679. void setDest(LiveRange *lr) {
  680. if (LR != lr && isDirty())
  681. flush();
  682. LR = lr;
  683. }
  684. /// Get the current destination live range.
  685. LiveRange *getDest() const { return LR; }
  686. void dump() const;
  687. void print(raw_ostream&) const;
  688. };
  689. inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
  690. X.print(OS);
  691. return OS;
  692. }
  693. /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
  694. /// LiveInterval into equivalence clases of connected components. A
  695. /// LiveInterval that has multiple connected components can be broken into
  696. /// multiple LiveIntervals.
  697. ///
  698. /// Given a LiveInterval that may have multiple connected components, run:
  699. ///
  700. /// unsigned numComps = ConEQ.Classify(LI);
  701. /// if (numComps > 1) {
  702. /// // allocate numComps-1 new LiveIntervals into LIS[1..]
  703. /// ConEQ.Distribute(LIS);
  704. /// }
  705. class ConnectedVNInfoEqClasses {
  706. LiveIntervals &LIS;
  707. IntEqClasses EqClass;
  708. // Note that values a and b are connected.
  709. void Connect(unsigned a, unsigned b);
  710. unsigned Renumber();
  711. public:
  712. explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
  713. /// Classify - Classify the values in LI into connected components.
  714. /// Return the number of connected components.
  715. unsigned Classify(const LiveInterval *LI);
  716. /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
  717. /// the equivalence class assigned the VNI.
  718. unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
  719. /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
  720. /// for each connected component. LIV must have a LiveInterval for each
  721. /// connected component. The LiveIntervals in Liv[1..] must be empty.
  722. /// Instructions using LIV[0] are rewritten.
  723. void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);
  724. };
  725. }
  726. #endif