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