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/Support/Streams.h"
24 #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 /// extendIntervalEndTo - This method is used when we want to extend the range
105 /// specified by I to end at the specified endpoint. To do this, we should
106 /// merge and eliminate all ranges that this will overlap with. The iterator is
108 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd) {
109 assert(I != ranges.end() && "Not a valid interval!");
110 unsigned ValId = I->ValId;
112 // Search for the first interval that we can't merge with.
113 Ranges::iterator MergeTo = next(I);
114 for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
115 assert(MergeTo->ValId == ValId && "Cannot merge with differing values!");
118 // If NewEnd was in the middle of an interval, make sure to get its endpoint.
119 I->end = std::max(NewEnd, prior(MergeTo)->end);
121 // Erase any dead ranges.
122 ranges.erase(next(I), MergeTo);
124 // If the newly formed range now touches the range after it and if they have
125 // the same value number, merge the two ranges into one range.
126 Ranges::iterator Next = next(I);
127 if (Next != ranges.end() && Next->start <= I->end && Next->ValId == ValId) {
134 /// extendIntervalStartTo - This method is used when we want to extend the range
135 /// specified by I to start at the specified endpoint. To do this, we should
136 /// merge and eliminate all ranges that this will overlap with.
137 LiveInterval::Ranges::iterator
138 LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) {
139 assert(I != ranges.end() && "Not a valid interval!");
140 unsigned ValId = I->ValId;
142 // Search for the first interval that we can't merge with.
143 Ranges::iterator MergeTo = I;
145 if (MergeTo == ranges.begin()) {
147 ranges.erase(MergeTo, I);
150 assert(MergeTo->ValId == ValId && "Cannot merge with differing values!");
152 } while (NewStart <= MergeTo->start);
154 // If we start in the middle of another interval, just delete a range and
155 // extend that interval.
156 if (MergeTo->end >= NewStart && MergeTo->ValId == ValId) {
157 MergeTo->end = I->end;
159 // Otherwise, extend the interval right after.
161 MergeTo->start = NewStart;
162 MergeTo->end = I->end;
165 ranges.erase(next(MergeTo), next(I));
169 LiveInterval::iterator
170 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
171 unsigned Start = LR.start, End = LR.end;
172 iterator it = std::upper_bound(From, ranges.end(), Start);
174 // If the inserted interval starts in the middle or right at the end of
175 // another interval, just extend that interval to contain the range of LR.
176 if (it != ranges.begin()) {
177 iterator B = prior(it);
178 if (LR.ValId == B->ValId) {
179 if (B->start <= Start && B->end >= Start) {
180 extendIntervalEndTo(B, End);
184 // Check to make sure that we are not overlapping two live ranges with
185 // different ValId's.
186 assert(B->end <= Start &&
187 "Cannot overlap two LiveRanges with differing ValID's"
188 " (did you def the same reg twice in a MachineInstr?)");
192 // Otherwise, if this range ends in the middle of, or right next to, another
193 // interval, merge it into that interval.
194 if (it != ranges.end())
195 if (LR.ValId == it->ValId) {
196 if (it->start <= End) {
197 it = extendIntervalStartTo(it, Start);
199 // If LR is a complete superset of an interval, we may need to grow its
202 extendIntervalEndTo(it, End);
206 // Check to make sure that we are not overlapping two live ranges with
207 // different ValId's.
208 assert(it->start >= End &&
209 "Cannot overlap two LiveRanges with differing ValID's");
212 // Otherwise, this is just a new range that doesn't interact with anything.
214 return ranges.insert(it, LR);
218 /// removeRange - Remove the specified range from this interval. Note that
219 /// the range must already be in this interval in its entirety.
220 void LiveInterval::removeRange(unsigned Start, unsigned End) {
221 // Find the LiveRange containing this span.
222 Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
223 assert(I != ranges.begin() && "Range is not in interval!");
225 assert(I->contains(Start) && I->contains(End-1) &&
226 "Range is not entirely in interval!");
228 // If the span we are removing is at the start of the LiveRange, adjust it.
229 if (I->start == Start) {
231 ranges.erase(I); // Removed the whole LiveRange.
237 // Otherwise if the span we are removing is at the end of the LiveRange,
238 // adjust the other way.
244 // Otherwise, we are splitting the LiveRange into two pieces.
245 unsigned OldEnd = I->end;
246 I->end = Start; // Trim the old interval.
248 // Insert the new one.
249 ranges.insert(next(I), LiveRange(End, OldEnd, I->ValId));
252 /// getLiveRangeContaining - Return the live range that contains the
253 /// specified index, or null if there is none.
254 LiveInterval::const_iterator
255 LiveInterval::FindLiveRangeContaining(unsigned Idx) const {
256 const_iterator It = std::upper_bound(begin(), end(), Idx);
257 if (It != ranges.begin()) {
259 if (It->contains(Idx))
266 LiveInterval::iterator
267 LiveInterval::FindLiveRangeContaining(unsigned Idx) {
268 iterator It = std::upper_bound(begin(), end(), Idx);
271 if (It->contains(Idx))
278 /// join - Join two live intervals (this, and other) together. This applies
279 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
280 /// the intervals are not joinable, this aborts.
281 void LiveInterval::join(LiveInterval &Other, int *LHSValNoAssignments,
282 int *RHSValNoAssignments,
283 SmallVector<std::pair<unsigned,
284 unsigned>, 16> &NewValueNumberInfo) {
286 // Try to do the least amount of work possible. In particular, if there are
287 // more liverange chunks in the other set than there are in the 'this' set,
288 // swap sets to merge the fewest chunks in possible.
290 // Also, if one range is a physreg and one is a vreg, we always merge from the
291 // vreg into the physreg, which leaves the vreg intervals pristine.
292 if ((Other.ranges.size() > ranges.size() &&
293 MRegisterInfo::isVirtualRegister(reg)) ||
294 MRegisterInfo::isPhysicalRegister(Other.reg)) {
296 std::swap(LHSValNoAssignments, RHSValNoAssignments);
299 // Determine if any of our live range values are mapped. This is uncommon, so
300 // we want to avoid the interval scan if not.
301 bool MustMapCurValNos = false;
302 for (unsigned i = 0, e = getNumValNums(); i != e; ++i) {
303 if (ValueNumberInfo[i].first == ~2U) continue; // tombstone value #
304 if (i != (unsigned)LHSValNoAssignments[i]) {
305 MustMapCurValNos = true;
310 // If we have to apply a mapping to our base interval assignment, rewrite it
312 if (MustMapCurValNos) {
313 // Map the first live range.
314 iterator OutIt = begin();
315 OutIt->ValId = LHSValNoAssignments[OutIt->ValId];
317 for (iterator I = OutIt, E = end(); I != E; ++I) {
318 OutIt->ValId = LHSValNoAssignments[I->ValId];
320 // If this live range has the same value # as its immediate predecessor,
321 // and if they are neighbors, remove one LiveRange. This happens when we
322 // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
323 if (OutIt->ValId == (OutIt-1)->ValId && (OutIt-1)->end == OutIt->start) {
324 (OutIt-1)->end = OutIt->end;
327 OutIt->start = I->start;
331 // Didn't merge, on to the next one.
336 // If we merge some live ranges, chop off the end.
337 ranges.erase(OutIt, end());
340 // Okay, now insert the RHS live ranges into the LHS.
341 iterator InsertPos = begin();
342 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I) {
343 // Map the ValId in the other live range to the current live range.
344 I->ValId = RHSValNoAssignments[I->ValId];
345 InsertPos = addRangeFrom(*I, InsertPos);
348 ValueNumberInfo.clear();
349 ValueNumberInfo.append(NewValueNumberInfo.begin(), NewValueNumberInfo.end());
350 weight += Other.weight;
353 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
354 /// interval as the specified value number. The LiveRanges in RHS are
355 /// allowed to overlap with LiveRanges in the current interval, but only if
356 /// the overlapping LiveRanges have the specified value number.
357 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
359 // TODO: Make this more efficient.
360 iterator InsertPos = begin();
361 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
362 // Map the ValId in the other live range to the current live range.
364 Tmp.ValId = LHSValNo;
365 InsertPos = addRangeFrom(Tmp, InsertPos);
370 /// MergeInClobberRanges - For any live ranges that are not defined in the
371 /// current interval, but are defined in the Clobbers interval, mark them
372 /// used with an unknown definition value.
373 void LiveInterval::MergeInClobberRanges(const LiveInterval &Clobbers) {
374 if (Clobbers.begin() == Clobbers.end()) return;
376 // Find a value # to use for the clobber ranges. If there is already a value#
377 // for unknown values, use it.
378 // FIXME: Use a single sentinal number for these!
379 unsigned ClobberValNo = getNextValue(~0U, 0);
381 iterator IP = begin();
382 for (const_iterator I = Clobbers.begin(), E = Clobbers.end(); I != E; ++I) {
383 unsigned Start = I->start, End = I->end;
384 IP = std::upper_bound(IP, end(), Start);
386 // If the start of this range overlaps with an existing liverange, trim it.
387 if (IP != begin() && IP[-1].end > Start) {
389 // Trimmed away the whole range?
390 if (Start >= End) continue;
392 // If the end of this range overlaps with an existing liverange, trim it.
393 if (IP != end() && End > IP->start) {
395 // If this trimmed away the whole range, ignore it.
396 if (Start == End) continue;
399 // Insert the clobber interval.
400 IP = addRangeFrom(LiveRange(Start, End, ClobberValNo), IP);
404 /// MergeValueNumberInto - This method is called when two value nubmers
405 /// are found to be equivalent. This eliminates V1, replacing all
406 /// LiveRanges with the V1 value number with the V2 value number. This can
407 /// cause merging of V1/V2 values numbers and compaction of the value space.
408 void LiveInterval::MergeValueNumberInto(unsigned V1, unsigned V2) {
409 assert(V1 != V2 && "Identical value#'s are always equivalent!");
411 // This code actually merges the (numerically) larger value number into the
412 // smaller value number, which is likely to allow us to compactify the value
413 // space. The only thing we have to be careful of is to preserve the
414 // instruction that defines the result value.
416 // Make sure V2 is smaller than V1.
418 setValueNumberInfo(V1, getValNumInfo(V2));
422 // Merge V1 live ranges into V2.
423 for (iterator I = begin(); I != end(); ) {
425 if (LR->ValId != V1) continue; // Not a V1 LiveRange.
427 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
430 iterator Prev = LR-1;
431 if (Prev->ValId == V2 && Prev->end == LR->start) {
434 // Erase this live-range.
441 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
442 // Ensure that it is a V2 live-range.
445 // If we can merge it into later V2 live ranges, do so now. We ignore any
446 // following V1 live ranges, as they will be merged in subsequent iterations
449 if (I->start == LR->end && I->ValId == V2) {
457 // Now that V1 is dead, remove it. If it is the largest value number, just
458 // nuke it (and any other deleted values neighboring it), otherwise mark it as
459 // ~1U so it can be nuked later.
460 if (V1 == getNumValNums()-1) {
462 ValueNumberInfo.pop_back();
463 } while (ValueNumberInfo.back().first == ~1U);
465 ValueNumberInfo[V1].first = ~1U;
469 std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) {
470 return os << '[' << LR.start << ',' << LR.end << ':' << LR.ValId << ")";
473 void LiveRange::dump() const {
474 cerr << *this << "\n";
477 void LiveInterval::print(OStream OS, const MRegisterInfo *MRI) const {
478 if (MRI && MRegisterInfo::isPhysicalRegister(reg))
479 OS << MRI->getName(reg);
489 for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
490 E = ranges.end(); I != E; ++I)
494 // Print value number info.
495 if (getNumValNums()) {
497 for (unsigned i = 0; i != getNumValNums(); ++i) {
500 if (ValueNumberInfo[i].first == ~0U) {
503 OS << ValueNumberInfo[i].first;
509 void LiveInterval::dump() const {
510 cerr << *this << "\n";