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