1 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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' abd 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 #include "llvm/CodeGen/LiveInterval.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Target/MRegisterInfo.h"
29 // An example for liveAt():
31 // this = [1,4), liveAt(0) will return false. The instruction defining this
32 // spans slots [0,3]. The interval belongs to an spilled definition of the
33 // variable it represents. This is because slot 1 is used (def slot) and spans
34 // up to slot 3 (store slot).
36 bool LiveInterval::liveAt(unsigned I) const {
37 Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
39 if (r == ranges.begin())
43 return r->contains(I);
46 // overlaps - Return true if the intersection of the two live intervals is
49 // An example for overlaps():
53 // 8: C = A + B ;; last use of A
55 // The live intervals should look like:
61 // A->overlaps(C) should return false since we want to be able to join
64 bool LiveInterval::overlapsFrom(const LiveInterval& other,
65 const_iterator StartPos) const {
66 const_iterator i = begin();
67 const_iterator ie = end();
68 const_iterator j = StartPos;
69 const_iterator je = other.end();
71 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
72 StartPos != other.end() && "Bogus start position hint!");
74 if (i->start < j->start) {
75 i = std::upper_bound(i, ie, j->start);
76 if (i != ranges.begin()) --i;
77 } else if (j->start < i->start) {
79 if (StartPos != other.end() && StartPos->start <= i->start) {
80 assert(StartPos < other.end() && i < end());
81 j = std::upper_bound(j, je, i->start);
82 if (j != other.ranges.begin()) --j;
88 if (j == je) return false;
91 if (i->start > j->start) {
96 if (i->end > j->start)
104 /// NontrivialOverlap - Check to see if the two live ranges specified by i and j
105 /// overlap. If so, check to see if they have value numbers that are not
106 /// iIdx/jIdx respectively. If both conditions are true, return true.
107 static inline bool NontrivialOverlap(const LiveRange &I, const LiveRange &J,
108 unsigned iIdx, unsigned jIdx) {
109 if (I.start == J.start) {
110 // If this is not the allowed value merge, we cannot join.
111 if (I.ValId != iIdx || J.ValId != jIdx)
113 } else if (I.start < J.start) {
114 if (I.end > J.start && (I.ValId != iIdx || J.ValId != jIdx)) {
118 if (J.end > I.start && (I.ValId != iIdx || J.ValId != jIdx))
125 /// joinable - Two intervals are joinable if the either don't overlap at all
126 /// or if the destination of the copy is a single assignment value, and it
127 /// only overlaps with one value in the source interval.
128 bool LiveInterval::joinable(const LiveInterval &other, unsigned CopyIdx) const {
129 const LiveRange *SourceLR = other.getLiveRangeContaining(CopyIdx-1);
130 const LiveRange *DestLR = getLiveRangeContaining(CopyIdx);
131 assert(SourceLR && DestLR && "Not joining due to a copy?");
132 unsigned OtherValIdx = SourceLR->ValId;
133 unsigned ThisValIdx = DestLR->ValId;
135 Ranges::const_iterator i = ranges.begin();
136 Ranges::const_iterator ie = ranges.end();
137 Ranges::const_iterator j = other.ranges.begin();
138 Ranges::const_iterator je = other.ranges.end();
140 if (i->start < j->start) {
141 i = std::upper_bound(i, ie, j->start);
142 if (i != ranges.begin()) --i;
143 } else if (j->start < i->start) {
144 j = std::upper_bound(j, je, i->start);
145 if (j != other.ranges.begin()) --j;
148 while (i != ie && j != je) {
149 if (NontrivialOverlap(*i, *j, ThisValIdx, OtherValIdx))
161 /// getOverlapingRanges - Given another live interval which is defined as a
162 /// copy from this one, return a list of all of the live ranges where the
163 /// two overlap and have different value numbers.
164 void LiveInterval::getOverlapingRanges(const LiveInterval &other,
166 std::vector<LiveRange*> &Ranges) {
167 const LiveRange *SourceLR = getLiveRangeContaining(CopyIdx-1);
168 const LiveRange *DestLR = other.getLiveRangeContaining(CopyIdx);
169 assert(SourceLR && DestLR && "Not joining due to a copy?");
170 unsigned OtherValIdx = SourceLR->ValId;
171 unsigned ThisValIdx = DestLR->ValId;
173 Ranges::iterator i = ranges.begin();
174 Ranges::iterator ie = ranges.end();
175 Ranges::const_iterator j = other.ranges.begin();
176 Ranges::const_iterator je = other.ranges.end();
178 if (i->start < j->start) {
179 i = std::upper_bound(i, ie, j->start);
180 if (i != ranges.begin()) --i;
181 } else if (j->start < i->start) {
182 j = std::upper_bound(j, je, i->start);
183 if (j != other.ranges.begin()) --j;
186 while (i != ie && j != je) {
187 if (NontrivialOverlap(*i, *j, ThisValIdx, OtherValIdx))
188 Ranges.push_back(&*i);
199 /// extendIntervalEndTo - This method is used when we want to extend the range
200 /// specified by I to end at the specified endpoint. To do this, we should
201 /// merge and eliminate all ranges that this will overlap with. The iterator is
203 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd) {
204 assert(I != ranges.end() && "Not a valid interval!");
205 unsigned ValId = I->ValId;
207 // Search for the first interval that we can't merge with.
208 Ranges::iterator MergeTo = next(I);
209 for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
210 assert(MergeTo->ValId == ValId && "Cannot merge with differing values!");
213 // If NewEnd was in the middle of an interval, make sure to get its endpoint.
214 I->end = std::max(NewEnd, prior(MergeTo)->end);
216 // Erase any dead ranges.
217 ranges.erase(next(I), MergeTo);
219 // If the newly formed range now touches the range after it and if they have
220 // the same value number, merge the two ranges into one range.
221 Ranges::iterator Next = next(I);
222 if (Next != ranges.end() && Next->start <= I->end && Next->ValId == ValId) {
229 /// extendIntervalStartTo - This method is used when we want to extend the range
230 /// specified by I to start at the specified endpoint. To do this, we should
231 /// merge and eliminate all ranges that this will overlap with.
232 LiveInterval::Ranges::iterator
233 LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) {
234 assert(I != ranges.end() && "Not a valid interval!");
235 unsigned ValId = I->ValId;
237 // Search for the first interval that we can't merge with.
238 Ranges::iterator MergeTo = I;
240 if (MergeTo == ranges.begin()) {
242 ranges.erase(MergeTo, I);
245 assert(MergeTo->ValId == ValId && "Cannot merge with differing values!");
247 } while (NewStart <= MergeTo->start);
249 // If we start in the middle of another interval, just delete a range and
250 // extend that interval.
251 if (MergeTo->end >= NewStart && MergeTo->ValId == ValId) {
252 MergeTo->end = I->end;
254 // Otherwise, extend the interval right after.
256 MergeTo->start = NewStart;
257 MergeTo->end = I->end;
260 ranges.erase(next(MergeTo), next(I));
264 LiveInterval::Ranges::iterator
265 LiveInterval::addRangeFrom(LiveRange LR, Ranges::iterator From) {
266 unsigned Start = LR.start, End = LR.end;
267 Ranges::iterator it = std::upper_bound(From, ranges.end(), Start);
269 // If the inserted interval starts in the middle or right at the end of
270 // another interval, just extend that interval to contain the range of LR.
271 if (it != ranges.begin()) {
272 Ranges::iterator B = prior(it);
273 if (LR.ValId == B->ValId) {
274 if (B->start <= Start && B->end >= Start) {
275 extendIntervalEndTo(B, End);
279 // Check to make sure that we are not overlapping two live ranges with
280 // different ValId's.
281 assert(B->end <= Start &&
282 "Cannot overlap two LiveRanges with differing ValID's"
283 " (did you def the same reg twice in a MachineInstr?)");
287 // Otherwise, if this range ends in the middle of, or right next to, another
288 // interval, merge it into that interval.
289 if (it != ranges.end())
290 if (LR.ValId == it->ValId) {
291 if (it->start <= End) {
292 it = extendIntervalStartTo(it, Start);
294 // If LR is a complete superset of an interval, we may need to grow its
297 extendIntervalEndTo(it, End);
301 // Check to make sure that we are not overlapping two live ranges with
302 // different ValId's.
303 assert(it->start >= End &&
304 "Cannot overlap two LiveRanges with differing ValID's");
307 // Otherwise, this is just a new range that doesn't interact with anything.
309 return ranges.insert(it, LR);
313 /// removeRange - Remove the specified range from this interval. Note that
314 /// the range must already be in this interval in its entirety.
315 void LiveInterval::removeRange(unsigned Start, unsigned End) {
316 // Find the LiveRange containing this span.
317 Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
318 assert(I != ranges.begin() && "Range is not in interval!");
320 assert(I->contains(Start) && I->contains(End-1) &&
321 "Range is not entirely in interval!");
323 // If the span we are removing is at the start of the LiveRange, adjust it.
324 if (I->start == Start) {
326 ranges.erase(I); // Removed the whole LiveRange.
332 // Otherwise if the span we are removing is at the end of the LiveRange,
333 // adjust the other way.
339 // Otherwise, we are splitting the LiveRange into two pieces.
340 unsigned OldEnd = I->end;
341 I->end = Start; // Trim the old interval.
343 // Insert the new one.
344 ranges.insert(next(I), LiveRange(End, OldEnd, I->ValId));
347 /// getLiveRangeContaining - Return the live range that contains the
348 /// specified index, or null if there is none.
349 LiveInterval::const_iterator
350 LiveInterval::FindLiveRangeContaining(unsigned Idx) const {
351 const_iterator It = std::upper_bound(begin(), end(), Idx);
352 if (It != ranges.begin()) {
354 if (It->contains(Idx))
361 LiveInterval::iterator
362 LiveInterval::FindLiveRangeContaining(unsigned Idx) {
363 iterator It = std::upper_bound(begin(), end(), Idx);
364 if (It != ranges.begin()) {
366 if (It->contains(Idx))
373 /// join - Join two live intervals (this, and other) together. This operation
374 /// is the result of a copy instruction in the source program, that occurs at
375 /// index 'CopyIdx' that copies from 'Other' to 'this'.
376 void LiveInterval::join(LiveInterval &Other, unsigned CopyIdx) {
377 const LiveRange *SourceLR = Other.getLiveRangeContaining(CopyIdx-1);
378 const LiveRange *DestLR = getLiveRangeContaining(CopyIdx);
379 assert(SourceLR && DestLR && "Not joining due to a copy?");
380 unsigned MergedSrcValIdx = SourceLR->ValId;
381 unsigned MergedDstValIdx = DestLR->ValId;
383 // Try to do the least amount of work possible. In particular, if there are
384 // more liverange chunks in the other set than there are in the 'this' set,
385 // swap sets to merge the fewest chunks in possible.
386 if (Other.ranges.size() > ranges.size()) {
387 std::swap(MergedSrcValIdx, MergedDstValIdx);
388 std::swap(ranges, Other.ranges);
389 std::swap(NumValues, Other.NumValues);
390 std::swap(InstDefiningValue, Other.InstDefiningValue);
393 // Join the ranges of other into the ranges of this interval.
394 Ranges::iterator InsertPos = ranges.begin();
395 std::map<unsigned, unsigned> Dst2SrcIdxMap;
396 for (Ranges::iterator I = Other.ranges.begin(),
397 E = Other.ranges.end(); I != E; ++I) {
398 // Map the ValId in the other live range to the current live range.
399 if (I->ValId == MergedSrcValIdx)
400 I->ValId = MergedDstValIdx;
402 unsigned &NV = Dst2SrcIdxMap[I->ValId];
403 if (NV == 0) NV = getNextValue(Other.getInstForValNum(I->ValId));
407 InsertPos = addRangeFrom(*I, InsertPos);
410 // Update the value number information for the value number defined by the
411 // copy. The copy is about to be removed, so ensure that the value is defined
412 // by whatever the other value is defined by.
413 if (InstDefiningValue[MergedDstValIdx] == CopyIdx) {
414 InstDefiningValue[MergedDstValIdx] =
415 Other.InstDefiningValue[MergedSrcValIdx];
418 weight += Other.weight;
421 /// MergeValueNumberInto - This method is called when two value nubmers
422 /// are found to be equivalent. This eliminates V1, replacing all
423 /// LiveRanges with the V1 value number with the V2 value number. This can
424 /// cause merging of V1/V2 values numbers and compaction of the value space.
425 void LiveInterval::MergeValueNumberInto(unsigned V1, unsigned V2) {
426 assert(V1 != V2 && "Identical value#'s are always equivalent!");
428 // This code actually merges the (numerically) larger value number into the
429 // smaller value number, which is likely to allow us to compactify the value
430 // space. The only thing we have to be careful of is to preserve the
431 // instruction that defines the result value.
433 // Make sure V2 is smaller than V1.
435 setInstDefiningValNum(V1, getInstForValNum(V2));
439 // Merge V1 live ranges into V2.
440 for (iterator I = begin(); I != end(); ) {
442 if (LR->ValId != V1) continue; // Not a V1 LiveRange.
444 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
447 iterator Prev = LR-1;
448 if (Prev->ValId == V2 && Prev->end == LR->start) {
451 // Erase this live-range.
458 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
459 // Ensure that it is a V2 live-range.
462 // If we can merge it into later V2 live ranges, do so now. We ignore any
463 // following V1 live ranges, as they will be merged in subsequent iterations
466 if (I->start == LR->end && I->ValId == V2) {
474 // Now that V1 is dead, remove it. If it is the largest value number, just
475 // nuke it (and any other deleted values neighboring it), otherwise mark it as
476 // ~1U so it can be nuked later.
477 if (V1 == NumValues-1) {
479 InstDefiningValue.pop_back();
481 } while (InstDefiningValue.back() == ~1U);
483 InstDefiningValue[V1] = ~1U;
488 std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) {
489 return os << '[' << LR.start << ',' << LR.end << ':' << LR.ValId << ")";
492 void LiveRange::dump() const {
493 std::cerr << *this << "\n";
496 void LiveInterval::print(std::ostream &OS, const MRegisterInfo *MRI) const {
497 if (MRI && MRegisterInfo::isPhysicalRegister(reg))
498 OS << MRI->getName(reg);
508 for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
509 E = ranges.end(); I != E; ++I)
513 // Print value number info.
516 for (unsigned i = 0; i != NumValues; ++i) {
519 if (InstDefiningValue[i] == ~0U) {
522 OS << InstDefiningValue[i];
528 void LiveInterval::dump() const {
529 std::cerr << *this << "\n";