Move LiveIntervalMap::extendTo into LiveInterval itself.
[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 // CompEnd - Compare LiveRange ends.
34 namespace {
35 struct CompEnd {
36   bool operator()(const LiveRange &A, const LiveRange &B) const {
37     return A.end < B.end;
38   }
39 };
40 }
41
42 LiveInterval::iterator LiveInterval::find(SlotIndex Pos) {
43   assert(Pos.isValid() && "Cannot search for an invalid index");
44   return std::upper_bound(begin(), end(), LiveRange(SlotIndex(), Pos, 0),
45                           CompEnd());
46 }
47
48 /// killedInRange - Return true if the interval has kills in [Start,End).
49 bool LiveInterval::killedInRange(SlotIndex Start, SlotIndex End) const {
50   Ranges::const_iterator r =
51     std::lower_bound(ranges.begin(), ranges.end(), End);
52
53   // Now r points to the first interval with start >= End, or ranges.end().
54   if (r == ranges.begin())
55     return false;
56
57   --r;
58   // Now r points to the last interval with end <= End.
59   // r->end is the kill point.
60   return r->end >= Start && r->end < End;
61 }
62
63 // overlaps - Return true if the intersection of the two live intervals is
64 // not empty.
65 //
66 // An example for overlaps():
67 //
68 // 0: A = ...
69 // 4: B = ...
70 // 8: C = A + B ;; last use of A
71 //
72 // The live intervals should look like:
73 //
74 // A = [3, 11)
75 // B = [7, x)
76 // C = [11, y)
77 //
78 // A->overlaps(C) should return false since we want to be able to join
79 // A and C.
80 //
81 bool LiveInterval::overlapsFrom(const LiveInterval& other,
82                                 const_iterator StartPos) const {
83   assert(!empty() && "empty interval");
84   const_iterator i = begin();
85   const_iterator ie = end();
86   const_iterator j = StartPos;
87   const_iterator je = other.end();
88
89   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
90          StartPos != other.end() && "Bogus start position hint!");
91
92   if (i->start < j->start) {
93     i = std::upper_bound(i, ie, j->start);
94     if (i != ranges.begin()) --i;
95   } else if (j->start < i->start) {
96     ++StartPos;
97     if (StartPos != other.end() && StartPos->start <= i->start) {
98       assert(StartPos < other.end() && i < end());
99       j = std::upper_bound(j, je, i->start);
100       if (j != other.ranges.begin()) --j;
101     }
102   } else {
103     return true;
104   }
105
106   if (j == je) return false;
107
108   while (i != ie) {
109     if (i->start > j->start) {
110       std::swap(i, j);
111       std::swap(ie, je);
112     }
113
114     if (i->end > j->start)
115       return true;
116     ++i;
117   }
118
119   return false;
120 }
121
122 /// overlaps - Return true if the live interval overlaps a range specified
123 /// by [Start, End).
124 bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const {
125   assert(Start < End && "Invalid range");
126   const_iterator I = std::lower_bound(begin(), end(), End);
127   return I != begin() && (--I)->end > Start;
128 }
129
130
131 /// ValNo is dead, remove it.  If it is the largest value number, just nuke it
132 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
133 /// it can be nuked later.
134 void LiveInterval::markValNoForDeletion(VNInfo *ValNo) {
135   if (ValNo->id == getNumValNums()-1) {
136     do {
137       valnos.pop_back();
138     } while (!valnos.empty() && valnos.back()->isUnused());
139   } else {
140     ValNo->setIsUnused(true);
141   }
142 }
143
144 /// RenumberValues - Renumber all values in order of appearance and delete the
145 /// remaining unused values.
146 void LiveInterval::RenumberValues(LiveIntervals &lis) {
147   SmallPtrSet<VNInfo*, 8> Seen;
148   bool seenPHIDef = false;
149   valnos.clear();
150   for (const_iterator I = begin(), E = end(); I != E; ++I) {
151     VNInfo *VNI = I->valno;
152     if (!Seen.insert(VNI))
153       continue;
154     assert(!VNI->isUnused() && "Unused valno used by live range");
155     VNI->id = (unsigned)valnos.size();
156     valnos.push_back(VNI);
157     VNI->setHasPHIKill(false);
158     if (VNI->isPHIDef())
159       seenPHIDef = true;
160   }
161
162   // Recompute phi kill flags.
163   if (!seenPHIDef)
164     return;
165   for (const_vni_iterator I = vni_begin(), E = vni_end(); I != E; ++I) {
166     VNInfo *VNI = *I;
167     if (!VNI->isPHIDef())
168       continue;
169     const MachineBasicBlock *PHIBB = lis.getMBBFromIndex(VNI->def);
170     assert(PHIBB && "No basic block for phi-def");
171     for (MachineBasicBlock::const_pred_iterator PI = PHIBB->pred_begin(),
172          PE = PHIBB->pred_end(); PI != PE; ++PI) {
173       VNInfo *KVNI = getVNInfoAt(lis.getMBBEndIdx(*PI).getPrevSlot());
174       if (KVNI)
175         KVNI->setHasPHIKill(true);
176     }
177   }
178 }
179
180 /// extendIntervalEndTo - This method is used when we want to extend the range
181 /// specified by I to end at the specified endpoint.  To do this, we should
182 /// merge and eliminate all ranges that this will overlap with.  The iterator is
183 /// not invalidated.
184 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
185   assert(I != ranges.end() && "Not a valid interval!");
186   VNInfo *ValNo = I->valno;
187
188   // Search for the first interval that we can't merge with.
189   Ranges::iterator MergeTo = llvm::next(I);
190   for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
191     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
192   }
193
194   // If NewEnd was in the middle of an interval, make sure to get its endpoint.
195   I->end = std::max(NewEnd, prior(MergeTo)->end);
196
197   // Erase any dead ranges.
198   ranges.erase(llvm::next(I), MergeTo);
199
200   // If the newly formed range now touches the range after it and if they have
201   // the same value number, merge the two ranges into one range.
202   Ranges::iterator Next = llvm::next(I);
203   if (Next != ranges.end() && Next->start <= I->end && Next->valno == ValNo) {
204     I->end = Next->end;
205     ranges.erase(Next);
206   }
207 }
208
209
210 /// extendIntervalStartTo - This method is used when we want to extend the range
211 /// specified by I to start at the specified endpoint.  To do this, we should
212 /// merge and eliminate all ranges that this will overlap with.
213 LiveInterval::Ranges::iterator
214 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
215   assert(I != ranges.end() && "Not a valid interval!");
216   VNInfo *ValNo = I->valno;
217
218   // Search for the first interval that we can't merge with.
219   Ranges::iterator MergeTo = I;
220   do {
221     if (MergeTo == ranges.begin()) {
222       I->start = NewStart;
223       ranges.erase(MergeTo, I);
224       return I;
225     }
226     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
227     --MergeTo;
228   } while (NewStart <= MergeTo->start);
229
230   // If we start in the middle of another interval, just delete a range and
231   // extend that interval.
232   if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
233     MergeTo->end = I->end;
234   } else {
235     // Otherwise, extend the interval right after.
236     ++MergeTo;
237     MergeTo->start = NewStart;
238     MergeTo->end = I->end;
239   }
240
241   ranges.erase(llvm::next(MergeTo), llvm::next(I));
242   return MergeTo;
243 }
244
245 LiveInterval::iterator
246 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
247   SlotIndex Start = LR.start, End = LR.end;
248   iterator it = std::upper_bound(From, ranges.end(), Start);
249
250   // If the inserted interval starts in the middle or right at the end of
251   // another interval, just extend that interval to contain the range of LR.
252   if (it != ranges.begin()) {
253     iterator B = prior(it);
254     if (LR.valno == B->valno) {
255       if (B->start <= Start && B->end >= Start) {
256         extendIntervalEndTo(B, End);
257         return B;
258       }
259     } else {
260       // Check to make sure that we are not overlapping two live ranges with
261       // different valno's.
262       assert(B->end <= Start &&
263              "Cannot overlap two LiveRanges with differing ValID's"
264              " (did you def the same reg twice in a MachineInstr?)");
265     }
266   }
267
268   // Otherwise, if this range ends in the middle of, or right next to, another
269   // interval, merge it into that interval.
270   if (it != ranges.end()) {
271     if (LR.valno == it->valno) {
272       if (it->start <= End) {
273         it = extendIntervalStartTo(it, Start);
274
275         // If LR is a complete superset of an interval, we may need to grow its
276         // endpoint as well.
277         if (End > it->end)
278           extendIntervalEndTo(it, End);
279         return it;
280       }
281     } else {
282       // Check to make sure that we are not overlapping two live ranges with
283       // different valno's.
284       assert(it->start >= End &&
285              "Cannot overlap two LiveRanges with differing ValID's");
286     }
287   }
288
289   // Otherwise, this is just a new range that doesn't interact with anything.
290   // Insert it.
291   return ranges.insert(it, LR);
292 }
293
294 /// extendInBlock - If this interval is live before UseIdx in the basic
295 /// block that starts at StartIdx, extend it to be live at UseIdx and return
296 /// the value. If there is no live range before UseIdx, return NULL.
297 VNInfo *LiveInterval::extendInBlock(SlotIndex StartIdx, SlotIndex UseIdx) {
298   if (empty())
299     return 0;
300   iterator I = std::upper_bound(begin(), end(), UseIdx);
301   if (I == begin())
302     return 0;
303   --I;
304   if (I->end <= StartIdx)
305     return 0;
306   if (I->end <= UseIdx)
307     extendIntervalEndTo(I, UseIdx.getNextSlot());
308   return I->valno;
309 }
310
311 /// removeRange - Remove the specified range from this interval.  Note that
312 /// the range must be in a single LiveRange in its entirety.
313 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
314                                bool RemoveDeadValNo) {
315   // Find the LiveRange containing this span.
316   Ranges::iterator I = find(Start);
317   assert(I != ranges.end() && "Range is not in interval!");
318   assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
319
320   // If the span we are removing is at the start of the LiveRange, adjust it.
321   VNInfo *ValNo = I->valno;
322   if (I->start == Start) {
323     if (I->end == End) {
324       if (RemoveDeadValNo) {
325         // Check if val# is dead.
326         bool isDead = true;
327         for (const_iterator II = begin(), EE = end(); II != EE; ++II)
328           if (II != I && II->valno == ValNo) {
329             isDead = false;
330             break;
331           }
332         if (isDead) {
333           // Now that ValNo is dead, remove it.
334           markValNoForDeletion(ValNo);
335         }
336       }
337
338       ranges.erase(I);  // Removed the whole LiveRange.
339     } else
340       I->start = End;
341     return;
342   }
343
344   // Otherwise if the span we are removing is at the end of the LiveRange,
345   // adjust the other way.
346   if (I->end == End) {
347     I->end = Start;
348     return;
349   }
350
351   // Otherwise, we are splitting the LiveRange into two pieces.
352   SlotIndex OldEnd = I->end;
353   I->end = Start;   // Trim the old interval.
354
355   // Insert the new one.
356   ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
357 }
358
359 /// removeValNo - Remove all the ranges defined by the specified value#.
360 /// Also remove the value# from value# list.
361 void LiveInterval::removeValNo(VNInfo *ValNo) {
362   if (empty()) return;
363   Ranges::iterator I = ranges.end();
364   Ranges::iterator E = ranges.begin();
365   do {
366     --I;
367     if (I->valno == ValNo)
368       ranges.erase(I);
369   } while (I != E);
370   // Now that ValNo is dead, remove it.
371   markValNoForDeletion(ValNo);
372 }
373
374 /// findDefinedVNInfo - Find the VNInfo defined by the specified
375 /// index (register interval).
376 VNInfo *LiveInterval::findDefinedVNInfoForRegInt(SlotIndex Idx) const {
377   for (LiveInterval::const_vni_iterator i = vni_begin(), e = vni_end();
378        i != e; ++i) {
379     if ((*i)->def == Idx)
380       return *i;
381   }
382
383   return 0;
384 }
385
386 /// join - Join two live intervals (this, and other) together.  This applies
387 /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
388 /// the intervals are not joinable, this aborts.
389 void LiveInterval::join(LiveInterval &Other,
390                         const int *LHSValNoAssignments,
391                         const int *RHSValNoAssignments,
392                         SmallVector<VNInfo*, 16> &NewVNInfo,
393                         MachineRegisterInfo *MRI) {
394   // Determine if any of our live range values are mapped.  This is uncommon, so
395   // we want to avoid the interval scan if not.
396   bool MustMapCurValNos = false;
397   unsigned NumVals = getNumValNums();
398   unsigned NumNewVals = NewVNInfo.size();
399   for (unsigned i = 0; i != NumVals; ++i) {
400     unsigned LHSValID = LHSValNoAssignments[i];
401     if (i != LHSValID ||
402         (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i)))
403       MustMapCurValNos = true;
404   }
405
406   // If we have to apply a mapping to our base interval assignment, rewrite it
407   // now.
408   if (MustMapCurValNos) {
409     // Map the first live range.
410     iterator OutIt = begin();
411     OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
412     ++OutIt;
413     for (iterator I = OutIt, E = end(); I != E; ++I) {
414       OutIt->valno = NewVNInfo[LHSValNoAssignments[I->valno->id]];
415
416       // If this live range has the same value # as its immediate predecessor,
417       // and if they are neighbors, remove one LiveRange.  This happens when we
418       // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
419       if (OutIt->valno == (OutIt-1)->valno && (OutIt-1)->end == OutIt->start) {
420         (OutIt-1)->end = OutIt->end;
421       } else {
422         if (I != OutIt) {
423           OutIt->start = I->start;
424           OutIt->end = I->end;
425         }
426
427         // Didn't merge, on to the next one.
428         ++OutIt;
429       }
430     }
431
432     // If we merge some live ranges, chop off the end.
433     ranges.erase(OutIt, end());
434   }
435
436   // Remember assignements because val# ids are changing.
437   SmallVector<unsigned, 16> OtherAssignments;
438   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
439     OtherAssignments.push_back(RHSValNoAssignments[I->valno->id]);
440
441   // Update val# info. Renumber them and make sure they all belong to this
442   // LiveInterval now. Also remove dead val#'s.
443   unsigned NumValNos = 0;
444   for (unsigned i = 0; i < NumNewVals; ++i) {
445     VNInfo *VNI = NewVNInfo[i];
446     if (VNI) {
447       if (NumValNos >= NumVals)
448         valnos.push_back(VNI);
449       else
450         valnos[NumValNos] = VNI;
451       VNI->id = NumValNos++;  // Renumber val#.
452     }
453   }
454   if (NumNewVals < NumVals)
455     valnos.resize(NumNewVals);  // shrinkify
456
457   // Okay, now insert the RHS live ranges into the LHS.
458   iterator InsertPos = begin();
459   unsigned RangeNo = 0;
460   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I, ++RangeNo) {
461     // Map the valno in the other live range to the current live range.
462     I->valno = NewVNInfo[OtherAssignments[RangeNo]];
463     assert(I->valno && "Adding a dead range?");
464     InsertPos = addRangeFrom(*I, InsertPos);
465   }
466
467   ComputeJoinedWeight(Other);
468 }
469
470 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
471 /// interval as the specified value number.  The LiveRanges in RHS are
472 /// allowed to overlap with LiveRanges in the current interval, but only if
473 /// the overlapping LiveRanges have the specified value number.
474 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
475                                         VNInfo *LHSValNo) {
476   // TODO: Make this more efficient.
477   iterator InsertPos = begin();
478   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
479     // Map the valno in the other live range to the current live range.
480     LiveRange Tmp = *I;
481     Tmp.valno = LHSValNo;
482     InsertPos = addRangeFrom(Tmp, InsertPos);
483   }
484 }
485
486
487 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
488 /// in RHS into this live interval as the specified value number.
489 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
490 /// current interval, it will replace the value numbers of the overlaped
491 /// live ranges with the specified value number.
492 void LiveInterval::MergeValueInAsValue(
493                                     const LiveInterval &RHS,
494                                     const VNInfo *RHSValNo, VNInfo *LHSValNo) {
495   SmallVector<VNInfo*, 4> ReplacedValNos;
496   iterator IP = begin();
497   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
498     assert(I->valno == RHS.getValNumInfo(I->valno->id) && "Bad VNInfo");
499     if (I->valno != RHSValNo)
500       continue;
501     SlotIndex Start = I->start, End = I->end;
502     IP = std::upper_bound(IP, end(), Start);
503     // If the start of this range overlaps with an existing liverange, trim it.
504     if (IP != begin() && IP[-1].end > Start) {
505       if (IP[-1].valno != LHSValNo) {
506         ReplacedValNos.push_back(IP[-1].valno);
507         IP[-1].valno = LHSValNo; // Update val#.
508       }
509       Start = IP[-1].end;
510       // Trimmed away the whole range?
511       if (Start >= End) continue;
512     }
513     // If the end of this range overlaps with an existing liverange, trim it.
514     if (IP != end() && End > IP->start) {
515       if (IP->valno != LHSValNo) {
516         ReplacedValNos.push_back(IP->valno);
517         IP->valno = LHSValNo;  // Update val#.
518       }
519       End = IP->start;
520       // If this trimmed away the whole range, ignore it.
521       if (Start == End) continue;
522     }
523
524     // Map the valno in the other live range to the current live range.
525     IP = addRangeFrom(LiveRange(Start, End, LHSValNo), IP);
526   }
527
528
529   SmallSet<VNInfo*, 4> Seen;
530   for (unsigned i = 0, e = ReplacedValNos.size(); i != e; ++i) {
531     VNInfo *V1 = ReplacedValNos[i];
532     if (Seen.insert(V1)) {
533       bool isDead = true;
534       for (const_iterator I = begin(), E = end(); I != E; ++I)
535         if (I->valno == V1) {
536           isDead = false;
537           break;
538         }
539       if (isDead) {
540         // Now that V1 is dead, remove it.
541         markValNoForDeletion(V1);
542       }
543     }
544   }
545 }
546
547
548
549 /// MergeValueNumberInto - This method is called when two value nubmers
550 /// are found to be equivalent.  This eliminates V1, replacing all
551 /// LiveRanges with the V1 value number with the V2 value number.  This can
552 /// cause merging of V1/V2 values numbers and compaction of the value space.
553 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
554   assert(V1 != V2 && "Identical value#'s are always equivalent!");
555
556   // This code actually merges the (numerically) larger value number into the
557   // smaller value number, which is likely to allow us to compactify the value
558   // space.  The only thing we have to be careful of is to preserve the
559   // instruction that defines the result value.
560
561   // Make sure V2 is smaller than V1.
562   if (V1->id < V2->id) {
563     V1->copyFrom(*V2);
564     std::swap(V1, V2);
565   }
566
567   // Merge V1 live ranges into V2.
568   for (iterator I = begin(); I != end(); ) {
569     iterator LR = I++;
570     if (LR->valno != V1) continue;  // Not a V1 LiveRange.
571
572     // Okay, we found a V1 live range.  If it had a previous, touching, V2 live
573     // range, extend it.
574     if (LR != begin()) {
575       iterator Prev = LR-1;
576       if (Prev->valno == V2 && Prev->end == LR->start) {
577         Prev->end = LR->end;
578
579         // Erase this live-range.
580         ranges.erase(LR);
581         I = Prev+1;
582         LR = Prev;
583       }
584     }
585
586     // Okay, now we have a V1 or V2 live range that is maximally merged forward.
587     // Ensure that it is a V2 live-range.
588     LR->valno = V2;
589
590     // If we can merge it into later V2 live ranges, do so now.  We ignore any
591     // following V1 live ranges, as they will be merged in subsequent iterations
592     // of the loop.
593     if (I != end()) {
594       if (I->start == LR->end && I->valno == V2) {
595         LR->end = I->end;
596         ranges.erase(I);
597         I = LR+1;
598       }
599     }
600   }
601
602   // Merge the relevant flags.
603   V2->mergeFlags(V1);
604
605   // Now that V1 is dead, remove it.
606   markValNoForDeletion(V1);
607
608   return V2;
609 }
610
611 void LiveInterval::Copy(const LiveInterval &RHS,
612                         MachineRegisterInfo *MRI,
613                         VNInfo::Allocator &VNInfoAllocator) {
614   ranges.clear();
615   valnos.clear();
616   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(RHS.reg);
617   MRI->setRegAllocationHint(reg, Hint.first, Hint.second);
618
619   weight = RHS.weight;
620   for (unsigned i = 0, e = RHS.getNumValNums(); i != e; ++i) {
621     const VNInfo *VNI = RHS.getValNumInfo(i);
622     createValueCopy(VNI, VNInfoAllocator);
623   }
624   for (unsigned i = 0, e = RHS.ranges.size(); i != e; ++i) {
625     const LiveRange &LR = RHS.ranges[i];
626     addRange(LiveRange(LR.start, LR.end, getValNumInfo(LR.valno->id)));
627   }
628 }
629
630 unsigned LiveInterval::getSize() const {
631   unsigned Sum = 0;
632   for (const_iterator I = begin(), E = end(); I != E; ++I)
633     Sum += I->start.distance(I->end);
634   return Sum;
635 }
636
637 /// ComputeJoinedWeight - Set the weight of a live interval Joined
638 /// after Other has been merged into it.
639 void LiveInterval::ComputeJoinedWeight(const LiveInterval &Other) {
640   // If either of these intervals was spilled, the weight is the
641   // weight of the non-spilled interval.  This can only happen with
642   // iterative coalescers.
643
644   if (Other.weight != HUGE_VALF) {
645     weight += Other.weight;
646   }
647   else if (weight == HUGE_VALF &&
648       !TargetRegisterInfo::isPhysicalRegister(reg)) {
649     // Remove this assert if you have an iterative coalescer
650     assert(0 && "Joining to spilled interval");
651     weight = Other.weight;
652   }
653   else {
654     // Otherwise the weight stays the same
655     // Remove this assert if you have an iterative coalescer
656     assert(0 && "Joining from spilled interval");
657   }
658 }
659
660 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
661   return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
662 }
663
664 void LiveRange::dump() const {
665   dbgs() << *this << "\n";
666 }
667
668 void LiveInterval::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const {
669   OS << PrintReg(reg, TRI);
670   if (weight != 0)
671     OS << ',' << weight;
672
673   if (empty())
674     OS << " EMPTY";
675   else {
676     OS << " = ";
677     for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
678            E = ranges.end(); I != E; ++I) {
679       OS << *I;
680       assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
681     }
682   }
683
684   // Print value number info.
685   if (getNumValNums()) {
686     OS << "  ";
687     unsigned vnum = 0;
688     for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
689          ++i, ++vnum) {
690       const VNInfo *vni = *i;
691       if (vnum) OS << " ";
692       OS << vnum << "@";
693       if (vni->isUnused()) {
694         OS << "x";
695       } else {
696         OS << vni->def;
697         if (vni->isPHIDef())
698           OS << "-phidef";
699         if (vni->hasPHIKill())
700           OS << "-phikill";
701         if (vni->hasRedefByEC())
702           OS << "-ec";
703       }
704     }
705   }
706 }
707
708 void LiveInterval::dump() const {
709   dbgs() << *this << "\n";
710 }
711
712
713 void LiveRange::print(raw_ostream &os) const {
714   os << *this;
715 }
716
717 unsigned ConnectedVNInfoEqClasses::Classify(const LiveInterval *LI) {
718   // Create initial equivalence classes.
719   eqClass_.clear();
720   eqClass_.grow(LI->getNumValNums());
721
722   const VNInfo *used = 0, *unused = 0;
723
724   // Determine connections.
725   for (LiveInterval::const_vni_iterator I = LI->vni_begin(), E = LI->vni_end();
726        I != E; ++I) {
727     const VNInfo *VNI = *I;
728     // Group all unused values into one class.
729     if (VNI->isUnused()) {
730       if (unused)
731         eqClass_.join(unused->id, VNI->id);
732       unused = VNI;
733       continue;
734     }
735     used = VNI;
736     if (VNI->isPHIDef()) {
737       const MachineBasicBlock *MBB = lis_.getMBBFromIndex(VNI->def);
738       assert(MBB && "Phi-def has no defining MBB");
739       // Connect to values live out of predecessors.
740       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
741            PE = MBB->pred_end(); PI != PE; ++PI)
742         if (const VNInfo *PVNI =
743               LI->getVNInfoAt(lis_.getMBBEndIdx(*PI).getPrevSlot()))
744           eqClass_.join(VNI->id, PVNI->id);
745     } else {
746       // Normal value defined by an instruction. Check for two-addr redef.
747       // FIXME: This could be coincidental. Should we really check for a tied
748       // operand constraint?
749       // Note that VNI->def may be a use slot for an early clobber def.
750       if (const VNInfo *UVNI = LI->getVNInfoAt(VNI->def.getPrevSlot()))
751         eqClass_.join(VNI->id, UVNI->id);
752     }
753   }
754
755   // Lump all the unused values in with the last used value.
756   if (used && unused)
757     eqClass_.join(used->id, unused->id);
758
759   eqClass_.compress();
760   return eqClass_.getNumClasses();
761 }
762
763 void ConnectedVNInfoEqClasses::Distribute(LiveInterval *LIV[]) {
764   assert(LIV[0] && "LIV[0] must be set");
765   LiveInterval &LI = *LIV[0];
766
767   // First move runs to new intervals.
768   LiveInterval::iterator J = LI.begin(), E = LI.end();
769   while (J != E && eqClass_[J->valno->id] == 0)
770     ++J;
771   for (LiveInterval::iterator I = J; I != E; ++I) {
772     if (unsigned eq = eqClass_[I->valno->id]) {
773       assert((LIV[eq]->empty() || LIV[eq]->expiredAt(I->start)) &&
774              "New intervals should be empty");
775       LIV[eq]->ranges.push_back(*I);
776     } else
777       *J++ = *I;
778   }
779   LI.ranges.erase(J, E);
780
781   // Transfer VNInfos to their new owners and renumber them.
782   unsigned j = 0, e = LI.getNumValNums();
783   while (j != e && eqClass_[j] == 0)
784     ++j;
785   for (unsigned i = j; i != e; ++i) {
786     VNInfo *VNI = LI.getValNumInfo(i);
787     if (unsigned eq = eqClass_[i]) {
788       VNI->id = LIV[eq]->getNumValNums();
789       LIV[eq]->valnos.push_back(VNI);
790     } else {
791       VNI->id = j;
792       LI.valnos[j++] = VNI;
793     }
794   }
795   LI.valnos.resize(j);
796 }