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 LiveInterval class. Given some numbering of each
11 // 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 segment is represented as an instance of LiveInterval::Segment,
17 // and the whole range 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 instructions 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 /// LiveInterval - This class represents some number of live segments for a
82 /// register or value. This class also contains a bit of register allocator
87 /// This represents a simple continuous liveness interval for a value.
88 /// The start point is inclusive, the end point exclusive. These intervals
89 /// are rendered as [start,end).
91 SlotIndex start; // Start point of the interval (inclusive)
92 SlotIndex end; // End point of the interval (exclusive)
93 VNInfo *valno; // identifier for the value contained in this segment.
95 Segment() : valno(0) {}
97 Segment(SlotIndex S, SlotIndex E, VNInfo *V)
98 : start(S), end(E), valno(V) {
99 assert(S < E && "Cannot create empty or backwards segment");
102 /// Return true if the index is covered by this segment.
103 bool contains(SlotIndex I) const {
104 return start <= I && I < end;
107 /// Return true if the given interval, [S, E), is covered by this segment.
108 bool containsInterval(SlotIndex S, SlotIndex E) const {
109 assert((S < E) && "Backwards interval?");
110 return (start <= S && S < end) && (start < E && E <= end);
113 bool operator<(const Segment &Other) const {
114 return start < Other.start || (start == Other.start && end < Other.end);
116 bool operator==(const Segment &Other) const {
117 return start == Other.start && end == Other.end;
123 typedef SmallVector<Segment,4> Segments;
124 typedef SmallVector<VNInfo*,4> VNInfoList;
126 const unsigned reg; // the register or stack slot of this interval.
127 float weight; // weight of this interval
128 Segments segments; // the segments in which this register is live
129 VNInfoList valnos; // value#'s
131 LiveInterval(unsigned Reg, float Weight)
132 : reg(Reg), weight(Weight) {}
134 typedef Segments::iterator iterator;
135 iterator begin() { return segments.begin(); }
136 iterator end() { return segments.end(); }
138 typedef Segments::const_iterator const_iterator;
139 const_iterator begin() const { return segments.begin(); }
140 const_iterator end() const { return segments.end(); }
142 typedef VNInfoList::iterator vni_iterator;
143 vni_iterator vni_begin() { return valnos.begin(); }
144 vni_iterator vni_end() { return valnos.end(); }
146 typedef VNInfoList::const_iterator const_vni_iterator;
147 const_vni_iterator vni_begin() const { return valnos.begin(); }
148 const_vni_iterator vni_end() const { return valnos.end(); }
150 /// advanceTo - Advance the specified iterator to point to the Segment
151 /// containing the specified position, or end() if the position is past the
152 /// end of the interval. If no Segment contains this position, but the
153 /// position is in a hole, this method returns an iterator pointing to the
154 /// Segment immediately after the hole.
155 iterator advanceTo(iterator I, SlotIndex Pos) {
157 if (Pos >= endIndex())
159 while (I->end <= Pos) ++I;
163 /// find - Return an iterator pointing to the first segment that ends after
164 /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
165 /// when searching large intervals.
167 /// If Pos is contained in a Segment, that segment is returned.
168 /// If Pos is in a hole, the following Segment is returned.
169 /// If Pos is beyond endIndex, end() is returned.
170 iterator find(SlotIndex Pos);
172 const_iterator find(SlotIndex Pos) const {
173 return const_cast<LiveInterval*>(this)->find(Pos);
181 size_t size() const {
182 return segments.size();
185 bool hasAtLeastOneValue() const { return !valnos.empty(); }
187 bool containsOneValue() const { return valnos.size() == 1; }
189 unsigned getNumValNums() const { return (unsigned)valnos.size(); }
191 /// getValNumInfo - Returns pointer to the specified val#.
193 inline VNInfo *getValNumInfo(unsigned ValNo) {
194 return valnos[ValNo];
196 inline const VNInfo *getValNumInfo(unsigned ValNo) const {
197 return valnos[ValNo];
200 /// containsValue - Returns true if VNI belongs to this interval.
201 bool containsValue(const VNInfo *VNI) const {
202 return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
205 /// getNextValue - Create a new value number and return it. MIIdx specifies
206 /// the instruction that defines the value number.
207 VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
209 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
210 valnos.push_back(VNI);
214 /// createDeadDef - Make sure the interval has a value defined at Def.
215 /// If one already exists, return it. Otherwise allocate a new value and
216 /// add liveness for a dead def.
217 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
219 /// Create a copy of the given value. The new value will be identical except
220 /// for the Value number.
221 VNInfo *createValueCopy(const VNInfo *orig,
222 VNInfo::Allocator &VNInfoAllocator) {
224 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
225 valnos.push_back(VNI);
229 /// RenumberValues - Renumber all values in order of appearance and remove
231 void RenumberValues();
233 /// MergeValueNumberInto - This method is called when two value numbers
234 /// are found to be equivalent. This eliminates V1, replacing all
235 /// segments with the V1 value number with the V2 value number. This can
236 /// cause merging of V1/V2 values numbers and compaction of the value space.
237 VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
239 /// Merge all of the live segments of a specific val# in RHS into this live
240 /// interval as the specified value number. The segments in RHS are allowed
241 /// to overlap with segments in the current interval, it will replace the
242 /// value numbers of the overlaped live segments with the specified value
244 void MergeSegmentsInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
246 /// MergeValueInAsValue - Merge all of the segments of a specific val#
247 /// in RHS into this live interval as the specified value number.
248 /// The segments in RHS are allowed to overlap with segments in the
249 /// current interval, but only if the overlapping segments have the
250 /// specified value number.
251 void MergeValueInAsValue(const LiveInterval &RHS,
252 const VNInfo *RHSValNo, VNInfo *LHSValNo);
254 bool empty() const { return segments.empty(); }
256 /// beginIndex - Return the lowest numbered slot covered by interval.
257 SlotIndex beginIndex() const {
258 assert(!empty() && "Call to beginIndex() on empty interval.");
259 return segments.front().start;
262 /// endNumber - return the maximum point of the interval of the whole,
264 SlotIndex endIndex() const {
265 assert(!empty() && "Call to endIndex() on empty interval.");
266 return segments.back().end;
269 bool expiredAt(SlotIndex index) const {
270 return index >= endIndex();
273 bool liveAt(SlotIndex index) const {
274 const_iterator r = find(index);
275 return r != end() && r->start <= index;
278 /// Return the segment that contains the specified index, or null if there
280 const Segment *getSegmentContaining(SlotIndex Idx) const {
281 const_iterator I = FindSegmentContaining(Idx);
282 return I == end() ? 0 : &*I;
285 /// Return the live segment that contains the specified index, or null if
287 Segment *getSegmentContaining(SlotIndex Idx) {
288 iterator I = FindSegmentContaining(Idx);
289 return I == end() ? 0 : &*I;
292 /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
293 VNInfo *getVNInfoAt(SlotIndex Idx) const {
294 const_iterator I = FindSegmentContaining(Idx);
295 return I == end() ? 0 : I->valno;
298 /// getVNInfoBefore - Return the VNInfo that is live up to but not
299 /// necessarilly including Idx, or NULL. Use this to find the reaching def
300 /// used by an instruction at this SlotIndex position.
301 VNInfo *getVNInfoBefore(SlotIndex Idx) const {
302 const_iterator I = FindSegmentContaining(Idx.getPrevSlot());
303 return I == end() ? 0 : I->valno;
306 /// Return an iterator to the segment that contains the specified index, or
307 /// end() if there is none.
308 iterator FindSegmentContaining(SlotIndex Idx) {
309 iterator I = find(Idx);
310 return I != end() && I->start <= Idx ? I : end();
313 const_iterator FindSegmentContaining(SlotIndex Idx) const {
314 const_iterator I = find(Idx);
315 return I != end() && I->start <= Idx ? I : end();
318 /// overlaps - Return true if the intersection of the two live intervals is
320 bool overlaps(const LiveInterval& other) const {
323 return overlapsFrom(other, other.begin());
326 /// overlaps - Return true if the two intervals have overlapping segments
327 /// that are not coalescable according to CP.
329 /// Overlapping segments where one interval is defined by a coalescable
330 /// copy are allowed.
331 bool overlaps(const LiveInterval &Other, const CoalescerPair &CP,
332 const SlotIndexes&) const;
334 /// overlaps - Return true if the live interval overlaps an interval
335 /// specified by [Start, End).
336 bool overlaps(SlotIndex Start, SlotIndex End) const;
338 /// overlapsFrom - Return true if the intersection of the two live intervals
339 /// is not empty. The specified iterator is a hint that we can begin
340 /// scanning the Other interval starting at I.
341 bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
343 /// Add the specified Segment to this interval, merging segments as
344 /// appropriate. This returns an iterator to the inserted segment (which
345 /// may have grown since it was inserted).
346 iterator addSegment(Segment S) {
347 return addSegmentFrom(S, segments.begin());
350 /// extendInBlock - If this interval is live before Kill in the basic block
351 /// that starts at StartIdx, extend it to be live up to Kill, and return
352 /// the value. If there is no segment before Kill, return NULL.
353 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
355 /// join - Join two live intervals (this, and other) together. This applies
356 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
357 /// the intervals are not joinable, this aborts.
358 void join(LiveInterval &Other,
359 const int *ValNoAssignments,
360 const int *RHSValNoAssignments,
361 SmallVectorImpl<VNInfo *> &NewVNInfo);
363 /// True iff this segment is a single segment that lies between the
364 /// specified boundaries, exclusively. Vregs live across a backedge are not
365 /// considered local. The boundaries are expected to lie within an extended
366 /// basic block, so vregs that are not live out should contain no holes.
367 bool isLocal(SlotIndex Start, SlotIndex End) const {
368 return beginIndex() > Start.getBaseIndex() &&
369 endIndex() < End.getBoundaryIndex();
372 /// Remove the specified segment from this interval. Note that the segment
373 /// must be a single Segment in its entirety.
374 void removeSegment(SlotIndex Start, SlotIndex End,
375 bool RemoveDeadValNo = false);
377 void removeSegment(Segment S, bool RemoveDeadValNo = false) {
378 removeSegment(S.start, S.end, RemoveDeadValNo);
381 /// removeValNo - Remove all the segments defined by the specified value#.
382 /// Also remove the value# from value# list.
383 void removeValNo(VNInfo *ValNo);
385 /// getSize - Returns the sum of sizes of all the Segment's.
387 unsigned getSize() const;
389 /// Returns true if the live interval is zero length, i.e. no segments
390 /// span instructions. It doesn't pay to spill such an interval.
391 bool isZeroLength(SlotIndexes *Indexes) const {
392 for (const_iterator i = begin(), e = end(); i != e; ++i)
393 if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
394 i->end.getBaseIndex())
399 /// isSpillable - Can this interval be spilled?
400 bool isSpillable() const {
401 return weight != HUGE_VALF;
404 /// markNotSpillable - Mark interval as not spillable
405 void markNotSpillable() {
409 bool operator<(const LiveInterval& other) const {
410 const SlotIndex &thisIndex = beginIndex();
411 const SlotIndex &otherIndex = other.beginIndex();
412 return (thisIndex < otherIndex ||
413 (thisIndex == otherIndex && reg < other.reg));
416 void print(raw_ostream &OS) const;
419 /// \brief Walk the interval and assert if any invariants fail to hold.
421 /// Note that this is a no-op when asserts are disabled.
423 void verify() const {}
430 iterator addSegmentFrom(Segment S, iterator From);
431 void extendSegmentEndTo(iterator I, SlotIndex NewEnd);
432 iterator extendSegmentStartTo(iterator I, SlotIndex NewStr);
433 void markValNoForDeletion(VNInfo *V);
435 LiveInterval& operator=(const LiveInterval& rhs) LLVM_DELETED_FUNCTION;
439 inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
444 raw_ostream &operator<<(raw_ostream &OS, const LiveInterval::Segment &S);
446 inline bool operator<(SlotIndex V, const LiveInterval::Segment &S) {
450 inline bool operator<(const LiveInterval::Segment &S, SlotIndex V) {
454 /// Helper class for performant LiveInterval bulk updates.
456 /// Calling LiveInterval::addSegment() repeatedly can be expensive on large
457 /// live ranges because segments after the insertion point may need to be
458 /// shifted. The LiveRangeUpdater class can defer the shifting when adding
459 /// many segments in order.
461 /// The LiveInterval will be in an invalid state until flush() is called.
462 class LiveRangeUpdater {
465 LiveInterval::iterator WriteI;
466 LiveInterval::iterator ReadI;
467 SmallVector<LiveInterval::Segment, 16> Spills;
471 /// Create a LiveRangeUpdater for adding segments to LI.
472 /// LI will temporarily be in an invalid state until flush() is called.
473 LiveRangeUpdater(LiveInterval *li = 0) : LI(li) {}
475 ~LiveRangeUpdater() { flush(); }
477 /// Add a segment to LI and coalesce when possible, just like
478 /// LI.addSegment(). Segments should be added in increasing start order for
479 /// best performance.
480 void add(LiveInterval::Segment);
482 void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
483 add(LiveInterval::Segment(Start, End, VNI));
486 /// Return true if the LI is currently in an invalid state, and flush()
487 /// needs to be called.
488 bool isDirty() const { return LastStart.isValid(); }
490 /// Flush the updater state to LI so it is valid and contains all added
494 /// Select a different destination live range.
495 void setDest(LiveInterval *li) {
496 if (LI != li && isDirty())
501 /// Get the current destination live range.
502 LiveInterval *getDest() const { return LI; }
505 void print(raw_ostream&) const;
508 inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
513 /// LiveRangeQuery - Query information about a live range around a given
514 /// instruction. This class hides the implementation details of live ranges,
515 /// and it should be used as the primary interface for examining live ranges
516 /// around instructions.
518 class LiveRangeQuery {
525 /// Create a LiveRangeQuery for the given live range and instruction index.
526 /// The sub-instruction slot of Idx doesn't matter, only the instruction it
527 /// refers to is considered.
528 LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
529 : EarlyVal(0), LateVal(0), Kill(false) {
530 // Find the segment that enters the instruction.
531 LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
532 LiveInterval::const_iterator E = LI.end();
535 // Is this an instruction live-in segment?
536 // If Idx is the start index of a basic block, include live-in segments
537 // that start at Idx.getBaseIndex().
538 if (I->start <= Idx.getBaseIndex()) {
541 // Move to the potentially live-out segment.
542 if (SlotIndex::isSameInstr(Idx, I->end)) {
547 // Special case: A PHIDef value can have its def in the middle of a
548 // segment if the value happens to be live out of the layout
550 // Such a value is not live-in.
551 if (EarlyVal->def == Idx.getBaseIndex())
554 // I now points to the segment that may be live-through, or defined by
555 // this instr. Ignore segments starting after the current instr.
556 if (SlotIndex::isEarlierInstr(Idx, I->start))
562 /// Return the value that is live-in to the instruction. This is the value
563 /// that will be read by the instruction's use operands. Return NULL if no
564 /// value is live-in.
565 VNInfo *valueIn() const {
569 /// Return true if the live-in value is killed by this instruction. This
570 /// means that either the live range ends at the instruction, or it changes
572 bool isKill() const {
576 /// Return true if this instruction has a dead def.
577 bool isDeadDef() const {
578 return EndPoint.isDead();
581 /// Return the value leaving the instruction, if any. This can be a
582 /// live-through value, or a live def. A dead def returns NULL.
583 VNInfo *valueOut() const {
584 return isDeadDef() ? 0 : LateVal;
587 /// Return the value defined by this instruction, if any. This includes
588 /// dead defs, it is the value created by the instruction's def operands.
589 VNInfo *valueDefined() const {
590 return EarlyVal == LateVal ? 0 : LateVal;
593 /// Return the end point of the last live range segment to interact with
594 /// the instruction, if any.
596 /// The end point is an invalid SlotIndex only if the live range doesn't
597 /// intersect the instruction at all.
599 /// The end point may be at or past the end of the instruction's basic
600 /// block. That means the value was live out of the block.
601 SlotIndex endPoint() const {
606 /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
607 /// LiveInterval into equivalence clases of connected components. A
608 /// LiveInterval that has multiple connected components can be broken into
609 /// multiple LiveIntervals.
611 /// Given a LiveInterval that may have multiple connected components, run:
613 /// unsigned numComps = ConEQ.Classify(LI);
614 /// if (numComps > 1) {
615 /// // allocate numComps-1 new LiveIntervals into LIS[1..]
616 /// ConEQ.Distribute(LIS);
619 class ConnectedVNInfoEqClasses {
621 IntEqClasses EqClass;
623 // Note that values a and b are connected.
624 void Connect(unsigned a, unsigned b);
629 explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
631 /// Classify - Classify the values in LI into connected components.
632 /// Return the number of connected components.
633 unsigned Classify(const LiveInterval *LI);
635 /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
636 /// the equivalence class assigned the VNI.
637 unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
639 /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
640 /// for each connected component. LIV must have a LiveInterval for each
641 /// connected component. The LiveIntervals in Liv[1..] must be empty.
642 /// Instructions using LIV[0] are rewritten.
643 void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);