1 //===-- llvm/CodeGen/LiveInterval.h - Interval representation ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 interval 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 intervals can have holes,
15 // i.e. an interval might look like [1,20), [50,65), [1000,1001). Each
16 // individual range is represented as an instance of LiveRange, and the whole
17 // interval is represented as an instance of LiveInterval.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_CODEGEN_LIVEINTERVAL_H
22 #define LLVM_CODEGEN_LIVEINTERVAL_H
24 #include "llvm/ADT/IntEqClasses.h"
25 #include "llvm/CodeGen/SlotIndexes.h"
26 #include "llvm/Support/AlignOf.h"
27 #include "llvm/Support/Allocator.h"
35 class MachineRegisterInfo;
36 class TargetRegisterInfo;
39 /// VNInfo - Value Number Information.
40 /// This class holds information about a machine level values, including
41 /// definition and use points.
45 typedef BumpPtrAllocator Allocator;
47 /// The ID number of this value.
50 /// The index of the defining instruction.
53 /// VNInfo constructor.
54 VNInfo(unsigned i, SlotIndex d)
58 /// VNInfo construtor, copies values from orig, except for the value number.
59 VNInfo(unsigned i, const VNInfo &orig)
60 : id(i), def(orig.def)
63 /// Copy from the parameter into this VNInfo.
64 void copyFrom(VNInfo &src) {
68 /// Returns true if this value is defined by a PHI instruction (or was,
69 /// PHI instrucions may have been eliminated).
70 /// PHI-defs begin at a block boundary, all other defs begin at register or
72 bool isPHIDef() const { return def.isBlock(); }
74 /// Returns true if this value is unused.
75 bool isUnused() const { return !def.isValid(); }
77 /// Mark this value as unused.
78 void markUnused() { def = SlotIndex(); }
81 /// LiveRange structure - This represents a simple register range in the
82 /// program, with an inclusive start point and an exclusive end point.
83 /// These ranges are rendered as [start,end).
85 SlotIndex start; // Start point of the interval (inclusive)
86 SlotIndex end; // End point of the interval (exclusive)
87 VNInfo *valno; // identifier for the value contained in this interval.
89 LiveRange() : valno(0) {}
91 LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
92 : start(S), end(E), valno(V) {
93 assert(S < E && "Cannot create empty or backwards range");
96 /// contains - Return true if the index is covered by this range.
98 bool contains(SlotIndex I) const {
99 return start <= I && I < end;
102 /// containsRange - Return true if the given range, [S, E), is covered by
104 bool containsRange(SlotIndex S, SlotIndex E) const {
105 assert((S < E) && "Backwards interval?");
106 return (start <= S && S < end) && (start < E && E <= end);
109 bool operator<(const LiveRange &LR) const {
110 return start < LR.start || (start == LR.start && end < LR.end);
112 bool operator==(const LiveRange &LR) const {
113 return start == LR.start && end == LR.end;
117 void print(raw_ostream &os) const;
120 template <> struct isPodLike<LiveRange> { static const bool value = true; };
122 raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
125 inline bool operator<(SlotIndex V, const LiveRange &LR) {
129 inline bool operator<(const LiveRange &LR, SlotIndex V) {
133 /// LiveInterval - This class represents some number of live ranges for a
134 /// register or value. This class also contains a bit of register allocator
139 typedef SmallVector<LiveRange,4> Ranges;
140 typedef SmallVector<VNInfo*,4> VNInfoList;
142 const unsigned reg; // the register or stack slot of this interval.
143 float weight; // weight of this interval
144 Ranges ranges; // the ranges in which this register is live
145 VNInfoList valnos; // value#'s
147 LiveInterval(unsigned Reg, float Weight)
148 : reg(Reg), weight(Weight) {}
150 typedef Ranges::iterator iterator;
151 iterator begin() { return ranges.begin(); }
152 iterator end() { return ranges.end(); }
154 typedef Ranges::const_iterator const_iterator;
155 const_iterator begin() const { return ranges.begin(); }
156 const_iterator end() const { return ranges.end(); }
158 typedef VNInfoList::iterator vni_iterator;
159 vni_iterator vni_begin() { return valnos.begin(); }
160 vni_iterator vni_end() { return valnos.end(); }
162 typedef VNInfoList::const_iterator const_vni_iterator;
163 const_vni_iterator vni_begin() const { return valnos.begin(); }
164 const_vni_iterator vni_end() const { return valnos.end(); }
166 /// advanceTo - Advance the specified iterator to point to the LiveRange
167 /// containing the specified position, or end() if the position is past the
168 /// end of the interval. If no LiveRange contains this position, but the
169 /// position is in a hole, this method returns an iterator pointing to the
170 /// LiveRange immediately after the hole.
171 iterator advanceTo(iterator I, SlotIndex Pos) {
173 if (Pos >= endIndex())
175 while (I->end <= Pos) ++I;
179 /// find - Return an iterator pointing to the first range that ends after
180 /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
181 /// when searching large intervals.
183 /// If Pos is contained in a LiveRange, that range is returned.
184 /// If Pos is in a hole, the following LiveRange is returned.
185 /// If Pos is beyond endIndex, end() is returned.
186 iterator find(SlotIndex Pos);
188 const_iterator find(SlotIndex Pos) const {
189 return const_cast<LiveInterval*>(this)->find(Pos);
197 bool hasAtLeastOneValue() const { return !valnos.empty(); }
199 bool containsOneValue() const { return valnos.size() == 1; }
201 unsigned getNumValNums() const { return (unsigned)valnos.size(); }
203 /// getValNumInfo - Returns pointer to the specified val#.
205 inline VNInfo *getValNumInfo(unsigned ValNo) {
206 return valnos[ValNo];
208 inline const VNInfo *getValNumInfo(unsigned ValNo) const {
209 return valnos[ValNo];
212 /// containsValue - Returns true if VNI belongs to this interval.
213 bool containsValue(const VNInfo *VNI) const {
214 return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
217 /// getNextValue - Create a new value number and return it. MIIdx specifies
218 /// the instruction that defines the value number.
219 VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
221 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
222 valnos.push_back(VNI);
226 /// createDeadDef - Make sure the interval has a value defined at Def.
227 /// If one already exists, return it. Otherwise allocate a new value and
228 /// add liveness for a dead def.
229 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
231 /// Create a copy of the given value. The new value will be identical except
232 /// for the Value number.
233 VNInfo *createValueCopy(const VNInfo *orig,
234 VNInfo::Allocator &VNInfoAllocator) {
236 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
237 valnos.push_back(VNI);
241 /// RenumberValues - Renumber all values in order of appearance and remove
243 void RenumberValues();
245 /// MergeValueNumberInto - This method is called when two value nubmers
246 /// are found to be equivalent. This eliminates V1, replacing all
247 /// LiveRanges with the V1 value number with the V2 value number. This can
248 /// cause merging of V1/V2 values numbers and compaction of the value space.
249 VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
251 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
252 /// in RHS into this live interval as the specified value number.
253 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
254 /// current interval, it will replace the value numbers of the overlaped
255 /// live ranges with the specified value number.
256 void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
258 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
259 /// in RHS into this live interval as the specified value number.
260 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
261 /// current interval, but only if the overlapping LiveRanges have the
262 /// specified value number.
263 void MergeValueInAsValue(const LiveInterval &RHS,
264 const VNInfo *RHSValNo, VNInfo *LHSValNo);
266 bool empty() const { return ranges.empty(); }
268 /// beginIndex - Return the lowest numbered slot covered by interval.
269 SlotIndex beginIndex() const {
270 assert(!empty() && "Call to beginIndex() on empty interval.");
271 return ranges.front().start;
274 /// endNumber - return the maximum point of the interval of the whole,
276 SlotIndex endIndex() const {
277 assert(!empty() && "Call to endIndex() on empty interval.");
278 return ranges.back().end;
281 bool expiredAt(SlotIndex index) const {
282 return index >= endIndex();
285 bool liveAt(SlotIndex index) const {
286 const_iterator r = find(index);
287 return r != end() && r->start <= index;
290 /// Return true if a live range ends at the instruction at this index. Note
291 /// that the kill point is not contained in the half-open live range. It is
292 /// usually the EarlyClobber or Register slot following its last use.
293 bool isKilledAtInstr(SlotIndex index) const {
294 SlotIndex BaseIdx = index.getBaseIndex();
295 const_iterator r = find(BaseIdx);
296 return r != end() && r->end.getBaseIndex() == BaseIdx;
299 /// Return true if a live range starts at the instruction at this index.
300 bool isDefinedByInstr(SlotIndex index) const {
301 const_iterator r = find(index.getDeadSlot());
302 return r != end() && r->end.getBaseIndex() == index.getBaseIndex();
305 /// getLiveRangeContaining - Return the live range that contains the
306 /// specified index, or null if there is none.
307 const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
308 const_iterator I = FindLiveRangeContaining(Idx);
309 return I == end() ? 0 : &*I;
312 /// getLiveRangeContaining - Return the live range that contains the
313 /// specified index, or null if there is none.
314 LiveRange *getLiveRangeContaining(SlotIndex Idx) {
315 iterator I = FindLiveRangeContaining(Idx);
316 return I == end() ? 0 : &*I;
319 /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
320 VNInfo *getVNInfoAt(SlotIndex Idx) const {
321 const_iterator I = FindLiveRangeContaining(Idx);
322 return I == end() ? 0 : I->valno;
325 /// getVNInfoBefore - Return the VNInfo that is live up to but not
326 /// necessarilly including Idx, or NULL. Use this to find the reaching def
327 /// used by an instruction at this SlotIndex position.
328 VNInfo *getVNInfoBefore(SlotIndex Idx) const {
329 const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
330 return I == end() ? 0 : I->valno;
333 /// FindLiveRangeContaining - Return an iterator to the live range that
334 /// contains the specified index, or end() if there is none.
335 iterator FindLiveRangeContaining(SlotIndex Idx) {
336 iterator I = find(Idx);
337 return I != end() && I->start <= Idx ? I : end();
340 const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
341 const_iterator I = find(Idx);
342 return I != end() && I->start <= Idx ? I : end();
345 /// overlaps - Return true if the intersection of the two live intervals is
347 bool overlaps(const LiveInterval& other) const {
350 return overlapsFrom(other, other.begin());
353 /// overlaps - Return true if the two intervals have overlapping segments
354 /// that are not coalescable according to CP.
356 /// Overlapping segments where one interval is defined by a coalescable
357 /// copy are allowed.
358 bool overlaps(const LiveInterval &Other, const CoalescerPair &CP,
359 const SlotIndexes&) const;
361 /// overlaps - Return true if the live interval overlaps a range specified
363 bool overlaps(SlotIndex Start, SlotIndex End) const;
365 /// overlapsFrom - Return true if the intersection of the two live intervals
366 /// is not empty. The specified iterator is a hint that we can begin
367 /// scanning the Other interval starting at I.
368 bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
370 /// addRange - Add the specified LiveRange to this interval, merging
371 /// intervals as appropriate. This returns an iterator to the inserted live
372 /// range (which may have grown since it was inserted.
373 iterator addRange(LiveRange LR) {
374 return addRangeFrom(LR, ranges.begin());
377 /// extendInBlock - If this interval is live before Kill in the basic block
378 /// that starts at StartIdx, extend it to be live up to Kill, and return
379 /// the value. If there is no live range before Kill, return NULL.
380 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
382 /// join - Join two live intervals (this, and other) together. This applies
383 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
384 /// the intervals are not joinable, this aborts.
385 void join(LiveInterval &Other,
386 const int *ValNoAssignments,
387 const int *RHSValNoAssignments,
388 SmallVectorImpl<VNInfo *> &NewVNInfo,
389 MachineRegisterInfo *MRI);
391 /// True iff this live range is a single segment that lies between the
392 /// specified boundaries, exclusively. Vregs live across a backedge are not
393 /// considered local. The boundaries are expected to lie within an extended
394 /// basic block, so vregs that are not live out should contain no holes.
395 bool isLocal(SlotIndex Start, SlotIndex End) const {
396 return beginIndex() > Start.getBaseIndex() &&
397 endIndex() < End.getBoundaryIndex();
400 /// removeRange - Remove the specified range from this interval. Note that
401 /// the range must be a single LiveRange in its entirety.
402 void removeRange(SlotIndex Start, SlotIndex End,
403 bool RemoveDeadValNo = false);
405 void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
406 removeRange(LR.start, LR.end, RemoveDeadValNo);
409 /// removeValNo - Remove all the ranges defined by the specified value#.
410 /// Also remove the value# from value# list.
411 void removeValNo(VNInfo *ValNo);
413 /// getSize - Returns the sum of sizes of all the LiveRange's.
415 unsigned getSize() const;
417 /// Returns true if the live interval is zero length, i.e. no live ranges
418 /// span instructions. It doesn't pay to spill such an interval.
419 bool isZeroLength(SlotIndexes *Indexes) const {
420 for (const_iterator i = begin(), e = end(); i != e; ++i)
421 if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
422 i->end.getBaseIndex())
427 /// isSpillable - Can this interval be spilled?
428 bool isSpillable() const {
429 return weight != HUGE_VALF;
432 /// markNotSpillable - Mark interval as not spillable
433 void markNotSpillable() {
437 bool operator<(const LiveInterval& other) const {
438 const SlotIndex &thisIndex = beginIndex();
439 const SlotIndex &otherIndex = other.beginIndex();
440 return (thisIndex < otherIndex ||
441 (thisIndex == otherIndex && reg < other.reg));
444 void print(raw_ostream &OS) const;
447 /// \brief Walk the interval and assert if any invariants fail to hold.
449 /// Note that this is a no-op when asserts are disabled.
451 void verify() const {}
458 Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
459 void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
460 Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
461 void markValNoForDeletion(VNInfo *V);
463 LiveInterval& operator=(const LiveInterval& rhs) LLVM_DELETED_FUNCTION;
467 inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
472 /// Helper class for performant LiveInterval bulk updates.
474 /// Calling LiveInterval::addRange() repeatedly can be expensive on large
475 /// live ranges because segments after the insertion point may need to be
476 /// shifted. The LiveRangeUpdater class can defer the shifting when adding
477 /// many segments in order.
479 /// The LiveInterval will be in an invalid state until flush() is called.
480 class LiveRangeUpdater {
483 LiveInterval::iterator WriteI;
484 LiveInterval::iterator ReadI;
485 SmallVector<LiveRange, 16> Spills;
489 /// Create a LiveRangeUpdater for adding segments to LI.
490 /// LI will temporarily be in an invalid state until flush() is called.
491 LiveRangeUpdater(LiveInterval *li = 0) : LI(li) {}
493 ~LiveRangeUpdater() { flush(); }
495 /// Add a segment to LI and coalesce when possible, just like LI.addRange().
496 /// Segments should be added in increasing start order for best performance.
499 void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
500 add(LiveRange(Start, End, VNI));
503 /// Return true if the LI is currently in an invalid state, and flush()
504 /// needs to be called.
505 bool isDirty() const { return LastStart.isValid(); }
507 /// Flush the updater state to LI so it is valid and contains all added
511 /// Select a different destination live range.
512 void setDest(LiveInterval *li) {
513 if (LI != li && isDirty())
518 /// Get the current destination live range.
519 LiveInterval *getDest() const { return LI; }
522 void print(raw_ostream&) const;
525 inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
530 /// LiveRangeQuery - Query information about a live range around a given
531 /// instruction. This class hides the implementation details of live ranges,
532 /// and it should be used as the primary interface for examining live ranges
533 /// around instructions.
535 class LiveRangeQuery {
542 /// Create a LiveRangeQuery for the given live range and instruction index.
543 /// The sub-instruction slot of Idx doesn't matter, only the instruction it
544 /// refers to is considered.
545 LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
546 : EarlyVal(0), LateVal(0), Kill(false) {
547 // Find the segment that enters the instruction.
548 LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
549 LiveInterval::const_iterator E = LI.end();
552 // Is this an instruction live-in segment?
553 // If Idx is the start index of a basic block, include live-in segments
554 // that start at Idx.getBaseIndex().
555 if (I->start <= Idx.getBaseIndex()) {
558 // Move to the potentially live-out segment.
559 if (SlotIndex::isSameInstr(Idx, I->end)) {
564 // Special case: A PHIDef value can have its def in the middle of a
565 // segment if the value happens to be live out of the layout
567 // Such a value is not live-in.
568 if (EarlyVal->def == Idx.getBaseIndex())
571 // I now points to the segment that may be live-through, or defined by
572 // this instr. Ignore segments starting after the current instr.
573 if (SlotIndex::isEarlierInstr(Idx, I->start))
579 /// Return the value that is live-in to the instruction. This is the value
580 /// that will be read by the instruction's use operands. Return NULL if no
581 /// value is live-in.
582 VNInfo *valueIn() const {
586 /// Return true if the live-in value is killed by this instruction. This
587 /// means that either the live range ends at the instruction, or it changes
589 bool isKill() const {
593 /// Return true if this instruction has a dead def.
594 bool isDeadDef() const {
595 return EndPoint.isDead();
598 /// Return the value leaving the instruction, if any. This can be a
599 /// live-through value, or a live def. A dead def returns NULL.
600 VNInfo *valueOut() const {
601 return isDeadDef() ? 0 : LateVal;
604 /// Return the value defined by this instruction, if any. This includes
605 /// dead defs, it is the value created by the instruction's def operands.
606 VNInfo *valueDefined() const {
607 return EarlyVal == LateVal ? 0 : LateVal;
610 /// Return the end point of the last live range segment to interact with
611 /// the instruction, if any.
613 /// The end point is an invalid SlotIndex only if the live range doesn't
614 /// intersect the instruction at all.
616 /// The end point may be at or past the end of the instruction's basic
617 /// block. That means the value was live out of the block.
618 SlotIndex endPoint() const {
623 /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
624 /// LiveInterval into equivalence clases of connected components. A
625 /// LiveInterval that has multiple connected components can be broken into
626 /// multiple LiveIntervals.
628 /// Given a LiveInterval that may have multiple connected components, run:
630 /// unsigned numComps = ConEQ.Classify(LI);
631 /// if (numComps > 1) {
632 /// // allocate numComps-1 new LiveIntervals into LIS[1..]
633 /// ConEQ.Distribute(LIS);
636 class ConnectedVNInfoEqClasses {
638 IntEqClasses EqClass;
640 // Note that values a and b are connected.
641 void Connect(unsigned a, unsigned b);
646 explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
648 /// Classify - Classify the values in LI into connected components.
649 /// Return the number of connected components.
650 unsigned Classify(const LiveInterval *LI);
652 /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
653 /// the equivalence class assigned the VNI.
654 unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
656 /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
657 /// for each connected component. LIV must have a LiveInterval for each
658 /// connected component. The LiveIntervals in Liv[1..] must be empty.
659 /// Instructions using LIV[0] are rewritten.
660 void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);