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/Support/Allocator.h"
26 #include "llvm/Support/AlignOf.h"
27 #include "llvm/CodeGen/SlotIndexes.h"
34 class MachineRegisterInfo;
35 class TargetRegisterInfo;
38 /// VNInfo - Value Number Information.
39 /// This class holds information about a machine level values, including
40 /// definition and use points.
52 typedef BumpPtrAllocator Allocator;
54 /// The ID number of this value.
57 /// The index of the defining instruction.
60 /// VNInfo constructor.
61 VNInfo(unsigned i, SlotIndex d)
62 : flags(0), id(i), def(d)
65 /// VNInfo construtor, copies values from orig, except for the value number.
66 VNInfo(unsigned i, const VNInfo &orig)
67 : flags(orig.flags), id(i), def(orig.def)
70 /// Copy from the parameter into this VNInfo.
71 void copyFrom(VNInfo &src) {
76 /// Used for copying value number info.
77 unsigned getFlags() const { return flags; }
78 void setFlags(unsigned flags) { this->flags = flags; }
80 /// Merge flags from another VNInfo
81 void mergeFlags(const VNInfo *VNI) {
82 flags = (flags | VNI->flags) & ~IS_UNUSED;
85 /// Returns true if one or more kills are PHI nodes.
86 /// Obsolete, do not use!
87 bool hasPHIKill() const { return flags & HAS_PHI_KILL; }
88 /// Set the PHI kill flag on this value.
89 void setHasPHIKill(bool hasKill) {
91 flags |= HAS_PHI_KILL;
93 flags &= ~HAS_PHI_KILL;
96 /// Returns true if this value is defined by a PHI instruction (or was,
97 /// PHI instrucions may have been eliminated).
98 /// PHI-defs begin at a block boundary, all other defs begin at register or
100 bool isPHIDef() const { return def.isBlock(); }
102 /// Returns true if this value is unused.
103 bool isUnused() const { return flags & IS_UNUSED; }
104 /// Set the "is unused" flag on this value.
105 void setIsUnused(bool unused) {
113 /// LiveRange structure - This represents a simple register range in the
114 /// program, with an inclusive start point and an exclusive end point.
115 /// These ranges are rendered as [start,end).
117 SlotIndex start; // Start point of the interval (inclusive)
118 SlotIndex end; // End point of the interval (exclusive)
119 VNInfo *valno; // identifier for the value contained in this interval.
121 LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
122 : start(S), end(E), valno(V) {
124 assert(S < E && "Cannot create empty or backwards range");
127 /// contains - Return true if the index is covered by this range.
129 bool contains(SlotIndex I) const {
130 return start <= I && I < end;
133 /// containsRange - Return true if the given range, [S, E), is covered by
135 bool containsRange(SlotIndex S, SlotIndex E) const {
136 assert((S < E) && "Backwards interval?");
137 return (start <= S && S < end) && (start < E && E <= end);
140 bool operator<(const LiveRange &LR) const {
141 return start < LR.start || (start == LR.start && end < LR.end);
143 bool operator==(const LiveRange &LR) const {
144 return start == LR.start && end == LR.end;
148 void print(raw_ostream &os) const;
151 LiveRange(); // DO NOT IMPLEMENT
154 template <> struct isPodLike<LiveRange> { static const bool value = true; };
156 raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
159 inline bool operator<(SlotIndex V, const LiveRange &LR) {
163 inline bool operator<(const LiveRange &LR, SlotIndex V) {
167 /// LiveInterval - This class represents some number of live ranges for a
168 /// register or value. This class also contains a bit of register allocator
173 typedef SmallVector<LiveRange,4> Ranges;
174 typedef SmallVector<VNInfo*,4> VNInfoList;
176 const unsigned reg; // the register or stack slot of this interval.
177 float weight; // weight of this interval
178 Ranges ranges; // the ranges in which this register is live
179 VNInfoList valnos; // value#'s
192 LiveInterval(unsigned Reg, float Weight)
193 : reg(Reg), weight(Weight) {}
195 typedef Ranges::iterator iterator;
196 iterator begin() { return ranges.begin(); }
197 iterator end() { return ranges.end(); }
199 typedef Ranges::const_iterator const_iterator;
200 const_iterator begin() const { return ranges.begin(); }
201 const_iterator end() const { return ranges.end(); }
203 typedef VNInfoList::iterator vni_iterator;
204 vni_iterator vni_begin() { return valnos.begin(); }
205 vni_iterator vni_end() { return valnos.end(); }
207 typedef VNInfoList::const_iterator const_vni_iterator;
208 const_vni_iterator vni_begin() const { return valnos.begin(); }
209 const_vni_iterator vni_end() const { return valnos.end(); }
211 /// advanceTo - Advance the specified iterator to point to the LiveRange
212 /// containing the specified position, or end() if the position is past the
213 /// end of the interval. If no LiveRange contains this position, but the
214 /// position is in a hole, this method returns an iterator pointing to the
215 /// LiveRange immediately after the hole.
216 iterator advanceTo(iterator I, SlotIndex Pos) {
218 if (Pos >= endIndex())
220 while (I->end <= Pos) ++I;
224 /// find - Return an iterator pointing to the first range that ends after
225 /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
226 /// when searching large intervals.
228 /// If Pos is contained in a LiveRange, that range is returned.
229 /// If Pos is in a hole, the following LiveRange is returned.
230 /// If Pos is beyond endIndex, end() is returned.
231 iterator find(SlotIndex Pos);
233 const_iterator find(SlotIndex Pos) const {
234 return const_cast<LiveInterval*>(this)->find(Pos);
242 bool hasAtLeastOneValue() const { return !valnos.empty(); }
244 bool containsOneValue() const { return valnos.size() == 1; }
246 unsigned getNumValNums() const { return (unsigned)valnos.size(); }
248 /// getValNumInfo - Returns pointer to the specified val#.
250 inline VNInfo *getValNumInfo(unsigned ValNo) {
251 return valnos[ValNo];
253 inline const VNInfo *getValNumInfo(unsigned ValNo) const {
254 return valnos[ValNo];
257 /// containsValue - Returns true if VNI belongs to this interval.
258 bool containsValue(const VNInfo *VNI) const {
259 return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
262 /// getNextValue - Create a new value number and return it. MIIdx specifies
263 /// the instruction that defines the value number.
264 VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
266 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
267 valnos.push_back(VNI);
271 /// createDeadDef - Make sure the interval has a value defined at Def.
272 /// If one already exists, return it. Otherwise allocate a new value and
273 /// add liveness for a dead def.
274 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
276 /// Create a copy of the given value. The new value will be identical except
277 /// for the Value number.
278 VNInfo *createValueCopy(const VNInfo *orig,
279 VNInfo::Allocator &VNInfoAllocator) {
281 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
282 valnos.push_back(VNI);
286 /// RenumberValues - Renumber all values in order of appearance and remove
288 void RenumberValues(LiveIntervals &lis);
290 /// MergeValueNumberInto - This method is called when two value nubmers
291 /// are found to be equivalent. This eliminates V1, replacing all
292 /// LiveRanges with the V1 value number with the V2 value number. This can
293 /// cause merging of V1/V2 values numbers and compaction of the value space.
294 VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
296 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
297 /// in RHS into this live interval as the specified value number.
298 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
299 /// current interval, it will replace the value numbers of the overlaped
300 /// live ranges with the specified value number.
301 void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
303 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
304 /// in RHS into this live interval as the specified value number.
305 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
306 /// current interval, but only if the overlapping LiveRanges have the
307 /// specified value number.
308 void MergeValueInAsValue(const LiveInterval &RHS,
309 const VNInfo *RHSValNo, VNInfo *LHSValNo);
311 /// Copy - Copy the specified live interval. This copies all the fields
312 /// except for the register of the interval.
313 void Copy(const LiveInterval &RHS, MachineRegisterInfo *MRI,
314 VNInfo::Allocator &VNInfoAllocator);
316 bool empty() const { return ranges.empty(); }
318 /// beginIndex - Return the lowest numbered slot covered by interval.
319 SlotIndex beginIndex() const {
320 assert(!empty() && "Call to beginIndex() on empty interval.");
321 return ranges.front().start;
324 /// endNumber - return the maximum point of the interval of the whole,
326 SlotIndex endIndex() const {
327 assert(!empty() && "Call to endIndex() on empty interval.");
328 return ranges.back().end;
331 bool expiredAt(SlotIndex index) const {
332 return index >= endIndex();
335 bool liveAt(SlotIndex index) const {
336 const_iterator r = find(index);
337 return r != end() && r->start <= index;
340 /// killedAt - Return true if a live range ends at index. Note that the kill
341 /// point is not contained in the half-open live range. It is usually the
342 /// getDefIndex() slot following its last use.
343 bool killedAt(SlotIndex index) const {
344 const_iterator r = find(index.getRegSlot(true));
345 return r != end() && r->end == index;
348 /// killedInRange - Return true if the interval has kills in [Start,End).
349 /// Note that the kill point is considered the end of a live range, so it is
350 /// not contained in the live range. If a live range ends at End, it won't
351 /// be counted as a kill by this method.
352 bool killedInRange(SlotIndex Start, SlotIndex End) const;
354 /// getLiveRangeContaining - Return the live range that contains the
355 /// specified index, or null if there is none.
356 const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
357 const_iterator I = FindLiveRangeContaining(Idx);
358 return I == end() ? 0 : &*I;
361 /// getLiveRangeContaining - Return the live range that contains the
362 /// specified index, or null if there is none.
363 LiveRange *getLiveRangeContaining(SlotIndex Idx) {
364 iterator I = FindLiveRangeContaining(Idx);
365 return I == end() ? 0 : &*I;
368 /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
369 VNInfo *getVNInfoAt(SlotIndex Idx) const {
370 const_iterator I = FindLiveRangeContaining(Idx);
371 return I == end() ? 0 : I->valno;
374 /// getVNInfoBefore - Return the VNInfo that is live up to but not
375 /// necessarilly including Idx, or NULL. Use this to find the reaching def
376 /// used by an instruction at this SlotIndex position.
377 VNInfo *getVNInfoBefore(SlotIndex Idx) const {
378 const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
379 return I == end() ? 0 : I->valno;
382 /// FindLiveRangeContaining - Return an iterator to the live range that
383 /// contains the specified index, or end() if there is none.
384 iterator FindLiveRangeContaining(SlotIndex Idx) {
385 iterator I = find(Idx);
386 return I != end() && I->start <= Idx ? I : end();
389 const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
390 const_iterator I = find(Idx);
391 return I != end() && I->start <= Idx ? I : end();
394 /// overlaps - Return true if the intersection of the two live intervals is
396 bool overlaps(const LiveInterval& other) const {
399 return overlapsFrom(other, other.begin());
402 /// overlaps - Return true if the live interval overlaps a range specified
404 bool overlaps(SlotIndex Start, SlotIndex End) const;
406 /// overlapsFrom - Return true if the intersection of the two live intervals
407 /// is not empty. The specified iterator is a hint that we can begin
408 /// scanning the Other interval starting at I.
409 bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
411 /// addRange - Add the specified LiveRange to this interval, merging
412 /// intervals as appropriate. This returns an iterator to the inserted live
413 /// range (which may have grown since it was inserted.
414 void addRange(LiveRange LR) {
415 addRangeFrom(LR, ranges.begin());
418 /// extendInBlock - If this interval is live before Kill in the basic block
419 /// that starts at StartIdx, extend it to be live up to Kill, and return
420 /// the value. If there is no live range before Kill, return NULL.
421 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
423 /// join - Join two live intervals (this, and other) together. This applies
424 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
425 /// the intervals are not joinable, this aborts.
426 void join(LiveInterval &Other,
427 const int *ValNoAssignments,
428 const int *RHSValNoAssignments,
429 SmallVector<VNInfo*, 16> &NewVNInfo,
430 MachineRegisterInfo *MRI);
432 /// isInOneLiveRange - Return true if the range specified is entirely in the
433 /// a single LiveRange of the live interval.
434 bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
435 const_iterator r = find(Start);
436 return r != end() && r->containsRange(Start, End);
439 /// removeRange - Remove the specified range from this interval. Note that
440 /// the range must be a single LiveRange in its entirety.
441 void removeRange(SlotIndex Start, SlotIndex End,
442 bool RemoveDeadValNo = false);
444 void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
445 removeRange(LR.start, LR.end, RemoveDeadValNo);
448 /// removeValNo - Remove all the ranges defined by the specified value#.
449 /// Also remove the value# from value# list.
450 void removeValNo(VNInfo *ValNo);
452 /// getSize - Returns the sum of sizes of all the LiveRange's.
454 unsigned getSize() const;
456 /// Returns true if the live interval is zero length, i.e. no live ranges
457 /// span instructions. It doesn't pay to spill such an interval.
458 bool isZeroLength(SlotIndexes *Indexes) const {
459 for (const_iterator i = begin(), e = end(); i != e; ++i)
460 if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
461 i->end.getBaseIndex())
466 /// isSpillable - Can this interval be spilled?
467 bool isSpillable() const {
468 return weight != HUGE_VALF;
471 /// markNotSpillable - Mark interval as not spillable
472 void markNotSpillable() {
476 bool operator<(const LiveInterval& other) const {
477 const SlotIndex &thisIndex = beginIndex();
478 const SlotIndex &otherIndex = other.beginIndex();
479 return (thisIndex < otherIndex ||
480 (thisIndex == otherIndex && reg < other.reg));
483 void print(raw_ostream &OS) const;
486 /// \brief Walk the interval and assert if any invariants fail to hold.
488 /// Note that this is a no-op when asserts are disabled.
490 void verify() const {}
497 Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
498 void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
499 Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
500 void markValNoForDeletion(VNInfo *V);
501 void mergeIntervalRanges(const LiveInterval &RHS,
502 VNInfo *LHSValNo = 0,
503 const VNInfo *RHSValNo = 0);
505 LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
509 inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
514 /// LiveRangeQuery - Query information about a live range around a given
515 /// instruction. This class hides the implementation details of live ranges,
516 /// and it should be used as the primary interface for examining live ranges
517 /// around instructions.
519 class LiveRangeQuery {
526 /// Create a LiveRangeQuery for the given live range and instruction index.
527 /// The sub-instruction slot of Idx doesn't matter, only the instruction it
528 /// refers to is considered.
529 LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
530 : EarlyVal(0), LateVal(0), Kill(false) {
531 // Find the segment that enters the instruction.
532 LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
533 LiveInterval::const_iterator E = LI.end();
536 // Is this an instruction live-in segment?
537 if (SlotIndex::isEarlierInstr(I->start, Idx)) {
540 // Move to the potentially live-out segment.
541 if (SlotIndex::isSameInstr(Idx, I->end)) {
547 // I now points to the segment that may be live-through, or defined by
548 // this instr. Ignore segments starting after the current instr.
549 if (SlotIndex::isEarlierInstr(Idx, I->start))
555 /// Return the value that is live-in to the instruction. This is the value
556 /// that will be read by the instruction's use operands. Return NULL if no
557 /// value is live-in.
558 VNInfo *valueIn() const {
562 /// Return true if the live-in value is killed by this instruction. This
563 /// means that either the live range ends at the instruction, or it changes
565 bool isKill() const {
569 /// Return true if this instruction has a dead def.
570 bool isDeadDef() const {
571 return EndPoint.isDead();
574 /// Return the value leaving the instruction, if any. This can be a
575 /// live-through value, or a live def. A dead def returns NULL.
576 VNInfo *valueOut() const {
577 return isDeadDef() ? 0 : LateVal;
580 /// Return the value defined by this instruction, if any. This includes
581 /// dead defs, it is the value created by the instruction's def operands.
582 VNInfo *valueDefined() const {
583 return EarlyVal == LateVal ? 0 : LateVal;
586 /// Return the end point of the last live range segment to interact with
587 /// the instruction, if any.
589 /// The end point is an invalid SlotIndex only if the live range doesn't
590 /// intersect the instruction at all.
592 /// The end point may be at or past the end of the instruction's basic
593 /// block. That means the value was live out of the block.
594 SlotIndex endPoint() const {
599 /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
600 /// LiveInterval into equivalence clases of connected components. A
601 /// LiveInterval that has multiple connected components can be broken into
602 /// multiple LiveIntervals.
604 /// Given a LiveInterval that may have multiple connected components, run:
606 /// unsigned numComps = ConEQ.Classify(LI);
607 /// if (numComps > 1) {
608 /// // allocate numComps-1 new LiveIntervals into LIS[1..]
609 /// ConEQ.Distribute(LIS);
612 class ConnectedVNInfoEqClasses {
614 IntEqClasses EqClass;
616 // Note that values a and b are connected.
617 void Connect(unsigned a, unsigned b);
622 explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
624 /// Classify - Classify the values in LI into connected components.
625 /// Return the number of connected components.
626 unsigned Classify(const LiveInterval *LI);
628 /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
629 /// the equivalence class assigned the VNI.
630 unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
632 /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
633 /// for each connected component. LIV must have a LiveInterval for each
634 /// connected component. The LiveIntervals in Liv[1..] must be empty.
635 /// Instructions using LIV[0] are rewritten.
636 void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);