Oops.
[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 "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "VirtRegMap.h"
21 #include "llvm/Value.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/MRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 #include <cmath>
37 using namespace llvm;
38
39 STATISTIC(numIntervals, "Number of original intervals");
40 STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
41 STATISTIC(numJoins    , "Number of interval joins performed");
42 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
43 STATISTIC(numFolded   , "Number of loads/stores folded into instructions");
44
45 namespace {
46   RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
47
48   static cl::opt<bool>
49   EnableJoining("join-liveintervals",
50                 cl::desc("Coallesce copies (default=true)"),
51                 cl::init(true));
52 }
53
54 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
55   AU.addRequired<LiveVariables>();
56   AU.addPreservedID(PHIEliminationID);
57   AU.addRequiredID(PHIEliminationID);
58   AU.addRequiredID(TwoAddressInstructionPassID);
59   AU.addRequired<LoopInfo>();
60   MachineFunctionPass::getAnalysisUsage(AU);
61 }
62
63 void LiveIntervals::releaseMemory() {
64   mi2iMap_.clear();
65   i2miMap_.clear();
66   r2iMap_.clear();
67   r2rMap_.clear();
68   JoinedLIs.clear();
69 }
70
71
72 static bool isZeroLengthInterval(LiveInterval *li) {
73   for (LiveInterval::Ranges::const_iterator
74          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
75     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
76       return false;
77   return true;
78 }
79
80
81 /// runOnMachineFunction - Register allocate the whole function
82 ///
83 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
84   mf_ = &fn;
85   tm_ = &fn.getTarget();
86   mri_ = tm_->getRegisterInfo();
87   tii_ = tm_->getInstrInfo();
88   lv_ = &getAnalysis<LiveVariables>();
89   allocatableRegs_ = mri_->getAllocatableSet(fn);
90   r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
91
92   // Number MachineInstrs and MachineBasicBlocks.
93   // Initialize MBB indexes to a sentinal.
94   MBB2IdxMap.resize(mf_->getNumBlockIDs(), ~0U);
95   
96   unsigned MIIndex = 0;
97   for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
98        MBB != E; ++MBB) {
99     // Set the MBB2IdxMap entry for this MBB.
100     MBB2IdxMap[MBB->getNumber()] = MIIndex;
101
102     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
103          I != E; ++I) {
104       bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
105       assert(inserted && "multiple MachineInstr -> index mappings");
106       i2miMap_.push_back(I);
107       MIIndex += InstrSlots::NUM;
108     }
109   }
110
111   computeIntervals();
112
113   numIntervals += getNumIntervals();
114
115   DOUT << "********** INTERVALS **********\n";
116   for (iterator I = begin(), E = end(); I != E; ++I) {
117     I->second.print(DOUT, mri_);
118     DOUT << "\n";
119   }
120
121   // Join (coallesce) intervals if requested.
122   if (EnableJoining) joinIntervals();
123
124   numIntervalsAfter += getNumIntervals();
125   
126
127   // perform a final pass over the instructions and compute spill
128   // weights, coalesce virtual registers and remove identity moves.
129   const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
130
131   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
132        mbbi != mbbe; ++mbbi) {
133     MachineBasicBlock* mbb = mbbi;
134     unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
135
136     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
137          mii != mie; ) {
138       // if the move will be an identity move delete it
139       unsigned srcReg, dstReg, RegRep;
140       if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
141           (RegRep = rep(srcReg)) == rep(dstReg)) {
142         // remove from def list
143         LiveInterval &RegInt = getOrCreateInterval(RegRep);
144         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
145         // If def of this move instruction is dead, remove its live range from
146         // the dstination register's live interval.
147         if (MO->isDead()) {
148           unsigned MoveIdx = getDefIndex(getInstructionIndex(mii));
149           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
150           RegInt.removeRange(MLR->start, MoveIdx+1);
151           if (RegInt.empty())
152             removeInterval(RegRep);
153         }
154         RemoveMachineInstrFromMaps(mii);
155         mii = mbbi->erase(mii);
156         ++numPeep;
157       }
158       else {
159         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
160           const MachineOperand &mop = mii->getOperand(i);
161           if (mop.isRegister() && mop.getReg() &&
162               MRegisterInfo::isVirtualRegister(mop.getReg())) {
163             // replace register with representative register
164             unsigned reg = rep(mop.getReg());
165             mii->getOperand(i).setReg(reg);
166
167             LiveInterval &RegInt = getInterval(reg);
168             RegInt.weight +=
169               (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
170           }
171         }
172         ++mii;
173       }
174     }
175   }
176
177   for (iterator I = begin(), E = end(); I != E; ++I) {
178     LiveInterval &LI = I->second;
179     if (MRegisterInfo::isVirtualRegister(LI.reg)) {
180       // If the live interval length is essentially zero, i.e. in every live
181       // range the use follows def immediately, it doesn't make sense to spill
182       // it and hope it will be easier to allocate for this li.
183       if (isZeroLengthInterval(&LI))
184         LI.weight = HUGE_VALF;
185       
186       // Divide the weight of the interval by its size.  This encourages 
187       // spilling of intervals that are large and have few uses, and
188       // discourages spilling of small intervals with many uses.
189       unsigned Size = 0;
190       for (LiveInterval::iterator II = LI.begin(), E = LI.end(); II != E;++II)
191         Size += II->end - II->start;
192       
193       LI.weight /= Size;
194     }
195   }
196
197   DEBUG(dump());
198   return true;
199 }
200
201 /// print - Implement the dump method.
202 void LiveIntervals::print(std::ostream &O, const Module* ) const {
203   O << "********** INTERVALS **********\n";
204   for (const_iterator I = begin(), E = end(); I != E; ++I) {
205     I->second.print(DOUT, mri_);
206     DOUT << "\n";
207   }
208
209   O << "********** MACHINEINSTRS **********\n";
210   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
211        mbbi != mbbe; ++mbbi) {
212     O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
213     for (MachineBasicBlock::iterator mii = mbbi->begin(),
214            mie = mbbi->end(); mii != mie; ++mii) {
215       O << getInstructionIndex(mii) << '\t' << *mii;
216     }
217   }
218 }
219
220 /// CreateNewLiveInterval - Create a new live interval with the given live
221 /// ranges. The new live interval will have an infinite spill weight.
222 LiveInterval&
223 LiveIntervals::CreateNewLiveInterval(const LiveInterval *LI,
224                                      const std::vector<LiveRange> &LRs) {
225   const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(LI->reg);
226
227   // Create a new virtual register for the spill interval.
228   unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(RC);
229
230   // Replace the old virtual registers in the machine operands with the shiny
231   // new one.
232   for (std::vector<LiveRange>::const_iterator
233          I = LRs.begin(), E = LRs.end(); I != E; ++I) {
234     unsigned Index = getBaseIndex(I->start);
235     unsigned End = getBaseIndex(I->end - 1) + InstrSlots::NUM;
236
237     for (; Index != End; Index += InstrSlots::NUM) {
238       // Skip deleted instructions
239       while (Index != End && !getInstructionFromIndex(Index))
240         Index += InstrSlots::NUM;
241
242       if (Index == End) break;
243
244       MachineInstr *MI = getInstructionFromIndex(Index);
245
246       for (unsigned J = 0, e = MI->getNumOperands(); J != e; ++J) {
247         MachineOperand &MOp = MI->getOperand(J);
248         if (MOp.isRegister() && rep(MOp.getReg()) == LI->reg)
249           MOp.setReg(NewVReg);
250       }
251     }
252   }
253
254   LiveInterval &NewLI = getOrCreateInterval(NewVReg);
255
256   // The spill weight is now infinity as it cannot be spilled again
257   NewLI.weight = float(HUGE_VAL);
258
259   for (std::vector<LiveRange>::const_iterator
260          I = LRs.begin(), E = LRs.end(); I != E; ++I) {
261     DOUT << "  Adding live range " << *I << " to new interval\n";
262     NewLI.addRange(*I);
263   }
264             
265   DOUT << "Created new live interval " << NewLI << "\n";
266   return NewLI;
267 }
268
269 std::vector<LiveInterval*> LiveIntervals::
270 addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
271   // since this is called after the analysis is done we don't know if
272   // LiveVariables is available
273   lv_ = getAnalysisToUpdate<LiveVariables>();
274
275   std::vector<LiveInterval*> added;
276
277   assert(li.weight != HUGE_VALF &&
278          "attempt to spill already spilled interval!");
279
280   DOUT << "\t\t\t\tadding intervals for spills for interval: ";
281   li.print(DOUT, mri_);
282   DOUT << '\n';
283
284   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
285
286   for (LiveInterval::Ranges::const_iterator
287          i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
288     unsigned index = getBaseIndex(i->start);
289     unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
290     for (; index != end; index += InstrSlots::NUM) {
291       // skip deleted instructions
292       while (index != end && !getInstructionFromIndex(index))
293         index += InstrSlots::NUM;
294       if (index == end) break;
295
296       MachineInstr *MI = getInstructionFromIndex(index);
297
298     RestartInstruction:
299       for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
300         MachineOperand& mop = MI->getOperand(i);
301         if (mop.isRegister() && mop.getReg() == li.reg) {
302           if (MachineInstr *fmi = mri_->foldMemoryOperand(MI, i, slot)) {
303             // Attempt to fold the memory reference into the instruction.  If we
304             // can do this, we don't need to insert spill code.
305             if (lv_)
306               lv_->instructionChanged(MI, fmi);
307             MachineBasicBlock &MBB = *MI->getParent();
308             vrm.virtFolded(li.reg, MI, i, fmi);
309             mi2iMap_.erase(MI);
310             i2miMap_[index/InstrSlots::NUM] = fmi;
311             mi2iMap_[fmi] = index;
312             MI = MBB.insert(MBB.erase(MI), fmi);
313             ++numFolded;
314             // Folding the load/store can completely change the instruction in
315             // unpredictable ways, rescan it from the beginning.
316             goto RestartInstruction;
317           } else {
318             // Create a new virtual register for the spill interval.
319             unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(rc);
320             
321             // Scan all of the operands of this instruction rewriting operands
322             // to use NewVReg instead of li.reg as appropriate.  We do this for
323             // two reasons:
324             //
325             //   1. If the instr reads the same spilled vreg multiple times, we
326             //      want to reuse the NewVReg.
327             //   2. If the instr is a two-addr instruction, we are required to
328             //      keep the src/dst regs pinned.
329             //
330             // Keep track of whether we replace a use and/or def so that we can
331             // create the spill interval with the appropriate range. 
332             mop.setReg(NewVReg);
333             
334             bool HasUse = mop.isUse();
335             bool HasDef = mop.isDef();
336             for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
337               if (MI->getOperand(j).isReg() &&
338                   MI->getOperand(j).getReg() == li.reg) {
339                 MI->getOperand(j).setReg(NewVReg);
340                 HasUse |= MI->getOperand(j).isUse();
341                 HasDef |= MI->getOperand(j).isDef();
342               }
343             }
344
345             // create a new register for this spill
346             vrm.grow();
347             vrm.assignVirt2StackSlot(NewVReg, slot);
348             LiveInterval &nI = getOrCreateInterval(NewVReg);
349             assert(nI.empty());
350
351             // the spill weight is now infinity as it
352             // cannot be spilled again
353             nI.weight = HUGE_VALF;
354
355             if (HasUse) {
356               LiveRange LR(getLoadIndex(index), getUseIndex(index),
357                            nI.getNextValue(~0U, 0));
358               DOUT << " +" << LR;
359               nI.addRange(LR);
360             }
361             if (HasDef) {
362               LiveRange LR(getDefIndex(index), getStoreIndex(index),
363                            nI.getNextValue(~0U, 0));
364               DOUT << " +" << LR;
365               nI.addRange(LR);
366             }
367             
368             added.push_back(&nI);
369
370             // update live variables if it is available
371             if (lv_)
372               lv_->addVirtualRegisterKilled(NewVReg, MI);
373             
374             DOUT << "\t\t\t\tadded new interval: ";
375             nI.print(DOUT, mri_);
376             DOUT << '\n';
377           }
378         }
379       }
380     }
381   }
382
383   return added;
384 }
385
386 void LiveIntervals::printRegName(unsigned reg) const {
387   if (MRegisterInfo::isPhysicalRegister(reg))
388     cerr << mri_->getName(reg);
389   else
390     cerr << "%reg" << reg;
391 }
392
393 /// isReDefinedByTwoAddr - Returns true if the Reg re-definition is due to
394 /// two addr elimination.
395 static bool isReDefinedByTwoAddr(MachineInstr *MI, unsigned Reg,
396                                 const TargetInstrInfo *TII) {
397   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
398     MachineOperand &MO1 = MI->getOperand(i);
399     if (MO1.isRegister() && MO1.isDef() && MO1.getReg() == Reg) {
400       for (unsigned j = i+1; j < e; ++j) {
401         MachineOperand &MO2 = MI->getOperand(j);
402         if (MO2.isRegister() && MO2.isUse() && MO2.getReg() == Reg &&
403             MI->getInstrDescriptor()->
404             getOperandConstraint(j, TOI::TIED_TO) == (int)i)
405           return true;
406       }
407     }
408   }
409   return false;
410 }
411
412 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
413                                              MachineBasicBlock::iterator mi,
414                                              unsigned MIIdx,
415                                              LiveInterval &interval) {
416   DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
417   LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
418
419   // Virtual registers may be defined multiple times (due to phi
420   // elimination and 2-addr elimination).  Much of what we do only has to be
421   // done once for the vreg.  We use an empty interval to detect the first
422   // time we see a vreg.
423   if (interval.empty()) {
424     // Get the Idx of the defining instructions.
425     unsigned defIndex = getDefIndex(MIIdx);
426
427     unsigned ValNum;
428     unsigned SrcReg, DstReg;
429     if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
430       ValNum = interval.getNextValue(~0U, 0);
431     else
432       ValNum = interval.getNextValue(defIndex, SrcReg);
433     
434     assert(ValNum == 0 && "First value in interval is not 0?");
435     ValNum = 0;  // Clue in the optimizer.
436
437     // Loop over all of the blocks that the vreg is defined in.  There are
438     // two cases we have to handle here.  The most common case is a vreg
439     // whose lifetime is contained within a basic block.  In this case there
440     // will be a single kill, in MBB, which comes after the definition.
441     if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
442       // FIXME: what about dead vars?
443       unsigned killIdx;
444       if (vi.Kills[0] != mi)
445         killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
446       else
447         killIdx = defIndex+1;
448
449       // If the kill happens after the definition, we have an intra-block
450       // live range.
451       if (killIdx > defIndex) {
452         assert(vi.AliveBlocks.none() &&
453                "Shouldn't be alive across any blocks!");
454         LiveRange LR(defIndex, killIdx, ValNum);
455         interval.addRange(LR);
456         DOUT << " +" << LR << "\n";
457         return;
458       }
459     }
460
461     // The other case we handle is when a virtual register lives to the end
462     // of the defining block, potentially live across some blocks, then is
463     // live into some number of blocks, but gets killed.  Start by adding a
464     // range that goes from this definition to the end of the defining block.
465     LiveRange NewLR(defIndex,
466                     getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
467                     ValNum);
468     DOUT << " +" << NewLR;
469     interval.addRange(NewLR);
470
471     // Iterate over all of the blocks that the variable is completely
472     // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
473     // live interval.
474     for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
475       if (vi.AliveBlocks[i]) {
476         MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
477         if (!MBB->empty()) {
478           LiveRange LR(getMBBStartIdx(i),
479                        getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
480                        ValNum);
481           interval.addRange(LR);
482           DOUT << " +" << LR;
483         }
484       }
485     }
486
487     // Finally, this virtual register is live from the start of any killing
488     // block to the 'use' slot of the killing instruction.
489     for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
490       MachineInstr *Kill = vi.Kills[i];
491       LiveRange LR(getMBBStartIdx(Kill->getParent()),
492                    getUseIndex(getInstructionIndex(Kill))+1,
493                    ValNum);
494       interval.addRange(LR);
495       DOUT << " +" << LR;
496     }
497
498   } else {
499     // If this is the second time we see a virtual register definition, it
500     // must be due to phi elimination or two addr elimination.  If this is
501     // the result of two address elimination, then the vreg is one of the
502     // def-and-use register operand.
503     if (isReDefinedByTwoAddr(mi, interval.reg, tii_)) {
504       // If this is a two-address definition, then we have already processed
505       // the live range.  The only problem is that we didn't realize there
506       // are actually two values in the live interval.  Because of this we
507       // need to take the LiveRegion that defines this register and split it
508       // into two values.
509       unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
510       unsigned RedefIndex = getDefIndex(MIIdx);
511
512       // Delete the initial value, which should be short and continuous,
513       // because the 2-addr copy must be in the same MBB as the redef.
514       interval.removeRange(DefIndex, RedefIndex);
515
516       // Two-address vregs should always only be redefined once.  This means
517       // that at this point, there should be exactly one value number in it.
518       assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
519
520       // The new value number (#1) is defined by the instruction we claimed
521       // defined value #0.
522       unsigned ValNo = interval.getNextValue(0, 0);
523       interval.setValueNumberInfo(1, interval.getValNumInfo(0));
524       
525       // Value#0 is now defined by the 2-addr instruction.
526       interval.setValueNumberInfo(0, std::make_pair(~0U, 0U));
527       
528       // Add the new live interval which replaces the range for the input copy.
529       LiveRange LR(DefIndex, RedefIndex, ValNo);
530       DOUT << " replace range with " << LR;
531       interval.addRange(LR);
532
533       // If this redefinition is dead, we need to add a dummy unit live
534       // range covering the def slot.
535       if (lv_->RegisterDefIsDead(mi, interval.reg))
536         interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
537
538       DOUT << "RESULT: ";
539       interval.print(DOUT, mri_);
540
541     } else {
542       // Otherwise, this must be because of phi elimination.  If this is the
543       // first redefinition of the vreg that we have seen, go back and change
544       // the live range in the PHI block to be a different value number.
545       if (interval.containsOneValue()) {
546         assert(vi.Kills.size() == 1 &&
547                "PHI elimination vreg should have one kill, the PHI itself!");
548
549         // Remove the old range that we now know has an incorrect number.
550         MachineInstr *Killer = vi.Kills[0];
551         unsigned Start = getMBBStartIdx(Killer->getParent());
552         unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
553         DOUT << "Removing [" << Start << "," << End << "] from: ";
554         interval.print(DOUT, mri_); DOUT << "\n";
555         interval.removeRange(Start, End);
556         DOUT << "RESULT: "; interval.print(DOUT, mri_);
557
558         // Replace the interval with one of a NEW value number.  Note that this
559         // value number isn't actually defined by an instruction, weird huh? :)
560         LiveRange LR(Start, End, interval.getNextValue(~0U, 0));
561         DOUT << " replace range with " << LR;
562         interval.addRange(LR);
563         DOUT << "RESULT: "; interval.print(DOUT, mri_);
564       }
565
566       // In the case of PHI elimination, each variable definition is only
567       // live until the end of the block.  We've already taken care of the
568       // rest of the live range.
569       unsigned defIndex = getDefIndex(MIIdx);
570       
571       unsigned ValNum;
572       unsigned SrcReg, DstReg;
573       if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
574         ValNum = interval.getNextValue(~0U, 0);
575       else
576         ValNum = interval.getNextValue(defIndex, SrcReg);
577       
578       LiveRange LR(defIndex,
579                    getInstructionIndex(&mbb->back()) + InstrSlots::NUM, ValNum);
580       interval.addRange(LR);
581       DOUT << " +" << LR;
582     }
583   }
584
585   DOUT << '\n';
586 }
587
588 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
589                                               MachineBasicBlock::iterator mi,
590                                               unsigned MIIdx,
591                                               LiveInterval &interval,
592                                               unsigned SrcReg) {
593   // A physical register cannot be live across basic block, so its
594   // lifetime must end somewhere in its defining basic block.
595   DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
596
597   unsigned baseIndex = MIIdx;
598   unsigned start = getDefIndex(baseIndex);
599   unsigned end = start;
600
601   // If it is not used after definition, it is considered dead at
602   // the instruction defining it. Hence its interval is:
603   // [defSlot(def), defSlot(def)+1)
604   if (lv_->RegisterDefIsDead(mi, interval.reg)) {
605     DOUT << " dead";
606     end = getDefIndex(start) + 1;
607     goto exit;
608   }
609
610   // If it is not dead on definition, it must be killed by a
611   // subsequent instruction. Hence its interval is:
612   // [defSlot(def), useSlot(kill)+1)
613   while (++mi != MBB->end()) {
614     baseIndex += InstrSlots::NUM;
615     if (lv_->KillsRegister(mi, interval.reg)) {
616       DOUT << " killed";
617       end = getUseIndex(baseIndex) + 1;
618       goto exit;
619     } else if (lv_->ModifiesRegister(mi, interval.reg)) {
620       // Another instruction redefines the register before it is ever read.
621       // Then the register is essentially dead at the instruction that defines
622       // it. Hence its interval is:
623       // [defSlot(def), defSlot(def)+1)
624       DOUT << " dead";
625       end = getDefIndex(start) + 1;
626       goto exit;
627     }
628   }
629   
630   // The only case we should have a dead physreg here without a killing or
631   // instruction where we know it's dead is if it is live-in to the function
632   // and never used.
633   assert(!SrcReg && "physreg was not killed in defining block!");
634   end = getDefIndex(start) + 1;  // It's dead.
635
636 exit:
637   assert(start < end && "did not find end of interval?");
638
639   LiveRange LR(start, end, interval.getNextValue(SrcReg != 0 ? start : ~0U,
640                                                  SrcReg));
641   interval.addRange(LR);
642   DOUT << " +" << LR << '\n';
643 }
644
645 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
646                                       MachineBasicBlock::iterator MI,
647                                       unsigned MIIdx,
648                                       unsigned reg) {
649   if (MRegisterInfo::isVirtualRegister(reg))
650     handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
651   else if (allocatableRegs_[reg]) {
652     unsigned SrcReg, DstReg;
653     if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
654       SrcReg = 0;
655     handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
656     for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
657       handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
658   }
659 }
660
661 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
662                                          unsigned MIIdx,
663                                          LiveInterval &interval) {
664   DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
665
666   // Look for kills, if it reaches a def before it's killed, then it shouldn't
667   // be considered a livein.
668   MachineBasicBlock::iterator mi = MBB->begin();
669   unsigned baseIndex = MIIdx;
670   unsigned start = baseIndex;
671   unsigned end = start;
672   while (mi != MBB->end()) {
673     if (lv_->KillsRegister(mi, interval.reg)) {
674       DOUT << " killed";
675       end = getUseIndex(baseIndex) + 1;
676       goto exit;
677     } else if (lv_->ModifiesRegister(mi, interval.reg)) {
678       // Another instruction redefines the register before it is ever read.
679       // Then the register is essentially dead at the instruction that defines
680       // it. Hence its interval is:
681       // [defSlot(def), defSlot(def)+1)
682       DOUT << " dead";
683       end = getDefIndex(start) + 1;
684       goto exit;
685     }
686
687     baseIndex += InstrSlots::NUM;
688     ++mi;
689   }
690
691 exit:
692   assert(start < end && "did not find end of interval?");
693
694   LiveRange LR(start, end, interval.getNextValue(~0U, 0));
695   DOUT << " +" << LR << '\n';
696   interval.addRange(LR);
697 }
698
699 /// computeIntervals - computes the live intervals for virtual
700 /// registers. for some ordering of the machine instructions [1,N] a
701 /// live interval is an interval [i, j) where 1 <= i <= j < N for
702 /// which a variable is live
703 void LiveIntervals::computeIntervals() {
704   DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
705        << "********** Function: "
706        << ((Value*)mf_->getFunction())->getName() << '\n';
707   // Track the index of the current machine instr.
708   unsigned MIIndex = 0;
709   for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
710        MBBI != E; ++MBBI) {
711     MachineBasicBlock *MBB = MBBI;
712     DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
713
714     MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
715
716     if (MBB->livein_begin() != MBB->livein_end()) {
717       // Create intervals for live-ins to this BB first.
718       for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
719              LE = MBB->livein_end(); LI != LE; ++LI) {
720         handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
721         for (const unsigned* AS = mri_->getAliasSet(*LI); *AS; ++AS)
722           handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS));
723       }
724     }
725     
726     for (; MI != miEnd; ++MI) {
727       DOUT << MIIndex << "\t" << *MI;
728
729       // Handle defs.
730       for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
731         MachineOperand &MO = MI->getOperand(i);
732         // handle register defs - build intervals
733         if (MO.isRegister() && MO.getReg() && MO.isDef())
734           handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
735       }
736       
737       MIIndex += InstrSlots::NUM;
738     }
739   }
740 }
741
742 /// AdjustCopiesBackFrom - We found a non-trivially-coallescable copy with IntA
743 /// being the source and IntB being the dest, thus this defines a value number
744 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
745 /// see if we can merge these two pieces of B into a single value number,
746 /// eliminating a copy.  For example:
747 ///
748 ///  A3 = B0
749 ///    ...
750 ///  B1 = A3      <- this copy
751 ///
752 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
753 /// value number to be replaced with B0 (which simplifies the B liveinterval).
754 ///
755 /// This returns true if an interval was modified.
756 ///
757 bool LiveIntervals::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
758                                          MachineInstr *CopyMI) {
759   unsigned CopyIdx = getDefIndex(getInstructionIndex(CopyMI));
760
761   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
762   // the example above.
763   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
764   unsigned BValNo = BLR->ValId;
765   
766   // Get the location that B is defined at.  Two options: either this value has
767   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
768   // can't process it.
769   unsigned BValNoDefIdx = IntB.getInstForValNum(BValNo);
770   if (BValNoDefIdx == ~0U) return false;
771   assert(BValNoDefIdx == CopyIdx &&
772          "Copy doesn't define the value?");
773   
774   // AValNo is the value number in A that defines the copy, A0 in the example.
775   LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
776   unsigned AValNo = AValLR->ValId;
777   
778   // If AValNo is defined as a copy from IntB, we can potentially process this.
779   
780   // Get the instruction that defines this value number.
781   unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
782   if (!SrcReg) return false;  // Not defined by a copy.
783     
784   // If the value number is not defined by a copy instruction, ignore it.
785     
786   // If the source register comes from an interval other than IntB, we can't
787   // handle this.
788   if (rep(SrcReg) != IntB.reg) return false;
789   
790   // Get the LiveRange in IntB that this value number starts with.
791   unsigned AValNoInstIdx = IntA.getInstForValNum(AValNo);
792   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
793   
794   // Make sure that the end of the live range is inside the same block as
795   // CopyMI.
796   MachineInstr *ValLREndInst = getInstructionFromIndex(ValLR->end-1);
797   if (!ValLREndInst || 
798       ValLREndInst->getParent() != CopyMI->getParent()) return false;
799
800   // Okay, we now know that ValLR ends in the same block that the CopyMI
801   // live-range starts.  If there are no intervening live ranges between them in
802   // IntB, we can merge them.
803   if (ValLR+1 != BLR) return false;
804   
805   DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
806   
807   // We are about to delete CopyMI, so need to remove it as the 'instruction
808   // that defines this value #'.
809   IntB.setValueNumberInfo(BValNo, std::make_pair(~0U, 0));
810   
811   // Okay, we can merge them.  We need to insert a new liverange:
812   // [ValLR.end, BLR.begin) of either value number, then we merge the
813   // two value numbers.
814   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
815   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
816
817   // If the IntB live range is assigned to a physical register, and if that
818   // physreg has aliases, 
819   if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
820     for (const unsigned *AS = mri_->getAliasSet(IntB.reg); *AS; ++AS) {
821       LiveInterval &AliasLI = getInterval(*AS);
822       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
823                                  AliasLI.getNextValue(~0U, 0)));
824     }
825   }
826
827   // Okay, merge "B1" into the same value number as "B0".
828   if (BValNo != ValLR->ValId)
829     IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
830   DOUT << "   result = "; IntB.print(DOUT, mri_);
831   DOUT << "\n";
832
833   // If the source instruction was killing the source register before the
834   // merge, unset the isKill marker given the live range has been extended.
835   MachineOperand *MOK = ValLREndInst->findRegisterUseOperand(IntB.reg, true);
836   if (MOK)
837     MOK->unsetIsKill();
838   
839   // Finally, delete the copy instruction.
840   RemoveMachineInstrFromMaps(CopyMI);
841   CopyMI->eraseFromParent();
842   ++numPeep;
843   return true;
844 }
845
846 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
847 /// which are the src/dst of the copy instruction CopyMI.  This returns true
848 /// if the copy was successfully coallesced away, or if it is never possible
849 /// to coallesce these this copy, due to register constraints.  It returns
850 /// false if it is not currently possible to coallesce this interval, but
851 /// it may be possible if other things get coallesced.
852 bool LiveIntervals::JoinCopy(MachineInstr *CopyMI,
853                              unsigned SrcReg, unsigned DstReg) {
854   DOUT << getInstructionIndex(CopyMI) << '\t' << *CopyMI;
855
856   // Get representative registers.
857   unsigned repSrcReg = rep(SrcReg);
858   unsigned repDstReg = rep(DstReg);
859   
860   // If they are already joined we continue.
861   if (repSrcReg == repDstReg) {
862     DOUT << "\tCopy already coallesced.\n";
863     return true;  // Not coallescable.
864   }
865   
866   // If they are both physical registers, we cannot join them.
867   if (MRegisterInfo::isPhysicalRegister(repSrcReg) &&
868       MRegisterInfo::isPhysicalRegister(repDstReg)) {
869     DOUT << "\tCan not coallesce physregs.\n";
870     return true;  // Not coallescable.
871   }
872   
873   // We only join virtual registers with allocatable physical registers.
874   if (MRegisterInfo::isPhysicalRegister(repSrcReg) &&
875       !allocatableRegs_[repSrcReg]) {
876     DOUT << "\tSrc reg is unallocatable physreg.\n";
877     return true;  // Not coallescable.
878   }
879   if (MRegisterInfo::isPhysicalRegister(repDstReg) &&
880       !allocatableRegs_[repDstReg]) {
881     DOUT << "\tDst reg is unallocatable physreg.\n";
882     return true;  // Not coallescable.
883   }
884   
885   // If they are not of the same register class, we cannot join them.
886   if (differingRegisterClasses(repSrcReg, repDstReg)) {
887     DOUT << "\tSrc/Dest are different register classes.\n";
888     return true;  // Not coallescable.
889   }
890   
891   LiveInterval &SrcInt = getInterval(repSrcReg);
892   LiveInterval &DestInt = getInterval(repDstReg);
893   assert(SrcInt.reg == repSrcReg && DestInt.reg == repDstReg &&
894          "Register mapping is horribly broken!");
895   
896   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
897   DOUT << " and "; DestInt.print(DOUT, mri_);
898   DOUT << ": ";
899
900   // Check if it is necessary to propagate "isDead" property before intervals
901   // are joined.
902   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
903   bool isDead = mopd->isDead();
904   bool isShorten = false;
905   unsigned SrcStart = 0;
906   unsigned SrcEnd = 0;
907   if (isDead) {
908     unsigned CopyIdx = getInstructionIndex(CopyMI);
909     LiveInterval::iterator SrcLR =
910       SrcInt.FindLiveRangeContaining(getUseIndex(CopyIdx));
911     SrcStart = SrcLR->start;
912     SrcEnd   = SrcLR->end;
913     // The instruction which defines the src is only truly dead if there are
914     // no intermediate uses and there isn't a use beyond the copy.
915     // FIXME: find the last use, mark is kill and shorten the live range.
916     if (SrcEnd > getDefIndex(CopyIdx))
917       isDead = false;
918     else {
919       MachineOperand *MOU;
920       MachineInstr *LastUse =
921         lastRegisterUse(repSrcReg, SrcStart, CopyIdx, MOU);
922       if (LastUse) {
923         // Shorten the liveinterval to the end of last use.
924         MOU->setIsKill();
925         isDead = false;
926         isShorten = true;
927         SrcEnd = getUseIndex(getInstructionIndex(LastUse));
928       }
929     }
930     if (isDead)
931       isShorten = true;
932   }
933
934   // Okay, attempt to join these two intervals.  On failure, this returns false.
935   // Otherwise, if one of the intervals being joined is a physreg, this method
936   // always canonicalizes DestInt to be it.  The output "SrcInt" will not have
937   // been modified, so we can use this information below to update aliases.
938   if (JoinIntervals(DestInt, SrcInt)) {
939     if (isDead) {
940       // Result of the copy is dead. Propagate this property.
941       if (SrcStart == 0 && MRegisterInfo::isPhysicalRegister(SrcReg)) {
942         // Live-in to the function but dead. Remove it from MBB live-in set.
943         // JoinIntervals may end up swapping the two intervals.
944         MachineBasicBlock *MBB = CopyMI->getParent();
945         MBB->removeLiveIn(SrcReg);
946       } else {
947         MachineInstr *SrcMI = getInstructionFromIndex(SrcStart);
948         if (SrcMI) {
949           MachineOperand *mops = SrcMI->findRegisterDefOperand(SrcReg);
950           if (mops)
951             // FIXME: mops == NULL means SrcMI defines a subregister?
952             mops->setIsDead();
953         }
954       }
955     }
956
957     if (isShorten) {
958       // Shorten the live interval.
959       LiveInterval &LiveInInt = (repSrcReg == DestInt.reg) ? DestInt : SrcInt;
960       LiveInInt.removeRange(SrcStart, SrcEnd);
961     }
962   } else {
963     // Coallescing failed.
964     
965     // If we can eliminate the copy without merging the live ranges, do so now.
966     if (AdjustCopiesBackFrom(SrcInt, DestInt, CopyMI))
967       return true;
968
969     // Otherwise, we are unable to join the intervals.
970     DOUT << "Interference!\n";
971     return false;
972   }
973
974   bool Swapped = repSrcReg == DestInt.reg;
975   if (Swapped)
976     std::swap(repSrcReg, repDstReg);
977   assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
978          "LiveInterval::join didn't work right!");
979                                
980   // If we're about to merge live ranges into a physical register live range,
981   // we have to update any aliased register's live ranges to indicate that they
982   // have clobbered values for this range.
983   if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
984     for (const unsigned *AS = mri_->getAliasSet(repDstReg); *AS; ++AS)
985       getInterval(*AS).MergeInClobberRanges(SrcInt);
986   }
987
988   DOUT << "\n\t\tJoined.  Result = "; DestInt.print(DOUT, mri_);
989   DOUT << "\n";
990
991   // Remember these liveintervals have been joined.
992   JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
993   if (MRegisterInfo::isVirtualRegister(repDstReg))
994     JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
995
996   // If the intervals were swapped by Join, swap them back so that the register
997   // mapping (in the r2i map) is correct.
998   if (Swapped) SrcInt.swap(DestInt);
999   removeInterval(repSrcReg);
1000   r2rMap_[repSrcReg] = repDstReg;
1001
1002   // Finally, delete the copy instruction.
1003   RemoveMachineInstrFromMaps(CopyMI);
1004   CopyMI->eraseFromParent();
1005   ++numPeep;
1006   ++numJoins;
1007   return true;
1008 }
1009
1010 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1011 /// compute what the resultant value numbers for each value in the input two
1012 /// ranges will be.  This is complicated by copies between the two which can
1013 /// and will commonly cause multiple value numbers to be merged into one.
1014 ///
1015 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1016 /// keeps track of the new InstDefiningValue assignment for the result
1017 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1018 /// whether a value in this or other is a copy from the opposite set.
1019 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1020 /// already been assigned.
1021 ///
1022 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1023 /// contains the value number the copy is from.
1024 ///
1025 static unsigned ComputeUltimateVN(unsigned VN,
1026                                   SmallVector<std::pair<unsigned,
1027                                                 unsigned>, 16> &ValueNumberInfo,
1028                                   SmallVector<int, 16> &ThisFromOther,
1029                                   SmallVector<int, 16> &OtherFromThis,
1030                                   SmallVector<int, 16> &ThisValNoAssignments,
1031                                   SmallVector<int, 16> &OtherValNoAssignments,
1032                                   LiveInterval &ThisLI, LiveInterval &OtherLI) {
1033   // If the VN has already been computed, just return it.
1034   if (ThisValNoAssignments[VN] >= 0)
1035     return ThisValNoAssignments[VN];
1036 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1037   
1038   // If this val is not a copy from the other val, then it must be a new value
1039   // number in the destination.
1040   int OtherValNo = ThisFromOther[VN];
1041   if (OtherValNo == -1) {
1042     ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
1043     return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
1044   }
1045
1046   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1047   // been computed, return it.
1048   if (OtherValNoAssignments[OtherValNo] >= 0)
1049     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo];
1050   
1051   // Mark this value number as currently being computed, then ask what the
1052   // ultimate value # of the other value is.
1053   ThisValNoAssignments[VN] = -2;
1054   unsigned UltimateVN =
1055     ComputeUltimateVN(OtherValNo, ValueNumberInfo,
1056                       OtherFromThis, ThisFromOther,
1057                       OtherValNoAssignments, ThisValNoAssignments,
1058                       OtherLI, ThisLI);
1059   return ThisValNoAssignments[VN] = UltimateVN;
1060 }
1061
1062 static bool InVector(unsigned Val, const SmallVector<unsigned, 8> &V) {
1063   return std::find(V.begin(), V.end(), Val) != V.end();
1064 }
1065
1066 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1067 /// caller of this method must guarantee that the RHS only contains a single
1068 /// value number and that the RHS is not defined by a copy from this
1069 /// interval.  This returns false if the intervals are not joinable, or it
1070 /// joins them and returns true.
1071 bool LiveIntervals::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
1072   assert(RHS.containsOneValue());
1073   
1074   // Some number (potentially more than one) value numbers in the current
1075   // interval may be defined as copies from the RHS.  Scan the overlapping
1076   // portions of the LHS and RHS, keeping track of this and looking for
1077   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1078   // cannot coallesce.
1079   
1080   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1081   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1082   
1083   if (LHSIt->start < RHSIt->start) {
1084     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1085     if (LHSIt != LHS.begin()) --LHSIt;
1086   } else if (RHSIt->start < LHSIt->start) {
1087     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1088     if (RHSIt != RHS.begin()) --RHSIt;
1089   }
1090   
1091   SmallVector<unsigned, 8> EliminatedLHSVals;
1092   
1093   while (1) {
1094     // Determine if these live intervals overlap.
1095     bool Overlaps = false;
1096     if (LHSIt->start <= RHSIt->start)
1097       Overlaps = LHSIt->end > RHSIt->start;
1098     else
1099       Overlaps = RHSIt->end > LHSIt->start;
1100     
1101     // If the live intervals overlap, there are two interesting cases: if the
1102     // LHS interval is defined by a copy from the RHS, it's ok and we record
1103     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1104     // coallesce these live ranges and we bail out.
1105     if (Overlaps) {
1106       // If we haven't already recorded that this value # is safe, check it.
1107       if (!InVector(LHSIt->ValId, EliminatedLHSVals)) {
1108         // Copy from the RHS?
1109         unsigned SrcReg = LHS.getSrcRegForValNum(LHSIt->ValId);
1110         if (rep(SrcReg) != RHS.reg)
1111           return false;    // Nope, bail out.
1112         
1113         EliminatedLHSVals.push_back(LHSIt->ValId);
1114       }
1115       
1116       // We know this entire LHS live range is okay, so skip it now.
1117       if (++LHSIt == LHSEnd) break;
1118       continue;
1119     }
1120     
1121     if (LHSIt->end < RHSIt->end) {
1122       if (++LHSIt == LHSEnd) break;
1123     } else {
1124       // One interesting case to check here.  It's possible that we have
1125       // something like "X3 = Y" which defines a new value number in the LHS,
1126       // and is the last use of this liverange of the RHS.  In this case, we
1127       // want to notice this copy (so that it gets coallesced away) even though
1128       // the live ranges don't actually overlap.
1129       if (LHSIt->start == RHSIt->end) {
1130         if (InVector(LHSIt->ValId, EliminatedLHSVals)) {
1131           // We already know that this value number is going to be merged in
1132           // if coallescing succeeds.  Just skip the liverange.
1133           if (++LHSIt == LHSEnd) break;
1134         } else {
1135           // Otherwise, if this is a copy from the RHS, mark it as being merged
1136           // in.
1137           if (rep(LHS.getSrcRegForValNum(LHSIt->ValId)) == RHS.reg) {
1138             EliminatedLHSVals.push_back(LHSIt->ValId);
1139
1140             // We know this entire LHS live range is okay, so skip it now.
1141             if (++LHSIt == LHSEnd) break;
1142           }
1143         }
1144       }
1145       
1146       if (++RHSIt == RHSEnd) break;
1147     }
1148   }
1149   
1150   // If we got here, we know that the coallescing will be successful and that
1151   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1152   // the most common case is that EliminatedLHSVals has a single number, we
1153   // optimize for it: if there is more than one value, we merge them all into
1154   // the lowest numbered one, then handle the interval as if we were merging
1155   // with one value number.
1156   unsigned LHSValNo;
1157   if (EliminatedLHSVals.size() > 1) {
1158     // Loop through all the equal value numbers merging them into the smallest
1159     // one.
1160     unsigned Smallest = EliminatedLHSVals[0];
1161     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1162       if (EliminatedLHSVals[i] < Smallest) {
1163         // Merge the current notion of the smallest into the smaller one.
1164         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1165         Smallest = EliminatedLHSVals[i];
1166       } else {
1167         // Merge into the smallest.
1168         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1169       }
1170     }
1171     LHSValNo = Smallest;
1172   } else {
1173     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1174     LHSValNo = EliminatedLHSVals[0];
1175   }
1176   
1177   // Okay, now that there is a single LHS value number that we're merging the
1178   // RHS into, update the value number info for the LHS to indicate that the
1179   // value number is defined where the RHS value number was.
1180   LHS.setValueNumberInfo(LHSValNo, RHS.getValNumInfo(0));
1181   
1182   // Okay, the final step is to loop over the RHS live intervals, adding them to
1183   // the LHS.
1184   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1185   LHS.weight += RHS.weight;
1186   
1187   return true;
1188 }
1189
1190 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1191 /// returns false.  Otherwise, if one of the intervals being joined is a
1192 /// physreg, this method always canonicalizes LHS to be it.  The output
1193 /// "RHS" will not have been modified, so we can use this information
1194 /// below to update aliases.
1195 bool LiveIntervals::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
1196   // Compute the final value assignment, assuming that the live ranges can be
1197   // coallesced.
1198   SmallVector<int, 16> LHSValNoAssignments;
1199   SmallVector<int, 16> RHSValNoAssignments;
1200   SmallVector<std::pair<unsigned,unsigned>, 16> ValueNumberInfo;
1201                           
1202   // Compute ultimate value numbers for the LHS and RHS values.
1203   if (RHS.containsOneValue()) {
1204     // Copies from a liveinterval with a single value are simple to handle and
1205     // very common, handle the special case here.  This is important, because
1206     // often RHS is small and LHS is large (e.g. a physreg).
1207     
1208     // Find out if the RHS is defined as a copy from some value in the LHS.
1209     int RHSValID = -1;
1210     std::pair<unsigned,unsigned> RHSValNoInfo;
1211     unsigned RHSSrcReg = RHS.getSrcRegForValNum(0);
1212     if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1213       // If RHS is not defined as a copy from the LHS, we can use simpler and
1214       // faster checks to see if the live ranges are coallescable.  This joiner
1215       // can't swap the LHS/RHS intervals though.
1216       if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
1217         return SimpleJoin(LHS, RHS);
1218       } else {
1219         RHSValNoInfo = RHS.getValNumInfo(0);
1220       }
1221     } else {
1222       // It was defined as a copy from the LHS, find out what value # it is.
1223       unsigned ValInst = RHS.getInstForValNum(0);
1224       RHSValID = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1225       RHSValNoInfo = LHS.getValNumInfo(RHSValID);
1226     }
1227     
1228     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1229     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1230     ValueNumberInfo.resize(LHS.getNumValNums());
1231     
1232     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1233     // should now get updated.
1234     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1235       if (unsigned LHSSrcReg = LHS.getSrcRegForValNum(VN)) {
1236         if (rep(LHSSrcReg) != RHS.reg) {
1237           // If this is not a copy from the RHS, its value number will be
1238           // unmodified by the coallescing.
1239           ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1240           LHSValNoAssignments[VN] = VN;
1241         } else if (RHSValID == -1) {
1242           // Otherwise, it is a copy from the RHS, and we don't already have a
1243           // value# for it.  Keep the current value number, but remember it.
1244           LHSValNoAssignments[VN] = RHSValID = VN;
1245           ValueNumberInfo[VN] = RHSValNoInfo;
1246         } else {
1247           // Otherwise, use the specified value #.
1248           LHSValNoAssignments[VN] = RHSValID;
1249           if (VN != (unsigned)RHSValID)
1250             ValueNumberInfo[VN].first = ~1U;
1251           else
1252             ValueNumberInfo[VN] = RHSValNoInfo;
1253         }
1254       } else {
1255         ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1256         LHSValNoAssignments[VN] = VN;
1257       }
1258     }
1259     
1260     assert(RHSValID != -1 && "Didn't find value #?");
1261     RHSValNoAssignments[0] = RHSValID;
1262     
1263   } else {
1264     // Loop over the value numbers of the LHS, seeing if any are defined from
1265     // the RHS.
1266     SmallVector<int, 16> LHSValsDefinedFromRHS;
1267     LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
1268     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1269       unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
1270       if (ValSrcReg == 0)  // Src not defined by a copy?
1271         continue;
1272       
1273       // DstReg is known to be a register in the LHS interval.  If the src is
1274       // from the RHS interval, we can use its value #.
1275       if (rep(ValSrcReg) != RHS.reg)
1276         continue;
1277       
1278       // Figure out the value # from the RHS.
1279       unsigned ValInst = LHS.getInstForValNum(VN);
1280       LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
1281     }
1282     
1283     // Loop over the value numbers of the RHS, seeing if any are defined from
1284     // the LHS.
1285     SmallVector<int, 16> RHSValsDefinedFromLHS;
1286     RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
1287     for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1288       unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
1289       if (ValSrcReg == 0)  // Src not defined by a copy?
1290         continue;
1291       
1292       // DstReg is known to be a register in the RHS interval.  If the src is
1293       // from the LHS interval, we can use its value #.
1294       if (rep(ValSrcReg) != LHS.reg)
1295         continue;
1296       
1297       // Figure out the value # from the LHS.
1298       unsigned ValInst = RHS.getInstForValNum(VN);
1299       RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1300     }
1301     
1302     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1303     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1304     ValueNumberInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1305     
1306     for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1307       if (LHSValNoAssignments[VN] >= 0 || LHS.getInstForValNum(VN) == ~2U) 
1308         continue;
1309       ComputeUltimateVN(VN, ValueNumberInfo,
1310                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1311                         LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
1312     }
1313     for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1314       if (RHSValNoAssignments[VN] >= 0 || RHS.getInstForValNum(VN) == ~2U)
1315         continue;
1316       // If this value number isn't a copy from the LHS, it's a new number.
1317       if (RHSValsDefinedFromLHS[VN] == -1) {
1318         ValueNumberInfo.push_back(RHS.getValNumInfo(VN));
1319         RHSValNoAssignments[VN] = ValueNumberInfo.size()-1;
1320         continue;
1321       }
1322       
1323       ComputeUltimateVN(VN, ValueNumberInfo,
1324                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1325                         RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
1326     }
1327   }
1328   
1329   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1330   // interval lists to see if these intervals are coallescable.
1331   LiveInterval::const_iterator I = LHS.begin();
1332   LiveInterval::const_iterator IE = LHS.end();
1333   LiveInterval::const_iterator J = RHS.begin();
1334   LiveInterval::const_iterator JE = RHS.end();
1335   
1336   // Skip ahead until the first place of potential sharing.
1337   if (I->start < J->start) {
1338     I = std::upper_bound(I, IE, J->start);
1339     if (I != LHS.begin()) --I;
1340   } else if (J->start < I->start) {
1341     J = std::upper_bound(J, JE, I->start);
1342     if (J != RHS.begin()) --J;
1343   }
1344   
1345   while (1) {
1346     // Determine if these two live ranges overlap.
1347     bool Overlaps;
1348     if (I->start < J->start) {
1349       Overlaps = I->end > J->start;
1350     } else {
1351       Overlaps = J->end > I->start;
1352     }
1353
1354     // If so, check value # info to determine if they are really different.
1355     if (Overlaps) {
1356       // If the live range overlap will map to the same value number in the
1357       // result liverange, we can still coallesce them.  If not, we can't.
1358       if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
1359         return false;
1360     }
1361     
1362     if (I->end < J->end) {
1363       ++I;
1364       if (I == IE) break;
1365     } else {
1366       ++J;
1367       if (J == JE) break;
1368     }
1369   }
1370
1371   // If we get here, we know that we can coallesce the live ranges.  Ask the
1372   // intervals to coallesce themselves now.
1373   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
1374            ValueNumberInfo);
1375   return true;
1376 }
1377
1378
1379 namespace {
1380   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1381   // depth of the basic block (the unsigned), and then on the MBB number.
1382   struct DepthMBBCompare {
1383     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1384     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1385       if (LHS.first > RHS.first) return true;   // Deeper loops first
1386       return LHS.first == RHS.first &&
1387         LHS.second->getNumber() < RHS.second->getNumber();
1388     }
1389   };
1390 }
1391
1392
1393 void LiveIntervals::CopyCoallesceInMBB(MachineBasicBlock *MBB,
1394                                        std::vector<CopyRec> &TryAgain) {
1395   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1396   
1397   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1398        MII != E;) {
1399     MachineInstr *Inst = MII++;
1400     
1401     // If this isn't a copy, we can't join intervals.
1402     unsigned SrcReg, DstReg;
1403     if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
1404     
1405     if (!JoinCopy(Inst, SrcReg, DstReg))
1406       TryAgain.push_back(getCopyRec(Inst, SrcReg, DstReg));
1407   }
1408 }
1409
1410
1411 void LiveIntervals::joinIntervals() {
1412   DOUT << "********** JOINING INTERVALS ***********\n";
1413
1414   JoinedLIs.resize(getNumIntervals());
1415   JoinedLIs.reset();
1416
1417   std::vector<CopyRec> TryAgainList;
1418   const LoopInfo &LI = getAnalysis<LoopInfo>();
1419   if (LI.begin() == LI.end()) {
1420     // If there are no loops in the function, join intervals in function order.
1421     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1422          I != E; ++I)
1423       CopyCoallesceInMBB(I, TryAgainList);
1424   } else {
1425     // Otherwise, join intervals in inner loops before other intervals.
1426     // Unfortunately we can't just iterate over loop hierarchy here because
1427     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1428     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1429     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1430          I != E; ++I)
1431       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1432
1433     // Sort by loop depth.
1434     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1435
1436     // Finally, join intervals in loop nest order.
1437     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1438       CopyCoallesceInMBB(MBBs[i].second, TryAgainList);
1439   }
1440   
1441   // Joining intervals can allow other intervals to be joined.  Iteratively join
1442   // until we make no progress.
1443   bool ProgressMade = true;
1444   while (ProgressMade) {
1445     ProgressMade = false;
1446
1447     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1448       CopyRec &TheCopy = TryAgainList[i];
1449       if (TheCopy.MI &&
1450           JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1451         TheCopy.MI = 0;   // Mark this one as done.
1452         ProgressMade = true;
1453       }
1454     }
1455   }
1456
1457   // Some live range has been lengthened due to colaescing, eliminate the
1458   // unnecessary kills.
1459   int RegNum = JoinedLIs.find_first();
1460   while (RegNum != -1) {
1461     unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
1462     unsigned repReg = rep(Reg);
1463     LiveInterval &LI = getInterval(repReg);
1464     LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
1465     for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
1466       MachineInstr *Kill = svi.Kills[i];
1467       // Suppose vr1 = op vr2, x
1468       // and vr1 and vr2 are coalesced. vr2 should still be marked kill
1469       // unless it is a two-address operand.
1470       if (isRemoved(Kill) || hasRegisterDef(Kill, repReg))
1471         continue;
1472       if (LI.liveAt(getInstructionIndex(Kill) + InstrSlots::NUM))
1473         unsetRegisterKill(Kill, repReg);
1474     }
1475     RegNum = JoinedLIs.find_next(RegNum);
1476   }
1477   
1478   DOUT << "*** Register mapping ***\n";
1479   for (int i = 0, e = r2rMap_.size(); i != e; ++i)
1480     if (r2rMap_[i]) {
1481       DOUT << "  reg " << i << " -> ";
1482       DEBUG(printRegName(r2rMap_[i]));
1483       DOUT << "\n";
1484     }
1485 }
1486
1487 /// Return true if the two specified registers belong to different register
1488 /// classes.  The registers may be either phys or virt regs.
1489 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
1490                                              unsigned RegB) const {
1491
1492   // Get the register classes for the first reg.
1493   if (MRegisterInfo::isPhysicalRegister(RegA)) {
1494     assert(MRegisterInfo::isVirtualRegister(RegB) &&
1495            "Shouldn't consider two physregs!");
1496     return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1497   }
1498
1499   // Compare against the regclass for the second reg.
1500   const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1501   if (MRegisterInfo::isVirtualRegister(RegB))
1502     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1503   else
1504     return !RegClass->contains(RegB);
1505 }
1506
1507 /// lastRegisterUse - Returns the last use of the specific register between
1508 /// cycles Start and End. It also returns the use operand by reference. It
1509 /// returns NULL if there are no uses.
1510 MachineInstr *
1511 LiveIntervals::lastRegisterUse(unsigned Reg, unsigned Start, unsigned End,
1512                                MachineOperand *&MOU) {
1513   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1514   int s = Start;
1515   while (e >= s) {
1516     // Skip deleted instructions
1517     MachineInstr *MI = getInstructionFromIndex(e);
1518     while ((e - InstrSlots::NUM) >= s && !MI) {
1519       e -= InstrSlots::NUM;
1520       MI = getInstructionFromIndex(e);
1521     }
1522     if (e < s || MI == NULL)
1523       return NULL;
1524
1525     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1526       MachineOperand &MO = MI->getOperand(i);
1527       if (MO.isReg() && MO.isUse() && MO.getReg() &&
1528           mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1529         MOU = &MO;
1530         return MI;
1531       }
1532     }
1533
1534     e -= InstrSlots::NUM;
1535   }
1536
1537   return NULL;
1538 }
1539
1540 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
1541 /// of the specific instruction.
1542 void LiveIntervals::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1543   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1544     MachineOperand &MO = MI->getOperand(i);
1545     if (MO.isReg() && MO.isUse() && MO.isKill() && MO.getReg() &&
1546         mri_->regsOverlap(rep(MO.getReg()), Reg))
1547       MO.unsetIsKill();
1548   }
1549 }
1550
1551 /// hasRegisterDef - True if the instruction defines the specific register.
1552 ///
1553 bool LiveIntervals::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1554   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1555     MachineOperand &MO = MI->getOperand(i);
1556     if (MO.isReg() && MO.isDef() &&
1557         mri_->regsOverlap(rep(MO.getReg()), Reg))
1558       return true;
1559   }
1560   return false;
1561 }
1562
1563 LiveInterval LiveIntervals::createInterval(unsigned reg) {
1564   float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
1565                        HUGE_VALF : 0.0F;
1566   return LiveInterval(reg, Weight);
1567 }