LiveIntervalAnalysis.cpp revision ec2bc645053e9051ada01fac6a555df17a85c91d
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
37using namespace llvm;
38
39namespace {
40    RegisterAnalysis<LiveIntervals> X("liveintervals",
41                                      "Live Interval Analysis");
42
43    Statistic<> numIntervals
44    ("liveintervals", "Number of original intervals");
45
46    Statistic<> numIntervalsAfter
47    ("liveintervals", "Number of intervals after coalescing");
48
49    Statistic<> numJoins
50    ("liveintervals", "Number of interval joins performed");
51
52    Statistic<> numPeep
53    ("liveintervals", "Number of identity moves eliminated after coalescing");
54
55    Statistic<> numFolded
56    ("liveintervals", "Number of loads/stores folded into instructions");
57
58    cl::opt<bool>
59    EnableJoining("join-liveintervals",
60                  cl::desc("Join compatible live intervals"),
61                  cl::init(true));
62};
63
64void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
65{
66    AU.addPreserved<LiveVariables>();
67    AU.addRequired<LiveVariables>();
68    AU.addPreservedID(PHIEliminationID);
69    AU.addRequiredID(PHIEliminationID);
70    AU.addRequiredID(TwoAddressInstructionPassID);
71    AU.addRequired<LoopInfo>();
72    MachineFunctionPass::getAnalysisUsage(AU);
73}
74
75void LiveIntervals::releaseMemory()
76{
77    mi2iMap_.clear();
78    i2miMap_.clear();
79    r2iMap_.clear();
80    r2rMap_.clear();
81    intervals_.clear();
82}
83
84
85/// runOnMachineFunction - Register allocate the whole function
86///
87bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
88    mf_ = &fn;
89    tm_ = &fn.getTarget();
90    mri_ = tm_->getRegisterInfo();
91    lv_ = &getAnalysis<LiveVariables>();
92
93    // number MachineInstrs
94    unsigned miIndex = 0;
95    for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
96         mbb != mbbEnd; ++mbb)
97        for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
98             mi != miEnd; ++mi) {
99            bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
100            assert(inserted && "multiple MachineInstr -> index mappings");
101            i2miMap_.push_back(mi);
102            miIndex += InstrSlots::NUM;
103        }
104
105    computeIntervals();
106
107    numIntervals += intervals_.size();
108
109    // join intervals if requested
110    if (EnableJoining) joinIntervals();
111
112    numIntervalsAfter += intervals_.size();
113
114    // perform a final pass over the instructions and compute spill
115    // weights, coalesce virtual registers and remove identity moves
116    const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
117    const TargetInstrInfo& tii = *tm_->getInstrInfo();
118
119    for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
120         mbbi != mbbe; ++mbbi) {
121        MachineBasicBlock* mbb = mbbi;
122        unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
123
124        for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
125             mii != mie; ) {
126            // if the move will be an identity move delete it
127            unsigned srcReg, dstReg;
128            if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
129                rep(srcReg) == rep(dstReg)) {
130                // remove from def list
131                LiveInterval& interval = getOrCreateInterval(rep(dstReg));
132                // remove index -> MachineInstr and
133                // MachineInstr -> index mappings
134                Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
135                if (mi2i != mi2iMap_.end()) {
136                    i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
137                    mi2iMap_.erase(mi2i);
138                }
139                mii = mbbi->erase(mii);
140                ++numPeep;
141            }
142            else {
143                for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
144                    const MachineOperand& mop = mii->getOperand(i);
145                    if (mop.isRegister() && mop.getReg() &&
146                        MRegisterInfo::isVirtualRegister(mop.getReg())) {
147                        // replace register with representative register
148                        unsigned reg = rep(mop.getReg());
149                        mii->SetMachineOperandReg(i, reg);
150
151                        Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
152                        assert(r2iit != r2iMap_.end());
153                        r2iit->second->weight +=
154                            (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
155                    }
156                }
157                ++mii;
158            }
159        }
160    }
161
162    DEBUG(std::cerr << "********** INTERVALS **********\n");
163    DEBUG(std::copy(intervals_.begin(), intervals_.end(),
164                    std::ostream_iterator<LiveInterval>(std::cerr, "\n")));
165    DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
166    DEBUG(
167        for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
168             mbbi != mbbe; ++mbbi) {
169            std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
170            for (MachineBasicBlock::iterator mii = mbbi->begin(),
171                     mie = mbbi->end(); mii != mie; ++mii) {
172                std::cerr << getInstructionIndex(mii) << '\t';
173                mii->print(std::cerr, tm_);
174            }
175        });
176
177    return true;
178}
179
180std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills(
181    const LiveInterval& li,
182    VirtRegMap& vrm,
183    int slot)
184{
185    std::vector<LiveInterval*> added;
186
187    assert(li.weight != HUGE_VAL &&
188           "attempt to spill already spilled interval!");
189
190    DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
191          << li << '\n');
192
193    const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
194
195    for (LiveInterval::Ranges::const_iterator
196              i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
197        unsigned index = getBaseIndex(i->start);
198        unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
199        for (; index != end; index += InstrSlots::NUM) {
200            // skip deleted instructions
201            while (index != end && !getInstructionFromIndex(index))
202                index += InstrSlots::NUM;
203            if (index == end) break;
204
205            MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
206
207        for_operand:
208            for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
209                MachineOperand& mop = mi->getOperand(i);
210                if (mop.isRegister() && mop.getReg() == li.reg) {
211                    if (MachineInstr* fmi =
212                        mri_->foldMemoryOperand(mi, i, slot)) {
213                        lv_->instructionChanged(mi, fmi);
214                        vrm.virtFolded(li.reg, mi, fmi);
215                        mi2iMap_.erase(mi);
216                        i2miMap_[index/InstrSlots::NUM] = fmi;
217                        mi2iMap_[fmi] = index;
218                        MachineBasicBlock& mbb = *mi->getParent();
219                        mi = mbb.insert(mbb.erase(mi), fmi);
220                        ++numFolded;
221                        goto for_operand;
222                    }
223                    else {
224                        // This is tricky. We need to add information in
225                        // the interval about the spill code so we have to
226                        // use our extra load/store slots.
227                        //
228                        // If we have a use we are going to have a load so
229                        // we start the interval from the load slot
230                        // onwards. Otherwise we start from the def slot.
231                        unsigned start = (mop.isUse() ?
232                                          getLoadIndex(index) :
233                                          getDefIndex(index));
234                        // If we have a def we are going to have a store
235                        // right after it so we end the interval after the
236                        // use of the next instruction. Otherwise we end
237                        // after the use of this instruction.
238                        unsigned end = 1 + (mop.isDef() ?
239                                            getStoreIndex(index) :
240                                            getUseIndex(index));
241
242                        // create a new register for this spill
243                        unsigned nReg =
244                            mf_->getSSARegMap()->createVirtualRegister(rc);
245                        mi->SetMachineOperandReg(i, nReg);
246                        vrm.grow();
247                        vrm.assignVirt2StackSlot(nReg, slot);
248                        LiveInterval& nI = getOrCreateInterval(nReg);
249                        assert(nI.empty());
250                        // the spill weight is now infinity as it
251                        // cannot be spilled again
252                        nI.weight = HUGE_VAL;
253                        nI.addRange(LiveRange(start, end));
254                        added.push_back(&nI);
255                        // update live variables
256                        lv_->addVirtualRegisterKilled(nReg, mi);
257                        DEBUG(std::cerr << "\t\t\t\tadded new interval: "
258                              << nI << '\n');
259                    }
260                }
261            }
262        }
263    }
264
265    return added;
266}
267
268void LiveIntervals::printRegName(unsigned reg) const
269{
270    if (MRegisterInfo::isPhysicalRegister(reg))
271        std::cerr << mri_->getName(reg);
272    else
273        std::cerr << "%reg" << reg;
274}
275
276void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
277                                             MachineBasicBlock::iterator mi,
278                                             LiveInterval& interval)
279{
280    DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
281    LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
282
283    // Virtual registers may be defined multiple times (due to phi
284    // elimination and 2-addr elimination).  Much of what we do only has to be
285    // done once for the vreg.  We use an empty interval to detect the first
286    // time we see a vreg.
287    if (interval.empty()) {
288       // Assume this interval is singly defined until we find otherwise.
289       interval.isDefinedOnce = true;
290
291       // Get the Idx of the defining instructions.
292       unsigned defIndex = getDefIndex(getInstructionIndex(mi));
293
294       // Loop over all of the blocks that the vreg is defined in.  There are
295       // two cases we have to handle here.  The most common case is a vreg
296       // whose lifetime is contained within a basic block.  In this case there
297       // will be a single kill, in MBB, which comes after the definition.
298       if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
299           // FIXME: what about dead vars?
300           unsigned killIdx;
301           if (vi.Kills[0] != mi)
302               killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
303           else
304               killIdx = defIndex+1;
305
306           // If the kill happens after the definition, we have an intra-block
307           // live range.
308           if (killIdx > defIndex) {
309              assert(vi.AliveBlocks.empty() &&
310                     "Shouldn't be alive across any blocks!");
311              interval.addRange(LiveRange(defIndex, killIdx));
312              DEBUG(std::cerr << "\n");
313              return;
314           }
315       }
316
317       // The other case we handle is when a virtual register lives to the end
318       // of the defining block, potentially live across some blocks, then is
319       // live into some number of blocks, but gets killed.  Start by adding a
320       // range that goes from this definition to the end of the defining block.
321       interval.addRange(LiveRange(defIndex,
322                                   getInstructionIndex(&mbb->back()) +
323                                         InstrSlots::NUM));
324
325       // Iterate over all of the blocks that the variable is completely
326       // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
327       // live interval.
328       for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
329           if (vi.AliveBlocks[i]) {
330               MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
331               if (!mbb->empty()) {
332                   interval.addRange(LiveRange(
333                       getInstructionIndex(&mbb->front()),
334                       getInstructionIndex(&mbb->back()) + InstrSlots::NUM));
335               }
336           }
337       }
338
339       // Finally, this virtual register is live from the start of any killing
340       // block to the 'use' slot of the killing instruction.
341       for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
342           MachineInstr *Kill = vi.Kills[i];
343           interval.addRange(LiveRange(
344                             getInstructionIndex(Kill->getParent()->begin()),
345                             getUseIndex(getInstructionIndex(Kill))+1));
346       }
347
348    } else {
349       // If this is the second time we see a virtual register definition, it
350       // must be due to phi elimination or two addr elimination.  If this is
351       // the result of two address elimination, then the vreg is the first
352       // operand, and is a def-and-use.
353       if (mi->getOperand(0).isRegister() &&
354           mi->getOperand(0).getReg() == interval.reg &&
355           mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
356         // If this is a two-address definition, just ignore it.
357       } else {
358         // Otherwise, this must be because of phi elimination.  In this case,
359         // the defined value will be live until the end of the basic block it
360         // is defined in.
361         unsigned defIndex = getDefIndex(getInstructionIndex(mi));
362         interval.addRange(LiveRange(defIndex,
363                           getInstructionIndex(&mbb->back()) +InstrSlots::NUM));
364       }
365       interval.isDefinedOnce = false;
366    }
367
368    DEBUG(std::cerr << '\n');
369}
370
371void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
372                                              MachineBasicBlock::iterator mi,
373                                              LiveInterval& interval)
374{
375    // A physical register cannot be live across basic block, so its
376    // lifetime must end somewhere in its defining basic block.
377    DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
378    typedef LiveVariables::killed_iterator KillIter;
379
380    MachineBasicBlock::iterator e = mbb->end();
381    unsigned baseIndex = getInstructionIndex(mi);
382    unsigned start = getDefIndex(baseIndex);
383    unsigned end = start;
384
385    // If it is not used after definition, it is considered dead at
386    // the instruction defining it. Hence its interval is:
387    // [defSlot(def), defSlot(def)+1)
388    for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
389         ki != ke; ++ki) {
390        if (interval.reg == ki->second) {
391            DEBUG(std::cerr << " dead");
392            end = getDefIndex(start) + 1;
393            goto exit;
394        }
395    }
396
397    // If it is not dead on definition, it must be killed by a
398    // subsequent instruction. Hence its interval is:
399    // [defSlot(def), useSlot(kill)+1)
400    do {
401        ++mi;
402        baseIndex += InstrSlots::NUM;
403        for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
404             ki != ke; ++ki) {
405            if (interval.reg == ki->second) {
406                DEBUG(std::cerr << " killed");
407                end = getUseIndex(baseIndex) + 1;
408                goto exit;
409            }
410        }
411    } while (mi != e);
412
413exit:
414    assert(start < end && "did not find end of interval?");
415    interval.addRange(LiveRange(start, end));
416    DEBUG(std::cerr << '\n');
417}
418
419void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
420                                      MachineBasicBlock::iterator mi,
421                                      unsigned reg)
422{
423    if (MRegisterInfo::isPhysicalRegister(reg)) {
424        if (lv_->getAllocatablePhysicalRegisters()[reg]) {
425            handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(reg));
426            for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as)
427                handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(*as));
428        }
429    }
430    else
431        handleVirtualRegisterDef(mbb, mi, getOrCreateInterval(reg));
432}
433
434unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
435{
436    Mi2IndexMap::const_iterator it = mi2iMap_.find(instr);
437    return (it == mi2iMap_.end() ?
438            std::numeric_limits<unsigned>::max() :
439            it->second);
440}
441
442MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const
443{
444    index /= InstrSlots::NUM; // convert index to vector index
445    assert(index < i2miMap_.size() &&
446           "index does not correspond to an instruction");
447    return i2miMap_[index];
448}
449
450/// computeIntervals - computes the live intervals for virtual
451/// registers. for some ordering of the machine instructions [1,N] a
452/// live interval is an interval [i, j) where 1 <= i <= j < N for
453/// which a variable is live
454void LiveIntervals::computeIntervals()
455{
456    DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
457    DEBUG(std::cerr << "********** Function: "
458          << ((Value*)mf_->getFunction())->getName() << '\n');
459
460    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
461         I != E; ++I) {
462        MachineBasicBlock* mbb = I;
463        DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
464
465        for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
466             mi != miEnd; ++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            // handle implicit defs
473            for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
474                handleRegisterDef(mbb, mi, *id);
475
476            // handle explicit defs
477            for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
478                MachineOperand& mop = mi->getOperand(i);
479                // handle register defs - build intervals
480                if (mop.isRegister() && mop.getReg() && mop.isDef())
481                    handleRegisterDef(mbb, mi, mop.getReg());
482            }
483        }
484    }
485}
486
487unsigned LiveIntervals::rep(unsigned reg)
488{
489    Reg2RegMap::iterator it = r2rMap_.find(reg);
490    if (it != r2rMap_.end())
491        return it->second = rep(it->second);
492    return reg;
493}
494
495void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
496    DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
497    const TargetInstrInfo& tii = *tm_->getInstrInfo();
498
499    for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
500         mi != mie; ++mi) {
501        const TargetInstrDescriptor& tid = tii.get(mi->getOpcode());
502        DEBUG(std::cerr << getInstructionIndex(mi) << '\t';
503              mi->print(std::cerr, tm_););
504
505        // we only join virtual registers with allocatable
506        // physical registers since we do not have liveness information
507        // on not allocatable physical registers
508        unsigned regA, regB;
509        if (tii.isMoveInstr(*mi, regA, regB) &&
510            (MRegisterInfo::isVirtualRegister(regA) ||
511             lv_->getAllocatablePhysicalRegisters()[regA]) &&
512            (MRegisterInfo::isVirtualRegister(regB) ||
513             lv_->getAllocatablePhysicalRegisters()[regB])) {
514
515            // get representative registers
516            regA = rep(regA);
517            regB = rep(regB);
518
519            // if they are already joined we continue
520            if (regA == regB)
521                continue;
522
523            Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA);
524            assert(r2iA != r2iMap_.end() &&
525                   "Found unknown vreg in 'isMoveInstr' instruction");
526            Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB);
527            assert(r2iB != r2iMap_.end() &&
528                   "Found unknown vreg in 'isMoveInstr' instruction");
529
530            Intervals::iterator intA = r2iA->second;
531            Intervals::iterator intB = r2iB->second;
532
533            DEBUG(std::cerr << "\t\tInspecting " << *intA << " and " << *intB
534                            << ": ");
535
536            // both A and B are virtual registers
537            if (MRegisterInfo::isVirtualRegister(intA->reg) &&
538                MRegisterInfo::isVirtualRegister(intB->reg)) {
539
540                const TargetRegisterClass *rcA, *rcB;
541                rcA = mf_->getSSARegMap()->getRegClass(intA->reg);
542                rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
543
544                // if they are not of the same register class we continue
545                if (rcA != rcB) {
546                    DEBUG(std::cerr << "Differing reg classes.\n");
547                    continue;
548                }
549
550                // if their intervals do not overlap we join them
551                if ((intA->isDefinedOnce && intB->isDefinedOnce) ||
552                    !intB->overlaps(*intA)) {
553                    intA->join(*intB);
554                    DEBUG(std::cerr << "Joined.  Result = " << *intA << "\n");
555                    r2iB->second = r2iA->second;
556                    r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
557                    intervals_.erase(intB);
558                } else {
559                    DEBUG(std::cerr << "Interference!\n");
560                }
561            } else if (!MRegisterInfo::isPhysicalRegister(intA->reg) ||
562                       !MRegisterInfo::isPhysicalRegister(intB->reg)) {
563                if (MRegisterInfo::isPhysicalRegister(intB->reg)) {
564                    std::swap(regA, regB);
565                    std::swap(intA, intB);
566                    std::swap(r2iA, r2iB);
567                }
568
569                assert(MRegisterInfo::isPhysicalRegister(intA->reg) &&
570                       MRegisterInfo::isVirtualRegister(intB->reg) &&
571                       "A must be physical and B must be virtual");
572
573                const TargetRegisterClass *rcA, *rcB;
574                rcA = mri_->getRegClass(intA->reg);
575                rcB = mf_->getSSARegMap()->getRegClass(intB->reg);
576                // if they are not of the same register class we continue
577                if (rcA != rcB) {
578                    DEBUG(std::cerr << "Differing reg classes.\n");
579                    continue;
580                }
581
582                if (!intA->overlaps(*intB) &&
583                    !overlapsAliases(*intA, *intB)) {
584                    intA->join(*intB);
585                    DEBUG(std::cerr << "Joined.  Result = " << *intA << "\n");
586                    r2iB->second = r2iA->second;
587                    r2rMap_.insert(std::make_pair(intB->reg, intA->reg));
588                    intervals_.erase(intB);
589                } else {
590                    DEBUG(std::cerr << "Interference!\n");
591                }
592            } else {
593                DEBUG(std::cerr << "Cannot join physregs.\n");
594            }
595        }
596    }
597}
598
599namespace {
600  // DepthMBBCompare - Comparison predicate that sort first based on the loop
601  // depth of the basic block (the unsigned), and then on the MBB number.
602  struct DepthMBBCompare {
603    typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
604    bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
605      if (LHS.first > RHS.first) return true;   // Deeper loops first
606      return LHS.first == RHS.first &&
607             LHS.second->getNumber() < RHS.second->getNumber();
608    }
609  };
610}
611
612void LiveIntervals::joinIntervals() {
613  DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
614
615  const LoopInfo &LI = getAnalysis<LoopInfo>();
616  if (LI.begin() == LI.end()) {
617    // If there are no loops in the function, join intervals in function order.
618    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
619         I != E; ++I)
620      joinIntervalsInMachineBB(I);
621  } else {
622    // Otherwise, join intervals in inner loops before other intervals.
623    // Unfortunately we can't just iterate over loop hierarchy here because
624    // there may be more MBB's than BB's.  Collect MBB's for sorting.
625    std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
626    for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
627         I != E; ++I)
628      MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
629
630    // Sort by loop depth.
631    std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
632
633    // Finally, join intervals in loop nest order.
634    for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
635      joinIntervalsInMachineBB(MBBs[i].second);
636  }
637}
638
639bool LiveIntervals::overlapsAliases(const LiveInterval& lhs,
640                                    const LiveInterval& rhs) const
641{
642    assert(MRegisterInfo::isPhysicalRegister(lhs.reg) &&
643           "first interval must describe a physical register");
644
645    for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) {
646        Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as);
647        assert(r2i != r2iMap_.end() && "alias does not have interval?");
648        if (rhs.overlaps(*r2i->second))
649            return true;
650    }
651
652    return false;
653}
654
655LiveInterval& LiveIntervals::getOrCreateInterval(unsigned reg)
656{
657    Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
658    if (r2iit == r2iMap_.end() || r2iit->first != reg) {
659        intervals_.push_back(LiveInterval(reg));
660        r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
661    }
662
663    return *r2iit->second;
664}
665
666LiveInterval::LiveInterval(unsigned r)
667    : reg(r),
668      weight((MRegisterInfo::isPhysicalRegister(r) ?  HUGE_VAL : 0.0F)),
669      isDefinedOnce(false) {
670}
671
672bool LiveInterval::spilled() const
673{
674    return (weight == HUGE_VAL &&
675            MRegisterInfo::isVirtualRegister(reg));
676}
677
678// An example for liveAt():
679//
680// this = [1,4), liveAt(0) will return false. The instruction defining
681// this spans slots [0,3]. The interval belongs to an spilled
682// definition of the variable it represents. This is because slot 1 is
683// used (def slot) and spans up to slot 3 (store slot).
684//
685bool LiveInterval::liveAt(unsigned index) const
686{
687    LiveRange dummy(index, index+1);
688    Ranges::const_iterator r = std::upper_bound(ranges.begin(),
689                                                ranges.end(),
690                                                dummy);
691    if (r == ranges.begin())
692        return false;
693
694    --r;
695    return index >= r->start && index < r->end;
696}
697
698// An example for overlaps():
699//
700// 0: A = ...
701// 4: B = ...
702// 8: C = A + B ;; last use of A
703//
704// The live intervals should look like:
705//
706// A = [3, 11)
707// B = [7, x)
708// C = [11, y)
709//
710// A->overlaps(C) should return false since we want to be able to join
711// A and C.
712bool LiveInterval::overlaps(const LiveInterval& other) const
713{
714    Ranges::const_iterator i = ranges.begin();
715    Ranges::const_iterator ie = ranges.end();
716    Ranges::const_iterator j = other.ranges.begin();
717    Ranges::const_iterator je = other.ranges.end();
718    if (i->start < j->start) {
719        i = std::upper_bound(i, ie, *j);
720        if (i != ranges.begin()) --i;
721    }
722    else if (j->start < i->start) {
723        j = std::upper_bound(j, je, *i);
724        if (j != other.ranges.begin()) --j;
725    }
726
727    while (i != ie && j != je) {
728        if (i->start == j->start)
729            return true;
730
731        if (i->start > j->start) {
732            swap(i, j);
733            swap(ie, je);
734        }
735        assert(i->start < j->start);
736
737        if (i->end > j->start)
738            return true;
739        ++i;
740    }
741
742    return false;
743}
744
745void LiveInterval::addRange(LiveRange LR) {
746    DEBUG(std::cerr << " +" << LR);
747    Ranges::iterator it =
748        ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), LR), LR);
749
750    mergeRangesBackward(mergeRangesForward(it));
751}
752
753void LiveInterval::join(const LiveInterval& other)
754{
755    Ranges::iterator cur = ranges.begin();
756    isDefinedOnce &= other.isDefinedOnce;
757
758    for (Ranges::const_iterator i = other.ranges.begin(),
759             e = other.ranges.end(); i != e; ++i) {
760        cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i);
761        cur = mergeRangesForward(cur);
762        cur = mergeRangesBackward(cur);
763    }
764    weight += other.weight;
765    ++numJoins;
766}
767
768LiveInterval::Ranges::iterator LiveInterval::
769mergeRangesForward(Ranges::iterator it)
770{
771    Ranges::iterator n;
772    while ((n = next(it)) != ranges.end()) {
773        if (n->start > it->end)
774            break;
775        it->end = std::max(it->end, n->end);
776        n = ranges.erase(n);
777    }
778    return it;
779}
780
781LiveInterval::Ranges::iterator LiveInterval::
782mergeRangesBackward(Ranges::iterator it)
783{
784    while (it != ranges.begin()) {
785        Ranges::iterator p = prior(it);
786        if (it->start > p->end)
787            break;
788
789        it->start = std::min(it->start, p->start);
790        it->end = std::max(it->end, p->end);
791        it = ranges.erase(p);
792    }
793
794    return it;
795}
796
797std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) {
798  return os << "[" << LR.start << "," << LR.end << ")";
799}
800
801
802std::ostream& llvm::operator<<(std::ostream& os, const LiveInterval& li)
803{
804    os << "%reg" << li.reg << ',' << li.weight;
805    if (li.empty())
806        return os << "EMPTY";
807
808    os << " = ";
809    for (LiveInterval::Ranges::const_iterator i = li.ranges.begin(),
810           e = li.ranges.end(); i != e; ++i)
811        os << *i;
812    return os;
813}
814