Home | History | Annotate | Download | only in CodeGen
      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     bool operator<(const LiveRange& other) const {
    548       const SlotIndex &thisIndex = beginIndex();
    549       const SlotIndex &otherIndex = other.beginIndex();
    550       return thisIndex < otherIndex;
    551     }
    552 
    553     /// Flush segment set into the regular segment vector.
    554     /// The method is to be called after the live range
    555     /// has been created, if use of the segment set was
    556     /// activated in the constructor of the live range.
    557     void flushSegmentSet();
    558 
    559     void print(raw_ostream &OS) const;
    560     void dump() const;
    561 
    562     /// \brief Walk the range and assert if any invariants fail to hold.
    563     ///
    564     /// Note that this is a no-op when asserts are disabled.
    565 #ifdef NDEBUG
    566     void verify() const {}
    567 #else
    568     void verify() const;
    569 #endif
    570 
    571   protected:
    572     /// Append a segment to the list of segments.
    573     void append(const LiveRange::Segment S);
    574 
    575   private:
    576     friend class LiveRangeUpdater;
    577     void addSegmentToSet(Segment S);
    578     void markValNoForDeletion(VNInfo *V);
    579 
    580   };
    581 
    582   inline raw_ostream &operator<<(raw_ostream &OS, const LiveRange &LR) {
    583     LR.print(OS);
    584     return OS;
    585   }
    586 
    587   /// LiveInterval - This class represents the liveness of a register,
    588   /// or stack slot.
    589   class LiveInterval : public LiveRange {
    590   public:
    591     typedef LiveRange super;
    592 
    593     /// A live range for subregisters. The LaneMask specifies which parts of the
    594     /// super register are covered by the interval.
    595     /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
    596     class SubRange : public LiveRange {
    597     public:
    598       SubRange *Next;
    599       LaneBitmask LaneMask;
    600 
    601       /// Constructs a new SubRange object.
    602       SubRange(LaneBitmask LaneMask)
    603         : Next(nullptr), LaneMask(LaneMask) {
    604       }
    605 
    606       /// Constructs a new SubRange object by copying liveness from @p Other.
    607       SubRange(LaneBitmask LaneMask, const LiveRange &Other,
    608                BumpPtrAllocator &Allocator)
    609         : LiveRange(Other, Allocator), Next(nullptr), LaneMask(LaneMask) {
    610       }
    611     };
    612 
    613   private:
    614     SubRange *SubRanges; ///< Single linked list of subregister live ranges.
    615 
    616   public:
    617     const unsigned reg;  // the register or stack slot of this interval.
    618     float weight;        // weight of this interval
    619 
    620     LiveInterval(unsigned Reg, float Weight)
    621       : SubRanges(nullptr), reg(Reg), weight(Weight) {}
    622 
    623     ~LiveInterval() {
    624       clearSubRanges();
    625     }
    626 
    627     template<typename T>
    628     class SingleLinkedListIterator {
    629       T *P;
    630     public:
    631       SingleLinkedListIterator<T>(T *P) : P(P) {}
    632       SingleLinkedListIterator<T> &operator++() {
    633         P = P->Next;
    634         return *this;
    635       }
    636       SingleLinkedListIterator<T> &operator++(int) {
    637         SingleLinkedListIterator res = *this;
    638         ++*this;
    639         return res;
    640       }
    641       bool operator!=(const SingleLinkedListIterator<T> &Other) {
    642         return P != Other.operator->();
    643       }
    644       bool operator==(const SingleLinkedListIterator<T> &Other) {
    645         return P == Other.operator->();
    646       }
    647       T &operator*() const {
    648         return *P;
    649       }
    650       T *operator->() const {
    651         return P;
    652       }
    653     };
    654 
    655     typedef SingleLinkedListIterator<SubRange> subrange_iterator;
    656     subrange_iterator subrange_begin() {
    657       return subrange_iterator(SubRanges);
    658     }
    659     subrange_iterator subrange_end() {
    660       return subrange_iterator(nullptr);
    661     }
    662 
    663     typedef SingleLinkedListIterator<const SubRange> const_subrange_iterator;
    664     const_subrange_iterator subrange_begin() const {
    665       return const_subrange_iterator(SubRanges);
    666     }
    667     const_subrange_iterator subrange_end() const {
    668       return const_subrange_iterator(nullptr);
    669     }
    670 
    671     iterator_range<subrange_iterator> subranges() {
    672       return make_range(subrange_begin(), subrange_end());
    673     }
    674 
    675     iterator_range<const_subrange_iterator> subranges() const {
    676       return make_range(subrange_begin(), subrange_end());
    677     }
    678 
    679     /// Creates a new empty subregister live range. The range is added at the
    680     /// beginning of the subrange list; subrange iterators stay valid.
    681     SubRange *createSubRange(BumpPtrAllocator &Allocator,
    682                              LaneBitmask LaneMask) {
    683       SubRange *Range = new (Allocator) SubRange(LaneMask);
    684       appendSubRange(Range);
    685       return Range;
    686     }
    687 
    688     /// Like createSubRange() but the new range is filled with a copy of the
    689     /// liveness information in @p CopyFrom.
    690     SubRange *createSubRangeFrom(BumpPtrAllocator &Allocator,
    691                                  LaneBitmask LaneMask,
    692                                  const LiveRange &CopyFrom) {
    693       SubRange *Range = new (Allocator) SubRange(LaneMask, CopyFrom, Allocator);
    694       appendSubRange(Range);
    695       return Range;
    696     }
    697 
    698     /// Returns true if subregister liveness information is available.
    699     bool hasSubRanges() const {
    700       return SubRanges != nullptr;
    701     }
    702 
    703     /// Removes all subregister liveness information.
    704     void clearSubRanges();
    705 
    706     /// Removes all subranges without any segments (subranges without segments
    707     /// are not considered valid and should only exist temporarily).
    708     void removeEmptySubRanges();
    709 
    710     /// Construct main live range by merging the SubRanges of @p LI.
    711     void constructMainRangeFromSubranges(const SlotIndexes &Indexes,
    712                                          VNInfo::Allocator &VNIAllocator);
    713 
    714     /// getSize - Returns the sum of sizes of all the LiveRange's.
    715     ///
    716     unsigned getSize() const;
    717 
    718     /// isSpillable - Can this interval be spilled?
    719     bool isSpillable() const {
    720       return weight != llvm::huge_valf;
    721     }
    722 
    723     /// markNotSpillable - Mark interval as not spillable
    724     void markNotSpillable() {
    725       weight = llvm::huge_valf;
    726     }
    727 
    728     bool operator<(const LiveInterval& other) const {
    729       const SlotIndex &thisIndex = beginIndex();
    730       const SlotIndex &otherIndex = other.beginIndex();
    731       return std::tie(thisIndex, reg) < std::tie(otherIndex, other.reg);
    732     }
    733 
    734     void print(raw_ostream &OS) const;
    735     void dump() const;
    736 
    737     /// \brief Walks the interval and assert if any invariants fail to hold.
    738     ///
    739     /// Note that this is a no-op when asserts are disabled.
    740 #ifdef NDEBUG
    741     void verify(const MachineRegisterInfo *MRI = nullptr) const {}
    742 #else
    743     void verify(const MachineRegisterInfo *MRI = nullptr) const;
    744 #endif
    745 
    746   private:
    747     /// Appends @p Range to SubRanges list.
    748     void appendSubRange(SubRange *Range) {
    749       Range->Next = SubRanges;
    750       SubRanges = Range;
    751     }
    752 
    753     /// Free memory held by SubRange.
    754     void freeSubRange(SubRange *S);
    755   };
    756 
    757   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
    758     LI.print(OS);
    759     return OS;
    760   }
    761 
    762   raw_ostream &operator<<(raw_ostream &OS, const LiveRange::Segment &S);
    763 
    764   inline bool operator<(SlotIndex V, const LiveRange::Segment &S) {
    765     return V < S.start;
    766   }
    767 
    768   inline bool operator<(const LiveRange::Segment &S, SlotIndex V) {
    769     return S.start < V;
    770   }
    771 
    772   /// Helper class for performant LiveRange bulk updates.
    773   ///
    774   /// Calling LiveRange::addSegment() repeatedly can be expensive on large
    775   /// live ranges because segments after the insertion point may need to be
    776   /// shifted. The LiveRangeUpdater class can defer the shifting when adding
    777   /// many segments in order.
    778   ///
    779   /// The LiveRange will be in an invalid state until flush() is called.
    780   class LiveRangeUpdater {
    781     LiveRange *LR;
    782     SlotIndex LastStart;
    783     LiveRange::iterator WriteI;
    784     LiveRange::iterator ReadI;
    785     SmallVector<LiveRange::Segment, 16> Spills;
    786     void mergeSpills();
    787 
    788   public:
    789     /// Create a LiveRangeUpdater for adding segments to LR.
    790     /// LR will temporarily be in an invalid state until flush() is called.
    791     LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
    792 
    793     ~LiveRangeUpdater() { flush(); }
    794 
    795     /// Add a segment to LR and coalesce when possible, just like
    796     /// LR.addSegment(). Segments should be added in increasing start order for
    797     /// best performance.
    798     void add(LiveRange::Segment);
    799 
    800     void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
    801       add(LiveRange::Segment(Start, End, VNI));
    802     }
    803 
    804     /// Return true if the LR is currently in an invalid state, and flush()
    805     /// needs to be called.
    806     bool isDirty() const { return LastStart.isValid(); }
    807 
    808     /// Flush the updater state to LR so it is valid and contains all added
    809     /// segments.
    810     void flush();
    811 
    812     /// Select a different destination live range.
    813     void setDest(LiveRange *lr) {
    814       if (LR != lr && isDirty())
    815         flush();
    816       LR = lr;
    817     }
    818 
    819     /// Get the current destination live range.
    820     LiveRange *getDest() const { return LR; }
    821 
    822     void dump() const;
    823     void print(raw_ostream&) const;
    824   };
    825 
    826   inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
    827     X.print(OS);
    828     return OS;
    829   }
    830 
    831   /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
    832   /// LiveInterval into equivalence clases of connected components. A
    833   /// LiveInterval that has multiple connected components can be broken into
    834   /// multiple LiveIntervals.
    835   ///
    836   /// Given a LiveInterval that may have multiple connected components, run:
    837   ///
    838   ///   unsigned numComps = ConEQ.Classify(LI);
    839   ///   if (numComps > 1) {
    840   ///     // allocate numComps-1 new LiveIntervals into LIS[1..]
    841   ///     ConEQ.Distribute(LIS);
    842   /// }
    843 
    844   class ConnectedVNInfoEqClasses {
    845     LiveIntervals &LIS;
    846     IntEqClasses EqClass;
    847 
    848   public:
    849     explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
    850 
    851     /// Classify - Classify the values in LI into connected components.
    852     /// Return the number of connected components.
    853     unsigned Classify(const LiveInterval *LI);
    854 
    855     /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
    856     /// the equivalence class assigned the VNI.
    857     unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
    858 
    859     /// Distribute values in \p LI into a separate LiveIntervals
    860     /// for each connected component. LIV must have an empty LiveInterval for
    861     /// each additional connected component. The first connected component is
    862     /// left in \p LI.
    863     void Distribute(LiveInterval &LI, LiveInterval *LIV[],
    864                     MachineRegisterInfo &MRI);
    865   };
    866 
    867 }
    868 #endif
    869