LiveInterval: Use range based for loops for subregister ranges.
[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     /// Query Liveness at Idx.
476     /// The sub-instruction slot of Idx doesn't matter, only the instruction
477     /// it refers to is considered.
478     LiveQueryResult Query(SlotIndex Idx) const {
479       // Find the segment that enters the instruction.
480       const_iterator I = find(Idx.getBaseIndex());
481       const_iterator E = end();
482       if (I == E)
483         return LiveQueryResult(nullptr, nullptr, SlotIndex(), false);
484
485       // Is this an instruction live-in segment?
486       // If Idx is the start index of a basic block, include live-in segments
487       // that start at Idx.getBaseIndex().
488       VNInfo *EarlyVal = nullptr;
489       VNInfo *LateVal  = nullptr;
490       SlotIndex EndPoint;
491       bool Kill = false;
492       if (I->start <= Idx.getBaseIndex()) {
493         EarlyVal = I->valno;
494         EndPoint = I->end;
495         // Move to the potentially live-out segment.
496         if (SlotIndex::isSameInstr(Idx, I->end)) {
497           Kill = true;
498           if (++I == E)
499             return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
500         }
501         // Special case: A PHIDef value can have its def in the middle of a
502         // segment if the value happens to be live out of the layout
503         // predecessor.
504         // Such a value is not live-in.
505         if (EarlyVal->def == Idx.getBaseIndex())
506           EarlyVal = nullptr;
507       }
508       // I now points to the segment that may be live-through, or defined by
509       // this instr. Ignore segments starting after the current instr.
510       if (!SlotIndex::isEarlierInstr(Idx, I->start)) {
511         LateVal = I->valno;
512         EndPoint = I->end;
513       }
514       return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
515     }
516
517     /// removeValNo - Remove all the segments defined by the specified value#.
518     /// Also remove the value# from value# list.
519     void removeValNo(VNInfo *ValNo);
520
521     /// Returns true if the live range is zero length, i.e. no live segments
522     /// span instructions. It doesn't pay to spill such a range.
523     bool isZeroLength(SlotIndexes *Indexes) const {
524       for (const Segment &S : segments)
525         if (Indexes->getNextNonNullIndex(S.start).getBaseIndex() <
526             S.end.getBaseIndex())
527           return false;
528       return true;
529     }
530
531     bool operator<(const LiveRange& other) const {
532       const SlotIndex &thisIndex = beginIndex();
533       const SlotIndex &otherIndex = other.beginIndex();
534       return thisIndex < otherIndex;
535     }
536
537     void print(raw_ostream &OS) const;
538     void dump() const;
539
540     /// \brief Walk the range and assert if any invariants fail to hold.
541     ///
542     /// Note that this is a no-op when asserts are disabled.
543 #ifdef NDEBUG
544     void verify() const {}
545 #else
546     void verify() const;
547 #endif
548
549   private:
550
551     iterator addSegmentFrom(Segment S, iterator From);
552     void extendSegmentEndTo(iterator I, SlotIndex NewEnd);
553     iterator extendSegmentStartTo(iterator I, SlotIndex NewStr);
554     void markValNoForDeletion(VNInfo *V);
555
556   };
557
558   inline raw_ostream &operator<<(raw_ostream &OS, const LiveRange &LR) {
559     LR.print(OS);
560     return OS;
561   }
562
563   /// LiveInterval - This class represents the liveness of a register,
564   /// or stack slot.
565   class LiveInterval : public LiveRange {
566   public:
567     typedef LiveRange super;
568
569     /// A live range for subregisters. The LaneMask specifies which parts of the
570     /// super register are covered by the interval.
571     /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
572     class SubRange : public LiveRange {
573     public:
574       SubRange *Next;
575       unsigned LaneMask;
576
577       /// Constructs a new SubRange object.
578       SubRange(unsigned LaneMask)
579         : Next(nullptr), LaneMask(LaneMask) {
580       }
581
582       /// Constructs a new SubRange object by copying liveness from @p Other.
583       SubRange(unsigned LaneMask, const LiveRange &Other,
584                BumpPtrAllocator &Allocator)
585         : LiveRange(Other, Allocator), Next(nullptr), LaneMask(LaneMask) {
586       }
587     };
588
589   private:
590     SubRange *SubRanges; ///< Single linked list of subregister live ranges.
591
592   public:
593     const unsigned reg;  // the register or stack slot of this interval.
594     float weight;        // weight of this interval
595
596     LiveInterval(unsigned Reg, float Weight)
597       : SubRanges(nullptr), reg(Reg), weight(Weight) {}
598
599     template<typename T>
600     class SingleLinkedListIterator {
601       T *P;
602     public:
603       SingleLinkedListIterator<T>(T *P) : P(P) {}
604       SingleLinkedListIterator<T> &operator++() {
605         P = P->Next;
606         return *this;
607       }
608       SingleLinkedListIterator<T> &operator++(int) {
609         SingleLinkedListIterator res = *this;
610         ++*this;
611         return res;
612       }
613       bool operator!=(const SingleLinkedListIterator<T> &Other) {
614         return P != Other.operator->();
615       }
616       bool operator==(const SingleLinkedListIterator<T> &Other) {
617         return P == Other.operator->();
618       }
619       T &operator*() const {
620         return *P;
621       }
622       T *operator->() const {
623         return P;
624       }
625     };
626
627     typedef SingleLinkedListIterator<SubRange> subrange_iterator;
628     subrange_iterator subrange_begin() {
629       return subrange_iterator(SubRanges);
630     }
631     subrange_iterator subrange_end() {
632       return subrange_iterator(nullptr);
633     }
634
635     typedef SingleLinkedListIterator<const SubRange> const_subrange_iterator;
636     const_subrange_iterator subrange_begin() const {
637       return const_subrange_iterator(SubRanges);
638     }
639     const_subrange_iterator subrange_end() const {
640       return const_subrange_iterator(nullptr);
641     }
642
643     iterator_range<subrange_iterator> subranges() {
644       return make_range(subrange_begin(), subrange_end());
645     }
646
647     iterator_range<const_subrange_iterator> subranges() const {
648       return make_range(subrange_begin(), subrange_end());
649     }
650
651     /// Creates a new empty subregister live range. The range is added at the
652     /// beginning of the subrange list; subrange iterators stay valid.
653     SubRange *createSubRange(BumpPtrAllocator &Allocator, unsigned LaneMask) {
654       SubRange *Range = new (Allocator) SubRange(LaneMask);
655       appendSubRange(Range);
656       return Range;
657     }
658
659     /// Like createSubRange() but the new range is filled with a copy of the
660     /// liveness information in @p CopyFrom.
661     SubRange *createSubRangeFrom(BumpPtrAllocator &Allocator, unsigned LaneMask,
662                                  const LiveRange &CopyFrom) {
663       SubRange *Range = new (Allocator) SubRange(LaneMask, CopyFrom, Allocator);
664       appendSubRange(Range);
665       return Range;
666     }
667
668     /// Returns true if subregister liveness information is available.
669     bool hasSubRanges() const {
670       return SubRanges != nullptr;
671     }
672
673     /// Removes all subregister liveness information.
674     void clearSubRanges() {
675       SubRanges = nullptr;
676     }
677
678     /// Removes all subranges without any segments (subranges without segments
679     /// are not considered valid and should only exist temporarily).
680     void removeEmptySubRanges();
681
682     /// getSize - Returns the sum of sizes of all the LiveRange's.
683     ///
684     unsigned getSize() const;
685
686     /// isSpillable - Can this interval be spilled?
687     bool isSpillable() const {
688       return weight != llvm::huge_valf;
689     }
690
691     /// markNotSpillable - Mark interval as not spillable
692     void markNotSpillable() {
693       weight = llvm::huge_valf;
694     }
695
696     bool operator<(const LiveInterval& other) const {
697       const SlotIndex &thisIndex = beginIndex();
698       const SlotIndex &otherIndex = other.beginIndex();
699       return std::tie(thisIndex, reg) < std::tie(otherIndex, other.reg);
700     }
701
702     void print(raw_ostream &OS) const;
703     void dump() const;
704
705     /// \brief Walks the interval and assert if any invariants fail to hold.
706     ///
707     /// Note that this is a no-op when asserts are disabled.
708 #ifdef NDEBUG
709     void verify(const MachineRegisterInfo *MRI = nullptr) const {}
710 #else
711     void verify(const MachineRegisterInfo *MRI = nullptr) const;
712 #endif
713
714   private:
715     LiveInterval& operator=(const LiveInterval& rhs) LLVM_DELETED_FUNCTION;
716
717     /// Appends @p Range to SubRanges list.
718     void appendSubRange(SubRange *Range) {
719       Range->Next = SubRanges;
720       SubRanges = Range;
721     }
722   };
723
724   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
725     LI.print(OS);
726     return OS;
727   }
728
729   raw_ostream &operator<<(raw_ostream &OS, const LiveRange::Segment &S);
730
731   inline bool operator<(SlotIndex V, const LiveRange::Segment &S) {
732     return V < S.start;
733   }
734
735   inline bool operator<(const LiveRange::Segment &S, SlotIndex V) {
736     return S.start < V;
737   }
738
739   /// Helper class for performant LiveRange bulk updates.
740   ///
741   /// Calling LiveRange::addSegment() repeatedly can be expensive on large
742   /// live ranges because segments after the insertion point may need to be
743   /// shifted. The LiveRangeUpdater class can defer the shifting when adding
744   /// many segments in order.
745   ///
746   /// The LiveRange will be in an invalid state until flush() is called.
747   class LiveRangeUpdater {
748     LiveRange *LR;
749     SlotIndex LastStart;
750     LiveRange::iterator WriteI;
751     LiveRange::iterator ReadI;
752     SmallVector<LiveRange::Segment, 16> Spills;
753     void mergeSpills();
754
755   public:
756     /// Create a LiveRangeUpdater for adding segments to LR.
757     /// LR will temporarily be in an invalid state until flush() is called.
758     LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
759
760     ~LiveRangeUpdater() { flush(); }
761
762     /// Add a segment to LR and coalesce when possible, just like
763     /// LR.addSegment(). Segments should be added in increasing start order for
764     /// best performance.
765     void add(LiveRange::Segment);
766
767     void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
768       add(LiveRange::Segment(Start, End, VNI));
769     }
770
771     /// Return true if the LR is currently in an invalid state, and flush()
772     /// needs to be called.
773     bool isDirty() const { return LastStart.isValid(); }
774
775     /// Flush the updater state to LR so it is valid and contains all added
776     /// segments.
777     void flush();
778
779     /// Select a different destination live range.
780     void setDest(LiveRange *lr) {
781       if (LR != lr && isDirty())
782         flush();
783       LR = lr;
784     }
785
786     /// Get the current destination live range.
787     LiveRange *getDest() const { return LR; }
788
789     void dump() const;
790     void print(raw_ostream&) const;
791   };
792
793   inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
794     X.print(OS);
795     return OS;
796   }
797
798   /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
799   /// LiveInterval into equivalence clases of connected components. A
800   /// LiveInterval that has multiple connected components can be broken into
801   /// multiple LiveIntervals.
802   ///
803   /// Given a LiveInterval that may have multiple connected components, run:
804   ///
805   ///   unsigned numComps = ConEQ.Classify(LI);
806   ///   if (numComps > 1) {
807   ///     // allocate numComps-1 new LiveIntervals into LIS[1..]
808   ///     ConEQ.Distribute(LIS);
809   /// }
810
811   class ConnectedVNInfoEqClasses {
812     LiveIntervals &LIS;
813     IntEqClasses EqClass;
814
815     // Note that values a and b are connected.
816     void Connect(unsigned a, unsigned b);
817
818     unsigned Renumber();
819
820   public:
821     explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
822
823     /// Classify - Classify the values in LI into connected components.
824     /// Return the number of connected components.
825     unsigned Classify(const LiveInterval *LI);
826
827     /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
828     /// the equivalence class assigned the VNI.
829     unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
830
831     /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
832     /// for each connected component. LIV must have a LiveInterval for each
833     /// connected component. The LiveIntervals in Liv[1..] must be empty.
834     /// Instructions using LIV[0] are rewritten.
835     void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);
836
837   };
838
839 }
840 #endif