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