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