0b31e227cbb4a25eb662a243b3aabc97a38fbef3
[oota-llvm.git] / lib / CodeGen / LiveIntervalAnalysis.cpp
1 //===-- LiveIntervalAnalysis.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 "LiveIntervalAnalysis.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
37 using namespace llvm;
38
39 namespace {
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
64 void 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
75 void 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 ///
87 bool 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 #if 1
110     DEBUG(std::cerr << "********** INTERVALS **********\n");
111     DEBUG(std::copy(intervals_.begin(), intervals_.end(),
112                     std::ostream_iterator<LiveInterval>(std::cerr, "\n")));
113 #endif
114
115     // join intervals if requested
116     if (EnableJoining) joinIntervals();
117
118     numIntervalsAfter += intervals_.size();
119
120     // perform a final pass over the instructions and compute spill
121     // weights, coalesce virtual registers and remove identity moves
122     const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
123     const TargetInstrInfo& tii = *tm_->getInstrInfo();
124
125     for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
126          mbbi != mbbe; ++mbbi) {
127         MachineBasicBlock* mbb = mbbi;
128         unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
129
130         for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
131              mii != mie; ) {
132             // if the move will be an identity move delete it
133             unsigned srcReg, dstReg;
134             if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
135                 rep(srcReg) == rep(dstReg)) {
136                 // remove from def list
137                 LiveInterval& interval = getOrCreateInterval(rep(dstReg));
138                 // remove index -> MachineInstr and
139                 // MachineInstr -> index mappings
140                 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
141                 if (mi2i != mi2iMap_.end()) {
142                     i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
143                     mi2iMap_.erase(mi2i);
144                 }
145                 mii = mbbi->erase(mii);
146                 ++numPeep;
147             }
148             else {
149                 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
150                     const MachineOperand& mop = mii->getOperand(i);
151                     if (mop.isRegister() && mop.getReg() &&
152                         MRegisterInfo::isVirtualRegister(mop.getReg())) {
153                         // replace register with representative register
154                         unsigned reg = rep(mop.getReg());
155                         mii->SetMachineOperandReg(i, reg);
156
157                         Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
158                         assert(r2iit != r2iMap_.end());
159                         r2iit->second->weight +=
160                             (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
161                     }
162                 }
163                 ++mii;
164             }
165         }
166     }
167
168     DEBUG(std::cerr << "********** INTERVALS **********\n");
169     DEBUG(std::copy(intervals_.begin(), intervals_.end(),
170                     std::ostream_iterator<LiveInterval>(std::cerr, "\n")));
171     DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
172     DEBUG(
173         for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
174              mbbi != mbbe; ++mbbi) {
175             std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
176             for (MachineBasicBlock::iterator mii = mbbi->begin(),
177                      mie = mbbi->end(); mii != mie; ++mii) {
178                 std::cerr << getInstructionIndex(mii) << '\t';
179                 mii->print(std::cerr, tm_);
180             }
181         });
182
183     return true;
184 }
185
186 std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills(
187     const LiveInterval& li,
188     VirtRegMap& vrm,
189     int slot)
190 {
191     std::vector<LiveInterval*> added;
192
193     assert(li.weight != HUGE_VAL &&
194            "attempt to spill already spilled interval!");
195
196     DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
197           << li << '\n');
198
199     const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
200
201     for (LiveInterval::Ranges::const_iterator
202               i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
203         unsigned index = getBaseIndex(i->start);
204         unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
205         for (; index != end; index += InstrSlots::NUM) {
206             // skip deleted instructions
207             while (index != end && !getInstructionFromIndex(index))
208                 index += InstrSlots::NUM;
209             if (index == end) break;
210
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                                             getStoreIndex(index) :
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                         LiveRange LR(start, end, nI.getNextValue());
260                         DEBUG(std::cerr << " +" << LR);
261                         nI.addRange(LR);
262                         added.push_back(&nI);
263                         // update live variables
264                         lv_->addVirtualRegisterKilled(nReg, mi);
265                         DEBUG(std::cerr << "\t\t\t\tadded new interval: "
266                               << nI << '\n');
267                     }
268                 }
269             }
270         }
271     }
272
273     return added;
274 }
275
276 void LiveIntervals::printRegName(unsigned reg) const
277 {
278     if (MRegisterInfo::isPhysicalRegister(reg))
279         std::cerr << mri_->getName(reg);
280     else
281         std::cerr << "%reg" << reg;
282 }
283
284 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
285                                              MachineBasicBlock::iterator mi,
286                                              LiveInterval& interval)
287 {
288     DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
289     LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
290
291     // Virtual registers may be defined multiple times (due to phi 
292     // elimination and 2-addr elimination).  Much of what we do only has to be 
293     // done once for the vreg.  We use an empty interval to detect the first 
294     // time we see a vreg.
295     if (interval.empty()) {
296        // Get the Idx of the defining instructions.
297        unsigned defIndex = getDefIndex(getInstructionIndex(mi));
298
299        unsigned ValNum = interval.getNextValue();
300        assert(ValNum == 0 && "First value in interval is not 0?");
301        ValNum = 0;  // Clue in the optimizer.
302
303        // Loop over all of the blocks that the vreg is defined in.  There are
304        // two cases we have to handle here.  The most common case is a vreg
305        // whose lifetime is contained within a basic block.  In this case there
306        // will be a single kill, in MBB, which comes after the definition.
307        if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
308            // FIXME: what about dead vars?
309            unsigned killIdx;
310            if (vi.Kills[0] != mi)
311                killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
312            else
313                killIdx = defIndex+1;
314
315            // If the kill happens after the definition, we have an intra-block
316            // live range.
317            if (killIdx > defIndex) {
318               assert(vi.AliveBlocks.empty() && 
319                      "Shouldn't be alive across any blocks!");
320               LiveRange LR(defIndex, killIdx, ValNum);
321               interval.addRange(LR);
322               DEBUG(std::cerr << " +" << LR << "\n");
323               return;
324            }
325        }
326
327        // The other case we handle is when a virtual register lives to the end
328        // of the defining block, potentially live across some blocks, then is
329        // live into some number of blocks, but gets killed.  Start by adding a
330        // range that goes from this definition to the end of the defining block.
331        LiveRange NewLR(defIndex, getInstructionIndex(&mbb->back()) +
332                                                    InstrSlots::NUM, ValNum);
333        DEBUG(std::cerr << " +" << NewLR);
334        interval.addRange(NewLR);
335
336        // Iterate over all of the blocks that the variable is completely
337        // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
338        // live interval.
339        for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
340            if (vi.AliveBlocks[i]) {
341                MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
342                if (!mbb->empty()) {
343                  LiveRange LR(getInstructionIndex(&mbb->front()),
344                               getInstructionIndex(&mbb->back())+InstrSlots::NUM,
345                               ValNum);
346                  interval.addRange(LR);
347                  DEBUG(std::cerr << " +" << LR);
348                }
349            }
350        }
351
352        // Finally, this virtual register is live from the start of any killing
353        // block to the 'use' slot of the killing instruction.
354        for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
355            MachineInstr *Kill = vi.Kills[i];
356            LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
357                         getUseIndex(getInstructionIndex(Kill))+1, ValNum);
358            interval.addRange(LR);
359            DEBUG(std::cerr << " +" << LR);
360        }
361
362     } else {
363        // If this is the second time we see a virtual register definition, it
364        // must be due to phi elimination or two addr elimination.  If this is
365        // the result of two address elimination, then the vreg is the first
366        // operand, and is a def-and-use.
367        if (mi->getOperand(0).isRegister() && 
368            mi->getOperand(0).getReg() == interval.reg &&
369            mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
370          // If this is a two-address definition, then we have already processed
371          // the live range.  The only problem is that we didn't realize there
372          // are actually two values in the live interval.  Because of this we
373          // need to take the LiveRegion that defines this register and split it
374          // into two values.
375          unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
376          unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
377
378          // Delete the initial value, which should be short and continuous,
379          // becuase the 2-addr copy must be in the same MBB as the redef.
380          interval.removeRange(DefIndex, RedefIndex);
381          
382          LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
383          DEBUG(std::cerr << " replace range with " << LR);
384          interval.addRange(LR);
385
386          // If this redefinition is dead, we need to add a dummy unit live
387          // range covering the def slot.
388          for (LiveVariables::killed_iterator KI = lv_->dead_begin(mi),
389                 E = lv_->dead_end(mi); KI != E; ++KI)
390            if (KI->second == interval.reg) {
391              interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
392              break;
393            }
394
395          DEBUG(std::cerr << "RESULT: " << interval);
396
397        } else {
398          // Otherwise, this must be because of phi elimination.  In this case, 
399          // the defined value will be live until the end of the basic block it
400          // is defined in.
401          unsigned defIndex = getDefIndex(getInstructionIndex(mi));
402          LiveRange LR(defIndex, 
403                       getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
404                       interval.getNextValue());
405          interval.addRange(LR);
406          DEBUG(std::cerr << " +" << LR);
407        }
408     }
409
410     DEBUG(std::cerr << '\n');
411 }
412
413 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
414                                               MachineBasicBlock::iterator mi,
415                                               LiveInterval& interval)
416 {
417     // A physical register cannot be live across basic block, so its
418     // lifetime must end somewhere in its defining basic block.
419     DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
420     typedef LiveVariables::killed_iterator KillIter;
421
422     unsigned baseIndex = getInstructionIndex(mi);
423     unsigned start = getDefIndex(baseIndex);
424     unsigned end = start;
425
426     // If it is not used after definition, it is considered dead at
427     // the instruction defining it. Hence its interval is:
428     // [defSlot(def), defSlot(def)+1)
429     for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
430          ki != ke; ++ki) {
431         if (interval.reg == ki->second) {
432             DEBUG(std::cerr << " dead");
433             end = getDefIndex(start) + 1;
434             goto exit;
435         }
436     }
437
438     // If it is not dead on definition, it must be killed by a
439     // subsequent instruction. Hence its interval is:
440     // [defSlot(def), useSlot(kill)+1)
441     while (true) {
442         ++mi;
443         assert(mi != MBB->end() && "physreg was not killed in defining block!");
444         baseIndex += InstrSlots::NUM;
445         for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
446              ki != ke; ++ki) {
447             if (interval.reg == ki->second) {
448                 DEBUG(std::cerr << " killed");
449                 end = getUseIndex(baseIndex) + 1;
450                 goto exit;
451             }
452         }
453     }
454
455 exit:
456     assert(start < end && "did not find end of interval?");
457     LiveRange LR(start, end, interval.getNextValue());
458     interval.addRange(LR);
459     DEBUG(std::cerr << " +" << LR << '\n');
460 }
461
462 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
463                                       MachineBasicBlock::iterator MI,
464                                       unsigned reg) {
465   if (MRegisterInfo::isVirtualRegister(reg))
466     handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
467   else if (lv_->getAllocatablePhysicalRegisters()[reg]) {
468     handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg));
469     for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
470       handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS));
471   }
472 }
473
474 /// computeIntervals - computes the live intervals for virtual
475 /// registers. for some ordering of the machine instructions [1,N] a
476 /// live interval is an interval [i, j) where 1 <= i <= j < N for
477 /// which a variable is live
478 void LiveIntervals::computeIntervals()
479 {
480     DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
481     DEBUG(std::cerr << "********** Function: "
482           << ((Value*)mf_->getFunction())->getName() << '\n');
483
484     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); 
485          I != E; ++I) {
486         MachineBasicBlock* mbb = I;
487         DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
488
489         for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
490              mi != miEnd; ++mi) {
491             const TargetInstrDescriptor& tid =
492                 tm_->getInstrInfo()->get(mi->getOpcode());
493             DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
494                   mi->print(std::cerr, tm_));
495
496             // handle implicit defs
497             for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
498                 handleRegisterDef(mbb, mi, *id);
499
500             // handle explicit defs
501             for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
502                 MachineOperand& mop = mi->getOperand(i);
503                 // handle register defs - build intervals
504                 if (mop.isRegister() && mop.getReg() && mop.isDef())
505                     handleRegisterDef(mbb, mi, mop.getReg());
506             }
507         }
508     }
509 }
510
511 void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
512   DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
513   const TargetInstrInfo &TII = *tm_->getInstrInfo();
514
515   for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
516        mi != mie; ++mi) {
517     DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
518
519     // we only join virtual registers with allocatable
520     // physical registers since we do not have liveness information
521     // on not allocatable physical registers
522     unsigned regA, regB;
523     if (TII.isMoveInstr(*mi, regA, regB) &&
524         (MRegisterInfo::isVirtualRegister(regA) ||
525                  lv_->getAllocatablePhysicalRegisters()[regA]) &&
526         (MRegisterInfo::isVirtualRegister(regB) ||
527                  lv_->getAllocatablePhysicalRegisters()[regB])) {
528       
529       // Get representative registers.
530       regA = rep(regA);
531       regB = rep(regB);
532       
533       // If they are already joined we continue.
534       if (regA == regB)
535         continue;
536             
537       // If they are both physical registers, we cannot join them.
538       if (MRegisterInfo::isPhysicalRegister(regA) && 
539           MRegisterInfo::isPhysicalRegister(regB))
540         continue;
541
542       // If they are not of the same register class, we cannot join them.
543       if (differingRegisterClasses(regA, regB))
544         continue;
545
546       LiveInterval &IntA = getInterval(regA);
547       LiveInterval &IntB = getInterval(regB);
548       assert(IntA.reg == regA && IntB.reg == regB &&
549              "Register mapping is horribly broken!");
550             
551       bool TriviallyJoinable =
552         IntA.containsOneValue() && IntB.containsOneValue();
553
554       unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
555       if ((TriviallyJoinable || !IntB.joinable(IntA, MIDefIdx)) &&
556           !overlapsAliases(&IntA, &IntB)) {
557         IntB.join(IntA, MIDefIdx);
558
559         // FIXME: Turn 'intervals_' into an ilist so we don't need to do these
560         // map lookups!
561         intervals_.erase(r2iMap_[regA]);
562         r2iMap_[regA] = r2iMap_[regB];
563
564         if (!MRegisterInfo::isPhysicalRegister(regA)) {
565           r2rMap_[regA] = regB;
566         } else {
567           // Otherwise merge the data structures the other way so we don't lose
568           // the physreg information.
569           r2rMap_[regB] = regA;
570           IntB.reg = regA;
571         }
572         DEBUG(std::cerr << "Joined.  Result = " << IntB << "\n");
573         ++numJoins;
574       } else {
575         DEBUG(std::cerr << "Interference!\n");
576       }
577     }
578   }
579 }
580
581 namespace {
582   // DepthMBBCompare - Comparison predicate that sort first based on the loop
583   // depth of the basic block (the unsigned), and then on the MBB number.
584   struct DepthMBBCompare {
585     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
586     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
587       if (LHS.first > RHS.first) return true;   // Deeper loops first
588       return LHS.first == RHS.first && 
589              LHS.second->getNumber() < RHS.second->getNumber();
590     }
591   };
592 }
593
594 void LiveIntervals::joinIntervals() {
595   DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
596
597   const LoopInfo &LI = getAnalysis<LoopInfo>();
598   if (LI.begin() == LI.end()) {
599     // If there are no loops in the function, join intervals in function order.
600     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
601          I != E; ++I)
602       joinIntervalsInMachineBB(I);
603   } else {
604     // Otherwise, join intervals in inner loops before other intervals.
605     // Unfortunately we can't just iterate over loop hierarchy here because
606     // there may be more MBB's than BB's.  Collect MBB's for sorting.
607     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
608     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
609          I != E; ++I)
610       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
611
612     // Sort by loop depth.
613     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
614
615     // Finally, join intervals in loop nest order. 
616     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
617       joinIntervalsInMachineBB(MBBs[i].second);
618   }
619 }
620
621 /// Return true if the two specified registers belong to different register
622 /// classes.  The registers may be either phys or virt regs.
623 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
624                                              unsigned RegB) const {
625   const TargetRegisterClass *RegClass;
626
627   // Get the register classes for the first reg.
628   if (MRegisterInfo::isVirtualRegister(RegA))
629     RegClass = mf_->getSSARegMap()->getRegClass(RegA);
630   else
631     RegClass = mri_->getRegClass(RegA);
632
633   // Compare against the regclass for the second reg.
634   if (MRegisterInfo::isVirtualRegister(RegB))
635     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
636   else
637     return RegClass != mri_->getRegClass(RegB);
638 }
639
640 bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
641                                     const LiveInterval *RHS) const {
642   if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
643     if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
644       return false;   // vreg-vreg merge has no aliases!
645     std::swap(LHS, RHS);
646   }
647
648   assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
649          MRegisterInfo::isVirtualRegister(RHS->reg) &&
650          "first interval must describe a physical register");
651
652     for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS) {
653         Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*AS);
654         assert(r2i != r2iMap_.end() && "alias does not have interval?");
655         if (RHS->overlaps(*r2i->second))
656             return true;
657     }
658
659     return false;
660 }
661
662 LiveInterval& LiveIntervals::getOrCreateInterval(unsigned reg)
663 {
664     Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg);
665     if (r2iit == r2iMap_.end() || r2iit->first != reg) {
666         float Weight = MRegisterInfo::isPhysicalRegister(reg) ?  HUGE_VAL :0.0F;
667         intervals_.push_back(LiveInterval(reg, Weight));
668         r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end()));
669     }
670
671     return *r2iit->second;
672 }
673