Change MRegisterInfo::foldMemoryOperand to return the folded
[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             for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
137                 const MachineOperand& mop = mii->getOperand(i);
138                 if (mop.isRegister() && mop.getReg()) {
139                     // replace register with representative register
140                     unsigned reg = rep(mop.getReg());
141                     mii->SetMachineOperandReg(i, reg);
142
143                     if (MRegisterInfo::isVirtualRegister(reg)) {
144                         Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
145                         assert(r2iit != r2iMap_.end());
146                         r2iit->second->weight += pow(10.0F, loopDepth);
147                     }
148                 }
149             }
150
151             // if the move is now an identity move delete it
152             unsigned srcReg, dstReg;
153             if (tii.isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
154                 // remove index -> MachineInstr and
155                 // MachineInstr -> index mappings
156                 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
157                 if (mi2i != mi2iMap_.end()) {
158                     i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
159                     mi2iMap_.erase(mi2i);
160                 }
161                 mii = mbbi->erase(mii);
162                 ++numPeep;
163             }
164             else
165                 ++mii;
166         }
167     }
168
169     intervals_.sort(StartPointComp());
170     DEBUG(std::cerr << "********** INTERVALS **********\n");
171     DEBUG(std::copy(intervals_.begin(), intervals_.end(),
172                     std::ostream_iterator<Interval>(std::cerr, "\n")));
173     DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
174     DEBUG(
175         for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
176              mbbi != mbbe; ++mbbi) {
177             std::cerr << mbbi->getBasicBlock()->getName() << ":\n";
178             for (MachineBasicBlock::iterator mii = mbbi->begin(),
179                      mie = mbbi->end(); mii != mie; ++mii) {
180                 std::cerr << getInstructionIndex(mii) << '\t';
181                 mii->print(std::cerr, *tm_);
182             }
183         });
184
185     return true;
186 }
187
188 void LiveIntervals::updateSpilledInterval(Interval& li,
189                                           VirtRegMap& vrm,
190                                           int slot)
191 {
192     assert(li.weight != std::numeric_limits<float>::infinity() &&
193            "attempt to spill already spilled interval!");
194     Interval::Ranges oldRanges;
195     swap(oldRanges, li.ranges);
196
197     DEBUG(std::cerr << "\t\t\t\tupdating interval: " << li);
198
199     for (Interval::Ranges::iterator i = oldRanges.begin(), e = oldRanges.end();
200          i != e; ++i) {
201         unsigned index = getBaseIndex(i->first);
202         unsigned end = getBaseIndex(i->second-1) + InstrSlots::NUM;
203         for (; index < end; index += InstrSlots::NUM) {
204             // skip deleted instructions
205             while (!getInstructionFromIndex(index)) index += InstrSlots::NUM;
206             MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
207
208         for_operand:
209             for (unsigned i = 0; i < mi->getNumOperands(); ++i) {
210                 MachineOperand& mop = mi->getOperand(i);
211                 if (mop.isRegister() && mop.getReg() == li.reg) {
212                     if (MachineInstr* fmi =
213                         mri_->foldMemoryOperand(mi, i, slot)) {
214                         lv_->instructionChanged(mi, fmi);
215                         vrm.virtFolded(li.reg, mi, fmi);
216                         mi2iMap_.erase(mi);
217                         i2miMap_[index/InstrSlots::NUM] = fmi;
218                         mi2iMap_[fmi] = index;
219                         MachineBasicBlock& mbb = *mi->getParent();
220                         mi = mbb.insert(mbb.erase(mi), fmi);
221                         ++numFolded;
222                         goto for_operand;
223                     }
224                     else {
225                         // This is tricky. We need to add information in
226                         // the interval about the spill code so we have to
227                         // use our extra load/store slots.
228                         //
229                         // If we have a use we are going to have a load so
230                         // we start the interval from the load slot
231                         // onwards. Otherwise we start from the def slot.
232                         unsigned start = (mop.isUse() ?
233                                           getLoadIndex(index) :
234                                           getDefIndex(index));
235                         // If we have a def we are going to have a store
236                         // right after it so we end the interval after the
237                         // use of the next instruction. Otherwise we end
238                         // after the use of this instruction.
239                         unsigned end = 1 + (mop.isDef() ?
240                                             getUseIndex(index+InstrSlots::NUM) :
241                                             getUseIndex(index));
242                         li.addRange(start, end);
243                     }
244                 }
245             }
246         }
247     }
248     // the new spill weight is now infinity as it cannot be spilled again
249     li.weight = std::numeric_limits<float>::infinity();
250     DEBUG(std::cerr << '\n');
251     DEBUG(std::cerr << "\t\t\t\tupdated interval: " << li << '\n');
252 }
253
254 void LiveIntervals::printRegName(unsigned reg) const
255 {
256     if (MRegisterInfo::isPhysicalRegister(reg))
257         std::cerr << mri_->getName(reg);
258     else
259         std::cerr << "%reg" << reg;
260 }
261
262 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
263                                              MachineBasicBlock::iterator mi,
264                                              unsigned reg)
265 {
266     DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
267     LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
268
269     Interval* interval = 0;
270     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
271     if (r2iit == r2iMap_.end() || r2iit->first != reg) {
272         // add new interval
273         intervals_.push_back(Interval(reg));
274         // update interval index for this register
275         r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
276         interval = &intervals_.back();
277
278         // iterate over all of the blocks that the variable is
279         // completely live in, adding them to the live
280         // interval. obviously we only need to do this once.
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     else {
293         interval = &*r2iit->second;
294     }
295
296     unsigned baseIndex = getInstructionIndex(mi);
297
298     bool killedInDefiningBasicBlock = false;
299     for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
300         MachineBasicBlock* killerBlock = vi.Kills[i].first;
301         MachineInstr* killerInstr = vi.Kills[i].second;
302         unsigned start = (mbb == killerBlock ?
303                           getDefIndex(baseIndex) :
304                           getInstructionIndex(&killerBlock->front()));
305         unsigned end = (killerInstr == mi ?
306                          // dead
307                         start + 1 :
308                         // killed
309                         getUseIndex(getInstructionIndex(killerInstr))+1);
310         // we do not want to add invalid ranges. these can happen when
311         // a variable has its latest use and is redefined later on in
312         // the same basic block (common with variables introduced by
313         // PHI elimination)
314         if (start < end) {
315             killedInDefiningBasicBlock |= mbb == killerBlock;
316             interval->addRange(start, end);
317         }
318     }
319
320     if (!killedInDefiningBasicBlock) {
321         unsigned end = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
322         interval->addRange(getDefIndex(baseIndex), end);
323     }
324     DEBUG(std::cerr << '\n');
325 }
326
327 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
328                                               MachineBasicBlock::iterator mi,
329                                               unsigned reg)
330 {
331     DEBUG(std::cerr << "\t\tregister: "; printRegName(reg));
332     typedef LiveVariables::killed_iterator KillIter;
333
334     MachineBasicBlock::iterator e = mbb->end();
335     unsigned baseIndex = getInstructionIndex(mi);
336     unsigned start = getDefIndex(baseIndex);
337     unsigned end = start;
338
339     // a variable can be dead by the instruction defining it
340     for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
341          ki != ke; ++ki) {
342         if (reg == ki->second) {
343             DEBUG(std::cerr << " dead");
344             end = getDefIndex(start) + 1;
345             goto exit;
346         }
347     }
348
349     // a variable can only be killed by subsequent instructions
350     do {
351         ++mi;
352         baseIndex += InstrSlots::NUM;
353         for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
354              ki != ke; ++ki) {
355             if (reg == ki->second) {
356                 DEBUG(std::cerr << " killed");
357                 end = getUseIndex(baseIndex) + 1;
358                 goto exit;
359             }
360         }
361     } while (mi != e);
362
363 exit:
364     assert(start < end && "did not find end of interval?");
365
366     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
367     if (r2iit != r2iMap_.end() && r2iit->first == reg) {
368         r2iit->second->addRange(start, end);
369     }
370     else {
371         intervals_.push_back(Interval(reg));
372         // update interval index for this register
373         r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
374         intervals_.back().addRange(start, end);
375     }
376     DEBUG(std::cerr << '\n');
377 }
378
379 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
380                                       MachineBasicBlock::iterator mi,
381                                       unsigned reg)
382 {
383     if (MRegisterInfo::isPhysicalRegister(reg)) {
384         if (lv_->getAllocatablePhysicalRegisters()[reg]) {
385             handlePhysicalRegisterDef(mbb, mi, reg);
386             for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
387                 handlePhysicalRegisterDef(mbb, mi, *as);
388         }
389     }
390     else {
391         handleVirtualRegisterDef(mbb, mi, reg);
392     }
393 }
394
395 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
396 {
397     Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
398     return (it == mi2iMap_.end() ?
399             std::numeric_limits<unsigned>::max() :
400             it->second);
401 }
402
403 MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const
404 {
405     index /= InstrSlots::NUM; // convert index to vector index
406     assert(index < i2miMap_.size() &&
407            "index does not correspond to an instruction");
408     return i2miMap_[index];
409 }
410
411 /// computeIntervals - computes the live intervals for virtual
412 /// registers. for some ordering of the machine instructions [1,N] a
413 /// live interval is an interval [i, j) where 1 <= i <= j < N for
414 /// which a variable is live
415 void LiveIntervals::computeIntervals()
416 {
417     DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
418     DEBUG(std::cerr << "********** Function: "
419           << mf_->getFunction()->getName() << '\n');
420
421     for (MbbIndex2MbbMap::iterator
422              it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
423          it != itEnd; ++it) {
424         MachineBasicBlock* mbb = it->second;
425         DEBUG(std::cerr << mbb->getBasicBlock()->getName() << ":\n");
426
427         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
428              mi != miEnd; ++mi) {
429             const TargetInstrDescriptor& tid =
430                 tm_->getInstrInfo().get(mi->getOpcode());
431             DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
432                   mi->print(std::cerr, *tm_));
433
434             // handle implicit defs
435             for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
436                 handleRegisterDef(mbb, mi, *id);
437
438             // handle explicit defs
439             for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
440                 MachineOperand& mop = mi->getOperand(i);
441                 // handle register defs - build intervals
442                 if (mop.isRegister() && mop.getReg() && mop.isDef())
443                     handleRegisterDef(mbb, mi, mop.getReg());
444             }
445         }
446     }
447 }
448
449 unsigned LiveIntervals::rep(unsigned reg)
450 {
451     Reg2RegMap::iterator it = r2rMap_.find(reg);
452     if (it != r2rMap_.end())
453         return it->second = rep(it->second);
454     return reg;
455 }
456
457 void LiveIntervals::joinIntervals()
458 {
459     DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
460
461     const TargetInstrInfo& tii = tm_->getInstrInfo();
462
463     for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
464          mbbi != mbbe; ++mbbi) {
465         MachineBasicBlock* mbb = mbbi;
466         DEBUG(std::cerr << mbb->getBasicBlock()->getName() << ":\n");
467
468         for (MachineBasicBlock::iterator mi = mbb->begin(), mie = mbb->end();
469              mi != mie; ++mi) {
470             const TargetInstrDescriptor& tid =
471                 tm_->getInstrInfo().get(mi->getOpcode());
472             DEBUG(std::cerr << getInstructionIndex(mi) << '\t';
473                   mi->print(std::cerr, *tm_););
474
475             // we only join virtual registers with allocatable
476             // physical registers since we do not have liveness information
477             // on not allocatable physical registers
478             unsigned regA, regB;
479             if (tii.isMoveInstr(*mi, regA, regB) &&
480                 (MRegisterInfo::isVirtualRegister(regA) ||
481                  lv_->getAllocatablePhysicalRegisters()[regA]) &&
482                 (MRegisterInfo::isVirtualRegister(regB) ||
483                  lv_->getAllocatablePhysicalRegisters()[regB])) {
484
485                 // get representative registers
486                 regA = rep(regA);
487                 regB = rep(regB);
488
489                 // if they are already joined we continue
490                 if (regA == regB)
491                     continue;
492
493                 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
494                 assert(r2iA != r2iMap_.end());
495                 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
496                 assert(r2iB != r2iMap_.end());
497
498                 Intervals::iterator intA = r2iA->second;
499                 Intervals::iterator intB = r2iB->second;
500
501                 // both A and B are virtual registers
502                 if (MRegisterInfo::isVirtualRegister(intA->reg) &&
503                     MRegisterInfo::isVirtualRegister(intB->reg)) {
504
505                     const TargetRegisterClass *rcA, *rcB;
506                     rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
507                     rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
508                     assert(rcA == rcB && "registers must be of the same class");
509
510                     // if their intervals do not overlap we join them
511                     if (!intB->overlaps(*intA)) {
512                         intA->join(*intB);
513                         r2iB->second = r2iA->second;
514                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
515                         intervals_.erase(intB);
516                     }
517                 }
518                 else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^
519                          MRegisterInfo::isPhysicalRegister(intB->reg)) {
520                     if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
521                         std::swap(regA, regB);
522                         std::swap(intA, intB);
523                         std::swap(r2iA, r2iB);
524                     }
525
526                     assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
527                            MRegisterInfo::isVirtualRegister(intB->reg) &&
528                            "A must be physical and B must be virtual");
529
530                     if (!intA->overlaps(*intB) &&
531                          !overlapsAliases(*intA, *intB)) {
532                         intA->join(*intB);
533                         r2iB->second = r2iA->second;
534                         r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
535                         intervals_.erase(intB);
536                     }
537                 }
538             }
539         }
540     }
541 }
542
543 bool LiveIntervals::overlapsAliases(const Interval& lhs,
544                                     const Interval& rhs) const
545 {
546     assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
547            "first interval must describe a physical register");
548
549     for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
550         Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
551         assert(r2i != r2iMap_.end() && "alias does not have interval?");
552         if (rhs.overlaps(*r2i->second))
553             return true;
554     }
555
556     return false;
557 }
558
559 LiveIntervals::Interval::Interval(unsigned r)
560     : reg(r),
561       weight((MRegisterInfo::isPhysicalRegister(r) ?
562               std::numeric_limits<float>::infinity() : 0.0F))
563 {
564
565 }
566
567 bool LiveIntervals::Interval::spilled() const
568 {
569     return (weight == std::numeric_limits<float>::infinity() &&
570             MRegisterInfo::isVirtualRegister(reg));
571 }
572
573 // An example for liveAt():
574 //
575 // this = [1,4), liveAt(0) will return false. The instruction defining
576 // this spans slots [0,3]. The interval belongs to an spilled
577 // definition of the variable it represents. This is because slot 1 is
578 // used (def slot) and spans up to slot 3 (store slot).
579 //
580 bool LiveIntervals::Interval::liveAt(unsigned index) const
581 {
582     Range dummy(index, index+1);
583     Ranges::const_iterator r = std::upper_bound(ranges.begin(),
584                                                 ranges.end(),
585                                                 dummy);
586     if (r == ranges.begin())
587         return false;
588
589     --r;
590     return index >= r->first && index < r->second;
591 }
592
593 // An example for overlaps():
594 //
595 // 0: A = ...
596 // 4: B = ...
597 // 8: C = A + B ;; last use of A
598 //
599 // The live intervals should look like:
600 //
601 // A = [3, 11)
602 // B = [7, x)
603 // C = [11, y)
604 //
605 // A->overlaps(C) should return false since we want to be able to join
606 // A and C.
607 bool LiveIntervals::Interval::overlaps(const Interval& other) const
608 {
609     Ranges::const_iterator i = ranges.begin();
610     Ranges::const_iterator ie = ranges.end();
611     Ranges::const_iterator j = other.ranges.begin();
612     Ranges::const_iterator je = other.ranges.end();
613     if (i->first < j->first) {
614         i = std::upper_bound(i, ie, *j);
615         if (i != ranges.begin()) --i;
616     }
617     else if (j->first < i->first) {
618         j = std::upper_bound(j, je, *i);
619         if (j != other.ranges.begin()) --j;
620     }
621
622     while (i != ie && j != je) {
623         if (i->first == j->first) {
624             return true;
625         }
626         else {
627             if (i->first > j->first) {
628                 swap(i, j);
629                 swap(ie, je);
630             }
631             assert(i->first < j->first);
632
633             if (i->second > j->first) {
634                 return true;
635             }
636             else {
637                 ++i;
638             }
639         }
640     }
641
642     return false;
643 }
644
645 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
646 {
647     assert(start < end && "Invalid range to add!");
648     DEBUG(std::cerr << " +[" << start << ',' << end << ")");
649     //assert(start < end && "invalid range?");
650     Range range = std::make_pair(start, end);
651     Ranges::iterator it =
652         ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
653                       range);
654
655     it = mergeRangesForward(it);
656     it = mergeRangesBackward(it);
657 }
658
659 void LiveIntervals::Interval::join(const LiveIntervals::Interval& other)
660 {
661     DEBUG(std::cerr << "\t\tjoining " << *this << " with " << other << '\n');
662     Ranges::iterator cur = ranges.begin();
663
664     for (Ranges::const_iterator i = other.ranges.begin(),
665              e = other.ranges.end(); i != e; ++i) {
666         cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
667         cur = mergeRangesForward(cur);
668         cur = mergeRangesBackward(cur);
669     }
670     weight += other.weight;
671     ++numJoins;
672 }
673
674 LiveIntervals::Interval::Ranges::iterator
675 LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
676 {
677     Ranges::iterator n;
678     while ((n = next(it)) != ranges.end()) {
679         if (n->first > it->second)
680             break;
681         it->second = std::max(it->second, n->second);
682         n = ranges.erase(n);
683     }
684     return it;
685 }
686
687 LiveIntervals::Interval::Ranges::iterator
688 LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
689 {
690     while (it != ranges.begin()) {
691         Ranges::iterator p = prior(it);
692         if (it->first > p->second)
693             break;
694
695         it->first = std::min(it->first, p->first);
696         it->second = std::max(it->second, p->second);
697         it = ranges.erase(p);
698     }
699
700     return it;
701 }
702
703 std::ostream& llvm::operator<<(std::ostream& os,
704                                const LiveIntervals::Interval& li)
705 {
706     os << "%reg" << li.reg << ',' << li.weight << " = ";
707     if (li.empty())
708         return os << "EMPTY";
709     for (LiveIntervals::Interval::Ranges::const_iterator
710              i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
711         os << "[" << i->first << "," << i->second << ")";
712     }
713     return os;
714 }