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