Fix bug introduced in previous commit.
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
1 //===-- LiveIntervals.cpp - Live Interval Analysis ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LiveInterval analysis pass which is used
11 // by the Linear Scan Register allocator. This pass linearizes the
12 // basic blocks of the function in DFS order and uses the
13 // LiveVariables pass to conservatively compute live intervals for
14 // each virtual and physical register.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "liveintervals"
19 #include "LiveIntervals.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/CFG.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Debug.h"
32 #include "Support/Statistic.h"
33 #include "Support/STLExtras.h"
34 #include "VirtRegMap.h"
35 #include <cmath>
36 #include <iostream>
37 #include <limits>
38
39 using namespace llvm;
40
41 namespace {
42     RegisterAnalysis<LiveIntervals> X("liveintervals",
43                                       "Live Interval Analysis");
44
45     Statistic<> numIntervals
46     ("liveintervals", "Number of original intervals");
47
48     Statistic<> numIntervalsAfter
49     ("liveintervals", "Number of intervals after coalescing");
50
51     Statistic<> numJoins
52     ("liveintervals", "Number of interval joins performed");
53
54     Statistic<> numPeep
55     ("liveintervals", "Number of identity moves eliminated after coalescing");
56
57     Statistic<> numFolded
58     ("liveintervals", "Number of loads/stores folded into instructions");
59
60     cl::opt<bool>
61     join("join-liveintervals",
62          cl::desc("Join compatible live intervals"),
63          cl::init(true));
64 };
65
66 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
67 {
68     AU.addPreserved<LiveVariables>();
69     AU.addRequired<LiveVariables>();
70     AU.addPreservedID(PHIEliminationID);
71     AU.addRequiredID(PHIEliminationID);
72     AU.addRequiredID(TwoAddressInstructionPassID);
73     AU.addRequired<LoopInfo>();
74     MachineFunctionPass::getAnalysisUsage(AU);
75 }
76
77 void LiveIntervals::releaseMemory()
78 {
79     mbbi2mbbMap_.clear();
80     mi2iMap_.clear();
81     i2miMap_.clear();
82     r2iMap_.clear();
83     r2rMap_.clear();
84     intervals_.clear();
85 }
86
87
88 /// runOnMachineFunction - Register allocate the whole function
89 ///
90 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
91     mf_ = &fn;
92     tm_ = &fn.getTarget();
93     mri_ = tm_->getRegisterInfo();
94     lv_ = &getAnalysis<LiveVariables>();
95
96     // number MachineInstrs
97     unsigned miIndex = 0;
98     for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
99          mbb != mbbEnd; ++mbb) {
100         const std::pair<MachineBasicBlock*, unsigned>& entry =
101             lv_->getMachineBasicBlockInfo(mbb);
102         bool inserted = mbbi2mbbMap_.insert(std::make_pair(entry.second,
103                                                            entry.first)).second;
104         assert(inserted && "multiple index -> MachineBasicBlock");
105
106         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
107              mi != miEnd; ++mi) {
108             inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
109             assert(inserted && "multiple MachineInstr -> index mappings");
110             i2miMap_.push_back(mi);
111             miIndex += InstrSlots::NUM;
112         }
113     }
114
115     computeIntervals();
116
117     numIntervals += intervals_.size();
118
119     // join intervals if requested
120     if (join) joinIntervals();
121
122     numIntervalsAfter += intervals_.size();
123
124     // perform a final pass over the instructions and compute spill
125     // weights, coalesce virtual registers and remove identity moves
126     const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
127     const TargetInstrInfo& tii = tm_->getInstrInfo();
128
129     for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
130          mbbi != mbbe; ++mbbi) {
131         MachineBasicBlock* mbb = mbbi;
132         unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
133
134         for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
135              mii != mie; ) {
136             // if the move will be an identity move delete it
137             unsigned srcReg, dstReg;
138             if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
139                 rep(srcReg) == rep(dstReg)) {
140                 // remove from def list
141                 Interval& interval = getOrCreateInterval(rep(dstReg));
142                 unsigned defIndex = getInstructionIndex(mii);
143                 Interval::Defs::iterator d = std::lower_bound(
144                     interval.defs.begin(), interval.defs.end(), defIndex);
145                 assert(*d == defIndex && "Def index not found in def list!");
146                 interval.defs.erase(d);
147                 // remove index -> MachineInstr and
148                 // MachineInstr -> index mappings
149                 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
150                 if (mi2i != mi2iMap_.end()) {
151                     i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
152                     mi2iMap_.erase(mi2i);
153                 }
154                 mii = mbbi->erase(mii);
155                 ++numPeep;
156             }
157             else {
158                 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
159                     const MachineOperand& mop = mii->getOperand(i);
160                     if (mop.isRegister() && mop.getReg() &&
161                         MRegisterInfo::isVirtualRegister(mop.getReg())) {
162                         // replace register with representative register
163                         unsigned reg = rep(mop.getReg());
164                         mii->SetMachineOperandReg(i, reg);
165
166                         Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
167                         assert(r2iit != r2iMap_.end());
168                         r2iit->second->weight +=
169                             (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
170                     }
171                 }
172                 ++mii;
173             }
174         }
175     }
176
177     intervals_.sort(StartPointComp());
178     DEBUG(std::cerr << "********** INTERVALS **********\n");
179     DEBUG(std::copy(intervals_.begin(), intervals_.end(),
180                     std::ostream_iterator<Interval>(std::cerr, "\n")));
181     DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
182     DEBUG(
183         for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
184              mbbi != mbbe; ++mbbi) {
185             std::cerr << mbbi->getBasicBlock()->getName() << ":\n";
186             for (MachineBasicBlock::iterator mii = mbbi->begin(),
187                      mie = mbbi->end(); mii != mie; ++mii) {
188                 std::cerr << getInstructionIndex(mii) << '\t';
189                 mii->print(std::cerr, *tm_);
190             }
191         });
192
193     return true;
194 }
195
196 void LiveIntervals::updateSpilledInterval(Interval& li,
197                                           VirtRegMap& vrm,
198                                           int slot)
199 {
200     assert(li.weight != std::numeric_limits<float>::infinity() &&
201            "attempt to spill already spilled interval!");
202     Interval::Ranges oldRanges;
203     swap(oldRanges, li.ranges);
204
205     DEBUG(std::cerr << "\t\t\t\tupdating interval: " << li);
206
207     for (Interval::Ranges::iterator i = oldRanges.begin(), e = oldRanges.end();
208          i != e; ++i) {
209         unsigned index = getBaseIndex(i->first);
210         unsigned end = getBaseIndex(i->second-1) + InstrSlots::NUM;
211         for (; index < end; index += InstrSlots::NUM) {
212             // skip deleted instructions
213             while (!getInstructionFromIndex(index)) index += InstrSlots::NUM;
214             MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
215
216         for_operand:
217             for (unsigned i = 0; i < mi->getNumOperands(); ++i) {
218                 MachineOperand& mop = mi->getOperand(i);
219                 if (mop.isRegister() && mop.getReg() == li.reg) {
220                     if (MachineInstr* fmi =
221                         mri_->foldMemoryOperand(mi, i, slot)) {
222                         lv_->instructionChanged(mi, fmi);
223                         vrm.virtFolded(li.reg, mi, fmi);
224                         mi2iMap_.erase(mi);
225                         i2miMap_[index/InstrSlots::NUM] = fmi;
226                         mi2iMap_[fmi] = index;
227                         MachineBasicBlock& mbb = *mi->getParent();
228                         mi = mbb.insert(mbb.erase(mi), fmi);
229                         ++numFolded;
230                         goto for_operand;
231                     }
232                     else {
233                         // This is tricky. We need to add information in
234                         // the interval about the spill code so we have to
235                         // use our extra load/store slots.
236                         //
237                         // If we have a use we are going to have a load so
238                         // we start the interval from the load slot
239                         // onwards. Otherwise we start from the def slot.
240                         unsigned start = (mop.isUse() ?
241                                           getLoadIndex(index) :
242                                           getDefIndex(index));
243                         // If we have a def we are going to have a store
244                         // right after it so we end the interval after the
245                         // use of the next instruction. Otherwise we end
246                         // after the use of this instruction.
247                         unsigned end = 1 + (mop.isDef() ?
248                                             getUseIndex(index+InstrSlots::NUM) :
249                                             getUseIndex(index));
250                         li.addRange(start, end);
251                     }
252                 }
253             }
254         }
255     }
256     // the new spill weight is now infinity as it cannot be spilled again
257     li.weight = std::numeric_limits<float>::infinity();
258     DEBUG(std::cerr << '\n');
259     DEBUG(std::cerr << "\t\t\t\tupdated interval: " << li << '\n');
260 }
261
262 void LiveIntervals::printRegName(unsigned reg) const
263 {
264     if (MRegisterInfo::isPhysicalRegister(reg))
265         std::cerr << mri_->getName(reg);
266     else
267         std::cerr << "%reg" << reg;
268 }
269
270 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
271                                              MachineBasicBlock::iterator mi,
272                                              Interval& interval)
273 {
274     DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
275     LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
276
277     // iterate over all of the blocks that the variable is completely
278     // live in, adding them to the live interval. obviously we only
279     // need to do this once.
280     if (interval.empty()) {
281         for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
282             if (vi.AliveBlocks[i]) {
283                 MachineBasicBlock* mbb = lv_->getIndexMachineBasicBlock(i);
284                 if (!mbb->empty()) {
285                     interval.addRange(
286                         getInstructionIndex(&mbb->front()),
287                         getInstructionIndex(&mbb->back()) + InstrSlots::NUM);
288                 }
289             }
290         }
291     }
292
293     unsigned baseIndex = getInstructionIndex(mi);
294     interval.defs.push_back(baseIndex);
295
296     bool killedInDefiningBasicBlock = false;
297     for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
298         MachineBasicBlock* killerBlock = vi.Kills[i].first;
299         MachineInstr* killerInstr = vi.Kills[i].second;
300         unsigned start = (mbb == killerBlock ?
301                           getDefIndex(baseIndex) :
302                           getInstructionIndex(&killerBlock->front()));
303         unsigned end = (killerInstr == mi ?
304                          // dead
305                         start + 1 :
306                         // killed
307                         getUseIndex(getInstructionIndex(killerInstr))+1);
308         // we do not want to add invalid ranges. these can happen when
309         // a variable has its latest use and is redefined later on in
310         // the same basic block (common with variables introduced by
311         // PHI elimination)
312         if (start < end) {
313             killedInDefiningBasicBlock |= mbb == killerBlock;
314             interval.addRange(start, end);
315         }
316     }
317
318     if (!killedInDefiningBasicBlock) {
319         unsigned end = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
320         interval.addRange(getDefIndex(baseIndex), end);
321     }
322     DEBUG(std::cerr << '\n');
323 }
324
325 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
326                                               MachineBasicBlock::iterator mi,
327                                               Interval& interval)
328 {
329     DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
330     typedef LiveVariables::killed_iterator KillIter;
331
332     MachineBasicBlock::iterator e = mbb->end();
333     unsigned baseIndex = getInstructionIndex(mi);
334     interval.defs.push_back(baseIndex);
335     unsigned start = getDefIndex(baseIndex);
336     unsigned end = start;
337
338     // a variable can be dead by the instruction defining it
339     for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
340          ki != ke; ++ki) {
341         if (interval.reg == ki->second) {
342             DEBUG(std::cerr << " dead");
343             end = getDefIndex(start) + 1;
344             goto exit;
345         }
346     }
347
348     // a variable can only be killed by subsequent instructions
349     do {
350         ++mi;
351         baseIndex += InstrSlots::NUM;
352         for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
353              ki != ke; ++ki) {
354             if (interval.reg == ki->second) {
355                 DEBUG(std::cerr << " killed");
356                 end = getUseIndex(baseIndex) + 1;
357                 goto exit;
358             }
359         }
360     } while (mi != e);
361
362 exit:
363     assert(start < end && "did not find end of interval?");
364     interval.addRange(start, end);
365     DEBUG(std::cerr << '\n');
366 }
367
368 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
369                                       MachineBasicBlock::iterator mi,
370                                       unsigned reg)
371 {
372     if (MRegisterInfo::isPhysicalRegister(reg)) {
373         if (lv_->getAllocatablePhysicalRegisters()[reg]) {
374             handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(reg));
375             for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
376                 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(*as));
377         }
378     }
379     else
380         handleVirtualRegisterDef(mbb, mi, getOrCreateInterval(reg));
381 }
382
383 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
384 {
385     Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
386     return (it == mi2iMap_.end() ?
387             std::numeric_limits<unsigned>::max() :
388             it->second);
389 }
390
391 MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const
392 {
393     index /= InstrSlots::NUM; // convert index to vector index
394     assert(index < i2miMap_.size() &&
395            "index does not correspond to an instruction");
396     return i2miMap_[index];
397 }
398
399 /// computeIntervals - computes the live intervals for virtual
400 /// registers. for some ordering of the machine instructions [1,N] a
401 /// live interval is an interval [i, j) where 1 <= i <= j < N for
402 /// which a variable is live
403 void LiveIntervals::computeIntervals()
404 {
405     DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
406     DEBUG(std::cerr << "********** Function: "
407           << mf_->getFunction()->getName() << '\n');
408
409     for (MbbIndex2MbbMap::iterator
410              it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
411          it != itEnd; ++it) {
412         MachineBasicBlock* mbb = it->second;
413         DEBUG(std::cerr << mbb->getBasicBlock()->getName() << ":\n");
414
415         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
416              mi != miEnd; ++mi) {
417             const TargetInstrDescriptor& tid =
418                 tm_->getInstrInfo().get(mi->getOpcode());
419             DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
420                   mi->print(std::cerr, *tm_));
421
422             // handle implicit defs
423             for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
424                 handleRegisterDef(mbb, mi, *id);
425
426             // handle explicit defs
427             for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
428                 MachineOperand& mop = mi->getOperand(i);
429                 // handle register defs - build intervals
430                 if (mop.isRegister() && mop.getReg() && mop.isDef())
431                     handleRegisterDef(mbb, mi, mop.getReg());
432             }
433         }
434     }
435 }
436
437 unsigned LiveIntervals::rep(unsigned reg)
438 {
439     Reg2RegMap::iterator it = r2rMap_.find(reg);
440     if (it != r2rMap_.end())
441         return it->second = rep(it->second);
442     return reg;
443 }
444
445 void LiveIntervals::joinIntervals()
446 {
447     DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
448
449     const TargetInstrInfo& tii = tm_->getInstrInfo();
450
451     for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
452          mbbi != mbbe; ++mbbi) {
453         MachineBasicBlock* mbb = mbbi;
454         DEBUG(std::cerr << mbb->getBasicBlock()->getName() << ":\n");
455
456         for (MachineBasicBlock::iterator mi = mbb->begin(), mie = mbb->end();
457              mi != mie; ++mi) {
458             const TargetInstrDescriptor& tid =
459                 tm_->getInstrInfo().get(mi->getOpcode());
460             DEBUG(std::cerr << getInstructionIndex(mi) << '\t';
461                   mi->print(std::cerr, *tm_););
462
463             // we only join virtual registers with allocatable
464             // physical registers since we do not have liveness information
465             // on not allocatable physical registers
466             unsigned regA, regB;
467             if (tii.isMoveInstr(*mi, regA, regB) &&
468                 (MRegisterInfo::isVirtualRegister(regA) ||
469                  lv_->getAllocatablePhysicalRegisters()[regA]) &&
470                 (MRegisterInfo::isVirtualRegister(regB) ||
471                  lv_->getAllocatablePhysicalRegisters()[regB])) {
472
473                 // get representative registers
474                 regA = rep(regA);
475                 regB = rep(regB);
476
477                 // if they are already joined we continue
478                 if (regA == regB)
479                     continue;
480
481                 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
482                 assert(r2iA != r2iMap_.end());
483                 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
484                 assert(r2iB != r2iMap_.end());
485
486                 Intervals::iterator intA = r2iA->second;
487                 Intervals::iterator intB = r2iB->second;
488
489                 // both A and B are virtual registers
490                 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
491                     MRegisterInfo::isVirtualRegister(intB->reg)) {
492
493                     const TargetRegisterClass *rcA, *rcB;
494                     rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
495                     rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
496                     assert(rcA == rcB && "registers must be of the same class");
497
498                     // if their intervals do not overlap we join them
499                     if (!intB->overlaps(*intA)) {
500                         intA->join(*intB);
501                         r2iB->second = r2iA->second;
502                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
503                         intervals_.erase(intB);
504                     }
505                 }
506                 else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^
507                          MRegisterInfo::isPhysicalRegister(intB->reg)) {
508                     if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
509                         std::swap(regA, regB);
510                         std::swap(intA, intB);
511                         std::swap(r2iA, r2iB);
512                     }
513
514                     assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
515                            MRegisterInfo::isVirtualRegister(intB->reg) &&
516                            "A must be physical and B must be virtual");
517
518                     if (!intA->overlaps(*intB) &&
519                         !overlapsAliases(*intA, *intB)) {
520                         intA->join(*intB);
521                         r2iB->second = r2iA->second;
522                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
523                         intervals_.erase(intB);
524                     }
525                 }
526             }
527         }
528     }
529 }
530
531 bool LiveIntervals::overlapsAliases(const Interval& lhs,
532                                     const Interval& rhs) const
533 {
534     assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
535            "first interval must describe a physical register");
536
537     for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
538         Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
539         assert(r2i != r2iMap_.end() && "alias does not have interval?");
540         if (rhs.overlaps(*r2i->second))
541             return true;
542     }
543
544     return false;
545 }
546
547 LiveIntervals::Interval& LiveIntervals::getOrCreateInterval(unsigned reg)
548 {
549     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
550     if (r2iit == r2iMap_.end() || r2iit->first != reg) {
551         intervals_.push_back(Interval(reg));
552         r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
553     }
554
555     return *r2iit->second;
556 }
557
558 LiveIntervals::Interval::Interval(unsigned r)
559     : reg(r),
560       weight((MRegisterInfo::isPhysicalRegister(r) ?
561               std::numeric_limits<float>::infinity() : 0.0F))
562 {
563
564 }
565
566 bool LiveIntervals::Interval::spilled() const
567 {
568     return (weight == std::numeric_limits<float>::infinity() &&
569             MRegisterInfo::isVirtualRegister(reg));
570 }
571
572 // An example for liveAt():
573 //
574 // this = [1,4), liveAt(0) will return false. The instruction defining
575 // this spans slots [0,3]. The interval belongs to an spilled
576 // definition of the variable it represents. This is because slot 1 is
577 // used (def slot) and spans up to slot 3 (store slot).
578 //
579 bool LiveIntervals::Interval::liveAt(unsigned index) const
580 {
581     Range dummy(index, index+1);
582     Ranges::const_iterator r = std::upper_bound(ranges.begin(),
583                                                 ranges.end(),
584                                                 dummy);
585     if (r == ranges.begin())
586         return false;
587
588     --r;
589     return index >= r->first && index < r->second;
590 }
591
592 // An example for overlaps():
593 //
594 // 0: A = ...
595 // 4: B = ...
596 // 8: C = A + B ;; last use of A
597 //
598 // The live intervals should look like:
599 //
600 // A = [3, 11)
601 // B = [7, x)
602 // C = [11, y)
603 //
604 // A->overlaps(C) should return false since we want to be able to join
605 // A and C.
606 bool LiveIntervals::Interval::overlaps(const Interval& other) const
607 {
608     Ranges::const_iterator i = ranges.begin();
609     Ranges::const_iterator ie = ranges.end();
610     Ranges::const_iterator j = other.ranges.begin();
611     Ranges::const_iterator je = other.ranges.end();
612     if (i->first < j->first) {
613         i = std::upper_bound(i, ie, *j);
614         if (i != ranges.begin()) --i;
615     }
616     else if (j->first < i->first) {
617         j = std::upper_bound(j, je, *i);
618         if (j != other.ranges.begin()) --j;
619     }
620
621     while (i != ie && j != je) {
622         if (i->first == j->first) {
623             return true;
624         }
625         else {
626             if (i->first > j->first) {
627                 swap(i, j);
628                 swap(ie, je);
629             }
630             assert(i->first < j->first);
631
632             if (i->second > j->first) {
633                 return true;
634             }
635             else {
636                 ++i;
637             }
638         }
639     }
640
641     return false;
642 }
643
644 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
645 {
646     assert(start < end && "Invalid range to add!");
647     DEBUG(std::cerr << " +[" << start << ',' << end << ")");
648     //assert(start < end && "invalid range?");
649     Range range = std::make_pair(start, end);
650     Ranges::iterator it =
651         ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
652                       range);
653
654     it = mergeRangesForward(it);
655     it = mergeRangesBackward(it);
656 }
657
658 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
659 {
660     DEBUG(std::cerr << "\t\tjoining " << *this << " with " << other << '\n');
661     Ranges::iterator cur = ranges.begin();
662
663     for (Ranges::const_iterator i = other.ranges.begin(),
664              e = other.ranges.end(); i != e; ++i) {
665         cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
666         cur = mergeRangesForward(cur);
667         cur = mergeRangesBackward(cur);
668     }
669     weight += other.weight;
670     Defs u;
671     std::set_union(defs.begin(), defs.end(),
672                    other.defs.begin(), other.defs.end(),
673                    std::back_inserter(u));
674     defs = u;
675     ++numJoins;
676 }
677
678 LiveIntervals::Interval::Ranges::iterator
679 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
680 {
681     Ranges::iterator n;
682     while ((n = next(it)) != ranges.end()) {
683         if (n->first > it->second)
684             break;
685         it->second = std::max(it->second, n->second);
686         n = ranges.erase(n);
687     }
688     return it;
689 }
690
691 LiveIntervals::Interval::Ranges::iterator
692 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
693 {
694     while (it != ranges.begin()) {
695         Ranges::iterator p = prior(it);
696         if (it->first > p->second)
697             break;
698
699         it->first = std::min(it->first, p->first);
700         it->second = std::max(it->second, p->second);
701         it = ranges.erase(p);
702     }
703
704     return it;
705 }
706
707 std::ostream& llvm::operator<<(std::ostream& os,
708                                const LiveIntervals::Interval& li)
709 {
710     os << "%reg" << li.reg << ',' << li.weight;
711     if (li.empty())
712         return os << "EMPTY";
713
714     os << " {" << li.defs.front();
715     for (LiveIntervals::Interval::Defs::const_iterator
716              i = next(li.defs.begin()), e = li.defs.end(); i != e; ++i)
717         os << "," << *i;
718     os << "}";
719
720     os << " = ";
721     for (LiveIntervals::Interval::Ranges::const_iterator
722              i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
723         os << "[" << i->first << "," << i->second << ")";
724     }
725     return os;
726 }