Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:29

0001 //===- llvm/CodeGen/LiveInterval.h - Interval representation ----*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file implements the LiveRange and LiveInterval classes.  Given some
0010 // numbering of each the machine instructions an interval [i, j) is said to be a
0011 // live range for register v if there is no instruction with number j' >= j
0012 // such that v is live at j' and there is no instruction with number i' < i such
0013 // that v is live at i'. In this implementation ranges can have holes,
0014 // i.e. a range might look like [1,20), [50,65), [1000,1001).  Each
0015 // individual segment is represented as an instance of LiveRange::Segment,
0016 // and the whole range is represented as an instance of LiveRange.
0017 //
0018 //===----------------------------------------------------------------------===//
0019 
0020 #ifndef LLVM_CODEGEN_LIVEINTERVAL_H
0021 #define LLVM_CODEGEN_LIVEINTERVAL_H
0022 
0023 #include "llvm/ADT/ArrayRef.h"
0024 #include "llvm/ADT/IntEqClasses.h"
0025 #include "llvm/ADT/STLExtras.h"
0026 #include "llvm/ADT/SmallVector.h"
0027 #include "llvm/ADT/iterator_range.h"
0028 #include "llvm/CodeGen/Register.h"
0029 #include "llvm/CodeGen/SlotIndexes.h"
0030 #include "llvm/MC/LaneBitmask.h"
0031 #include "llvm/Support/Allocator.h"
0032 #include "llvm/Support/MathExtras.h"
0033 #include <algorithm>
0034 #include <cassert>
0035 #include <cstddef>
0036 #include <functional>
0037 #include <memory>
0038 #include <set>
0039 #include <tuple>
0040 #include <utility>
0041 
0042 namespace llvm {
0043 
0044   class CoalescerPair;
0045   class LiveIntervals;
0046   class MachineRegisterInfo;
0047   class raw_ostream;
0048 
0049   /// VNInfo - Value Number Information.
0050   /// This class holds information about a machine level values, including
0051   /// definition and use points.
0052   ///
0053   class VNInfo {
0054   public:
0055     using Allocator = BumpPtrAllocator;
0056 
0057     /// The ID number of this value.
0058     unsigned id;
0059 
0060     /// The index of the defining instruction.
0061     SlotIndex def;
0062 
0063     /// VNInfo constructor.
0064     VNInfo(unsigned i, SlotIndex d) : id(i), def(d) {}
0065 
0066     /// VNInfo constructor, copies values from orig, except for the value number.
0067     VNInfo(unsigned i, const VNInfo &orig) : id(i), def(orig.def) {}
0068 
0069     /// Copy from the parameter into this VNInfo.
0070     void copyFrom(VNInfo &src) {
0071       def = src.def;
0072     }
0073 
0074     /// Returns true if this value is defined by a PHI instruction (or was,
0075     /// PHI instructions may have been eliminated).
0076     /// PHI-defs begin at a block boundary, all other defs begin at register or
0077     /// EC slots.
0078     bool isPHIDef() const { return def.isBlock(); }
0079 
0080     /// Returns true if this value is unused.
0081     bool isUnused() const { return !def.isValid(); }
0082 
0083     /// Mark this value as unused.
0084     void markUnused() { def = SlotIndex(); }
0085   };
0086 
0087   /// Result of a LiveRange query. This class hides the implementation details
0088   /// of live ranges, and it should be used as the primary interface for
0089   /// examining live ranges around instructions.
0090   class LiveQueryResult {
0091     VNInfo *const EarlyVal;
0092     VNInfo *const LateVal;
0093     const SlotIndex EndPoint;
0094     const bool Kill;
0095 
0096   public:
0097     LiveQueryResult(VNInfo *EarlyVal, VNInfo *LateVal, SlotIndex EndPoint,
0098                     bool Kill)
0099       : EarlyVal(EarlyVal), LateVal(LateVal), EndPoint(EndPoint), Kill(Kill)
0100     {}
0101 
0102     /// Return the value that is live-in to the instruction. This is the value
0103     /// that will be read by the instruction's use operands. Return NULL if no
0104     /// value is live-in.
0105     VNInfo *valueIn() const {
0106       return EarlyVal;
0107     }
0108 
0109     /// Return true if the live-in value is killed by this instruction. This
0110     /// means that either the live range ends at the instruction, or it changes
0111     /// value.
0112     bool isKill() const {
0113       return Kill;
0114     }
0115 
0116     /// Return true if this instruction has a dead def.
0117     bool isDeadDef() const {
0118       return EndPoint.isDead();
0119     }
0120 
0121     /// Return the value leaving the instruction, if any. This can be a
0122     /// live-through value, or a live def. A dead def returns NULL.
0123     VNInfo *valueOut() const {
0124       return isDeadDef() ? nullptr : LateVal;
0125     }
0126 
0127     /// Returns the value alive at the end of the instruction, if any. This can
0128     /// be a live-through value, a live def or a dead def.
0129     VNInfo *valueOutOrDead() const {
0130       return LateVal;
0131     }
0132 
0133     /// Return the value defined by this instruction, if any. This includes
0134     /// dead defs, it is the value created by the instruction's def operands.
0135     VNInfo *valueDefined() const {
0136       return EarlyVal == LateVal ? nullptr : LateVal;
0137     }
0138 
0139     /// Return the end point of the last live range segment to interact with
0140     /// the instruction, if any.
0141     ///
0142     /// The end point is an invalid SlotIndex only if the live range doesn't
0143     /// intersect the instruction at all.
0144     ///
0145     /// The end point may be at or past the end of the instruction's basic
0146     /// block. That means the value was live out of the block.
0147     SlotIndex endPoint() const {
0148       return EndPoint;
0149     }
0150   };
0151 
0152   /// This class represents the liveness of a register, stack slot, etc.
0153   /// It manages an ordered list of Segment objects.
0154   /// The Segments are organized in a static single assignment form: At places
0155   /// where a new value is defined or different values reach a CFG join a new
0156   /// segment with a new value number is used.
0157   class LiveRange {
0158   public:
0159     /// This represents a simple continuous liveness interval for a value.
0160     /// The start point is inclusive, the end point exclusive. These intervals
0161     /// are rendered as [start,end).
0162     struct Segment {
0163       SlotIndex start;  // Start point of the interval (inclusive)
0164       SlotIndex end;    // End point of the interval (exclusive)
0165       VNInfo *valno = nullptr; // identifier for the value contained in this
0166                                // segment.
0167 
0168       Segment() = default;
0169 
0170       Segment(SlotIndex S, SlotIndex E, VNInfo *V)
0171         : start(S), end(E), valno(V) {
0172         assert(S < E && "Cannot create empty or backwards segment");
0173       }
0174 
0175       /// Return true if the index is covered by this segment.
0176       bool contains(SlotIndex I) const {
0177         return start <= I && I < end;
0178       }
0179 
0180       /// Return true if the given interval, [S, E), is covered by this segment.
0181       bool containsInterval(SlotIndex S, SlotIndex E) const {
0182         assert((S < E) && "Backwards interval?");
0183         return (start <= S && S < end) && (start < E && E <= end);
0184       }
0185 
0186       bool operator<(const Segment &Other) const {
0187         return std::tie(start, end) < std::tie(Other.start, Other.end);
0188       }
0189       bool operator==(const Segment &Other) const {
0190         return start == Other.start && end == Other.end;
0191       }
0192 
0193       bool operator!=(const Segment &Other) const {
0194         return !(*this == Other);
0195       }
0196 
0197       void dump() const;
0198     };
0199 
0200     using Segments = SmallVector<Segment, 2>;
0201     using VNInfoList = SmallVector<VNInfo *, 2>;
0202 
0203     Segments segments;   // the liveness segments
0204     VNInfoList valnos;   // value#'s
0205 
0206     // The segment set is used temporarily to accelerate initial computation
0207     // of live ranges of physical registers in computeRegUnitRange.
0208     // After that the set is flushed to the segment vector and deleted.
0209     using SegmentSet = std::set<Segment>;
0210     std::unique_ptr<SegmentSet> segmentSet;
0211 
0212     using iterator = Segments::iterator;
0213     using const_iterator = Segments::const_iterator;
0214 
0215     iterator begin() { return segments.begin(); }
0216     iterator end()   { return segments.end(); }
0217 
0218     const_iterator begin() const { return segments.begin(); }
0219     const_iterator end() const  { return segments.end(); }
0220 
0221     using vni_iterator = VNInfoList::iterator;
0222     using const_vni_iterator = VNInfoList::const_iterator;
0223 
0224     vni_iterator vni_begin() { return valnos.begin(); }
0225     vni_iterator vni_end()   { return valnos.end(); }
0226 
0227     const_vni_iterator vni_begin() const { return valnos.begin(); }
0228     const_vni_iterator vni_end() const   { return valnos.end(); }
0229 
0230     iterator_range<vni_iterator> vnis() {
0231       return make_range(vni_begin(), vni_end());
0232     }
0233 
0234     iterator_range<const_vni_iterator> vnis() const {
0235       return make_range(vni_begin(), vni_end());
0236     }
0237 
0238     /// Constructs a new LiveRange object.
0239     LiveRange(bool UseSegmentSet = false)
0240         : segmentSet(UseSegmentSet ? std::make_unique<SegmentSet>()
0241                                    : nullptr) {}
0242 
0243     /// Constructs a new LiveRange object by copying segments and valnos from
0244     /// another LiveRange.
0245     LiveRange(const LiveRange &Other, BumpPtrAllocator &Allocator) {
0246       assert(Other.segmentSet == nullptr &&
0247              "Copying of LiveRanges with active SegmentSets is not supported");
0248       assign(Other, Allocator);
0249     }
0250 
0251     /// Copies values numbers and live segments from \p Other into this range.
0252     void assign(const LiveRange &Other, BumpPtrAllocator &Allocator) {
0253       if (this == &Other)
0254         return;
0255 
0256       assert(Other.segmentSet == nullptr &&
0257              "Copying of LiveRanges with active SegmentSets is not supported");
0258       // Duplicate valnos.
0259       for (const VNInfo *VNI : Other.valnos)
0260         createValueCopy(VNI, Allocator);
0261       // Now we can copy segments and remap their valnos.
0262       for (const Segment &S : Other.segments)
0263         segments.push_back(Segment(S.start, S.end, valnos[S.valno->id]));
0264     }
0265 
0266     /// advanceTo - Advance the specified iterator to point to the Segment
0267     /// containing the specified position, or end() if the position is past the
0268     /// end of the range.  If no Segment contains this position, but the
0269     /// position is in a hole, this method returns an iterator pointing to the
0270     /// Segment immediately after the hole.
0271     iterator advanceTo(iterator I, SlotIndex Pos) {
0272       assert(I != end());
0273       if (Pos >= endIndex())
0274         return end();
0275       while (I->end <= Pos) ++I;
0276       return I;
0277     }
0278 
0279     const_iterator advanceTo(const_iterator I, SlotIndex Pos) const {
0280       assert(I != end());
0281       if (Pos >= endIndex())
0282         return end();
0283       while (I->end <= Pos) ++I;
0284       return I;
0285     }
0286 
0287     /// find - Return an iterator pointing to the first segment that ends after
0288     /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
0289     /// when searching large ranges.
0290     ///
0291     /// If Pos is contained in a Segment, that segment is returned.
0292     /// If Pos is in a hole, the following Segment is returned.
0293     /// If Pos is beyond endIndex, end() is returned.
0294     iterator find(SlotIndex Pos);
0295 
0296     const_iterator find(SlotIndex Pos) const {
0297       return const_cast<LiveRange*>(this)->find(Pos);
0298     }
0299 
0300     void clear() {
0301       valnos.clear();
0302       segments.clear();
0303     }
0304 
0305     size_t size() const {
0306       return segments.size();
0307     }
0308 
0309     bool hasAtLeastOneValue() const { return !valnos.empty(); }
0310 
0311     bool containsOneValue() const { return valnos.size() == 1; }
0312 
0313     unsigned getNumValNums() const { return (unsigned)valnos.size(); }
0314 
0315     /// getValNumInfo - Returns pointer to the specified val#.
0316     ///
0317     inline VNInfo *getValNumInfo(unsigned ValNo) {
0318       return valnos[ValNo];
0319     }
0320     inline const VNInfo *getValNumInfo(unsigned ValNo) const {
0321       return valnos[ValNo];
0322     }
0323 
0324     /// containsValue - Returns true if VNI belongs to this range.
0325     bool containsValue(const VNInfo *VNI) const {
0326       return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
0327     }
0328 
0329     /// getNextValue - Create a new value number and return it.
0330     /// @p Def is the index of instruction that defines the value number.
0331     VNInfo *getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator) {
0332       VNInfo *VNI =
0333         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), Def);
0334       valnos.push_back(VNI);
0335       return VNI;
0336     }
0337 
0338     /// createDeadDef - Make sure the range has a value defined at Def.
0339     /// If one already exists, return it. Otherwise allocate a new value and
0340     /// add liveness for a dead def.
0341     VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc);
0342 
0343     /// Create a def of value @p VNI. Return @p VNI. If there already exists
0344     /// a definition at VNI->def, the value defined there must be @p VNI.
0345     VNInfo *createDeadDef(VNInfo *VNI);
0346 
0347     /// Create a copy of the given value. The new value will be identical except
0348     /// for the Value number.
0349     VNInfo *createValueCopy(const VNInfo *orig,
0350                             VNInfo::Allocator &VNInfoAllocator) {
0351       VNInfo *VNI =
0352         new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
0353       valnos.push_back(VNI);
0354       return VNI;
0355     }
0356 
0357     /// RenumberValues - Renumber all values in order of appearance and remove
0358     /// unused values.
0359     void RenumberValues();
0360 
0361     /// MergeValueNumberInto - This method is called when two value numbers
0362     /// are found to be equivalent.  This eliminates V1, replacing all
0363     /// segments with the V1 value number with the V2 value number.  This can
0364     /// cause merging of V1/V2 values numbers and compaction of the value space.
0365     VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
0366 
0367     /// Merge all of the live segments of a specific val# in RHS into this live
0368     /// range as the specified value number. The segments in RHS are allowed
0369     /// to overlap with segments in the current range, it will replace the
0370     /// value numbers of the overlaped live segments with the specified value
0371     /// number.
0372     void MergeSegmentsInAsValue(const LiveRange &RHS, VNInfo *LHSValNo);
0373 
0374     /// MergeValueInAsValue - Merge all of the segments of a specific val#
0375     /// in RHS into this live range as the specified value number.
0376     /// The segments in RHS are allowed to overlap with segments in the
0377     /// current range, but only if the overlapping segments have the
0378     /// specified value number.
0379     void MergeValueInAsValue(const LiveRange &RHS,
0380                              const VNInfo *RHSValNo, VNInfo *LHSValNo);
0381 
0382     bool empty() const { return segments.empty(); }
0383 
0384     /// beginIndex - Return the lowest numbered slot covered.
0385     SlotIndex beginIndex() const {
0386       assert(!empty() && "Call to beginIndex() on empty range.");
0387       return segments.front().start;
0388     }
0389 
0390     /// endNumber - return the maximum point of the range of the whole,
0391     /// exclusive.
0392     SlotIndex endIndex() const {
0393       assert(!empty() && "Call to endIndex() on empty range.");
0394       return segments.back().end;
0395     }
0396 
0397     bool expiredAt(SlotIndex index) const {
0398       return index >= endIndex();
0399     }
0400 
0401     bool liveAt(SlotIndex index) const {
0402       const_iterator r = find(index);
0403       return r != end() && r->start <= index;
0404     }
0405 
0406     /// Return the segment that contains the specified index, or null if there
0407     /// is none.
0408     const Segment *getSegmentContaining(SlotIndex Idx) const {
0409       const_iterator I = FindSegmentContaining(Idx);
0410       return I == end() ? nullptr : &*I;
0411     }
0412 
0413     /// Return the live segment that contains the specified index, or null if
0414     /// there is none.
0415     Segment *getSegmentContaining(SlotIndex Idx) {
0416       iterator I = FindSegmentContaining(Idx);
0417       return I == end() ? nullptr : &*I;
0418     }
0419 
0420     /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
0421     VNInfo *getVNInfoAt(SlotIndex Idx) const {
0422       const_iterator I = FindSegmentContaining(Idx);
0423       return I == end() ? nullptr : I->valno;
0424     }
0425 
0426     /// getVNInfoBefore - Return the VNInfo that is live up to but not
0427     /// necessarily including Idx, or NULL. Use this to find the reaching def
0428     /// used by an instruction at this SlotIndex position.
0429     VNInfo *getVNInfoBefore(SlotIndex Idx) const {
0430       const_iterator I = FindSegmentContaining(Idx.getPrevSlot());
0431       return I == end() ? nullptr : I->valno;
0432     }
0433 
0434     /// Return an iterator to the segment that contains the specified index, or
0435     /// end() if there is none.
0436     iterator FindSegmentContaining(SlotIndex Idx) {
0437       iterator I = find(Idx);
0438       return I != end() && I->start <= Idx ? I : end();
0439     }
0440 
0441     const_iterator FindSegmentContaining(SlotIndex Idx) const {
0442       const_iterator I = find(Idx);
0443       return I != end() && I->start <= Idx ? I : end();
0444     }
0445 
0446     /// overlaps - Return true if the intersection of the two live ranges is
0447     /// not empty.
0448     bool overlaps(const LiveRange &other) const {
0449       if (other.empty())
0450         return false;
0451       return overlapsFrom(other, other.begin());
0452     }
0453 
0454     /// overlaps - Return true if the two ranges have overlapping segments
0455     /// that are not coalescable according to CP.
0456     ///
0457     /// Overlapping segments where one range is defined by a coalescable
0458     /// copy are allowed.
0459     bool overlaps(const LiveRange &Other, const CoalescerPair &CP,
0460                   const SlotIndexes&) const;
0461 
0462     /// overlaps - Return true if the live range overlaps an interval specified
0463     /// by [Start, End).
0464     bool overlaps(SlotIndex Start, SlotIndex End) const;
0465 
0466     /// overlapsFrom - Return true if the intersection of the two live ranges
0467     /// is not empty.  The specified iterator is a hint that we can begin
0468     /// scanning the Other range starting at I.
0469     bool overlapsFrom(const LiveRange &Other, const_iterator StartPos) const;
0470 
0471     /// Returns true if all segments of the @p Other live range are completely
0472     /// covered by this live range.
0473     /// Adjacent live ranges do not affect the covering:the liverange
0474     /// [1,5](5,10] covers (3,7].
0475     bool covers(const LiveRange &Other) const;
0476 
0477     /// Add the specified Segment to this range, merging segments as
0478     /// appropriate.  This returns an iterator to the inserted segment (which
0479     /// may have grown since it was inserted).
0480     iterator addSegment(Segment S);
0481 
0482     /// Attempt to extend a value defined after @p StartIdx to include @p Use.
0483     /// Both @p StartIdx and @p Use should be in the same basic block. In case
0484     /// of subranges, an extension could be prevented by an explicit "undef"
0485     /// caused by a <def,read-undef> on a non-overlapping lane. The list of
0486     /// location of such "undefs" should be provided in @p Undefs.
0487     /// The return value is a pair: the first element is VNInfo of the value
0488     /// that was extended (possibly nullptr), the second is a boolean value
0489     /// indicating whether an "undef" was encountered.
0490     /// If this range is live before @p Use in the basic block that starts at
0491     /// @p StartIdx, and there is no intervening "undef", extend it to be live
0492     /// up to @p Use, and return the pair {value, false}. If there is no
0493     /// segment before @p Use and there is no "undef" between @p StartIdx and
0494     /// @p Use, return {nullptr, false}. If there is an "undef" before @p Use,
0495     /// return {nullptr, true}.
0496     std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
0497         SlotIndex StartIdx, SlotIndex Kill);
0498 
0499     /// Simplified version of the above "extendInBlock", which assumes that
0500     /// no register lanes are undefined by <def,read-undef> operands.
0501     /// If this range is live before @p Use in the basic block that starts
0502     /// at @p StartIdx, extend it to be live up to @p Use, and return the
0503     /// value. If there is no segment before @p Use, return nullptr.
0504     VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
0505 
0506     /// join - Join two live ranges (this, and other) together.  This applies
0507     /// mappings to the value numbers in the LHS/RHS ranges as specified.  If
0508     /// the ranges are not joinable, this aborts.
0509     void join(LiveRange &Other,
0510               const int *ValNoAssignments,
0511               const int *RHSValNoAssignments,
0512               SmallVectorImpl<VNInfo *> &NewVNInfo);
0513 
0514     /// True iff this segment is a single segment that lies between the
0515     /// specified boundaries, exclusively. Vregs live across a backedge are not
0516     /// considered local. The boundaries are expected to lie within an extended
0517     /// basic block, so vregs that are not live out should contain no holes.
0518     bool isLocal(SlotIndex Start, SlotIndex End) const {
0519       return beginIndex() > Start.getBaseIndex() &&
0520         endIndex() < End.getBoundaryIndex();
0521     }
0522 
0523     /// Remove the specified interval from this live range.
0524     /// Does nothing if interval is not part of this live range.
0525     /// Note that the interval must be within a single Segment in its entirety.
0526     void removeSegment(SlotIndex Start, SlotIndex End,
0527                        bool RemoveDeadValNo = false);
0528 
0529     void removeSegment(Segment S, bool RemoveDeadValNo = false) {
0530       removeSegment(S.start, S.end, RemoveDeadValNo);
0531     }
0532 
0533     /// Remove segment pointed to by iterator @p I from this range.
0534     iterator removeSegment(iterator I, bool RemoveDeadValNo = false);
0535 
0536     /// Mark \p ValNo for deletion if no segments in this range use it.
0537     void removeValNoIfDead(VNInfo *ValNo);
0538 
0539     /// Query Liveness at Idx.
0540     /// The sub-instruction slot of Idx doesn't matter, only the instruction
0541     /// it refers to is considered.
0542     LiveQueryResult Query(SlotIndex Idx) const {
0543       // Find the segment that enters the instruction.
0544       const_iterator I = find(Idx.getBaseIndex());
0545       const_iterator E = end();
0546       if (I == E)
0547         return LiveQueryResult(nullptr, nullptr, SlotIndex(), false);
0548 
0549       // Is this an instruction live-in segment?
0550       // If Idx is the start index of a basic block, include live-in segments
0551       // that start at Idx.getBaseIndex().
0552       VNInfo *EarlyVal = nullptr;
0553       VNInfo *LateVal  = nullptr;
0554       SlotIndex EndPoint;
0555       bool Kill = false;
0556       if (I->start <= Idx.getBaseIndex()) {
0557         EarlyVal = I->valno;
0558         EndPoint = I->end;
0559         // Move to the potentially live-out segment.
0560         if (SlotIndex::isSameInstr(Idx, I->end)) {
0561           Kill = true;
0562           if (++I == E)
0563             return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
0564         }
0565         // Special case: A PHIDef value can have its def in the middle of a
0566         // segment if the value happens to be live out of the layout
0567         // predecessor.
0568         // Such a value is not live-in.
0569         if (EarlyVal->def == Idx.getBaseIndex())
0570           EarlyVal = nullptr;
0571       }
0572       // I now points to the segment that may be live-through, or defined by
0573       // this instr. Ignore segments starting after the current instr.
0574       if (!SlotIndex::isEarlierInstr(Idx, I->start)) {
0575         LateVal = I->valno;
0576         EndPoint = I->end;
0577       }
0578       return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
0579     }
0580 
0581     /// removeValNo - Remove all the segments defined by the specified value#.
0582     /// Also remove the value# from value# list.
0583     void removeValNo(VNInfo *ValNo);
0584 
0585     /// Returns true if the live range is zero length, i.e. no live segments
0586     /// span instructions. It doesn't pay to spill such a range.
0587     bool isZeroLength(SlotIndexes *Indexes) const {
0588       for (const Segment &S : segments)
0589         if (Indexes->getNextNonNullIndex(S.start).getBaseIndex() <
0590             S.end.getBaseIndex())
0591           return false;
0592       return true;
0593     }
0594 
0595     // Returns true if any segment in the live range contains any of the
0596     // provided slot indexes.  Slots which occur in holes between
0597     // segments will not cause the function to return true.
0598     bool isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const;
0599 
0600     bool operator<(const LiveRange& other) const {
0601       const SlotIndex &thisIndex = beginIndex();
0602       const SlotIndex &otherIndex = other.beginIndex();
0603       return thisIndex < otherIndex;
0604     }
0605 
0606     /// Returns true if there is an explicit "undef" between @p Begin
0607     /// @p End.
0608     bool isUndefIn(ArrayRef<SlotIndex> Undefs, SlotIndex Begin,
0609                    SlotIndex End) const {
0610       return llvm::any_of(Undefs, [Begin, End](SlotIndex Idx) -> bool {
0611         return Begin <= Idx && Idx < End;
0612       });
0613     }
0614 
0615     /// Flush segment set into the regular segment vector.
0616     /// The method is to be called after the live range
0617     /// has been created, if use of the segment set was
0618     /// activated in the constructor of the live range.
0619     void flushSegmentSet();
0620 
0621     /// Stores indexes from the input index sequence R at which this LiveRange
0622     /// is live to the output O iterator.
0623     /// R is a range of _ascending sorted_ _random_ access iterators
0624     /// to the input indexes. Indexes stored at O are ascending sorted so it
0625     /// can be used directly in the subsequent search (for example for
0626     /// subranges). Returns true if found at least one index.
0627     template <typename Range, typename OutputIt>
0628     bool findIndexesLiveAt(Range &&R, OutputIt O) const {
0629       assert(llvm::is_sorted(R));
0630       auto Idx = R.begin(), EndIdx = R.end();
0631       auto Seg = segments.begin(), EndSeg = segments.end();
0632       bool Found = false;
0633       while (Idx != EndIdx && Seg != EndSeg) {
0634         // if the Seg is lower find first segment that is above Idx using binary
0635         // search
0636         if (Seg->end <= *Idx) {
0637           Seg =
0638               std::upper_bound(++Seg, EndSeg, *Idx, [=](auto V, const auto &S) {
0639                 return V < S.end;
0640               });
0641           if (Seg == EndSeg)
0642             break;
0643         }
0644         auto NotLessStart = std::lower_bound(Idx, EndIdx, Seg->start);
0645         if (NotLessStart == EndIdx)
0646           break;
0647         auto NotLessEnd = std::lower_bound(NotLessStart, EndIdx, Seg->end);
0648         if (NotLessEnd != NotLessStart) {
0649           Found = true;
0650           O = std::copy(NotLessStart, NotLessEnd, O);
0651         }
0652         Idx = NotLessEnd;
0653         ++Seg;
0654       }
0655       return Found;
0656     }
0657 
0658     void print(raw_ostream &OS) const;
0659     void dump() const;
0660 
0661     /// Walk the range and assert if any invariants fail to hold.
0662     ///
0663     /// Note that this is a no-op when asserts are disabled.
0664 #ifdef NDEBUG
0665     [[nodiscard]] bool verify() const { return true; }
0666 #else
0667     [[nodiscard]] bool verify() const;
0668 #endif
0669 
0670   protected:
0671     /// Append a segment to the list of segments.
0672     void append(const LiveRange::Segment S);
0673 
0674   private:
0675     friend class LiveRangeUpdater;
0676     void addSegmentToSet(Segment S);
0677     void markValNoForDeletion(VNInfo *V);
0678   };
0679 
0680   inline raw_ostream &operator<<(raw_ostream &OS, const LiveRange &LR) {
0681     LR.print(OS);
0682     return OS;
0683   }
0684 
0685   /// LiveInterval - This class represents the liveness of a register,
0686   /// or stack slot.
0687   class LiveInterval : public LiveRange {
0688   public:
0689     using super = LiveRange;
0690 
0691     /// A live range for subregisters. The LaneMask specifies which parts of the
0692     /// super register are covered by the interval.
0693     /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
0694     class SubRange : public LiveRange {
0695     public:
0696       SubRange *Next = nullptr;
0697       LaneBitmask LaneMask;
0698 
0699       /// Constructs a new SubRange object.
0700       SubRange(LaneBitmask LaneMask) : LaneMask(LaneMask) {}
0701 
0702       /// Constructs a new SubRange object by copying liveness from @p Other.
0703       SubRange(LaneBitmask LaneMask, const LiveRange &Other,
0704                BumpPtrAllocator &Allocator)
0705         : LiveRange(Other, Allocator), LaneMask(LaneMask) {}
0706 
0707       void print(raw_ostream &OS) const;
0708       void dump() const;
0709     };
0710 
0711   private:
0712     SubRange *SubRanges = nullptr; ///< Single linked list of subregister live
0713                                    /// ranges.
0714     const Register Reg; // the register or stack slot of this interval.
0715     float Weight = 0.0; // weight of this interval
0716 
0717   public:
0718     Register reg() const { return Reg; }
0719     float weight() const { return Weight; }
0720     void incrementWeight(float Inc) { Weight += Inc; }
0721     void setWeight(float Value) { Weight = Value; }
0722 
0723     LiveInterval(unsigned Reg, float Weight) : Reg(Reg), Weight(Weight) {}
0724 
0725     ~LiveInterval() {
0726       clearSubRanges();
0727     }
0728 
0729     template<typename T>
0730     class SingleLinkedListIterator {
0731       T *P;
0732 
0733     public:
0734       using difference_type = ptrdiff_t;
0735       using value_type = T;
0736       using pointer = T *;
0737       using reference = T &;
0738       using iterator_category = std::forward_iterator_tag;
0739 
0740       SingleLinkedListIterator(T *P) : P(P) {}
0741 
0742       SingleLinkedListIterator<T> &operator++() {
0743         P = P->Next;
0744         return *this;
0745       }
0746       SingleLinkedListIterator<T> operator++(int) {
0747         SingleLinkedListIterator res = *this;
0748         ++*this;
0749         return res;
0750       }
0751       bool operator!=(const SingleLinkedListIterator<T> &Other) const {
0752         return P != Other.operator->();
0753       }
0754       bool operator==(const SingleLinkedListIterator<T> &Other) const {
0755         return P == Other.operator->();
0756       }
0757       T &operator*() const {
0758         return *P;
0759       }
0760       T *operator->() const {
0761         return P;
0762       }
0763     };
0764 
0765     using subrange_iterator = SingleLinkedListIterator<SubRange>;
0766     using const_subrange_iterator = SingleLinkedListIterator<const SubRange>;
0767 
0768     subrange_iterator subrange_begin() {
0769       return subrange_iterator(SubRanges);
0770     }
0771     subrange_iterator subrange_end() {
0772       return subrange_iterator(nullptr);
0773     }
0774 
0775     const_subrange_iterator subrange_begin() const {
0776       return const_subrange_iterator(SubRanges);
0777     }
0778     const_subrange_iterator subrange_end() const {
0779       return const_subrange_iterator(nullptr);
0780     }
0781 
0782     iterator_range<subrange_iterator> subranges() {
0783       return make_range(subrange_begin(), subrange_end());
0784     }
0785 
0786     iterator_range<const_subrange_iterator> subranges() const {
0787       return make_range(subrange_begin(), subrange_end());
0788     }
0789 
0790     /// Creates a new empty subregister live range. The range is added at the
0791     /// beginning of the subrange list; subrange iterators stay valid.
0792     SubRange *createSubRange(BumpPtrAllocator &Allocator,
0793                              LaneBitmask LaneMask) {
0794       SubRange *Range = new (Allocator) SubRange(LaneMask);
0795       appendSubRange(Range);
0796       return Range;
0797     }
0798 
0799     /// Like createSubRange() but the new range is filled with a copy of the
0800     /// liveness information in @p CopyFrom.
0801     SubRange *createSubRangeFrom(BumpPtrAllocator &Allocator,
0802                                  LaneBitmask LaneMask,
0803                                  const LiveRange &CopyFrom) {
0804       SubRange *Range = new (Allocator) SubRange(LaneMask, CopyFrom, Allocator);
0805       appendSubRange(Range);
0806       return Range;
0807     }
0808 
0809     /// Returns true if subregister liveness information is available.
0810     bool hasSubRanges() const {
0811       return SubRanges != nullptr;
0812     }
0813 
0814     /// Removes all subregister liveness information.
0815     void clearSubRanges();
0816 
0817     /// Removes all subranges without any segments (subranges without segments
0818     /// are not considered valid and should only exist temporarily).
0819     void removeEmptySubRanges();
0820 
0821     /// getSize - Returns the sum of sizes of all the LiveRange's.
0822     ///
0823     unsigned getSize() const;
0824 
0825     /// isSpillable - Can this interval be spilled?
0826     bool isSpillable() const { return Weight != huge_valf; }
0827 
0828     /// markNotSpillable - Mark interval as not spillable
0829     void markNotSpillable() { Weight = huge_valf; }
0830 
0831     /// For a given lane mask @p LaneMask, compute indexes at which the
0832     /// lane is marked undefined by subregister <def,read-undef> definitions.
0833     void computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
0834                                LaneBitmask LaneMask,
0835                                const MachineRegisterInfo &MRI,
0836                                const SlotIndexes &Indexes) const;
0837 
0838     /// Refines the subranges to support \p LaneMask. This may only be called
0839     /// for LI.hasSubrange()==true. Subregister ranges are split or created
0840     /// until \p LaneMask can be matched exactly. \p Mod is executed on the
0841     /// matching subranges.
0842     ///
0843     /// Example:
0844     ///    Given an interval with subranges with lanemasks L0F00, L00F0 and
0845     ///    L000F, refining for mask L0018. Will split the L00F0 lane into
0846     ///    L00E0 and L0010 and the L000F lane into L0007 and L0008. The Mod
0847     ///    function will be applied to the L0010 and L0008 subranges.
0848     ///
0849     /// \p Indexes and \p TRI are required to clean up the VNIs that
0850     /// don't define the related lane masks after they get shrunk. E.g.,
0851     /// when L000F gets split into L0007 and L0008 maybe only a subset
0852     /// of the VNIs that defined L000F defines L0007.
0853     ///
0854     /// The clean up of the VNIs need to look at the actual instructions
0855     /// to decide what is or is not live at a definition point. If the
0856     /// update of the subranges occurs while the IR does not reflect these
0857     /// changes, \p ComposeSubRegIdx can be used to specify how the
0858     /// definition are going to be rewritten.
0859     /// E.g., let say we want to merge:
0860     ///     V1.sub1:<2 x s32> = COPY V2.sub3:<4 x s32>
0861     /// We do that by choosing a class where sub1:<2 x s32> and sub3:<4 x s32>
0862     /// overlap, i.e., by choosing a class where we can find "offset + 1 == 3".
0863     /// Put differently we align V2's sub3 with V1's sub1:
0864     /// V2: sub0 sub1 sub2 sub3
0865     /// V1: <offset>  sub0 sub1
0866     ///
0867     /// This offset will look like a composed subregidx in the class:
0868     ///     V1.(composed sub2 with sub1):<4 x s32> = COPY V2.sub3:<4 x s32>
0869     /// =>  V1.(composed sub2 with sub1):<4 x s32> = COPY V2.sub3:<4 x s32>
0870     ///
0871     /// Now if we didn't rewrite the uses and def of V1, all the checks for V1
0872     /// need to account for this offset.
0873     /// This happens during coalescing where we update the live-ranges while
0874     /// still having the old IR around because updating the IR on-the-fly
0875     /// would actually clobber some information on how the live-ranges that
0876     /// are being updated look like.
0877     void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
0878                          std::function<void(LiveInterval::SubRange &)> Apply,
0879                          const SlotIndexes &Indexes,
0880                          const TargetRegisterInfo &TRI,
0881                          unsigned ComposeSubRegIdx = 0);
0882 
0883     bool operator<(const LiveInterval& other) const {
0884       const SlotIndex &thisIndex = beginIndex();
0885       const SlotIndex &otherIndex = other.beginIndex();
0886       return std::tie(thisIndex, Reg) < std::tie(otherIndex, other.Reg);
0887     }
0888 
0889     void print(raw_ostream &OS) const;
0890     void dump() const;
0891 
0892     /// Walks the interval and assert if any invariants fail to hold.
0893     ///
0894     /// Note that this is a no-op when asserts are disabled.
0895 #ifdef NDEBUG
0896     [[nodiscard]] bool verify(const MachineRegisterInfo *MRI = nullptr) const {
0897       return true;
0898     }
0899 #else
0900     [[nodiscard]] bool verify(const MachineRegisterInfo *MRI = nullptr) const;
0901 #endif
0902 
0903   private:
0904     /// Appends @p Range to SubRanges list.
0905     void appendSubRange(SubRange *Range) {
0906       Range->Next = SubRanges;
0907       SubRanges = Range;
0908     }
0909 
0910     /// Free memory held by SubRange.
0911     void freeSubRange(SubRange *S);
0912   };
0913 
0914   inline raw_ostream &operator<<(raw_ostream &OS,
0915                                  const LiveInterval::SubRange &SR) {
0916     SR.print(OS);
0917     return OS;
0918   }
0919 
0920   inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
0921     LI.print(OS);
0922     return OS;
0923   }
0924 
0925   raw_ostream &operator<<(raw_ostream &OS, const LiveRange::Segment &S);
0926 
0927   inline bool operator<(SlotIndex V, const LiveRange::Segment &S) {
0928     return V < S.start;
0929   }
0930 
0931   inline bool operator<(const LiveRange::Segment &S, SlotIndex V) {
0932     return S.start < V;
0933   }
0934 
0935   /// Helper class for performant LiveRange bulk updates.
0936   ///
0937   /// Calling LiveRange::addSegment() repeatedly can be expensive on large
0938   /// live ranges because segments after the insertion point may need to be
0939   /// shifted. The LiveRangeUpdater class can defer the shifting when adding
0940   /// many segments in order.
0941   ///
0942   /// The LiveRange will be in an invalid state until flush() is called.
0943   class LiveRangeUpdater {
0944     LiveRange *LR;
0945     SlotIndex LastStart;
0946     LiveRange::iterator WriteI;
0947     LiveRange::iterator ReadI;
0948     SmallVector<LiveRange::Segment, 16> Spills;
0949     void mergeSpills();
0950 
0951   public:
0952     /// Create a LiveRangeUpdater for adding segments to LR.
0953     /// LR will temporarily be in an invalid state until flush() is called.
0954     LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
0955 
0956     ~LiveRangeUpdater() { flush(); }
0957 
0958     /// Add a segment to LR and coalesce when possible, just like
0959     /// LR.addSegment(). Segments should be added in increasing start order for
0960     /// best performance.
0961     void add(LiveRange::Segment);
0962 
0963     void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
0964       add(LiveRange::Segment(Start, End, VNI));
0965     }
0966 
0967     /// Return true if the LR is currently in an invalid state, and flush()
0968     /// needs to be called.
0969     bool isDirty() const { return LastStart.isValid(); }
0970 
0971     /// Flush the updater state to LR so it is valid and contains all added
0972     /// segments.
0973     void flush();
0974 
0975     /// Select a different destination live range.
0976     void setDest(LiveRange *lr) {
0977       if (LR != lr && isDirty())
0978         flush();
0979       LR = lr;
0980     }
0981 
0982     /// Get the current destination live range.
0983     LiveRange *getDest() const { return LR; }
0984 
0985     void dump() const;
0986     void print(raw_ostream&) const;
0987   };
0988 
0989   inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
0990     X.print(OS);
0991     return OS;
0992   }
0993 
0994   /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
0995   /// LiveInterval into equivalence clases of connected components. A
0996   /// LiveInterval that has multiple connected components can be broken into
0997   /// multiple LiveIntervals.
0998   ///
0999   /// Given a LiveInterval that may have multiple connected components, run:
1000   ///
1001   ///   unsigned numComps = ConEQ.Classify(LI);
1002   ///   if (numComps > 1) {
1003   ///     // allocate numComps-1 new LiveIntervals into LIS[1..]
1004   ///     ConEQ.Distribute(LIS);
1005   /// }
1006 
1007   class ConnectedVNInfoEqClasses {
1008     LiveIntervals &LIS;
1009     IntEqClasses EqClass;
1010 
1011   public:
1012     explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
1013 
1014     /// Classify the values in \p LR into connected components.
1015     /// Returns the number of connected components.
1016     unsigned Classify(const LiveRange &LR);
1017 
1018     /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
1019     /// the equivalence class assigned the VNI.
1020     unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
1021 
1022     /// Distribute values in \p LI into a separate LiveIntervals
1023     /// for each connected component. LIV must have an empty LiveInterval for
1024     /// each additional connected component. The first connected component is
1025     /// left in \p LI.
1026     void Distribute(LiveInterval &LI, LiveInterval *LIV[],
1027                     MachineRegisterInfo &MRI);
1028   };
1029 
1030 } // end namespace llvm
1031 
1032 #endif // LLVM_CODEGEN_LIVEINTERVAL_H