f4c06b203cbcba3bce67ff1d446afd0f740ab220
[oota-llvm.git] / lib / CodeGen / LiveInterval.cpp
1 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
18 //
19 //===----------------------------------------------------------------------===//
20
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"
30 #include <algorithm>
31 using namespace llvm;
32
33 // An example for liveAt():
34 //
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).
39 //
40 bool LiveInterval::liveAt(SlotIndex I) const {
41   Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I);
42
43   if (r == ranges.begin())
44     return false;
45
46   --r;
47   return r->contains(I);
48 }
49
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);
55
56   if (r == ranges.begin())
57     return false;
58
59   --r;
60   if (!r->contains(I))
61     return false;
62   if (I != r->start)
63     return true;
64   // I is the start of a live range. Check if the previous live range ends
65   // at I-1.
66   if (r == ranges.begin())
67     return false;
68   return r->end == I;
69 }
70
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);
76
77   // Now r points to the first interval with start >= I, or ranges.end().
78   if (r == ranges.begin())
79     return false;
80
81   --r;
82   // Now r points to the last interval with end <= I.
83   // r->end is the kill point.
84   return r->end == I;
85 }
86
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);
91
92   // Now r points to the first interval with start >= End, or ranges.end().
93   if (r == ranges.begin())
94     return false;
95
96   --r;
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;
100 }
101
102 // overlaps - Return true if the intersection of the two live intervals is
103 // not empty.
104 //
105 // An example for overlaps():
106 //
107 // 0: A = ...
108 // 4: B = ...
109 // 8: C = A + B ;; last use of A
110 //
111 // The live intervals should look like:
112 //
113 // A = [3, 11)
114 // B = [7, x)
115 // C = [11, y)
116 //
117 // A->overlaps(C) should return false since we want to be able to join
118 // A and C.
119 //
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();
127
128   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
129          StartPos != other.end() && "Bogus start position hint!");
130
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) {
135     ++StartPos;
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;
140     }
141   } else {
142     return true;
143   }
144
145   if (j == je) return false;
146
147   while (i != ie) {
148     if (i->start > j->start) {
149       std::swap(i, j);
150       std::swap(ie, je);
151     }
152
153     if (i->end > j->start)
154       return true;
155     ++i;
156   }
157
158   return false;
159 }
160
161 /// overlaps - Return true if the live interval overlaps a range specified
162 /// by [Start, End).
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;
167 }
168
169
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) {
175     do {
176       valnos.pop_back();
177     } while (!valnos.empty() && valnos.back()->isUnused());
178   } else {
179     ValNo->setIsUnused(true);
180   }
181 }
182
183 /// RenumberValues - Renumber all values in order of appearance and delete the
184 /// remaining unused values.
185 void LiveInterval::RenumberValues() {
186   SmallPtrSet<VNInfo*, 8> Seen;
187   valnos.clear();
188   for (const_iterator I = begin(), E = end(); I != E; ++I) {
189     VNInfo *VNI = I->valno;
190     if (!Seen.insert(VNI))
191       continue;
192     assert(!VNI->isUnused() && "Unused valno used by live range");
193     VNI->id = (unsigned)valnos.size();
194     valnos.push_back(VNI);
195   }
196 }
197
198 /// extendIntervalEndTo - This method is used when we want to extend the range
199 /// specified by I to end at the specified endpoint.  To do this, we should
200 /// merge and eliminate all ranges that this will overlap with.  The iterator is
201 /// not invalidated.
202 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
203   assert(I != ranges.end() && "Not a valid interval!");
204   VNInfo *ValNo = I->valno;
205
206   // Search for the first interval that we can't merge with.
207   Ranges::iterator MergeTo = llvm::next(I);
208   for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
209     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
210   }
211
212   // If NewEnd was in the middle of an interval, make sure to get its endpoint.
213   I->end = std::max(NewEnd, prior(MergeTo)->end);
214
215   // Erase any dead ranges.
216   ranges.erase(llvm::next(I), MergeTo);
217
218   // If the newly formed range now touches the range after it and if they have
219   // the same value number, merge the two ranges into one range.
220   Ranges::iterator Next = llvm::next(I);
221   if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
222     I->end = Next->end;
223     ranges.erase(Next);
224   }
225 }
226
227
228 /// extendIntervalStartTo - This method is used when we want to extend the range
229 /// specified by I to start at the specified endpoint.  To do this, we should
230 /// merge and eliminate all ranges that this will overlap with.
231 LiveInterval::Ranges::iterator
232 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
233   assert(I != ranges.end() && "Not a valid interval!");
234   VNInfo *ValNo = I->valno;
235
236   // Search for the first interval that we can't merge with.
237   Ranges::iterator MergeTo = I;
238   do {
239     if (MergeTo == ranges.begin()) {
240       I->start = NewStart;
241       ranges.erase(MergeTo, I);
242       return I;
243     }
244     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
245     --MergeTo;
246   } while (NewStart <= MergeTo->start);
247
248   // If we start in the middle of another interval, just delete a range and
249   // extend that interval.
250   if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
251     MergeTo->end = I->end;
252   } else {
253     // Otherwise, extend the interval right after.
254     ++MergeTo;
255     MergeTo->start = NewStart;
256     MergeTo->end = I->end;
257   }
258
259   ranges.erase(llvm::next(MergeTo), llvm::next(I));
260   return MergeTo;
261 }
262
263 LiveInterval::iterator
264 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
265   SlotIndex Start = LR.start, End = LR.end;
266   iterator it = std::upper_bound(From, ranges.end(), Start);
267
268   // If the inserted interval starts in the middle or right at the end of
269   // another interval, just extend that interval to contain the range of LR.
270   if (it != ranges.begin()) {
271     iterator B = prior(it);
272     if (LR.valno == B->valno) {
273       if (B->start <= Start && B->end >= Start) {
274         extendIntervalEndTo(B, End);
275         return B;
276       }
277     } else {
278       // Check to make sure that we are not overlapping two live ranges with
279       // different valno's.
280       assert(B->end <= Start &&
281              "Cannot overlap two LiveRanges with differing ValID's"
282              " (did you def the same reg twice in a MachineInstr?)");
283     }
284   }
285
286   // Otherwise, if this range ends in the middle of, or right next to, another
287   // interval, merge it into that interval.
288   if (it != ranges.end()) {
289     if (LR.valno == it->valno) {
290       if (it->start <= End) {
291         it = extendIntervalStartTo(it, Start);
292
293         // If LR is a complete superset of an interval, we may need to grow its
294         // endpoint as well.
295         if (End > it->end)
296           extendIntervalEndTo(it, End);
297         return it;
298       }
299     } else {
300       // Check to make sure that we are not overlapping two live ranges with
301       // different valno's.
302       assert(it->start >= End &&
303              "Cannot overlap two LiveRanges with differing ValID's");
304     }
305   }
306
307   // Otherwise, this is just a new range that doesn't interact with anything.
308   // Insert it.
309   return ranges.insert(it, LR);
310 }
311
312 /// isInOneLiveRange - Return true if the range specified is entirely in 
313 /// a single LiveRange of the live interval.
314 bool LiveInterval::isInOneLiveRange(SlotIndex Start, SlotIndex End) {
315   Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
316   if (I == ranges.begin())
317     return false;
318   --I;
319   return I->containsRange(Start, End);
320 }
321
322
323 /// removeRange - Remove the specified range from this interval.  Note that
324 /// the range must be in a single LiveRange in its entirety.
325 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
326                                bool RemoveDeadValNo) {
327   // Find the LiveRange containing this span.
328   Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start);
329   assert(I != ranges.begin() && "Range is not in interval!");
330   --I;
331   assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
332
333   // If the span we are removing is at the start of the LiveRange, adjust it.
334   VNInfo *ValNo = I->valno;
335   if (I->start == Start) {
336     if (I->end == End) {
337       if (RemoveDeadValNo) {
338         // Check if val# is dead.
339         bool isDead = true;
340         for (const_iterator II = begin(), EE = end(); II != EE; ++II)
341           if (II != I && II->valno == ValNo) {
342             isDead = false;
343             break;
344           }
345         if (isDead) {
346           // Now that ValNo is dead, remove it.
347           markValNoForDeletion(ValNo);
348         }
349       }
350
351       ranges.erase(I);  // Removed the whole LiveRange.
352     } else
353       I->start = End;
354     return;
355   }
356
357   // Otherwise if the span we are removing is at the end of the LiveRange,
358   // adjust the other way.
359   if (I->end == End) {
360     I->end = Start;
361     return;
362   }
363
364   // Otherwise, we are splitting the LiveRange into two pieces.
365   SlotIndex OldEnd = I->end;
366   I->end = Start;   // Trim the old interval.
367
368   // Insert the new one.
369   ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
370 }
371
372 /// removeValNo - Remove all the ranges defined by the specified value#.
373 /// Also remove the value# from value# list.
374 void LiveInterval::removeValNo(VNInfo *ValNo) {
375   if (empty()) return;
376   Ranges::iterator I = ranges.end();
377   Ranges::iterator E = ranges.begin();
378   do {
379     --I;
380     if (I->valno == ValNo)
381       ranges.erase(I);
382   } while (I != E);
383   // Now that ValNo is dead, remove it.
384   markValNoForDeletion(ValNo);
385 }
386
387 /// getLiveRangeContaining - Return the live range that contains the
388 /// specified index, or null if there is none.
389 LiveInterval::const_iterator 
390 LiveInterval::FindLiveRangeContaining(SlotIndex Idx) const {
391   const_iterator It = std::upper_bound(begin(), end(), Idx);
392   if (It != ranges.begin()) {
393     --It;
394     if (It->contains(Idx))
395       return It;
396   }
397
398   return end();
399 }
400
401 LiveInterval::iterator 
402 LiveInterval::FindLiveRangeContaining(SlotIndex Idx) {
403   iterator It = std::upper_bound(begin(), end(), Idx);
404   if (It != begin()) {
405     --It;
406     if (It->contains(Idx))
407       return It;
408   }
409   
410   return end();
411 }
412
413 /// findDefinedVNInfo - Find the VNInfo defined by the specified
414 /// index (register interval).
415 VNInfo *LiveInterval::findDefinedVNInfoForRegInt(SlotIndex Idx) const {
416   for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
417        i != e; ++i) {
418     if ((*i)->def == Idx)
419       return *i;
420   }
421
422   return 0;
423 }
424
425 /// findDefinedVNInfo - Find the VNInfo defined by the specified
426 /// register (stack inteval).
427 VNInfo *LiveInterval::findDefinedVNInfoForStackInt(unsigned reg) const {
428   for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
429        i != e; ++i) {
430     if ((*i)->getReg() == reg)
431       return *i;
432   }
433   return 0;
434 }
435
436 /// join - Join two live intervals (this, and other) together.  This applies
437 /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
438 /// the intervals are not joinable, this aborts.
439 void LiveInterval::join(LiveInterval &Other,
440                         const int *LHSValNoAssignments,
441                         const int *RHSValNoAssignments, 
442                         SmallVector<VNInfo*, 16> &NewVNInfo,
443                         MachineRegisterInfo *MRI) {
444   // Determine if any of our live range values are mapped.  This is uncommon, so
445   // we want to avoid the interval scan if not. 
446   bool MustMapCurValNos = false;
447   unsigned NumVals = getNumValNums();
448   unsigned NumNewVals = NewVNInfo.size();
449   for (unsigned i = 0; i != NumVals; ++i) {
450     unsigned LHSValID = LHSValNoAssignments[i];
451     if (i != LHSValID ||
452         (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
453       MustMapCurValNos = true;
454   }
455
456   // If we have to apply a mapping to our base interval assignment, rewrite it
457   // now.
458   if (MustMapCurValNos) {
459     // Map the first live range.
460     iterator OutIt = begin();
461     OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
462     ++OutIt;
463     for (iterator I = OutIt, E = end(); I != E; ++I) {
464       OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
465       
466       // If this live range has the same value # as its immediate predecessor,
467       // and if they are neighbors, remove one LiveRange.  This happens when we
468       // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
469       if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
470         (OutIt-1)->end = OutIt->end;
471       } else {
472         if (I != OutIt) {
473           OutIt->start = I->start;
474           OutIt->end = I->end;
475         }
476         
477         // Didn't merge, on to the next one.
478         ++OutIt;
479       }
480     }
481     
482     // If we merge some live ranges, chop off the end.
483     ranges.erase(OutIt, end());
484   }
485
486   // Remember assignements because val# ids are changing.
487   SmallVector<unsigned, 16> OtherAssignments;
488   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
489     OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
490
491   // Update val# info. Renumber them and make sure they all belong to this
492   // LiveInterval now. Also remove dead val#'s.
493   unsigned NumValNos = 0;
494   for (unsigned i = 0; i < NumNewVals; ++i) {
495     VNInfo *VNI = NewVNInfo[i];
496     if (VNI) {
497       if (NumValNos >= NumVals)
498         valnos.push_back(VNI);
499       else 
500         valnos[NumValNos] = VNI;
501       VNI->id = NumValNos++;  // Renumber val#.
502     }
503   }
504   if (NumNewVals < NumVals)
505     valnos.resize(NumNewVals);  // shrinkify
506
507   // Okay, now insert the RHS live ranges into the LHS.
508   iterator InsertPos = begin();
509   unsigned RangeNo = 0;
510   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
511     // Map the valno in the other live range to the current live range.
512     I->valno = NewVNInfo[OtherAssignments[RangeNo]];
513     assert(I->valno && "Adding a dead range?");
514     InsertPos = addRangeFrom(*I, InsertPos);
515   }
516
517   ComputeJoinedWeight(Other);
518
519   // Update regalloc hint if currently there isn't one.
520   if (TargetRegisterInfo::isVirtualRegister(reg) &&
521       TargetRegisterInfo::isVirtualRegister(Other.reg)) {
522     std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(reg);
523     if (Hint.first == 0 && Hint.second == 0) {
524       std::pair<unsigned, unsigned> OtherHint =
525         MRI->getRegAllocationHint(Other.reg);
526       if (OtherHint.first || OtherHint.second)
527         MRI->setRegAllocationHint(reg, OtherHint.first, OtherHint.second);
528     }
529   }
530 }
531
532 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
533 /// interval as the specified value number.  The LiveRanges in RHS are
534 /// allowed to overlap with LiveRanges in the current interval, but only if
535 /// the overlapping LiveRanges have the specified value number.
536 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS, 
537                                         VNInfo *LHSValNo) {
538   // TODO: Make this more efficient.
539   iterator InsertPos = begin();
540   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
541     // Map the valno in the other live range to the current live range.
542     LiveRange Tmp = *I;
543     Tmp.valno = LHSValNo;
544     InsertPos = addRangeFrom(Tmp, InsertPos);
545   }
546 }
547
548
549 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
550 /// in RHS into this live interval as the specified value number.
551 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
552 /// current interval, it will replace the value numbers of the overlaped
553 /// live ranges with the specified value number.
554 void LiveInterval::MergeValueInAsValue(
555                                     const LiveInterval &RHS,
556                                     const VNInfo *RHSValNo, VNInfo *LHSValNo) {
557   SmallVector<VNInfo*, 4> ReplacedValNos;
558   iterator IP = begin();
559   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
560     assert(I->valno == RHS.getValNumInfo(I->valno->id) && "Bad VNInfo");
561     if (I->valno != RHSValNo)
562       continue;
563     SlotIndex Start = I->start, End = I->end;
564     IP = std::upper_bound(IP, end(), Start);
565     // If the start of this range overlaps with an existing liverange, trim it.
566     if (IP != begin() && IP[-1].end > Start) {
567       if (IP[-1].valno != LHSValNo) {
568         ReplacedValNos.push_back(IP[-1].valno);
569         IP[-1].valno = LHSValNo; // Update val#.
570       }
571       Start = IP[-1].end;
572       // Trimmed away the whole range?
573       if (Start >= End) continue;
574     }
575     // If the end of this range overlaps with an existing liverange, trim it.
576     if (IP != end() && End > IP->start) {
577       if (IP->valno != LHSValNo) {
578         ReplacedValNos.push_back(IP->valno);
579         IP->valno = LHSValNo;  // Update val#.
580       }
581       End = IP->start;
582       // If this trimmed away the whole range, ignore it.
583       if (Start == End) continue;
584     }
585     
586     // Map the valno in the other live range to the current live range.
587     IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
588   }
589
590
591   SmallSet<VNInfo*, 4> Seen;
592   for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
593     VNInfo *V1 = ReplacedValNos[i];
594     if (Seen.insert(V1)) {
595       bool isDead = true;
596       for (const_iterator I = begin(), E = end(); I != E; ++I)
597         if (I->valno == V1) {
598           isDead = false;
599           break;
600         }          
601       if (isDead) {
602         // Now that V1 is dead, remove it.
603         markValNoForDeletion(V1);
604       }
605     }
606   }
607 }
608
609
610 /// MergeInClobberRanges - For any live ranges that are not defined in the
611 /// current interval, but are defined in the Clobbers interval, mark them
612 /// used with an unknown definition value.
613 void LiveInterval::MergeInClobberRanges(LiveIntervals &li_,
614                                         const LiveInterval &Clobbers,
615                                         VNInfo::Allocator &VNInfoAllocator) {
616   if (Clobbers.empty()) return;
617   
618   DenseMap<VNInfo*, VNInfo*> ValNoMaps;
619   VNInfo *UnusedValNo = 0;
620   iterator IP = begin();
621   for (const_iterator I = Clobbers.begin(), E = Clobbers.end(); I != E; ++I) {
622     // For every val# in the Clobbers interval, create a new "unknown" val#.
623     VNInfo *ClobberValNo = 0;
624     DenseMap<VNInfo*, VNInfo*>::iterator VI = ValNoMaps.find(I->valno);
625     if (VI != ValNoMaps.end())
626       ClobberValNo = VI->second;
627     else if (UnusedValNo)
628       ClobberValNo = UnusedValNo;
629     else {
630       UnusedValNo = ClobberValNo =
631         getNextValue(li_.getInvalidIndex(), 0, false, VNInfoAllocator);
632       ValNoMaps.insert(std::make_pair(I->valno, ClobberValNo));
633     }
634
635     bool Done = false;
636     SlotIndex Start = I->start, End = I->end;
637     // If a clobber range starts before an existing range and ends after
638     // it, the clobber range will need to be split into multiple ranges.
639     // Loop until the entire clobber range is handled.
640     while (!Done) {
641       Done = true;
642       IP = std::upper_bound(IP, end(), Start);
643       SlotIndex SubRangeStart = Start;
644       SlotIndex SubRangeEnd = End;
645
646       // If the start of this range overlaps with an existing liverange, trim it.
647       if (IP != begin() && IP[-1].end > SubRangeStart) {
648         SubRangeStart = IP[-1].end;
649         // Trimmed away the whole range?
650         if (SubRangeStart >= SubRangeEnd) continue;
651       }
652       // If the end of this range overlaps with an existing liverange, trim it.
653       if (IP != end() && SubRangeEnd > IP->start) {
654         // If the clobber live range extends beyond the existing live range,
655         // it'll need at least another live range, so set the flag to keep
656         // iterating.
657         if (SubRangeEnd > IP->end) {
658           Start = IP->end;
659           Done = false;
660         }
661         SubRangeEnd = IP->start;
662         // If this trimmed away the whole range, ignore it.
663         if (SubRangeStart == SubRangeEnd) continue;
664       }
665
666       // Insert the clobber interval.
667       IP = addRangeFrom(LiveRange(SubRangeStart, SubRangeEnd, ClobberValNo),
668                         IP);
669       UnusedValNo = 0;
670     }
671   }
672
673   if (UnusedValNo) {
674     // Delete the last unused val#.
675     valnos.pop_back();
676   }
677 }
678
679 void LiveInterval::MergeInClobberRange(LiveIntervals &li_,
680                                        SlotIndex Start,
681                                        SlotIndex End,
682                                        VNInfo::Allocator &VNInfoAllocator) {
683   // Find a value # to use for the clobber ranges.  If there is already a value#
684   // for unknown values, use it.
685   VNInfo *ClobberValNo =
686     getNextValue(li_.getInvalidIndex(), 0, false, VNInfoAllocator);
687   
688   iterator IP = begin();
689   IP = std::upper_bound(IP, end(), Start);
690     
691   // If the start of this range overlaps with an existing liverange, trim it.
692   if (IP != begin() && IP[-1].end > Start) {
693     Start = IP[-1].end;
694     // Trimmed away the whole range?
695     if (Start >= End) return;
696   }
697   // If the end of this range overlaps with an existing liverange, trim it.
698   if (IP != end() && End > IP->start) {
699     End = IP->start;
700     // If this trimmed away the whole range, ignore it.
701     if (Start == End) return;
702   }
703     
704   // Insert the clobber interval.
705   addRangeFrom(LiveRange(Start, End, ClobberValNo), IP);
706 }
707
708 /// MergeValueNumberInto - This method is called when two value nubmers
709 /// are found to be equivalent.  This eliminates V1, replacing all
710 /// LiveRanges with the V1 value number with the V2 value number.  This can
711 /// cause merging of V1/V2 values numbers and compaction of the value space.
712 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
713   assert(V1 != V2 && "Identical value#'s are always equivalent!");
714
715   // This code actually merges the (numerically) larger value number into the
716   // smaller value number, which is likely to allow us to compactify the value
717   // space.  The only thing we have to be careful of is to preserve the
718   // instruction that defines the result value.
719
720   // Make sure V2 is smaller than V1.
721   if (V1->id < V2->id) {
722     V1->copyFrom(*V2);
723     std::swap(V1, V2);
724   }
725
726   // Merge V1 live ranges into V2.
727   for (iterator I = begin(); I != end(); ) {
728     iterator LR = I++;
729     if (LR->valno != V1) continue;  // Not a V1 LiveRange.
730     
731     // Okay, we found a V1 live range.  If it had a previous, touching, V2 live
732     // range, extend it.
733     if (LR != begin()) {
734       iterator Prev = LR-1;
735       if (Prev->valno == V2 && Prev->end == LR->start) {
736         Prev->end = LR->end;
737
738         // Erase this live-range.
739         ranges.erase(LR);
740         I = Prev+1;
741         LR = Prev;
742       }
743     }
744     
745     // Okay, now we have a V1 or V2 live range that is maximally merged forward.
746     // Ensure that it is a V2 live-range.
747     LR->valno = V2;
748     
749     // If we can merge it into later V2 live ranges, do so now.  We ignore any
750     // following V1 live ranges, as they will be merged in subsequent iterations
751     // of the loop.
752     if (I != end()) {
753       if (I->start == LR->end && I->valno == V2) {
754         LR->end = I->end;
755         ranges.erase(I);
756         I = LR+1;
757       }
758     }
759   }
760   
761   // Now that V1 is dead, remove it.
762   markValNoForDeletion(V1);
763   
764   return V2;
765 }
766
767 void LiveInterval::Copy(const LiveInterval &RHS,
768                         MachineRegisterInfo *MRI,
769                         VNInfo::Allocator &VNInfoAllocator) {
770   ranges.clear();
771   valnos.clear();
772   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(RHS.reg);
773   MRI->setRegAllocationHint(reg, Hint.first, Hint.second);
774
775   weight = RHS.weight;
776   for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
777     const VNInfo *VNI = RHS.getValNumInfo(i);
778     createValueCopy(VNI, VNInfoAllocator);
779   }
780   for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
781     const LiveRange &LR = RHS.ranges[i];
782     addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
783   }
784 }
785
786 unsigned LiveInterval::getSize() const {
787   unsigned Sum = 0;
788   for (const_iterator I = begin(), E = end(); I != E; ++I)
789     Sum += I->start.distance(I->end);
790   return Sum;
791 }
792
793 /// ComputeJoinedWeight - Set the weight of a live interval Joined
794 /// after Other has been merged into it.
795 void LiveInterval::ComputeJoinedWeight(const LiveInterval &Other) {
796   // If either of these intervals was spilled, the weight is the
797   // weight of the non-spilled interval.  This can only happen with
798   // iterative coalescers.
799
800   if (Other.weight != HUGE_VALF) {
801     weight += Other.weight;
802   }
803   else if (weight == HUGE_VALF &&
804       !TargetRegisterInfo::isPhysicalRegister(reg)) {
805     // Remove this assert if you have an iterative coalescer
806     assert(0 && "Joining to spilled interval");
807     weight = Other.weight;
808   }
809   else {
810     // Otherwise the weight stays the same
811     // Remove this assert if you have an iterative coalescer
812     assert(0 && "Joining from spilled interval");
813   }
814 }
815
816 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
817   return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
818 }
819
820 void LiveRange::dump() const {
821   dbgs() << *this << "\n";
822 }
823
824 void LiveInterval::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const {
825   if (isStackSlot())
826     OS << "SS#" << getStackSlotIndex();
827   else if (TRI && TargetRegisterInfo::isPhysicalRegister(reg))
828     OS << TRI->getName(reg);
829   else
830     OS << "%reg" << reg;
831
832   OS << ',' << weight;
833
834   if (empty())
835     OS << " EMPTY";
836   else {
837     OS << " = ";
838     for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
839            E = ranges.end(); I != E; ++I) {
840       OS << *I;
841       assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
842     }
843   }
844
845   // Print value number info.
846   if (getNumValNums()) {
847     OS << "  ";
848     unsigned vnum = 0;
849     for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
850          ++i, ++vnum) {
851       const VNInfo *vni = *i;
852       if (vnum) OS << " ";
853       OS << vnum << "@";
854       if (vni->isUnused()) {
855         OS << "x";
856       } else {
857         if (!vni->isDefAccurate() && !vni->isPHIDef())
858           OS << "?";
859         else
860           OS << vni->def;
861         if (vni->hasPHIKill())
862           OS << "-phikill";
863         if (vni->hasRedefByEC())
864           OS << "-ec";
865       }
866     }
867   }
868 }
869
870 void LiveInterval::dump() const {
871   dbgs() << *this << "\n";
872 }
873
874
875 void LiveRange::print(raw_ostream &os) const {
876   os << *this;
877 }