LLVM API Documentation

LiveInterval.cpp
Go to the documentation of this file.
00001 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the LiveRange and LiveInterval classes.  Given some
00011 // numbering of each the machine instructions an interval [i, j) is said to be a
00012 // live interval for register v if there is no instruction with number j' > j
00013 // such that v is live at j' and there is no instruction with number i' < i such
00014 // that v is live at i'. In this implementation intervals can have holes,
00015 // i.e. an interval might look like [1,20), [50,65), [1000,1001).  Each
00016 // individual range is represented as an instance of LiveRange, and the whole
00017 // interval is represented as an instance of LiveInterval.
00018 //
00019 //===----------------------------------------------------------------------===//
00020 
00021 #include "llvm/CodeGen/LiveInterval.h"
00022 #include "RegisterCoalescer.h"
00023 #include "llvm/ADT/DenseMap.h"
00024 #include "llvm/ADT/STLExtras.h"
00025 #include "llvm/ADT/SmallSet.h"
00026 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00027 #include "llvm/CodeGen/MachineRegisterInfo.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Target/TargetRegisterInfo.h"
00031 #include <algorithm>
00032 using namespace llvm;
00033 
00034 LiveInterval::iterator LiveInterval::find(SlotIndex Pos) {
00035   // This algorithm is basically std::upper_bound.
00036   // Unfortunately, std::upper_bound cannot be used with mixed types until we
00037   // adopt C++0x. Many libraries can do it, but not all.
00038   if (empty() || Pos >= endIndex())
00039     return end();
00040   iterator I = begin();
00041   size_t Len = ranges.size();
00042   do {
00043     size_t Mid = Len >> 1;
00044     if (Pos < I[Mid].end)
00045       Len = Mid;
00046     else
00047       I += Mid + 1, Len -= Mid + 1;
00048   } while (Len);
00049   return I;
00050 }
00051 
00052 VNInfo *LiveInterval::createDeadDef(SlotIndex Def,
00053                                     VNInfo::Allocator &VNInfoAllocator) {
00054   assert(!Def.isDead() && "Cannot define a value at the dead slot");
00055   iterator I = find(Def);
00056   if (I == end()) {
00057     VNInfo *VNI = getNextValue(Def, VNInfoAllocator);
00058     ranges.push_back(LiveRange(Def, Def.getDeadSlot(), VNI));
00059     return VNI;
00060   }
00061   if (SlotIndex::isSameInstr(Def, I->start)) {
00062     assert(I->valno->def == I->start && "Inconsistent existing value def");
00063 
00064     // It is possible to have both normal and early-clobber defs of the same
00065     // register on an instruction. It doesn't make a lot of sense, but it is
00066     // possible to specify in inline assembly.
00067     //
00068     // Just convert everything to early-clobber.
00069     Def = std::min(Def, I->start);
00070     if (Def != I->start)
00071       I->start = I->valno->def = Def;
00072     return I->valno;
00073   }
00074   assert(SlotIndex::isEarlierInstr(Def, I->start) && "Already live at def");
00075   VNInfo *VNI = getNextValue(Def, VNInfoAllocator);
00076   ranges.insert(I, LiveRange(Def, Def.getDeadSlot(), VNI));
00077   return VNI;
00078 }
00079 
00080 // overlaps - Return true if the intersection of the two live intervals is
00081 // not empty.
00082 //
00083 // An example for overlaps():
00084 //
00085 // 0: A = ...
00086 // 4: B = ...
00087 // 8: C = A + B ;; last use of A
00088 //
00089 // The live intervals should look like:
00090 //
00091 // A = [3, 11)
00092 // B = [7, x)
00093 // C = [11, y)
00094 //
00095 // A->overlaps(C) should return false since we want to be able to join
00096 // A and C.
00097 //
00098 bool LiveInterval::overlapsFrom(const LiveInterval& other,
00099                                 const_iterator StartPos) const {
00100   assert(!empty() && "empty interval");
00101   const_iterator i = begin();
00102   const_iterator ie = end();
00103   const_iterator j = StartPos;
00104   const_iterator je = other.end();
00105 
00106   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
00107          StartPos != other.end() && "Bogus start position hint!");
00108 
00109   if (i->start < j->start) {
00110     i = std::upper_bound(i, ie, j->start);
00111     if (i != ranges.begin()) --i;
00112   } else if (j->start < i->start) {
00113     ++StartPos;
00114     if (StartPos != other.end() && StartPos->start <= i->start) {
00115       assert(StartPos < other.end() && i < end());
00116       j = std::upper_bound(j, je, i->start);
00117       if (j != other.ranges.begin()) --j;
00118     }
00119   } else {
00120     return true;
00121   }
00122 
00123   if (j == je) return false;
00124 
00125   while (i != ie) {
00126     if (i->start > j->start) {
00127       std::swap(i, j);
00128       std::swap(ie, je);
00129     }
00130 
00131     if (i->end > j->start)
00132       return true;
00133     ++i;
00134   }
00135 
00136   return false;
00137 }
00138 
00139 bool LiveInterval::overlaps(const LiveInterval &Other,
00140                             const CoalescerPair &CP,
00141                             const SlotIndexes &Indexes) const {
00142   assert(!empty() && "empty interval");
00143   if (Other.empty())
00144     return false;
00145 
00146   // Use binary searches to find initial positions.
00147   const_iterator I = find(Other.beginIndex());
00148   const_iterator IE = end();
00149   if (I == IE)
00150     return false;
00151   const_iterator J = Other.find(I->start);
00152   const_iterator JE = Other.end();
00153   if (J == JE)
00154     return false;
00155 
00156   for (;;) {
00157     // J has just been advanced to satisfy:
00158     assert(J->end >= I->start);
00159     // Check for an overlap.
00160     if (J->start < I->end) {
00161       // I and J are overlapping. Find the later start.
00162       SlotIndex Def = std::max(I->start, J->start);
00163       // Allow the overlap if Def is a coalescable copy.
00164       if (Def.isBlock() ||
00165           !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
00166         return true;
00167     }
00168     // Advance the iterator that ends first to check for more overlaps.
00169     if (J->end > I->end) {
00170       std::swap(I, J);
00171       std::swap(IE, JE);
00172     }
00173     // Advance J until J->end >= I->start.
00174     do
00175       if (++J == JE)
00176         return false;
00177     while (J->end < I->start);
00178   }
00179 }
00180 
00181 /// overlaps - Return true if the live interval overlaps a range specified
00182 /// by [Start, End).
00183 bool LiveInterval::overlaps(SlotIndex Start, SlotIndex End) const {
00184   assert(Start < End && "Invalid range");
00185   const_iterator I = std::lower_bound(begin(), end(), End);
00186   return I != begin() && (--I)->end > Start;
00187 }
00188 
00189 
00190 /// ValNo is dead, remove it.  If it is the largest value number, just nuke it
00191 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
00192 /// it can be nuked later.
00193 void LiveInterval::markValNoForDeletion(VNInfo *ValNo) {
00194   if (ValNo->id == getNumValNums()-1) {
00195     do {
00196       valnos.pop_back();
00197     } while (!valnos.empty() && valnos.back()->isUnused());
00198   } else {
00199     ValNo->markUnused();
00200   }
00201 }
00202 
00203 /// RenumberValues - Renumber all values in order of appearance and delete the
00204 /// remaining unused values.
00205 void LiveInterval::RenumberValues(LiveIntervals &lis) {
00206   SmallPtrSet<VNInfo*, 8> Seen;
00207   valnos.clear();
00208   for (const_iterator I = begin(), E = end(); I != E; ++I) {
00209     VNInfo *VNI = I->valno;
00210     if (!Seen.insert(VNI))
00211       continue;
00212     assert(!VNI->isUnused() && "Unused valno used by live range");
00213     VNI->id = (unsigned)valnos.size();
00214     valnos.push_back(VNI);
00215   }
00216 }
00217 
00218 /// extendIntervalEndTo - This method is used when we want to extend the range
00219 /// specified by I to end at the specified endpoint.  To do this, we should
00220 /// merge and eliminate all ranges that this will overlap with.  The iterator is
00221 /// not invalidated.
00222 void LiveInterval::extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd) {
00223   assert(I != ranges.end() && "Not a valid interval!");
00224   VNInfo *ValNo = I->valno;
00225 
00226   // Search for the first interval that we can't merge with.
00227   Ranges::iterator MergeTo = llvm::next(I);
00228   for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) {
00229     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
00230   }
00231 
00232   // If NewEnd was in the middle of an interval, make sure to get its endpoint.
00233   I->end = std::max(NewEnd, prior(MergeTo)->end);
00234 
00235   // If the newly formed range now touches the range after it and if they have
00236   // the same value number, merge the two ranges into one range.
00237   if (MergeTo != ranges.end() && MergeTo->start <= I->end &&
00238       MergeTo->valno == ValNo) {
00239     I->end = MergeTo->end;
00240     ++MergeTo;
00241   }
00242 
00243   // Erase any dead ranges.
00244   ranges.erase(llvm::next(I), MergeTo);
00245 }
00246 
00247 
00248 /// extendIntervalStartTo - This method is used when we want to extend the range
00249 /// specified by I to start at the specified endpoint.  To do this, we should
00250 /// merge and eliminate all ranges that this will overlap with.
00251 LiveInterval::Ranges::iterator
00252 LiveInterval::extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStart) {
00253   assert(I != ranges.end() && "Not a valid interval!");
00254   VNInfo *ValNo = I->valno;
00255 
00256   // Search for the first interval that we can't merge with.
00257   Ranges::iterator MergeTo = I;
00258   do {
00259     if (MergeTo == ranges.begin()) {
00260       I->start = NewStart;
00261       ranges.erase(MergeTo, I);
00262       return I;
00263     }
00264     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
00265     --MergeTo;
00266   } while (NewStart <= MergeTo->start);
00267 
00268   // If we start in the middle of another interval, just delete a range and
00269   // extend that interval.
00270   if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
00271     MergeTo->end = I->end;
00272   } else {
00273     // Otherwise, extend the interval right after.
00274     ++MergeTo;
00275     MergeTo->start = NewStart;
00276     MergeTo->end = I->end;
00277   }
00278 
00279   ranges.erase(llvm::next(MergeTo), llvm::next(I));
00280   return MergeTo;
00281 }
00282 
00283 LiveInterval::iterator
00284 LiveInterval::addRangeFrom(LiveRange LR, iterator From) {
00285   SlotIndex Start = LR.start, End = LR.end;
00286   iterator it = std::upper_bound(From, ranges.end(), Start);
00287 
00288   // If the inserted interval starts in the middle or right at the end of
00289   // another interval, just extend that interval to contain the range of LR.
00290   if (it != ranges.begin()) {
00291     iterator B = prior(it);
00292     if (LR.valno == B->valno) {
00293       if (B->start <= Start && B->end >= Start) {
00294         extendIntervalEndTo(B, End);
00295         return B;
00296       }
00297     } else {
00298       // Check to make sure that we are not overlapping two live ranges with
00299       // different valno's.
00300       assert(B->end <= Start &&
00301              "Cannot overlap two LiveRanges with differing ValID's"
00302              " (did you def the same reg twice in a MachineInstr?)");
00303     }
00304   }
00305 
00306   // Otherwise, if this range ends in the middle of, or right next to, another
00307   // interval, merge it into that interval.
00308   if (it != ranges.end()) {
00309     if (LR.valno == it->valno) {
00310       if (it->start <= End) {
00311         it = extendIntervalStartTo(it, Start);
00312 
00313         // If LR is a complete superset of an interval, we may need to grow its
00314         // endpoint as well.
00315         if (End > it->end)
00316           extendIntervalEndTo(it, End);
00317         return it;
00318       }
00319     } else {
00320       // Check to make sure that we are not overlapping two live ranges with
00321       // different valno's.
00322       assert(it->start >= End &&
00323              "Cannot overlap two LiveRanges with differing ValID's");
00324     }
00325   }
00326 
00327   // Otherwise, this is just a new range that doesn't interact with anything.
00328   // Insert it.
00329   return ranges.insert(it, LR);
00330 }
00331 
00332 /// extendInBlock - If this interval is live before Kill in the basic
00333 /// block that starts at StartIdx, extend it to be live up to Kill and return
00334 /// the value. If there is no live range before Kill, return NULL.
00335 VNInfo *LiveInterval::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
00336   if (empty())
00337     return 0;
00338   iterator I = std::upper_bound(begin(), end(), Kill.getPrevSlot());
00339   if (I == begin())
00340     return 0;
00341   --I;
00342   if (I->end <= StartIdx)
00343     return 0;
00344   if (I->end < Kill)
00345     extendIntervalEndTo(I, Kill);
00346   return I->valno;
00347 }
00348 
00349 /// removeRange - Remove the specified range from this interval.  Note that
00350 /// the range must be in a single LiveRange in its entirety.
00351 void LiveInterval::removeRange(SlotIndex Start, SlotIndex End,
00352                                bool RemoveDeadValNo) {
00353   // Find the LiveRange containing this span.
00354   Ranges::iterator I = find(Start);
00355   assert(I != ranges.end() && "Range is not in interval!");
00356   assert(I->containsRange(Start, End) && "Range is not entirely in interval!");
00357 
00358   // If the span we are removing is at the start of the LiveRange, adjust it.
00359   VNInfo *ValNo = I->valno;
00360   if (I->start == Start) {
00361     if (I->end == End) {
00362       if (RemoveDeadValNo) {
00363         // Check if val# is dead.
00364         bool isDead = true;
00365         for (const_iterator II = begin(), EE = end(); II != EE; ++II)
00366           if (II != I && II->valno == ValNo) {
00367             isDead = false;
00368             break;
00369           }
00370         if (isDead) {
00371           // Now that ValNo is dead, remove it.
00372           markValNoForDeletion(ValNo);
00373         }
00374       }
00375 
00376       ranges.erase(I);  // Removed the whole LiveRange.
00377     } else
00378       I->start = End;
00379     return;
00380   }
00381 
00382   // Otherwise if the span we are removing is at the end of the LiveRange,
00383   // adjust the other way.
00384   if (I->end == End) {
00385     I->end = Start;
00386     return;
00387   }
00388 
00389   // Otherwise, we are splitting the LiveRange into two pieces.
00390   SlotIndex OldEnd = I->end;
00391   I->end = Start;   // Trim the old interval.
00392 
00393   // Insert the new one.
00394   ranges.insert(llvm::next(I), LiveRange(End, OldEnd, ValNo));
00395 }
00396 
00397 /// removeValNo - Remove all the ranges defined by the specified value#.
00398 /// Also remove the value# from value# list.
00399 void LiveInterval::removeValNo(VNInfo *ValNo) {
00400   if (empty()) return;
00401   Ranges::iterator I = ranges.end();
00402   Ranges::iterator E = ranges.begin();
00403   do {
00404     --I;
00405     if (I->valno == ValNo)
00406       ranges.erase(I);
00407   } while (I != E);
00408   // Now that ValNo is dead, remove it.
00409   markValNoForDeletion(ValNo);
00410 }
00411 
00412 /// join - Join two live intervals (this, and other) together.  This applies
00413 /// mappings to the value numbers in the LHS/RHS intervals as specified.  If
00414 /// the intervals are not joinable, this aborts.
00415 void LiveInterval::join(LiveInterval &Other,
00416                         const int *LHSValNoAssignments,
00417                         const int *RHSValNoAssignments,
00418                         SmallVector<VNInfo*, 16> &NewVNInfo,
00419                         MachineRegisterInfo *MRI) {
00420   verify();
00421 
00422   // Determine if any of our live range values are mapped.  This is uncommon, so
00423   // we want to avoid the interval scan if not.
00424   bool MustMapCurValNos = false;
00425   unsigned NumVals = getNumValNums();
00426   unsigned NumNewVals = NewVNInfo.size();
00427   for (unsigned i = 0; i != NumVals; ++i) {
00428     unsigned LHSValID = LHSValNoAssignments[i];
00429     if (i != LHSValID ||
00430         (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
00431       MustMapCurValNos = true;
00432       break;
00433     }
00434   }
00435 
00436   // If we have to apply a mapping to our base interval assignment, rewrite it
00437   // now.
00438   if (MustMapCurValNos && !empty()) {
00439     // Map the first live range.
00440 
00441     iterator OutIt = begin();
00442     OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
00443     for (iterator I = llvm::next(OutIt), E = end(); I != E; ++I) {
00444       VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
00445       assert(nextValNo != 0 && "Huh?");
00446 
00447       // If this live range has the same value # as its immediate predecessor,
00448       // and if they are neighbors, remove one LiveRange.  This happens when we
00449       // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
00450       if (OutIt->valno == nextValNo && OutIt->end == I->start) {
00451         OutIt->end = I->end;
00452       } else {
00453         // Didn't merge. Move OutIt to the next interval,
00454         ++OutIt;
00455         OutIt->valno = nextValNo;
00456         if (OutIt != I) {
00457           OutIt->start = I->start;
00458           OutIt->end = I->end;
00459         }
00460       }
00461     }
00462     // If we merge some live ranges, chop off the end.
00463     ++OutIt;
00464     ranges.erase(OutIt, end());
00465   }
00466 
00467   // Rewrite Other values before changing the VNInfo ids.
00468   // This can leave Other in an invalid state because we're not coalescing
00469   // touching segments that now have identical values. That's OK since Other is
00470   // not supposed to be valid after calling join();
00471   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
00472     I->valno = NewVNInfo[RHSValNoAssignments[I->valno->id]];
00473 
00474   // Update val# info. Renumber them and make sure they all belong to this
00475   // LiveInterval now. Also remove dead val#'s.
00476   unsigned NumValNos = 0;
00477   for (unsigned i = 0; i < NumNewVals; ++i) {
00478     VNInfo *VNI = NewVNInfo[i];
00479     if (VNI) {
00480       if (NumValNos >= NumVals)
00481         valnos.push_back(VNI);
00482       else
00483         valnos[NumValNos] = VNI;
00484       VNI->id = NumValNos++;  // Renumber val#.
00485     }
00486   }
00487   if (NumNewVals < NumVals)
00488     valnos.resize(NumNewVals);  // shrinkify
00489 
00490   // Okay, now insert the RHS live ranges into the LHS.
00491   LiveRangeUpdater Updater(this);
00492   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
00493     Updater.add(*I);
00494 }
00495 
00496 /// MergeRangesInAsValue - Merge all of the intervals in RHS into this live
00497 /// interval as the specified value number.  The LiveRanges in RHS are
00498 /// allowed to overlap with LiveRanges in the current interval, but only if
00499 /// the overlapping LiveRanges have the specified value number.
00500 void LiveInterval::MergeRangesInAsValue(const LiveInterval &RHS,
00501                                         VNInfo *LHSValNo) {
00502   LiveRangeUpdater Updater(this);
00503   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
00504     Updater.add(I->start, I->end, LHSValNo);
00505 }
00506 
00507 /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
00508 /// in RHS into this live interval as the specified value number.
00509 /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
00510 /// current interval, it will replace the value numbers of the overlaped
00511 /// live ranges with the specified value number.
00512 void LiveInterval::MergeValueInAsValue(const LiveInterval &RHS,
00513                                        const VNInfo *RHSValNo,
00514                                        VNInfo *LHSValNo) {
00515   LiveRangeUpdater Updater(this);
00516   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
00517     if (I->valno == RHSValNo)
00518       Updater.add(I->start, I->end, LHSValNo);
00519 }
00520 
00521 /// MergeValueNumberInto - This method is called when two value nubmers
00522 /// are found to be equivalent.  This eliminates V1, replacing all
00523 /// LiveRanges with the V1 value number with the V2 value number.  This can
00524 /// cause merging of V1/V2 values numbers and compaction of the value space.
00525 VNInfo* LiveInterval::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
00526   assert(V1 != V2 && "Identical value#'s are always equivalent!");
00527 
00528   // This code actually merges the (numerically) larger value number into the
00529   // smaller value number, which is likely to allow us to compactify the value
00530   // space.  The only thing we have to be careful of is to preserve the
00531   // instruction that defines the result value.
00532 
00533   // Make sure V2 is smaller than V1.
00534   if (V1->id < V2->id) {
00535     V1->copyFrom(*V2);
00536     std::swap(V1, V2);
00537   }
00538 
00539   // Merge V1 live ranges into V2.
00540   for (iterator I = begin(); I != end(); ) {
00541     iterator LR = I++;
00542     if (LR->valno != V1) continue;  // Not a V1 LiveRange.
00543 
00544     // Okay, we found a V1 live range.  If it had a previous, touching, V2 live
00545     // range, extend it.
00546     if (LR != begin()) {
00547       iterator Prev = LR-1;
00548       if (Prev->valno == V2 && Prev->end == LR->start) {
00549         Prev->end = LR->end;
00550 
00551         // Erase this live-range.
00552         ranges.erase(LR);
00553         I = Prev+1;
00554         LR = Prev;
00555       }
00556     }
00557 
00558     // Okay, now we have a V1 or V2 live range that is maximally merged forward.
00559     // Ensure that it is a V2 live-range.
00560     LR->valno = V2;
00561 
00562     // If we can merge it into later V2 live ranges, do so now.  We ignore any
00563     // following V1 live ranges, as they will be merged in subsequent iterations
00564     // of the loop.
00565     if (I != end()) {
00566       if (I->start == LR->end && I->valno == V2) {
00567         LR->end = I->end;
00568         ranges.erase(I);
00569         I = LR+1;
00570       }
00571     }
00572   }
00573 
00574   // Now that V1 is dead, remove it.
00575   markValNoForDeletion(V1);
00576 
00577   return V2;
00578 }
00579 
00580 unsigned LiveInterval::getSize() const {
00581   unsigned Sum = 0;
00582   for (const_iterator I = begin(), E = end(); I != E; ++I)
00583     Sum += I->start.distance(I->end);
00584   return Sum;
00585 }
00586 
00587 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange &LR) {
00588   return os << '[' << LR.start << ',' << LR.end << ':' << LR.valno->id << ")";
00589 }
00590 
00591 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00592 void LiveRange::dump() const {
00593   dbgs() << *this << "\n";
00594 }
00595 #endif
00596 
00597 void LiveInterval::print(raw_ostream &OS) const {
00598   if (empty())
00599     OS << "EMPTY";
00600   else {
00601     for (LiveInterval::Ranges::const_iterator I = ranges.begin(),
00602            E = ranges.end(); I != E; ++I) {
00603       OS << *I;
00604       assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
00605     }
00606   }
00607 
00608   // Print value number info.
00609   if (getNumValNums()) {
00610     OS << "  ";
00611     unsigned vnum = 0;
00612     for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
00613          ++i, ++vnum) {
00614       const VNInfo *vni = *i;
00615       if (vnum) OS << " ";
00616       OS << vnum << "@";
00617       if (vni->isUnused()) {
00618         OS << "x";
00619       } else {
00620         OS << vni->def;
00621         if (vni->isPHIDef())
00622           OS << "-phi";
00623       }
00624     }
00625   }
00626 }
00627 
00628 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00629 void LiveInterval::dump() const {
00630   dbgs() << *this << "\n";
00631 }
00632 #endif
00633 
00634 #ifndef NDEBUG
00635 void LiveInterval::verify() const {
00636   for (const_iterator I = begin(), E = end(); I != E; ++I) {
00637     assert(I->start.isValid());
00638     assert(I->end.isValid());
00639     assert(I->start < I->end);
00640     assert(I->valno != 0);
00641     assert(I->valno == valnos[I->valno->id]);
00642     if (llvm::next(I) != E) {
00643       assert(I->end <= llvm::next(I)->start);
00644       if (I->end == llvm::next(I)->start)
00645         assert(I->valno != llvm::next(I)->valno);
00646     }
00647   }
00648 }
00649 #endif
00650 
00651 
00652 void LiveRange::print(raw_ostream &os) const {
00653   os << *this;
00654 }
00655 
00656 //===----------------------------------------------------------------------===//
00657 //                           LiveRangeUpdater class
00658 //===----------------------------------------------------------------------===//
00659 //
00660 // The LiveRangeUpdater class always maintains these invariants:
00661 //
00662 // - When LastStart is invalid, Spills is empty and the iterators are invalid.
00663 //   This is the initial state, and the state created by flush().
00664 //   In this state, isDirty() returns false.
00665 //
00666 // Otherwise, segments are kept in three separate areas:
00667 //
00668 // 1. [begin; WriteI) at the front of LI.
00669 // 2. [ReadI; end) at the back of LI.
00670 // 3. Spills.
00671 //
00672 // - LI.begin() <= WriteI <= ReadI <= LI.end().
00673 // - Segments in all three areas are fully ordered and coalesced.
00674 // - Segments in area 1 precede and can't coalesce with segments in area 2.
00675 // - Segments in Spills precede and can't coalesce with segments in area 2.
00676 // - No coalescing is possible between segments in Spills and segments in area
00677 //   1, and there are no overlapping segments.
00678 //
00679 // The segments in Spills are not ordered with respect to the segments in area
00680 // 1. They need to be merged.
00681 //
00682 // When they exist, Spills.back().start <= LastStart,
00683 //                 and WriteI[-1].start <= LastStart.
00684 
00685 void LiveRangeUpdater::print(raw_ostream &OS) const {
00686   if (!isDirty()) {
00687     if (LI)
00688       OS << "Clean " << PrintReg(LI->reg) << " updater: " << *LI << '\n';
00689     else
00690       OS << "Null updater.\n";
00691     return;
00692   }
00693   assert(LI && "Can't have null LI in dirty updater.");
00694   OS << PrintReg(LI->reg) << " updater with gap = " << (ReadI - WriteI)
00695      << ", last start = " << LastStart
00696      << ":\n  Area 1:";
00697   for (LiveInterval::const_iterator I = LI->begin(); I != WriteI; ++I)
00698     OS << ' ' << *I;
00699   OS << "\n  Spills:";
00700   for (unsigned I = 0, E = Spills.size(); I != E; ++I)
00701     OS << ' ' << Spills[I];
00702   OS << "\n  Area 2:";
00703   for (LiveInterval::const_iterator I = ReadI, E = LI->end(); I != E; ++I)
00704     OS << ' ' << *I;
00705   OS << '\n';
00706 }
00707 
00708 void LiveRangeUpdater::dump() const
00709 {
00710   print(errs());
00711 }
00712 
00713 // Determine if A and B should be coalesced.
00714 static inline bool coalescable(const LiveRange &A, const LiveRange &B) {
00715   assert(A.start <= B.start && "Unordered live ranges.");
00716   if (A.end == B.start)
00717     return A.valno == B.valno;
00718   if (A.end < B.start)
00719     return false;
00720   assert(A.valno == B.valno && "Cannot overlap different values");
00721   return true;
00722 }
00723 
00724 void LiveRangeUpdater::add(LiveRange Seg) {
00725   assert(LI && "Cannot add to a null destination");
00726 
00727   // Flush the state if Start moves backwards.
00728   if (!LastStart.isValid() || LastStart > Seg.start) {
00729     if (isDirty())
00730       flush();
00731     // This brings us to an uninitialized state. Reinitialize.
00732     assert(Spills.empty() && "Leftover spilled segments");
00733     WriteI = ReadI = LI->begin();
00734   }
00735 
00736   // Remember start for next time.
00737   LastStart = Seg.start;
00738 
00739   // Advance ReadI until it ends after Seg.start.
00740   LiveInterval::iterator E = LI->end();
00741   if (ReadI != E && ReadI->end <= Seg.start) {
00742     // First try to close the gap between WriteI and ReadI with spills.
00743     if (ReadI != WriteI)
00744       mergeSpills();
00745     // Then advance ReadI.
00746     if (ReadI == WriteI)
00747       ReadI = WriteI = LI->find(Seg.start);
00748     else
00749       while (ReadI != E && ReadI->end <= Seg.start)
00750         *WriteI++ = *ReadI++;
00751   }
00752 
00753   assert(ReadI == E || ReadI->end > Seg.start);
00754 
00755   // Check if the ReadI segment begins early.
00756   if (ReadI != E && ReadI->start <= Seg.start) {
00757     assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
00758     // Bail if Seg is completely contained in ReadI.
00759     if (ReadI->end >= Seg.end)
00760       return;
00761     // Coalesce into Seg.
00762     Seg.start = ReadI->start;
00763     ++ReadI;
00764   }
00765 
00766   // Coalesce as much as possible from ReadI into Seg.
00767   while (ReadI != E && coalescable(Seg, *ReadI)) {
00768     Seg.end = std::max(Seg.end, ReadI->end);
00769     ++ReadI;
00770   }
00771 
00772   // Try coalescing Spills.back() into Seg.
00773   if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
00774     Seg.start = Spills.back().start;
00775     Seg.end = std::max(Spills.back().end, Seg.end);
00776     Spills.pop_back();
00777   }
00778 
00779   // Try coalescing Seg into WriteI[-1].
00780   if (WriteI != LI->begin() && coalescable(WriteI[-1], Seg)) {
00781     WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
00782     return;
00783   }
00784 
00785   // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
00786   if (WriteI != ReadI) {
00787     *WriteI++ = Seg;
00788     return;
00789   }
00790 
00791   // Finally, append to LI or Spills.
00792   if (WriteI == E) {
00793     LI->ranges.push_back(Seg);
00794     WriteI = ReadI = LI->ranges.end();
00795   } else
00796     Spills.push_back(Seg);
00797 }
00798 
00799 // Merge as many spilled segments as possible into the gap between WriteI
00800 // and ReadI. Advance WriteI to reflect the inserted instructions.
00801 void LiveRangeUpdater::mergeSpills() {
00802   // Perform a backwards merge of Spills and [SpillI;WriteI).
00803   size_t GapSize = ReadI - WriteI;
00804   size_t NumMoved = std::min(Spills.size(), GapSize);
00805   LiveInterval::iterator Src = WriteI;
00806   LiveInterval::iterator Dst = Src + NumMoved;
00807   LiveInterval::iterator SpillSrc = Spills.end();
00808   LiveInterval::iterator B = LI->begin();
00809 
00810   // This is the new WriteI position after merging spills.
00811   WriteI = Dst;
00812 
00813   // Now merge Src and Spills backwards.
00814   while (Src != Dst) {
00815     if (Src != B && Src[-1].start > SpillSrc[-1].start)
00816       *--Dst = *--Src;
00817     else
00818       *--Dst = *--SpillSrc;
00819   }
00820   assert(NumMoved == size_t(Spills.end() - SpillSrc));
00821   Spills.erase(SpillSrc, Spills.end());
00822 }
00823 
00824 void LiveRangeUpdater::flush() {
00825   if (!isDirty())
00826     return;
00827   // Clear the dirty state.
00828   LastStart = SlotIndex();
00829 
00830   assert(LI && "Cannot add to a null destination");
00831 
00832   // Nothing to merge?
00833   if (Spills.empty()) {
00834     LI->ranges.erase(WriteI, ReadI);
00835     LI->verify();
00836     return;
00837   }
00838 
00839   // Resize the WriteI - ReadI gap to match Spills.
00840   size_t GapSize = ReadI - WriteI;
00841   if (GapSize < Spills.size()) {
00842     // The gap is too small. Make some room.
00843     size_t WritePos = WriteI - LI->begin();
00844     LI->ranges.insert(ReadI, Spills.size() - GapSize, LiveRange());
00845     // This also invalidated ReadI, but it is recomputed below.
00846     WriteI = LI->ranges.begin() + WritePos;
00847   } else {
00848     // Shrink the gap if necessary.
00849     LI->ranges.erase(WriteI + Spills.size(), ReadI);
00850   }
00851   ReadI = WriteI + Spills.size();
00852   mergeSpills();
00853   LI->verify();
00854 }
00855 
00856 unsigned ConnectedVNInfoEqClasses::Classify(const LiveInterval *LI) {
00857   // Create initial equivalence classes.
00858   EqClass.clear();
00859   EqClass.grow(LI->getNumValNums());
00860 
00861   const VNInfo *used = 0, *unused = 0;
00862 
00863   // Determine connections.
00864   for (LiveInterval::const_vni_iterator I = LI->vni_begin(), E = LI->vni_end();
00865        I != E; ++I) {
00866     const VNInfo *VNI = *I;
00867     // Group all unused values into one class.
00868     if (VNI->isUnused()) {
00869       if (unused)
00870         EqClass.join(unused->id, VNI->id);
00871       unused = VNI;
00872       continue;
00873     }
00874     used = VNI;
00875     if (VNI->isPHIDef()) {
00876       const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
00877       assert(MBB && "Phi-def has no defining MBB");
00878       // Connect to values live out of predecessors.
00879       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
00880            PE = MBB->pred_end(); PI != PE; ++PI)
00881         if (const VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI)))
00882           EqClass.join(VNI->id, PVNI->id);
00883     } else {
00884       // Normal value defined by an instruction. Check for two-addr redef.
00885       // FIXME: This could be coincidental. Should we really check for a tied
00886       // operand constraint?
00887       // Note that VNI->def may be a use slot for an early clobber def.
00888       if (const VNInfo *UVNI = LI->getVNInfoBefore(VNI->def))
00889         EqClass.join(VNI->id, UVNI->id);
00890     }
00891   }
00892 
00893   // Lump all the unused values in with the last used value.
00894   if (used && unused)
00895     EqClass.join(used->id, unused->id);
00896 
00897   EqClass.compress();
00898   return EqClass.getNumClasses();
00899 }
00900 
00901 void ConnectedVNInfoEqClasses::Distribute(LiveInterval *LIV[],
00902                                           MachineRegisterInfo &MRI) {
00903   assert(LIV[0] && "LIV[0] must be set");
00904   LiveInterval &LI = *LIV[0];
00905 
00906   // Rewrite instructions.
00907   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg),
00908        RE = MRI.reg_end(); RI != RE;) {
00909     MachineOperand &MO = RI.getOperand();
00910     MachineInstr *MI = MO.getParent();
00911     ++RI;
00912     // DBG_VALUE instructions should have been eliminated earlier.
00913     LiveRangeQuery LRQ(LI, LIS.getInstructionIndex(MI));
00914     const VNInfo *VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
00915     // In the case of an <undef> use that isn't tied to any def, VNI will be
00916     // NULL. If the use is tied to a def, VNI will be the defined value.
00917     if (!VNI)
00918       continue;
00919     MO.setReg(LIV[getEqClass(VNI)]->reg);
00920   }
00921 
00922   // Move runs to new intervals.
00923   LiveInterval::iterator J = LI.begin(), E = LI.end();
00924   while (J != E && EqClass[J->valno->id] == 0)
00925     ++J;
00926   for (LiveInterval::iterator I = J; I != E; ++I) {
00927     if (unsigned eq = EqClass[I->valno->id]) {
00928       assert((LIV[eq]->empty() || LIV[eq]->expiredAt(I->start)) &&
00929              "New intervals should be empty");
00930       LIV[eq]->ranges.push_back(*I);
00931     } else
00932       *J++ = *I;
00933   }
00934   LI.ranges.erase(J, E);
00935 
00936   // Transfer VNInfos to their new owners and renumber them.
00937   unsigned j = 0, e = LI.getNumValNums();
00938   while (j != e && EqClass[j] == 0)
00939     ++j;
00940   for (unsigned i = j; i != e; ++i) {
00941     VNInfo *VNI = LI.getValNumInfo(i);
00942     if (unsigned eq = EqClass[i]) {
00943       VNI->id = LIV[eq]->getNumValNums();
00944       LIV[eq]->valnos.push_back(VNI);
00945     } else {
00946       VNI->id = j;
00947       LI.valnos[j++] = VNI;
00948     }
00949   }
00950   LI.valnos.resize(j);
00951 }