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.
53 typedef BumpPtrAllocator Allocator;
55 /// The ID number of this value.
58 /// The index of the defining instruction.
61 /// VNInfo constructor.
62 VNInfo(unsigned i, SlotIndex d)
63 : flags(0), id(i), def(d)
66 /// VNInfo construtor, copies values from orig, except for the value number.
67 VNInfo(unsigned i, const VNInfo &orig)
68 : flags(orig.flags), id(i), def(orig.def)
71 /// Copy from the parameter into this VNInfo.
72 void copyFrom(VNInfo &src) {
77 /// Used for copying value number info.
78 unsigned getFlags() const { return flags; }
79 void setFlags(unsigned flags) { this->flags = flags; }
81 /// Merge flags from another VNInfo
82 void mergeFlags(const VNInfo *VNI) {
83 flags = (flags | VNI->flags) & ~IS_UNUSED;
86 /// Returns true if one or more kills are PHI nodes.
87 /// Obsolete, do not use!
88 bool hasPHIKill() const { return flags & HAS_PHI_KILL; }
89 /// Set the PHI kill flag on this value.
90 void setHasPHIKill(bool hasKill) {
92 flags |= HAS_PHI_KILL;
94 flags &= ~HAS_PHI_KILL;
97 /// Returns true if this value is defined by a PHI instruction (or was,
98 /// PHI instrucions may have been eliminated).
99 bool isPHIDef() const { return flags & IS_PHI_DEF; }
100 /// Set the "phi def" flag on this value.
101 void setIsPHIDef(bool phiDef) {
105 flags &= ~IS_PHI_DEF;
108 /// Returns true if this value is unused.
109 bool isUnused() const { return flags & IS_UNUSED; }
110 /// Set the "is unused" flag on this value.
111 void setIsUnused(bool unused) {
119 /// LiveRange structure - This represents a simple register range in the
120 /// program, with an inclusive start point and an exclusive end point.
121 /// These ranges are rendered as [start,end).
123 SlotIndex start; // Start point of the interval (inclusive)
124 SlotIndex end; // End point of the interval (exclusive)
125 VNInfo *valno; // identifier for the value contained in this interval.
127 LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
128 : start(S), end(E), valno(V) {
130 assert(S < E && "Cannot create empty or backwards range");
133 /// contains - Return true if the index is covered by this range.
135 bool contains(SlotIndex I) const {
136 return start <= I && I < end;
139 /// containsRange - Return true if the given range, [S, E), is covered by
141 bool containsRange(SlotIndex S, SlotIndex E) const {
142 assert((S < E) && "Backwards interval?");
143 return (start <= S && S < end) && (start < E && E <= end);
146 bool operator<(const LiveRange &LR) const {
147 return start < LR.start || (start == LR.start && end < LR.end);
149 bool operator==(const LiveRange &LR) const {
150 return start == LR.start && end == LR.end;
154 void print(raw_ostream &os) const;
157 LiveRange(); // DO NOT IMPLEMENT
160 template <> struct isPodLike<LiveRange> { static const bool value = true; };
162 raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
165 inline bool operator<(SlotIndex V, const LiveRange &LR) {
169 inline bool operator<(const LiveRange &LR, SlotIndex V) {
173 /// LiveInterval - This class represents some number of live ranges for a
174 /// register or value. This class also contains a bit of register allocator
179 typedef SmallVector<LiveRange,4> Ranges;
180 typedef SmallVector<VNInfo*,4> VNInfoList;
182 const unsigned reg; // the register or stack slot of this interval.
183 float weight; // weight of this interval
184 Ranges ranges; // the ranges in which this register is live
185 VNInfoList valnos; // value#'s
198 LiveInterval(unsigned Reg, float Weight)
199 : reg(Reg), weight(Weight) {}
201 typedef Ranges::iterator iterator;
202 iterator begin() { return ranges.begin(); }
203 iterator end() { return ranges.end(); }
205 typedef Ranges::const_iterator const_iterator;
206 const_iterator begin() const { return ranges.begin(); }
207 const_iterator end() const { return ranges.end(); }
209 typedef VNInfoList::iterator vni_iterator;
210 vni_iterator vni_begin() { return valnos.begin(); }
211 vni_iterator vni_end() { return valnos.end(); }
213 typedef VNInfoList::const_iterator const_vni_iterator;
214 const_vni_iterator vni_begin() const { return valnos.begin(); }
215 const_vni_iterator vni_end() const { return valnos.end(); }
217 /// advanceTo - Advance the specified iterator to point to the LiveRange
218 /// containing the specified position, or end() if the position is past the
219 /// end of the interval. If no LiveRange contains this position, but the
220 /// position is in a hole, this method returns an iterator pointing to the
221 /// LiveRange immediately after the hole.
222 iterator advanceTo(iterator I, SlotIndex Pos) {
224 if (Pos >= endIndex())
226 while (I->end <= Pos) ++I;
230 /// find - Return an iterator pointing to the first range that ends after
231 /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
232 /// when searching large intervals.
234 /// If Pos is contained in a LiveRange, that range is returned.
235 /// If Pos is in a hole, the following LiveRange is returned.
236 /// If Pos is beyond endIndex, end() is returned.
237 iterator find(SlotIndex Pos);
239 const_iterator find(SlotIndex Pos) const {
240 return const_cast<LiveInterval*>(this)->find(Pos);
248 bool hasAtLeastOneValue() const { return !valnos.empty(); }
250 bool containsOneValue() const { return valnos.size() == 1; }
252 unsigned getNumValNums() const { return (unsigned)valnos.size(); }
254 /// getValNumInfo - Returns pointer to the specified val#.
256 inline VNInfo *getValNumInfo(unsigned ValNo) {
257 return valnos[ValNo];
259 inline const VNInfo *getValNumInfo(unsigned ValNo) const {
260 return valnos[ValNo];
263 /// containsValue - Returns true if VNI belongs to this interval.
264 bool containsValue(const VNInfo *VNI) const {
265 return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
268 /// getNextValue - Create a new value number and return it. MIIdx specifies
269 /// the instruction that defines the value number.
270 VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
272 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
273 valnos.push_back(VNI);
277 /// Create a copy of the given value. The new value will be identical except
278 /// for the Value number.
279 VNInfo *createValueCopy(const VNInfo *orig,
280 VNInfo::Allocator &VNInfoAllocator) {
282 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
283 valnos.push_back(VNI);
287 /// RenumberValues - Renumber all values in order of appearance and remove
289 void RenumberValues(LiveIntervals &lis);
291 /// MergeValueNumberInto - This method is called when two value nubmers
292 /// are found to be equivalent. This eliminates V1, replacing all
293 /// LiveRanges with the V1 value number with the V2 value number. This can
294 /// cause merging of V1/V2 values numbers and compaction of the value space.
295 VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
297 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
298 /// in RHS into this live interval as the specified value number.
299 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
300 /// current interval, it will replace the value numbers of the overlaped
301 /// live ranges with the specified value number.
302 void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
304 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
305 /// in RHS into this live interval as the specified value number.
306 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
307 /// current interval, but only if the overlapping LiveRanges have the
308 /// specified value number.
309 void MergeValueInAsValue(const LiveInterval &RHS,
310 const VNInfo *RHSValNo, VNInfo *LHSValNo);
312 /// Copy - Copy the specified live interval. This copies all the fields
313 /// except for the register of the interval.
314 void Copy(const LiveInterval &RHS, MachineRegisterInfo *MRI,
315 VNInfo::Allocator &VNInfoAllocator);
317 bool empty() const { return ranges.empty(); }
319 /// beginIndex - Return the lowest numbered slot covered by interval.
320 SlotIndex beginIndex() const {
321 assert(!empty() && "Call to beginIndex() on empty interval.");
322 return ranges.front().start;
325 /// endNumber - return the maximum point of the interval of the whole,
327 SlotIndex endIndex() const {
328 assert(!empty() && "Call to endIndex() on empty interval.");
329 return ranges.back().end;
332 bool expiredAt(SlotIndex index) const {
333 return index >= endIndex();
336 bool liveAt(SlotIndex index) const {
337 const_iterator r = find(index);
338 return r != end() && r->start <= index;
341 /// killedAt - Return true if a live range ends at index. Note that the kill
342 /// point is not contained in the half-open live range. It is usually the
343 /// getDefIndex() slot following its last use.
344 bool killedAt(SlotIndex index) const {
345 const_iterator r = find(index.getRegSlot(true));
346 return r != end() && r->end == index;
349 /// killedInRange - Return true if the interval has kills in [Start,End).
350 /// Note that the kill point is considered the end of a live range, so it is
351 /// not contained in the live range. If a live range ends at End, it won't
352 /// be counted as a kill by this method.
353 bool killedInRange(SlotIndex Start, SlotIndex End) const;
355 /// getLiveRangeContaining - Return the live range that contains the
356 /// specified index, or null if there is none.
357 const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
358 const_iterator I = FindLiveRangeContaining(Idx);
359 return I == end() ? 0 : &*I;
362 /// getLiveRangeContaining - Return the live range that contains the
363 /// specified index, or null if there is none.
364 LiveRange *getLiveRangeContaining(SlotIndex Idx) {
365 iterator I = FindLiveRangeContaining(Idx);
366 return I == end() ? 0 : &*I;
369 /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
370 VNInfo *getVNInfoAt(SlotIndex Idx) const {
371 const_iterator I = FindLiveRangeContaining(Idx);
372 return I == end() ? 0 : I->valno;
375 /// getVNInfoBefore - Return the VNInfo that is live up to but not
376 /// necessarilly including Idx, or NULL. Use this to find the reaching def
377 /// used by an instruction at this SlotIndex position.
378 VNInfo *getVNInfoBefore(SlotIndex Idx) const {
379 const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
380 return I == end() ? 0 : I->valno;
383 /// FindLiveRangeContaining - Return an iterator to the live range that
384 /// contains the specified index, or end() if there is none.
385 iterator FindLiveRangeContaining(SlotIndex Idx) {
386 iterator I = find(Idx);
387 return I != end() && I->start <= Idx ? I : end();
390 const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
391 const_iterator I = find(Idx);
392 return I != end() && I->start <= Idx ? I : end();
395 /// overlaps - Return true if the intersection of the two live intervals is
397 bool overlaps(const LiveInterval& other) const {
400 return overlapsFrom(other, other.begin());
403 /// overlaps - Return true if the live interval overlaps a range specified
405 bool overlaps(SlotIndex Start, SlotIndex End) const;
407 /// overlapsFrom - Return true if the intersection of the two live intervals
408 /// is not empty. The specified iterator is a hint that we can begin
409 /// scanning the Other interval starting at I.
410 bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
412 /// addRange - Add the specified LiveRange to this interval, merging
413 /// intervals as appropriate. This returns an iterator to the inserted live
414 /// range (which may have grown since it was inserted.
415 void addRange(LiveRange LR) {
416 addRangeFrom(LR, ranges.begin());
419 /// extendInBlock - If this interval is live before Kill in the basic block
420 /// that starts at StartIdx, extend it to be live up to Kill, and return
421 /// the value. If there is no live range before Kill, return NULL.
422 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
424 /// join - Join two live intervals (this, and other) together. This applies
425 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
426 /// the intervals are not joinable, this aborts.
427 void join(LiveInterval &Other,
428 const int *ValNoAssignments,
429 const int *RHSValNoAssignments,
430 SmallVector<VNInfo*, 16> &NewVNInfo,
431 MachineRegisterInfo *MRI);
433 /// isInOneLiveRange - Return true if the range specified is entirely in the
434 /// a single LiveRange of the live interval.
435 bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
436 const_iterator r = find(Start);
437 return r != end() && r->containsRange(Start, End);
440 /// removeRange - Remove the specified range from this interval. Note that
441 /// the range must be a single LiveRange in its entirety.
442 void removeRange(SlotIndex Start, SlotIndex End,
443 bool RemoveDeadValNo = false);
445 void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
446 removeRange(LR.start, LR.end, RemoveDeadValNo);
449 /// removeValNo - Remove all the ranges defined by the specified value#.
450 /// Also remove the value# from value# list.
451 void removeValNo(VNInfo *ValNo);
453 /// getSize - Returns the sum of sizes of all the LiveRange's.
455 unsigned getSize() const;
457 /// Returns true if the live interval is zero length, i.e. no live ranges
458 /// span instructions. It doesn't pay to spill such an interval.
459 bool isZeroLength(SlotIndexes *Indexes) const {
460 for (const_iterator i = begin(), e = end(); i != e; ++i)
461 if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
462 i->end.getBaseIndex())
467 /// isSpillable - Can this interval be spilled?
468 bool isSpillable() const {
469 return weight != HUGE_VALF;
472 /// markNotSpillable - Mark interval as not spillable
473 void markNotSpillable() {
477 bool operator<(const LiveInterval& other) const {
478 const SlotIndex &thisIndex = beginIndex();
479 const SlotIndex &otherIndex = other.beginIndex();
480 return (thisIndex < otherIndex ||
481 (thisIndex == otherIndex && reg < other.reg));
484 void print(raw_ostream &OS, const TargetRegisterInfo *TRI = 0) const;
489 Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
490 void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
491 Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
492 void markValNoForDeletion(VNInfo *V);
494 LiveInterval& operator=(const LiveInterval& rhs); // DO NOT IMPLEMENT
498 inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
503 /// LiveRangeQuery - Query information about a live range around a given
504 /// instruction. This class hides the implementation details of live ranges,
505 /// and it should be used as the primary interface for examining live ranges
506 /// around instructions.
508 class LiveRangeQuery {
515 /// Create a LiveRangeQuery for the given live range and instruction index.
516 /// The sub-instruction slot of Idx doesn't matter, only the instruction it
517 /// refers to is considered.
518 LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
519 : EarlyVal(0), LateVal(0), Kill(false) {
520 // Find the segment that enters the instruction.
521 LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
522 LiveInterval::const_iterator E = LI.end();
525 // Is this an instruction live-in segment?
526 if (SlotIndex::isEarlierInstr(I->start, Idx)) {
529 // Move to the potentially live-out segment.
530 if (SlotIndex::isSameInstr(Idx, I->end)) {
536 // I now points to the segment that may be live-through, or defined by
537 // this instr. Ignore segments starting after the current instr.
538 if (SlotIndex::isEarlierInstr(Idx, I->start))
544 /// Return the value that is live-in to the instruction. This is the value
545 /// that will be read by the instruction's use operands. Return NULL if no
546 /// value is live-in.
547 VNInfo *valueIn() const {
551 /// Return true if the live-in value is killed by this instruction. This
552 /// means that either the live range ends at the instruction, or it changes
554 bool isKill() const {
558 /// Return true if this instruction has a dead def.
559 bool isDeadDef() const {
560 return EndPoint.isDead();
563 /// Return the value leaving the instruction, if any. This can be a
564 /// live-through value, or a live def. A dead def returns NULL.
565 VNInfo *valueOut() const {
566 return isDeadDef() ? 0 : LateVal;
569 /// Return the value defined by this instruction, if any. This includes
570 /// dead defs, it is the value created by the instruction's def operands.
571 VNInfo *valueDefined() const {
572 return EarlyVal == LateVal ? 0 : LateVal;
575 /// Return the end point of the last live range segment to interact with
576 /// the instruction, if any.
578 /// The end point is an invalid SlotIndex only if the live range doesn't
579 /// intersect the instruction at all.
581 /// The end point may be at or past the end of the instruction's basic
582 /// block. That means the value was live out of the block.
583 SlotIndex endPoint() const {
588 /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
589 /// LiveInterval into equivalence clases of connected components. A
590 /// LiveInterval that has multiple connected components can be broken into
591 /// multiple LiveIntervals.
593 /// Given a LiveInterval that may have multiple connected components, run:
595 /// unsigned numComps = ConEQ.Classify(LI);
596 /// if (numComps > 1) {
597 /// // allocate numComps-1 new LiveIntervals into LIS[1..]
598 /// ConEQ.Distribute(LIS);
601 class ConnectedVNInfoEqClasses {
603 IntEqClasses EqClass;
605 // Note that values a and b are connected.
606 void Connect(unsigned a, unsigned b);
611 explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
613 /// Classify - Classify the values in LI into connected components.
614 /// Return the number of connected components.
615 unsigned Classify(const LiveInterval *LI);
617 /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
618 /// the equivalence class assigned the VNI.
619 unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
621 /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
622 /// for each connected component. LIV must have a LiveInterval for each
623 /// connected component. The LiveIntervals in Liv[1..] must be empty.
624 /// Instructions using LIV[0] are rewritten.
625 void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);