LiveInterval: Introduce LiveQuery accessor for dead or live out values.
[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 (LiveRange::const_vni_iterator I = Other.vni_begin(),
222            E = Other.vni_end(); I != E; ++I) {
223         createValueCopy(*I, Allocator);
224       }
225       // Now we can copy segments and remap their valnos.
226       for (LiveRange::const_iterator I = Other.begin(), E = Other.end();
227            I != E; ++I) {
228         segments.push_back(Segment(I->start, I->end, valnos[I->valno->id]));
229       }
230     }
231
232     /// advanceTo - Advance the specified iterator to point to the Segment
233     /// containing the specified position, or end() if the position is past the
234     /// end of the range.  If no Segment contains this position, but the
235     /// position is in a hole, this method returns an iterator pointing to the
236     /// Segment immediately after the hole.
237     iterator advanceTo(iterator I, SlotIndex Pos) {
238       assert(I != end());
239       if (Pos >= endIndex())
240         return end();
241       while (I->end <= Pos) ++I;
242       return I;
243     }
244
245     const_iterator advanceTo(const_iterator I, SlotIndex Pos) const {
246       assert(I != end());
247       if (Pos >= endIndex())
248         return end();
249       while (I->end <= Pos) ++I;
250       return I;
251     }
252
253     /// find - Return an iterator pointing to the first segment that ends after
254     /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
255     /// when searching large ranges.
256     ///
257     /// If Pos is contained in a Segment, that segment is returned.
258     /// If Pos is in a hole, the following Segment is returned.
259     /// If Pos is beyond endIndex, end() is returned.
260     iterator find(SlotIndex Pos);
261
262     const_iterator find(SlotIndex Pos) const {
263       return const_cast<LiveRange*>(this)->find(Pos);
264     }
265
266     void clear() {
267       valnos.clear();
268       segments.clear();
269     }
270
271     size_t size() const {
272       return segments.size();
273     }
274
275     bool hasAtLeastOneValue() const { return !valnos.empty(); }
276
277     bool containsOneValue() const { return valnos.size() == 1; }
278
279     unsigned getNumValNums() const { return (unsigned)valnos.size(); }
280
281     /// getValNumInfo - Returns pointer to the specified val#.
282     ///
283     inline VNInfo *getValNumInfo(unsigned ValNo) {
284       return valnos[ValNo];
285     }
286     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
287       return valnos[ValNo];
288     }
289
290     /// containsValue - Returns true if VNI belongs to this range.
291     bool containsValue(const VNInfo *VNI) const {
292       return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
293     }
294
295     /// getNextValue - Create a new value number and return it.  MIIdx specifies
296     /// the instruction that defines the value number.
297     VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
298       VNInfo *VNI =
299         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
300       valnos.push_back(VNI);
301       return VNI;
302     }
303
304     /// createDeadDef - Make sure the range has a value defined at Def.
305     /// If one already exists, return it. Otherwise allocate a new value and
306     /// add liveness for a dead def.
307     VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
308
309     /// Create a copy of the given value. The new value will be identical except
310     /// for the Value number.
311     VNInfo *createValueCopy(const VNInfo *orig,
312                             VNInfo::Allocator &VNInfoAllocator) {
313       VNInfo *VNI =
314         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
315       valnos.push_back(VNI);
316       return VNI;
317     }
318
319     /// RenumberValues - Renumber all values in order of appearance and remove
320     /// unused values.
321     void RenumberValues();
322
323     /// MergeValueNumberInto - This method is called when two value numbers
324     /// are found to be equivalent.  This eliminates V1, replacing all
325     /// segments with the V1 value number with the V2 value number.  This can
326     /// cause merging of V1/V2 values numbers and compaction of the value space.
327     VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
328
329     /// Merge all of the live segments of a specific val# in RHS into this live
330     /// range as the specified value number. The segments in RHS are allowed
331     /// to overlap with segments in the current range, it will replace the
332     /// value numbers of the overlaped live segments with the specified value
333     /// number.
334     void MergeSegmentsInAsValue(const LiveRange &RHS, VNInfo *LHSValNo);
335
336     /// MergeValueInAsValue - Merge all of the segments of a specific val#
337     /// in RHS into this live range as the specified value number.
338     /// The segments in RHS are allowed to overlap with segments in the
339     /// current range, but only if the overlapping segments have the
340     /// specified value number.
341     void MergeValueInAsValue(const LiveRange &RHS,
342                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
343
344     bool empty() const { return segments.empty(); }
345
346     /// beginIndex - Return the lowest numbered slot covered.
347     SlotIndex beginIndex() const {
348       assert(!empty() && "Call to beginIndex() on empty range.");
349       return segments.front().start;
350     }
351
352     /// endNumber - return the maximum point of the range of the whole,
353     /// exclusive.
354     SlotIndex endIndex() const {
355       assert(!empty() && "Call to endIndex() on empty range.");
356       return segments.back().end;
357     }
358
359     bool expiredAt(SlotIndex index) const {
360       return index >= endIndex();
361     }
362
363     bool liveAt(SlotIndex index) const {
364       const_iterator r = find(index);
365       return r != end() && r->start <= index;
366     }
367
368     /// Return the segment that contains the specified index, or null if there
369     /// is none.
370     const Segment *getSegmentContaining(SlotIndex Idx) const {
371       const_iterator I = FindSegmentContaining(Idx);
372       return I == end() ? nullptr : &*I;
373     }
374
375     /// Return the live segment that contains the specified index, or null if
376     /// there is none.
377     Segment *getSegmentContaining(SlotIndex Idx) {
378       iterator I = FindSegmentContaining(Idx);
379       return I == end() ? nullptr : &*I;
380     }
381
382     /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
383     VNInfo *getVNInfoAt(SlotIndex Idx) const {
384       const_iterator I = FindSegmentContaining(Idx);
385       return I == end() ? nullptr : I->valno;
386     }
387
388     /// getVNInfoBefore - Return the VNInfo that is live up to but not
389     /// necessarilly including Idx, or NULL. Use this to find the reaching def
390     /// used by an instruction at this SlotIndex position.
391     VNInfo *getVNInfoBefore(SlotIndex Idx) const {
392       const_iterator I = FindSegmentContaining(Idx.getPrevSlot());
393       return I == end() ? nullptr : I->valno;
394     }
395
396     /// Return an iterator to the segment that contains the specified index, or
397     /// end() if there is none.
398     iterator FindSegmentContaining(SlotIndex Idx) {
399       iterator I = find(Idx);
400       return I != end() && I->start <= Idx ? I : end();
401     }
402
403     const_iterator FindSegmentContaining(SlotIndex Idx) const {
404       const_iterator I = find(Idx);
405       return I != end() && I->start <= Idx ? I : end();
406     }
407
408     /// overlaps - Return true if the intersection of the two live ranges is
409     /// not empty.
410     bool overlaps(const LiveRange &other) const {
411       if (other.empty())
412         return false;
413       return overlapsFrom(other, other.begin());
414     }
415
416     /// overlaps - Return true if the two ranges have overlapping segments
417     /// that are not coalescable according to CP.
418     ///
419     /// Overlapping segments where one range is defined by a coalescable
420     /// copy are allowed.
421     bool overlaps(const LiveRange &Other, const CoalescerPair &CP,
422                   const SlotIndexes&) const;
423
424     /// overlaps - Return true if the live range overlaps an interval specified
425     /// by [Start, End).
426     bool overlaps(SlotIndex Start, SlotIndex End) const;
427
428     /// overlapsFrom - Return true if the intersection of the two live ranges
429     /// is not empty.  The specified iterator is a hint that we can begin
430     /// scanning the Other range starting at I.
431     bool overlapsFrom(const LiveRange &Other, const_iterator I) const;
432
433     /// Returns true if all segments of the @p Other live range are completely
434     /// covered by this live range.
435     /// Adjacent live ranges do not affect the covering:the liverange
436     /// [1,5](5,10] covers (3,7].
437     bool covers(const LiveRange &Other) const;
438
439     /// Add the specified Segment to this range, merging segments as
440     /// appropriate.  This returns an iterator to the inserted segment (which
441     /// may have grown since it was inserted).
442     iterator addSegment(Segment S) {
443       return addSegmentFrom(S, segments.begin());
444     }
445
446     /// extendInBlock - If this range is live before Kill in the basic block
447     /// that starts at StartIdx, extend it to be live up to Kill, and return
448     /// the value. If there is no segment before Kill, return NULL.
449     VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
450
451     /// join - Join two live ranges (this, and other) together.  This applies
452     /// mappings to the value numbers in the LHS/RHS ranges as specified.  If
453     /// the ranges are not joinable, this aborts.
454     void join(LiveRange &Other,
455               const int *ValNoAssignments,
456               const int *RHSValNoAssignments,
457               SmallVectorImpl<VNInfo *> &NewVNInfo);
458
459     /// True iff this segment is a single segment that lies between the
460     /// specified boundaries, exclusively. Vregs live across a backedge are not
461     /// considered local. The boundaries are expected to lie within an extended
462     /// basic block, so vregs that are not live out should contain no holes.
463     bool isLocal(SlotIndex Start, SlotIndex End) const {
464       return beginIndex() > Start.getBaseIndex() &&
465         endIndex() < End.getBoundaryIndex();
466     }
467
468     /// Remove the specified segment from this range.  Note that the segment
469     /// must be a single Segment in its entirety.
470     void removeSegment(SlotIndex Start, SlotIndex End,
471                        bool RemoveDeadValNo = false);
472
473     void removeSegment(Segment S, bool RemoveDeadValNo = false) {
474       removeSegment(S.start, S.end, RemoveDeadValNo);
475     }
476
477     /// Query Liveness at Idx.
478     /// The sub-instruction slot of Idx doesn't matter, only the instruction
479     /// it refers to is considered.
480     LiveQueryResult Query(SlotIndex Idx) const {
481       // Find the segment that enters the instruction.
482       const_iterator I = find(Idx.getBaseIndex());
483       const_iterator E = end();
484       if (I == E)
485         return LiveQueryResult(nullptr, nullptr, SlotIndex(), false);
486
487       // Is this an instruction live-in segment?
488       // If Idx is the start index of a basic block, include live-in segments
489       // that start at Idx.getBaseIndex().
490       VNInfo *EarlyVal = nullptr;
491       VNInfo *LateVal  = nullptr;
492       SlotIndex EndPoint;
493       bool Kill = false;
494       if (I->start <= Idx.getBaseIndex()) {
495         EarlyVal = I->valno;
496         EndPoint = I->end;
497         // Move to the potentially live-out segment.
498         if (SlotIndex::isSameInstr(Idx, I->end)) {
499           Kill = true;
500           if (++I == E)
501             return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
502         }
503         // Special case: A PHIDef value can have its def in the middle of a
504         // segment if the value happens to be live out of the layout
505         // predecessor.
506         // Such a value is not live-in.
507         if (EarlyVal->def == Idx.getBaseIndex())
508           EarlyVal = nullptr;
509       }
510       // I now points to the segment that may be live-through, or defined by
511       // this instr. Ignore segments starting after the current instr.
512       if (!SlotIndex::isEarlierInstr(Idx, I->start)) {
513         LateVal = I->valno;
514         EndPoint = I->end;
515       }
516       return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
517     }
518
519     /// removeValNo - Remove all the segments defined by the specified value#.
520     /// Also remove the value# from value# list.
521     void removeValNo(VNInfo *ValNo);
522
523     /// Returns true if the live range is zero length, i.e. no live segments
524     /// span instructions. It doesn't pay to spill such a range.
525     bool isZeroLength(SlotIndexes *Indexes) const {
526       for (const_iterator i = begin(), e = end(); i != e; ++i)
527         if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
528             i->end.getBaseIndex())
529           return false;
530       return true;
531     }
532
533     bool operator<(const LiveRange& other) const {
534       const SlotIndex &thisIndex = beginIndex();
535       const SlotIndex &otherIndex = other.beginIndex();
536       return thisIndex < otherIndex;
537     }
538
539     void print(raw_ostream &OS) const;
540     void dump() const;
541
542     /// \brief Walk the range and assert if any invariants fail to hold.
543     ///
544     /// Note that this is a no-op when asserts are disabled.
545 #ifdef NDEBUG
546     void verify() const {}
547 #else
548     void verify() const;
549 #endif
550
551   private:
552
553     iterator addSegmentFrom(Segment S, iterator From);
554     void extendSegmentEndTo(iterator I, SlotIndex NewEnd);
555     iterator extendSegmentStartTo(iterator I, SlotIndex NewStr);
556     void markValNoForDeletion(VNInfo *V);
557
558   };
559
560   inline raw_ostream &operator<<(raw_ostream &OS, const LiveRange &LR) {
561     LR.print(OS);
562     return OS;
563   }
564
565   /// LiveInterval - This class represents the liveness of a register,
566   /// or stack slot.
567   class LiveInterval : public LiveRange {
568   public:
569     typedef LiveRange super;
570
571     /// A live range for subregisters. The LaneMask specifies which parts of the
572     /// super register are covered by the interval.
573     /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
574     class SubRange : public LiveRange {
575     public:
576       SubRange *Next;
577       unsigned LaneMask;
578
579       /// Constructs a new SubRange object.
580       SubRange(unsigned LaneMask)
581         : Next(nullptr), LaneMask(LaneMask) {
582       }
583
584       /// Constructs a new SubRange object by copying liveness from @p Other.
585       SubRange(unsigned LaneMask, const LiveRange &Other,
586                BumpPtrAllocator &Allocator)
587         : LiveRange(Other, Allocator), Next(nullptr), LaneMask(LaneMask) {
588       }
589     };
590
591   private:
592     SubRange *SubRanges; ///< Single linked list of subregister live ranges.
593
594   public:
595     const unsigned reg;  // the register or stack slot of this interval.
596     float weight;        // weight of this interval
597
598     LiveInterval(unsigned Reg, float Weight)
599       : SubRanges(nullptr), reg(Reg), weight(Weight) {}
600
601     template<typename T>
602     class SingleLinkedListIterator {
603       T *P;
604     public:
605       SingleLinkedListIterator<T>(T *P) : P(P) {}
606       SingleLinkedListIterator<T> &operator++() {
607         P = P->Next;
608         return *this;
609       }
610       SingleLinkedListIterator<T> &operator++(int) {
611         SingleLinkedListIterator res = *this;
612         ++*this;
613         return res;
614       }
615       bool operator!=(const SingleLinkedListIterator<T> &Other) {
616         return P != Other.operator->();
617       }
618       bool operator==(const SingleLinkedListIterator<T> &Other) {
619         return P == Other.operator->();
620       }
621       T &operator*() const {
622         return *P;
623       }
624       T *operator->() const {
625         return P;
626       }
627     };
628
629     typedef SingleLinkedListIterator<SubRange> subrange_iterator;
630     subrange_iterator subrange_begin() {
631       return subrange_iterator(SubRanges);
632     }
633     subrange_iterator subrange_end() {
634       return subrange_iterator(nullptr);
635     }
636
637     typedef SingleLinkedListIterator<const SubRange> const_subrange_iterator;
638     const_subrange_iterator subrange_begin() const {
639       return const_subrange_iterator(SubRanges);
640     }
641     const_subrange_iterator subrange_end() const {
642       return const_subrange_iterator(nullptr);
643     }
644
645     /// Creates a new empty subregister live range. The range is added at the
646     /// beginning of the subrange list; subrange iterators stay valid.
647     SubRange *createSubRange(BumpPtrAllocator &Allocator, unsigned LaneMask) {
648       SubRange *Range = new (Allocator) SubRange(LaneMask);
649       appendSubRange(Range);
650       return Range;
651     }
652
653     /// Like createSubRange() but the new range is filled with a copy of the
654     /// liveness information in @p CopyFrom.
655     SubRange *createSubRangeFrom(BumpPtrAllocator &Allocator, unsigned LaneMask,
656                                  const LiveRange &CopyFrom) {
657       SubRange *Range = new (Allocator) SubRange(LaneMask, CopyFrom, Allocator);
658       appendSubRange(Range);
659       return Range;
660     }
661
662     /// Returns true if subregister liveness information is available.
663     bool hasSubRanges() const {
664       return SubRanges != nullptr;
665     }
666
667     /// Removes all subregister liveness information.
668     void clearSubRanges() {
669       SubRanges = nullptr;
670     }
671
672     /// getSize - Returns the sum of sizes of all the LiveRange's.
673     ///
674     unsigned getSize() const;
675
676     /// isSpillable - Can this interval be spilled?
677     bool isSpillable() const {
678       return weight != llvm::huge_valf;
679     }
680
681     /// markNotSpillable - Mark interval as not spillable
682     void markNotSpillable() {
683       weight = llvm::huge_valf;
684     }
685
686     bool operator<(const LiveInterval& other) const {
687       const SlotIndex &thisIndex = beginIndex();
688       const SlotIndex &otherIndex = other.beginIndex();
689       return std::tie(thisIndex, reg) < std::tie(otherIndex, other.reg);
690     }
691
692     void print(raw_ostream &OS) const;
693     void dump() const;
694
695     /// \brief Walks the interval and assert if any invariants fail to hold.
696     ///
697     /// Note that this is a no-op when asserts are disabled.
698 #ifdef NDEBUG
699     void verify(const MachineRegisterInfo *MRI = nullptr) const {}
700 #else
701     void verify(const MachineRegisterInfo *MRI = nullptr) const;
702 #endif
703
704   private:
705     LiveInterval& operator=(const LiveInterval& rhs) LLVM_DELETED_FUNCTION;
706
707     /// Appends @p Range to SubRanges list.
708     void appendSubRange(SubRange *Range) {
709       Range->Next = SubRanges;
710       SubRanges = Range;
711     }
712   };
713
714   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
715     LI.print(OS);
716     return OS;
717   }
718
719   raw_ostream &operator<<(raw_ostream &OS, const LiveRange::Segment &S);
720
721   inline bool operator<(SlotIndex V, const LiveRange::Segment &S) {
722     return V < S.start;
723   }
724
725   inline bool operator<(const LiveRange::Segment &S, SlotIndex V) {
726     return S.start < V;
727   }
728
729   /// Helper class for performant LiveRange bulk updates.
730   ///
731   /// Calling LiveRange::addSegment() repeatedly can be expensive on large
732   /// live ranges because segments after the insertion point may need to be
733   /// shifted. The LiveRangeUpdater class can defer the shifting when adding
734   /// many segments in order.
735   ///
736   /// The LiveRange will be in an invalid state until flush() is called.
737   class LiveRangeUpdater {
738     LiveRange *LR;
739     SlotIndex LastStart;
740     LiveRange::iterator WriteI;
741     LiveRange::iterator ReadI;
742     SmallVector<LiveRange::Segment, 16> Spills;
743     void mergeSpills();
744
745   public:
746     /// Create a LiveRangeUpdater for adding segments to LR.
747     /// LR will temporarily be in an invalid state until flush() is called.
748     LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
749
750     ~LiveRangeUpdater() { flush(); }
751
752     /// Add a segment to LR and coalesce when possible, just like
753     /// LR.addSegment(). Segments should be added in increasing start order for
754     /// best performance.
755     void add(LiveRange::Segment);
756
757     void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
758       add(LiveRange::Segment(Start, End, VNI));
759     }
760
761     /// Return true if the LR is currently in an invalid state, and flush()
762     /// needs to be called.
763     bool isDirty() const { return LastStart.isValid(); }
764
765     /// Flush the updater state to LR so it is valid and contains all added
766     /// segments.
767     void flush();
768
769     /// Select a different destination live range.
770     void setDest(LiveRange *lr) {
771       if (LR != lr && isDirty())
772         flush();
773       LR = lr;
774     }
775
776     /// Get the current destination live range.
777     LiveRange *getDest() const { return LR; }
778
779     void dump() const;
780     void print(raw_ostream&) const;
781   };
782
783   inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
784     X.print(OS);
785     return OS;
786   }
787
788   /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
789   /// LiveInterval into equivalence clases of connected components. A
790   /// LiveInterval that has multiple connected components can be broken into
791   /// multiple LiveIntervals.
792   ///
793   /// Given a LiveInterval that may have multiple connected components, run:
794   ///
795   ///   unsigned numComps = ConEQ.Classify(LI);
796   ///   if (numComps > 1) {
797   ///     // allocate numComps-1 new LiveIntervals into LIS[1..]
798   ///     ConEQ.Distribute(LIS);
799   /// }
800
801   class ConnectedVNInfoEqClasses {
802     LiveIntervals &LIS;
803     IntEqClasses EqClass;
804
805     // Note that values a and b are connected.
806     void Connect(unsigned a, unsigned b);
807
808     unsigned Renumber();
809
810   public:
811     explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
812
813     /// Classify - Classify the values in LI into connected components.
814     /// Return the number of connected components.
815     unsigned Classify(const LiveInterval *LI);
816
817     /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
818     /// the equivalence class assigned the VNI.
819     unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
820
821     /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
822     /// for each connected component. LIV must have a LiveInterval for each
823     /// connected component. The LiveIntervals in Liv[1..] must be empty.
824     /// Instructions using LIV[0] are rewritten.
825     void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);
826
827   };
828
829 }
830 #endif