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