1 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
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 #include "llvm/CodeGen/LiveInterval.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
33 // An example for liveAt():
35 // this = [1,4), liveAt(0) will return false. The instruction defining this
36 // spans slots [0,3]. The interval belongs to an spilled definition of the
37 // variable it represents. This is because slot 1 is used (def slot) and spans
38 // up to slot 3 (store slot).
40 bool LiveInterval::liveAt(SlotIndex I) const {
41 Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
43 if (r == ranges.begin())
47 return r->contains(I);
50 // liveBeforeAndAt - Check if the interval is live at the index and the index
51 // just before it. If index is liveAt, check if it starts a new live range.
52 // If it does, then check if the previous live range ends at index-1.
53 bool LiveInterval::liveBeforeAndAt(SlotIndex I) const {
54 Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
56 if (r == ranges.begin())
64 // I is the start of a live range. Check if the previous live range ends
66 if (r == ranges.begin())
71 /// killedAt - Return true if a live range ends at index. Note that the kill
72 /// point is not contained in the half-open live range. It is usually the
73 /// getDefIndex() slot following its last use.
74 bool LiveInterval::killedAt(SlotIndex I) const {
75 Ranges::const_iterator r = std::lower_bound(ranges.begin(), ranges.end(), I);
77 // Now r points to the first interval with start >= I, or ranges.end().
78 if (r == ranges.begin())
82 // Now r points to the last interval with end <= I.
83 // r->end is the kill point.
87 /// killedInRange - Return true if the interval has kills in [Start,End).
88 bool LiveInterval::killedInRange(SlotIndex Start, SlotIndex End) const {
89 Ranges::const_iterator r =
90 std::lower_bound(ranges.begin(), ranges.end(), End);
92 // Now r points to the first interval with start >= End, or ranges.end().
93 if (r == ranges.begin())
97 // Now r points to the last interval with end <= End.
98 // r->end is the kill point.
99 return r->end >= Start && r->end < End;
102 // overlaps - Return true if the intersection of the two live intervals is
105 // An example for overlaps():
109 // 8: C = A + B ;; last use of A
111 // The live intervals should look like:
117 // A->overlaps(C) should return false since we want to be able to join
120 bool LiveInterval::overlapsFrom(const LiveInterval& other,
121 const_iterator StartPos) const {
122 assert(!empty() && "empty interval");
123 const_iterator i = begin();
124 const_iterator ie = end();
125 const_iterator j = StartPos;
126 const_iterator je = other.end();
128 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
129 StartPos != other.end() && "Bogus start position hint!");
131 if (i->start < j->start) {
132 i = std::upper_bound(i, ie, j->start);
133 if (i != ranges.begin()) --i;
134 } else if (j->start < i->start) {
136 if (StartPos != other.end() && StartPos->start <= i->start) {
137 assert(StartPos < other.end() && i < end());
138 j = std::upper_bound(j, je, i->start);
139 if (j != other.ranges.begin()) --j;
145 if (j == je) return false;
148 if (i->start > j->start) {
153 if (i->end > j->start)
161 /// overlaps - Return true if the live interval overlaps a range specified
163 bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const {
164 assert(Start < End && "Invalid range");
165 const_iterator I = std::lower_bound(begin(), end(), End);
166 return I != begin() && (--I)->end > Start;
170 /// ValNo is dead, remove it. If it is the largest value number, just nuke it
171 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
172 /// it can be nuked later.
173 void LiveInterval::markValNoForDeletion(VNInfo *ValNo) {
174 if (ValNo->id == getNumValNums()-1) {
177 } while (!valnos.empty() && valnos.back()->isUnused());
179 ValNo->setIsUnused(true);
183 /// RenumberValues - Renumber all values in order of appearance and delete the
184 /// remaining unused values.
185 void LiveInterval::RenumberValues(LiveIntervals &lis) {
186 SmallPtrSet<VNInfo*, 8> Seen;
187 bool seenPHIDef = false;
189 for (const_iterator I = begin(), E = end(); I != E; ++I) {
190 VNInfo *VNI = I->valno;
191 if (!Seen.insert(VNI))
193 assert(!VNI->isUnused() && "Unused valno used by live range");
194 VNI->id = (unsigned)valnos.size();
195 valnos.push_back(VNI);
196 VNI->setHasPHIKill(false);
201 // Recompute phi kill flags.
204 for (const_vni_iterator I = vni_begin(), E = vni_end(); I != E; ++I) {
206 if (!VNI->isPHIDef())
208 const MachineBasicBlock *PHIBB = lis.getMBBFromIndex(VNI->def);
209 assert(PHIBB && "No basic block for phi-def");
210 for (MachineBasicBlock::const_pred_iterator PI = PHIBB->pred_begin(),
211 PE = PHIBB->pred_end(); PI != PE; ++PI) {
212 VNInfo *KVNI = getVNInfoAt(lis.getMBBEndIdx(*PI).getPrevSlot());
214 KVNI->setHasPHIKill(true);
219 /// extendIntervalEndTo - This method is used when we want to extend the range
220 /// specified by I to end at the specified endpoint. To do this, we should
221 /// merge and eliminate all ranges that this will overlap with. The iterator is
223 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
224 assert(I != ranges.end() && "Not a valid interval!");
225 VNInfo *ValNo = I->valno;
227 // Search for the first interval that we can't merge with.
228 Ranges::iterator MergeTo = llvm::next(I);
229 for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
230 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
233 // If NewEnd was in the middle of an interval, make sure to get its endpoint.
234 I->end = std::max(NewEnd, prior(MergeTo)->end);
236 // Erase any dead ranges.
237 ranges.erase(llvm::next(I), MergeTo);
239 // If the newly formed range now touches the range after it and if they have
240 // the same value number, merge the two ranges into one range.
241 Ranges::iterator Next = llvm::next(I);
242 if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
249 /// extendIntervalStartTo - This method is used when we want to extend the range
250 /// specified by I to start at the specified endpoint. To do this, we should
251 /// merge and eliminate all ranges that this will overlap with.
252 LiveInterval::Ranges::iterator
253 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
254 assert(I != ranges.end() && "Not a valid interval!");
255 VNInfo *ValNo = I->valno;
257 // Search for the first interval that we can't merge with.
258 Ranges::iterator MergeTo = I;
260 if (MergeTo == ranges.begin()) {
262 ranges.erase(MergeTo, I);
265 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
267 } while (NewStart <= MergeTo->start);
269 // If we start in the middle of another interval, just delete a range and
270 // extend that interval.
271 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
272 MergeTo->end = I->end;
274 // Otherwise, extend the interval right after.
276 MergeTo->start = NewStart;
277 MergeTo->end = I->end;
280 ranges.erase(llvm::next(MergeTo), llvm::next(I));
284 LiveInterval::iterator
285 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
286 SlotIndex Start = LR.start, End = LR.end;
287 iterator it = std::upper_bound(From, ranges.end(), Start);
289 // If the inserted interval starts in the middle or right at the end of
290 // another interval, just extend that interval to contain the range of LR.
291 if (it != ranges.begin()) {
292 iterator B = prior(it);
293 if (LR.valno == B->valno) {
294 if (B->start <= Start && B->end >= Start) {
295 extendIntervalEndTo(B, End);
299 // Check to make sure that we are not overlapping two live ranges with
300 // different valno's.
301 assert(B->end <= Start &&
302 "Cannot overlap two LiveRanges with differing ValID's"
303 " (did you def the same reg twice in a MachineInstr?)");
307 // Otherwise, if this range ends in the middle of, or right next to, another
308 // interval, merge it into that interval.
309 if (it != ranges.end()) {
310 if (LR.valno == it->valno) {
311 if (it->start <= End) {
312 it = extendIntervalStartTo(it, Start);
314 // If LR is a complete superset of an interval, we may need to grow its
317 extendIntervalEndTo(it, End);
321 // Check to make sure that we are not overlapping two live ranges with
322 // different valno's.
323 assert(it->start >= End &&
324 "Cannot overlap two LiveRanges with differing ValID's");
328 // Otherwise, this is just a new range that doesn't interact with anything.
330 return ranges.insert(it, LR);
333 /// isInOneLiveRange - Return true if the range specified is entirely in
334 /// a single LiveRange of the live interval.
335 bool LiveInterval::isInOneLiveRange(SlotIndex Start, SlotIndex End) {
336 Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
337 if (I == ranges.begin())
340 return I->containsRange(Start, End);
344 /// removeRange - Remove the specified range from this interval. Note that
345 /// the range must be in a single LiveRange in its entirety.
346 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
347 bool RemoveDeadValNo) {
348 // Find the LiveRange containing this span.
349 Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
350 assert(I != ranges.begin() && "Range is not in interval!");
352 assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
354 // If the span we are removing is at the start of the LiveRange, adjust it.
355 VNInfo *ValNo = I->valno;
356 if (I->start == Start) {
358 if (RemoveDeadValNo) {
359 // Check if val# is dead.
361 for (const_iterator II = begin(), EE = end(); II != EE; ++II)
362 if (II != I && II->valno == ValNo) {
367 // Now that ValNo is dead, remove it.
368 markValNoForDeletion(ValNo);
372 ranges.erase(I); // Removed the whole LiveRange.
378 // Otherwise if the span we are removing is at the end of the LiveRange,
379 // adjust the other way.
385 // Otherwise, we are splitting the LiveRange into two pieces.
386 SlotIndex OldEnd = I->end;
387 I->end = Start; // Trim the old interval.
389 // Insert the new one.
390 ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
393 /// removeValNo - Remove all the ranges defined by the specified value#.
394 /// Also remove the value# from value# list.
395 void LiveInterval::removeValNo(VNInfo *ValNo) {
397 Ranges::iterator I = ranges.end();
398 Ranges::iterator E = ranges.begin();
401 if (I->valno == ValNo)
404 // Now that ValNo is dead, remove it.
405 markValNoForDeletion(ValNo);
408 /// getLiveRangeContaining - Return the live range that contains the
409 /// specified index, or null if there is none.
410 LiveInterval::const_iterator
411 LiveInterval::FindLiveRangeContaining(SlotIndex Idx) const {
412 const_iterator It = std::upper_bound(begin(), end(), Idx);
413 if (It != ranges.begin()) {
415 if (It->contains(Idx))
422 LiveInterval::iterator
423 LiveInterval::FindLiveRangeContaining(SlotIndex Idx) {
424 iterator It = std::upper_bound(begin(), end(), Idx);
427 if (It->contains(Idx))
434 /// findDefinedVNInfo - Find the VNInfo defined by the specified
435 /// index (register interval).
436 VNInfo *LiveInterval::findDefinedVNInfoForRegInt(SlotIndex Idx) const {
437 for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
439 if ((*i)->def == Idx)
446 /// findDefinedVNInfo - Find the VNInfo defined by the specified
447 /// register (stack inteval).
448 VNInfo *LiveInterval::findDefinedVNInfoForStackInt(unsigned reg) const {
449 for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
451 if ((*i)->getReg() == reg)
457 /// join - Join two live intervals (this, and other) together. This applies
458 /// mappings to the value numbers in the LHS/RHS intervals as specified. If
459 /// the intervals are not joinable, this aborts.
460 void LiveInterval::join(LiveInterval &Other,
461 const int *LHSValNoAssignments,
462 const int *RHSValNoAssignments,
463 SmallVector<VNInfo*, 16> &NewVNInfo,
464 MachineRegisterInfo *MRI) {
465 // Determine if any of our live range values are mapped. This is uncommon, so
466 // we want to avoid the interval scan if not.
467 bool MustMapCurValNos = false;
468 unsigned NumVals = getNumValNums();
469 unsigned NumNewVals = NewVNInfo.size();
470 for (unsigned i = 0; i != NumVals; ++i) {
471 unsigned LHSValID = LHSValNoAssignments[i];
473 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
474 MustMapCurValNos = true;
477 // If we have to apply a mapping to our base interval assignment, rewrite it
479 if (MustMapCurValNos) {
480 // Map the first live range.
481 iterator OutIt = begin();
482 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
484 for (iterator I = OutIt, E = end(); I != E; ++I) {
485 OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
487 // If this live range has the same value # as its immediate predecessor,
488 // and if they are neighbors, remove one LiveRange. This happens when we
489 // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
490 if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
491 (OutIt-1)->end = OutIt->end;
494 OutIt->start = I->start;
498 // Didn't merge, on to the next one.
503 // If we merge some live ranges, chop off the end.
504 ranges.erase(OutIt, end());
507 // Remember assignements because val# ids are changing.
508 SmallVector<unsigned, 16> OtherAssignments;
509 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
510 OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
512 // Update val# info. Renumber them and make sure they all belong to this
513 // LiveInterval now. Also remove dead val#'s.
514 unsigned NumValNos = 0;
515 for (unsigned i = 0; i < NumNewVals; ++i) {
516 VNInfo *VNI = NewVNInfo[i];
518 if (NumValNos >= NumVals)
519 valnos.push_back(VNI);
521 valnos[NumValNos] = VNI;
522 VNI->id = NumValNos++; // Renumber val#.
525 if (NumNewVals < NumVals)
526 valnos.resize(NumNewVals); // shrinkify
528 // Okay, now insert the RHS live ranges into the LHS.
529 iterator InsertPos = begin();
530 unsigned RangeNo = 0;
531 for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
532 // Map the valno in the other live range to the current live range.
533 I->valno = NewVNInfo[OtherAssignments[RangeNo]];
534 assert(I->valno && "Adding a dead range?");
535 InsertPos = addRangeFrom(*I, InsertPos);
538 ComputeJoinedWeight(Other);
541 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
542 /// interval as the specified value number. The LiveRanges in RHS are
543 /// allowed to overlap with LiveRanges in the current interval, but only if
544 /// the overlapping LiveRanges have the specified value number.
545 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
547 // TODO: Make this more efficient.
548 iterator InsertPos = begin();
549 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
550 // Map the valno in the other live range to the current live range.
552 Tmp.valno = LHSValNo;
553 InsertPos = addRangeFrom(Tmp, InsertPos);
558 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
559 /// in RHS into this live interval as the specified value number.
560 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
561 /// current interval, it will replace the value numbers of the overlaped
562 /// live ranges with the specified value number.
563 void LiveInterval::MergeValueInAsValue(
564 const LiveInterval &RHS,
565 const VNInfo *RHSValNo, VNInfo *LHSValNo) {
566 SmallVector<VNInfo*, 4> ReplacedValNos;
567 iterator IP = begin();
568 for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
569 assert(I->valno == RHS.getValNumInfo(I->valno->id) && "Bad VNInfo");
570 if (I->valno != RHSValNo)
572 SlotIndex Start = I->start, End = I->end;
573 IP = std::upper_bound(IP, end(), Start);
574 // If the start of this range overlaps with an existing liverange, trim it.
575 if (IP != begin() && IP[-1].end > Start) {
576 if (IP[-1].valno != LHSValNo) {
577 ReplacedValNos.push_back(IP[-1].valno);
578 IP[-1].valno = LHSValNo; // Update val#.
581 // Trimmed away the whole range?
582 if (Start >= End) continue;
584 // If the end of this range overlaps with an existing liverange, trim it.
585 if (IP != end() && End > IP->start) {
586 if (IP->valno != LHSValNo) {
587 ReplacedValNos.push_back(IP->valno);
588 IP->valno = LHSValNo; // Update val#.
591 // If this trimmed away the whole range, ignore it.
592 if (Start == End) continue;
595 // Map the valno in the other live range to the current live range.
596 IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
600 SmallSet<VNInfo*, 4> Seen;
601 for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
602 VNInfo *V1 = ReplacedValNos[i];
603 if (Seen.insert(V1)) {
605 for (const_iterator I = begin(), E = end(); I != E; ++I)
606 if (I->valno == V1) {
611 // Now that V1 is dead, remove it.
612 markValNoForDeletion(V1);
620 /// MergeValueNumberInto - This method is called when two value nubmers
621 /// are found to be equivalent. This eliminates V1, replacing all
622 /// LiveRanges with the V1 value number with the V2 value number. This can
623 /// cause merging of V1/V2 values numbers and compaction of the value space.
624 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
625 assert(V1 != V2 && "Identical value#'s are always equivalent!");
627 // This code actually merges the (numerically) larger value number into the
628 // smaller value number, which is likely to allow us to compactify the value
629 // space. The only thing we have to be careful of is to preserve the
630 // instruction that defines the result value.
632 // Make sure V2 is smaller than V1.
633 if (V1->id < V2->id) {
638 // Merge V1 live ranges into V2.
639 for (iterator I = begin(); I != end(); ) {
641 if (LR->valno != V1) continue; // Not a V1 LiveRange.
643 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
646 iterator Prev = LR-1;
647 if (Prev->valno == V2 && Prev->end == LR->start) {
650 // Erase this live-range.
657 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
658 // Ensure that it is a V2 live-range.
661 // If we can merge it into later V2 live ranges, do so now. We ignore any
662 // following V1 live ranges, as they will be merged in subsequent iterations
665 if (I->start == LR->end && I->valno == V2) {
673 // Now that V1 is dead, remove it.
674 markValNoForDeletion(V1);
679 void LiveInterval::Copy(const LiveInterval &RHS,
680 MachineRegisterInfo *MRI,
681 VNInfo::Allocator &VNInfoAllocator) {
684 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(RHS.reg);
685 MRI->setRegAllocationHint(reg, Hint.first, Hint.second);
688 for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
689 const VNInfo *VNI = RHS.getValNumInfo(i);
690 createValueCopy(VNI, VNInfoAllocator);
692 for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
693 const LiveRange &LR = RHS.ranges[i];
694 addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
698 unsigned LiveInterval::getSize() const {
700 for (const_iterator I = begin(), E = end(); I != E; ++I)
701 Sum += I->start.distance(I->end);
705 /// ComputeJoinedWeight - Set the weight of a live interval Joined
706 /// after Other has been merged into it.
707 void LiveInterval::ComputeJoinedWeight(const LiveInterval &Other) {
708 // If either of these intervals was spilled, the weight is the
709 // weight of the non-spilled interval. This can only happen with
710 // iterative coalescers.
712 if (Other.weight != HUGE_VALF) {
713 weight += Other.weight;
715 else if (weight == HUGE_VALF &&
716 !TargetRegisterInfo::isPhysicalRegister(reg)) {
717 // Remove this assert if you have an iterative coalescer
718 assert(0 && "Joining to spilled interval");
719 weight = Other.weight;
722 // Otherwise the weight stays the same
723 // Remove this assert if you have an iterative coalescer
724 assert(0 && "Joining from spilled interval");
728 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
729 return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
732 void LiveRange::dump() const {
733 dbgs() << *this << "\n";
736 void LiveInterval::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const {
738 OS << "SS#" << getStackSlotIndex();
739 else if (TRI && TargetRegisterInfo::isPhysicalRegister(reg))
740 OS << TRI->getName(reg);
750 for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
751 E = ranges.end(); I != E; ++I) {
753 assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
757 // Print value number info.
758 if (getNumValNums()) {
761 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
763 const VNInfo *vni = *i;
766 if (vni->isUnused()) {
769 if (!vni->isDefAccurate() && !vni->isPHIDef())
773 if (vni->hasPHIKill())
775 if (vni->hasRedefByEC())
782 void LiveInterval::dump() const {
783 dbgs() << *this << "\n";
787 void LiveRange::print(raw_ostream &os) const {