The copy instruction being coalesced will be removed, it is not a kill.
[oota-llvm.git] / lib / CodeGen / SimpleRegisterCoalescing.cpp
1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include <algorithm>
35 #include <cmath>
36 using namespace llvm;
37
38 STATISTIC(numJoins    , "Number of interval joins performed");
39 STATISTIC(numCommutes , "Number of instruction commuting performed");
40 STATISTIC(numExtends  , "Number of copies extended");
41 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
42 STATISTIC(numAborts   , "Number of times interval joining aborted");
43
44 char SimpleRegisterCoalescing::ID = 0;
45 namespace {
46   static cl::opt<bool>
47   EnableJoining("join-liveintervals",
48                 cl::desc("Coalesce copies (default=true)"),
49                 cl::init(true));
50
51   static cl::opt<bool>
52   NewHeuristic("new-coalescer-heuristic",
53                 cl::desc("Use new coalescer heuristic"),
54                 cl::init(false));
55
56   static cl::opt<bool>
57   CommuteDef("coalescer-commute-instrs",
58              cl::init(false), cl::Hidden);
59
60   RegisterPass<SimpleRegisterCoalescing> 
61   X("simple-register-coalescing", "Simple Register Coalescing");
62
63   // Declare that we implement the RegisterCoalescer interface
64   RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
65 }
66
67 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
68
69 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
70   AU.addPreserved<LiveIntervals>();
71   AU.addPreserved<MachineLoopInfo>();
72   AU.addPreservedID(MachineDominatorsID);
73   AU.addPreservedID(PHIEliminationID);
74   AU.addPreservedID(TwoAddressInstructionPassID);
75   AU.addRequired<LiveVariables>();
76   AU.addRequired<LiveIntervals>();
77   AU.addRequired<MachineLoopInfo>();
78   MachineFunctionPass::getAnalysisUsage(AU);
79 }
80
81 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
82 /// being the source and IntB being the dest, thus this defines a value number
83 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
84 /// see if we can merge these two pieces of B into a single value number,
85 /// eliminating a copy.  For example:
86 ///
87 ///  A3 = B0
88 ///    ...
89 ///  B1 = A3      <- this copy
90 ///
91 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
92 /// value number to be replaced with B0 (which simplifies the B liveinterval).
93 ///
94 /// This returns true if an interval was modified.
95 ///
96 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
97                                                     LiveInterval &IntB,
98                                                     MachineInstr *CopyMI) {
99   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
100
101   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
102   // the example above.
103   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
104   VNInfo *BValNo = BLR->valno;
105   
106   // Get the location that B is defined at.  Two options: either this value has
107   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
108   // can't process it.
109   if (!BValNo->copy) return false;
110   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
111   
112   // AValNo is the value number in A that defines the copy, A3 in the example.
113   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
114   VNInfo *AValNo = ALR->valno;
115   
116   // If AValNo is defined as a copy from IntB, we can potentially process this.  
117   // Get the instruction that defines this value number.
118   unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
119   if (!SrcReg) return false;  // Not defined by a copy.
120     
121   // If the value number is not defined by a copy instruction, ignore it.
122
123   // If the source register comes from an interval other than IntB, we can't
124   // handle this.
125   if (SrcReg != IntB.reg) return false;
126   
127   // Get the LiveRange in IntB that this value number starts with.
128   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
129   
130   // Make sure that the end of the live range is inside the same block as
131   // CopyMI.
132   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
133   if (!ValLREndInst || 
134       ValLREndInst->getParent() != CopyMI->getParent()) return false;
135
136   // Okay, we now know that ValLR ends in the same block that the CopyMI
137   // live-range starts.  If there are no intervening live ranges between them in
138   // IntB, we can merge them.
139   if (ValLR+1 != BLR) return false;
140
141   // If a live interval is a physical register, conservatively check if any
142   // of its sub-registers is overlapping the live interval of the virtual
143   // register. If so, do not coalesce.
144   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
145       *tri_->getSubRegisters(IntB.reg)) {
146     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
147       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
148         DOUT << "Interfere with sub-register ";
149         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
150         return false;
151       }
152   }
153   
154   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
155   
156   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
157   // We are about to delete CopyMI, so need to remove it as the 'instruction
158   // that defines this value #'. Update the the valnum with the new defining
159   // instruction #.
160   BValNo->def  = FillerStart;
161   BValNo->copy = NULL;
162   
163   // Okay, we can merge them.  We need to insert a new liverange:
164   // [ValLR.end, BLR.begin) of either value number, then we merge the
165   // two value numbers.
166   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
167
168   // If the IntB live range is assigned to a physical register, and if that
169   // physreg has aliases, 
170   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
171     // Update the liveintervals of sub-registers.
172     for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
173       LiveInterval &AliasLI = li_->getInterval(*AS);
174       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
175               AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
176     }
177   }
178
179   // Okay, merge "B1" into the same value number as "B0".
180   if (BValNo != ValLR->valno)
181     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
182   DOUT << "   result = "; IntB.print(DOUT, tri_);
183   DOUT << "\n";
184
185   // If the source instruction was killing the source register before the
186   // merge, unset the isKill marker given the live range has been extended.
187   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
188   if (UIdx != -1)
189     ValLREndInst->getOperand(UIdx).setIsKill(false);
190
191   ++numExtends;
192   return true;
193 }
194
195 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
196 /// being the source and IntB being the dest, thus this defines a value number
197 /// in IntB.  If the source value number (in IntA) is defined by a commutable
198 /// instruction and its other operand is coalesced to the copy dest register,
199 /// see if we can transform the copy into a noop by commuting the definition. For
200 /// example,
201 ///
202 ///  A3 = op A2 B0<kill>
203 ///    ...
204 ///  B1 = A3      <- this copy
205 ///    ...
206 ///     = op A3   <- more uses
207 ///
208 /// ==>
209 ///
210 ///  B2 = op B0 A2<kill>
211 ///    ...
212 ///  B1 = B2      <- now an identify copy
213 ///    ...
214 ///     = op B2   <- more uses
215 ///
216 /// This returns true if an interval was modified.
217 ///
218 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
219                                                         LiveInterval &IntB,
220                                                         MachineInstr *CopyMI) {
221   if (!CommuteDef) return false;
222
223   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
224
225   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
226   // the example above.
227   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
228   VNInfo *BValNo = BLR->valno;
229   
230   // Get the location that B is defined at.  Two options: either this value has
231   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
232   // can't process it.
233   if (!BValNo->copy) return false;
234   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
235   
236   // AValNo is the value number in A that defines the copy, A3 in the example.
237   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
238   VNInfo *AValNo = ALR->valno;
239   // If other defs can reach uses of this def, then it's not safe to perform
240   // the optimization.
241   if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
242     return false;
243   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
244   const TargetInstrDesc &TID = DefMI->getDesc();
245   unsigned NewDstIdx;
246   if (!TID.isCommutable() ||
247       !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
248     return false;
249
250   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
251   unsigned NewReg = NewDstMO.getReg();
252   if (NewReg != IntB.reg || !NewDstMO.isKill())
253     return false;
254
255   // Make sure there are no other definitions of IntB that would reach the
256   // uses which the new definition can reach.
257   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
258        AI != AE; ++AI) {
259     if (AI->valno != AValNo) continue;
260     LiveInterval::Ranges::iterator BI =
261       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
262     if (BI != IntB.ranges.begin())
263       --BI;
264     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
265       if (BI->valno == BLR->valno)
266         continue;
267       if (BI->start <= AI->start && BI->end > AI->start)
268         return false;
269       if (BI->start > AI->start && BI->start < AI->end)
270         return false;
271     }
272   }
273
274   // At this point we have decided that it is legal to do this
275   // transformation.  Start by commuting the instruction.
276   MachineBasicBlock *MBB = DefMI->getParent();
277   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
278   if (NewMI != DefMI) {
279     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
280     MBB->insert(DefMI, NewMI);
281     MBB->erase(DefMI);
282   }
283   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg);
284   NewMI->getOperand(OpIdx).setIsKill();
285
286   // Update uses of IntA of the specific Val# with IntB.
287   bool BHasPHIKill = BValNo->hasPHIKill;
288   SmallVector<VNInfo*, 4> BDeadValNos;
289   SmallVector<unsigned, 4> BKills;
290   std::map<unsigned, unsigned> BExtend;
291   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
292          UE = mri_->use_end(); UI != UE;) {
293     MachineOperand &UseMO = UI.getOperand();
294     MachineInstr *UseMI = &*UI;
295     ++UI;
296     if (JoinedCopies.count(UseMI))
297       continue;
298     unsigned UseIdx = li_->getInstructionIndex(UseMI);
299     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
300     if (ULR->valno != AValNo)
301       continue;
302     UseMO.setReg(NewReg);
303     if (UseMI == CopyMI)
304       continue;
305     if (UseMO.isKill())
306       BKills.push_back(li_->getUseIndex(UseIdx)+1);
307     unsigned SrcReg, DstReg;
308     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
309       continue;
310     if (DstReg == IntB.reg) {
311       // This copy will become a noop. If it's defining a new val#,
312       // remove that val# as well. However this live range is being
313       // extended to the end of the existing live range defined by the copy.
314       unsigned DefIdx = li_->getDefIndex(UseIdx);
315       LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
316       BHasPHIKill |= DLR->valno->hasPHIKill;
317       assert(DLR->valno->def == DefIdx);
318       BDeadValNos.push_back(DLR->valno);
319       BExtend[DLR->start] = DLR->end;
320       JoinedCopies.insert(UseMI);
321       // If this is a kill but it's going to be removed, the last use
322       // of the same val# is the new kill.
323       if (UseMO.isKill()) {
324         BKills.pop_back();
325       }
326     }
327   }
328
329   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
330   // simply extend BLR if CopyMI doesn't end the range.
331   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
332
333   IntB.removeValNo(BValNo);
334   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
335     IntB.removeValNo(BDeadValNos[i]);
336   VNInfo *ValNo = IntB.getNextValue(ALR->start, 0, li_->getVNInfoAllocator());
337   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
338        AI != AE; ++AI) {
339     if (AI->valno != AValNo) continue;
340     unsigned End = AI->end;
341     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
342     if (EI != BExtend.end())
343       End = EI->second;
344     IntB.addRange(LiveRange(AI->start, End, ValNo));
345   }
346   IntB.addKills(ValNo, BKills);
347   ValNo->hasPHIKill = BHasPHIKill;
348
349   DOUT << "   result = "; IntB.print(DOUT, tri_);
350   DOUT << "\n";
351
352   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
353   IntA.removeValNo(AValNo);
354   DOUT << "   result = "; IntA.print(DOUT, tri_);
355   DOUT << "\n";
356
357   ++numCommutes;
358   return true;
359 }
360
361 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
362 /// due to live range lengthening as the result of coalescing.
363 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
364                                                       LiveInterval &LI) {
365   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
366          UE = mri_->use_end(); UI != UE; ++UI) {
367     MachineOperand &UseMO = UI.getOperand();
368     if (UseMO.isKill()) {
369       MachineInstr *UseMI = UseMO.getParent();
370       unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
371       if (JoinedCopies.count(UseMI))
372         continue;
373       LiveInterval::const_iterator UI = LI.FindLiveRangeContaining(UseIdx);
374       assert(UI != LI.end());
375       if (!LI.isKill(UI->valno, UseIdx+1))
376         UseMO.setIsKill(false);
377     }
378   }
379 }
380
381 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
382 ///
383 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
384                                               unsigned DstReg) {
385   MachineBasicBlock *MBB = CopyMI->getParent();
386   const MachineLoop *L = loopInfo->getLoopFor(MBB);
387   if (!L)
388     return false;
389   if (MBB != L->getLoopLatch())
390     return false;
391
392   LiveInterval &LI = li_->getInterval(DstReg);
393   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
394   LiveInterval::const_iterator DstLR =
395     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
396   if (DstLR == LI.end())
397     return false;
398   unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
399   if (DstLR->valno->kills.size() == 1 &&
400       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
401     return true;
402   return false;
403 }
404
405 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
406 /// update the subregister number if it is not zero. If DstReg is a
407 /// physical register and the existing subregister number of the def / use
408 /// being updated is not zero, make sure to set it to the correct physical
409 /// subregister.
410 void
411 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
412                                             unsigned SubIdx) {
413   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
414   if (DstIsPhys && SubIdx) {
415     // Figure out the real physical register we are updating with.
416     DstReg = tri_->getSubReg(DstReg, SubIdx);
417     SubIdx = 0;
418   }
419
420   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
421          E = mri_->reg_end(); I != E; ) {
422     MachineOperand &O = I.getOperand();
423     ++I;
424     if (DstIsPhys) {
425       unsigned UseSubIdx = O.getSubReg();
426       unsigned UseDstReg = DstReg;
427       if (UseSubIdx)
428         UseDstReg = tri_->getSubReg(DstReg, UseSubIdx);
429       O.setReg(UseDstReg);
430       O.setSubReg(0);
431     } else {
432       unsigned OldSubIdx = O.getSubReg();
433       assert((!SubIdx || !OldSubIdx) && "Conflicting sub-register index!");
434       if (SubIdx)
435         O.setSubReg(SubIdx);
436       O.setReg(DstReg);
437     }
438   }
439 }
440
441 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
442 /// which are the src/dst of the copy instruction CopyMI.  This returns true
443 /// if the copy was successfully coalesced away. If it is not currently
444 /// possible to coalesce this interval, but it may be possible if other
445 /// things get coalesced, then it returns true by reference in 'Again'.
446 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
447   MachineInstr *CopyMI = TheCopy.MI;
448
449   Again = false;
450   if (JoinedCopies.count(CopyMI))
451     return false; // Already done.
452
453   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
454
455   unsigned SrcReg;
456   unsigned DstReg;
457   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
458   unsigned SubIdx = 0;
459   if (isExtSubReg) {
460     DstReg = CopyMI->getOperand(0).getReg();
461     SrcReg = CopyMI->getOperand(1).getReg();
462   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
463     assert(0 && "Unrecognized copy instruction!");
464     return false;
465   }
466
467   // If they are already joined we continue.
468   if (SrcReg == DstReg) {
469     DOUT << "\tCopy already coalesced.\n";
470     return false;  // Not coalescable.
471   }
472   
473   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
474   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
475
476   // If they are both physical registers, we cannot join them.
477   if (SrcIsPhys && DstIsPhys) {
478     DOUT << "\tCan not coalesce physregs.\n";
479     return false;  // Not coalescable.
480   }
481   
482   // We only join virtual registers with allocatable physical registers.
483   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
484     DOUT << "\tSrc reg is unallocatable physreg.\n";
485     return false;  // Not coalescable.
486   }
487   if (DstIsPhys && !allocatableRegs_[DstReg]) {
488     DOUT << "\tDst reg is unallocatable physreg.\n";
489     return false;  // Not coalescable.
490   }
491
492   unsigned RealDstReg = 0;
493   if (isExtSubReg) {
494     SubIdx = CopyMI->getOperand(2).getImm();
495     if (SrcIsPhys) {
496       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
497       // coalesced with AX.
498       SrcReg = tri_->getSubReg(SrcReg, SubIdx);
499       SubIdx = 0;
500     } else if (DstIsPhys) {
501       // If this is a extract_subreg where dst is a physical register, e.g.
502       // cl = EXTRACT_SUBREG reg1024, 1
503       // then create and update the actual physical register allocated to RHS.
504       const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
505       for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
506            unsigned SR = *SRs; ++SRs) {
507         if (DstReg == tri_->getSubReg(SR, SubIdx) &&
508             RC->contains(SR)) {
509           RealDstReg = SR;
510           break;
511         }
512       }
513       assert(RealDstReg && "Invalid extra_subreg instruction!");
514
515       // For this type of EXTRACT_SUBREG, conservatively
516       // check if the live interval of the source register interfere with the
517       // actual super physical register we are trying to coalesce with.
518       LiveInterval &RHS = li_->getInterval(SrcReg);
519       if (li_->hasInterval(RealDstReg) &&
520           RHS.overlaps(li_->getInterval(RealDstReg))) {
521         DOUT << "Interfere with register ";
522         DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
523         return false; // Not coalescable
524       }
525       for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
526         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
527           DOUT << "Interfere with sub-register ";
528           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
529           return false; // Not coalescable
530         }
531       SubIdx = 0;
532     } else {
533       unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
534       unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
535       const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
536       unsigned Threshold = allocatableRCRegs_[RC].count();
537       // Be conservative. If both sides are virtual registers, do not coalesce
538       // if this will cause a high use density interval to target a smaller set
539       // of registers.
540       if (DstSize > Threshold || SrcSize > Threshold) {
541         LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
542         LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
543         if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
544           Again = true;  // May be possible to coalesce later.
545           return false;
546         }
547       }
548     }
549   } else if (differingRegisterClasses(SrcReg, DstReg)) {
550     // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
551     // with another? If it's the resulting destination register, then
552     // the subidx must be propagated to uses (but only those defined
553     // by the EXTRACT_SUBREG). If it's being coalesced into another
554     // register, it should be safe because register is assumed to have
555     // the register class of the super-register.
556
557     // If they are not of the same register class, we cannot join them.
558     DOUT << "\tSrc/Dest are different register classes.\n";
559     // Allow the coalescer to try again in case either side gets coalesced to
560     // a physical register that's compatible with the other side. e.g.
561     // r1024 = MOV32to32_ r1025
562     // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
563     Again = true;  // May be possible to coalesce later.
564     return false;
565   }
566   
567   LiveInterval &SrcInt = li_->getInterval(SrcReg);
568   LiveInterval &DstInt = li_->getInterval(DstReg);
569   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
570          "Register mapping is horribly broken!");
571
572   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
573   DOUT << " and "; DstInt.print(DOUT, tri_);
574   DOUT << ": ";
575
576   // Check if it is necessary to propagate "isDead" property before intervals
577   // are joined.
578   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
579   bool isDead = mopd->isDead();
580   bool isShorten = false;
581   unsigned SrcStart = 0, RemoveStart = 0;
582   unsigned SrcEnd = 0, RemoveEnd = 0;
583   if (isDead) {
584     unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
585     LiveInterval::iterator SrcLR =
586       SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
587     RemoveStart = SrcStart = SrcLR->start;
588     RemoveEnd   = SrcEnd   = SrcLR->end;
589     // The instruction which defines the src is only truly dead if there are
590     // no intermediate uses and there isn't a use beyond the copy.
591     // FIXME: find the last use, mark is kill and shorten the live range.
592     if (SrcEnd > li_->getDefIndex(CopyIdx)) {
593       isDead = false;
594     } else {
595       unsigned LastUseIdx;
596       MachineOperand *LastUse =
597         lastRegisterUse(SrcStart, CopyIdx, SrcReg, LastUseIdx);
598       if (LastUse) {
599         // Shorten the liveinterval to the end of last use.
600         LastUse->setIsKill();
601         isDead = false;
602         isShorten = true;
603         RemoveStart = li_->getDefIndex(LastUseIdx);
604         RemoveEnd = SrcEnd;
605       } else {
606         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
607         if (SrcMI) {
608           MachineOperand *mops = findDefOperand(SrcMI, SrcReg);
609           if (mops)
610             // A dead def should have a single cycle interval.
611             ++RemoveStart;
612         }
613       }
614     }
615   }
616
617   // We need to be careful about coalescing a source physical register with a
618   // virtual register. Once the coalescing is done, it cannot be broken and
619   // these are not spillable! If the destination interval uses are far away,
620   // think twice about coalescing them!
621   if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
622     LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
623     unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
624     unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
625     const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
626     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
627     if (TheCopy.isBackEdge)
628       Threshold *= 2; // Favors back edge copies.
629
630     // If the virtual register live interval is long but it has low use desity,
631     // do not join them, instead mark the physical register as its allocation
632     // preference.
633     unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
634     LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
635     if (Length > Threshold &&
636         (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
637       JoinVInt.preference = JoinPReg;
638       ++numAborts;
639       DOUT << "\tMay tie down a physical register, abort!\n";
640       Again = true;  // May be possible to coalesce later.
641       return false;
642     }
643   }
644
645   // Okay, attempt to join these two intervals.  On failure, this returns false.
646   // Otherwise, if one of the intervals being joined is a physreg, this method
647   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
648   // been modified, so we can use this information below to update aliases.
649   bool Swapped = false;
650   if (JoinIntervals(DstInt, SrcInt, Swapped)) {
651     if (isDead) {
652       // Result of the copy is dead. Propagate this property.
653       if (SrcStart == 0) {
654         assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
655                "Live-in must be a physical register!");
656         // Live-in to the function but dead. Remove it from entry live-in set.
657         // JoinIntervals may end up swapping the two intervals.
658         mf_->begin()->removeLiveIn(SrcReg);
659       } else {
660         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
661         if (SrcMI) {
662           MachineOperand *mops = findDefOperand(SrcMI, SrcReg);
663           if (mops)
664             mops->setIsDead();
665         }
666       }
667     }
668
669     if (isShorten || isDead) {
670       // Shorten the destination live interval.
671       if (Swapped)
672         SrcInt.removeRange(RemoveStart, RemoveEnd, true);
673     }
674   } else {
675     // Coalescing failed.
676     
677     // If we can eliminate the copy without merging the live ranges, do so now.
678     if (!isExtSubReg &&
679         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
680          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
681       JoinedCopies.insert(CopyMI);
682       return true;
683     }
684     
685
686     // Otherwise, we are unable to join the intervals.
687     DOUT << "Interference!\n";
688     Again = true;  // May be possible to coalesce later.
689     return false;
690   }
691
692   LiveInterval *ResSrcInt = &SrcInt;
693   LiveInterval *ResDstInt = &DstInt;
694   if (Swapped) {
695     std::swap(SrcReg, DstReg);
696     std::swap(ResSrcInt, ResDstInt);
697   }
698   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
699          "LiveInterval::join didn't work right!");
700                                
701   // If we're about to merge live ranges into a physical register live range,
702   // we have to update any aliased register's live ranges to indicate that they
703   // have clobbered values for this range.
704   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
705     // Unset unnecessary kills.
706     if (!ResDstInt->containsOneValue()) {
707       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
708              E = ResSrcInt->end(); I != E; ++I)
709         unsetRegisterKills(I->start, I->end, DstReg);
710     }
711
712     // If this is a extract_subreg where dst is a physical register, e.g.
713     // cl = EXTRACT_SUBREG reg1024, 1
714     // then create and update the actual physical register allocated to RHS.
715     if (RealDstReg) {
716       LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
717       SmallSet<const VNInfo*, 4> CopiedValNos;
718       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
719              E = ResSrcInt->ranges.end(); I != E; ++I) {
720         LiveInterval::const_iterator DstLR =
721           ResDstInt->FindLiveRangeContaining(I->start);
722         assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
723         const VNInfo *DstValNo = DstLR->valno;
724         if (CopiedValNos.insert(DstValNo)) {
725           VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
726                                                   li_->getVNInfoAllocator());
727           ValNo->hasPHIKill = DstValNo->hasPHIKill;
728           RealDstInt.addKills(ValNo, DstValNo->kills);
729           RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
730         }
731       }
732       DstReg = RealDstReg;
733     }
734
735     // Update the liveintervals of sub-registers.
736     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
737       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
738                                                  li_->getVNInfoAllocator());
739   } else {
740     // Merge use info if the destination is a virtual register.
741     LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
742     LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
743     dVI.NumUses += sVI.NumUses;
744   }
745
746   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
747   // larger super-register.
748   if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
749     if (!Swapped) {
750       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
751       std::swap(SrcReg, DstReg);
752       std::swap(ResSrcInt, ResDstInt);
753     }
754   }
755
756   if (NewHeuristic) {
757     // Add all copies that define val# in the source interval into the queue.
758     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
759            e = ResSrcInt->vni_end(); i != e; ++i) {
760       const VNInfo *vni = *i;
761       if (!vni->def || vni->def == ~1U || vni->def == ~0U)
762         continue;
763       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
764       unsigned NewSrcReg, NewDstReg;
765       if (CopyMI &&
766           JoinedCopies.count(CopyMI) == 0 &&
767           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
768         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
769         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
770                                 isBackEdgeCopy(CopyMI, DstReg)));
771       }
772     }
773   }
774
775   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
776   DOUT << "\n";
777
778   // Remember to delete the copy instruction.
779   JoinedCopies.insert(CopyMI);
780
781   // Some live range has been lengthened due to colaescing, eliminate the
782   // unnecessary kills.
783   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
784   if (TargetRegisterInfo::isVirtualRegister(DstReg))
785     RemoveUnnecessaryKills(DstReg, *ResDstInt);
786
787   // SrcReg is guarateed to be the register whose live interval that is
788   // being merged.
789   li_->removeInterval(SrcReg);
790   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
791
792   ++numJoins;
793   return true;
794 }
795
796 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
797 /// compute what the resultant value numbers for each value in the input two
798 /// ranges will be.  This is complicated by copies between the two which can
799 /// and will commonly cause multiple value numbers to be merged into one.
800 ///
801 /// VN is the value number that we're trying to resolve.  InstDefiningValue
802 /// keeps track of the new InstDefiningValue assignment for the result
803 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
804 /// whether a value in this or other is a copy from the opposite set.
805 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
806 /// already been assigned.
807 ///
808 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
809 /// contains the value number the copy is from.
810 ///
811 static unsigned ComputeUltimateVN(VNInfo *VNI,
812                                   SmallVector<VNInfo*, 16> &NewVNInfo,
813                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
814                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
815                                   SmallVector<int, 16> &ThisValNoAssignments,
816                                   SmallVector<int, 16> &OtherValNoAssignments) {
817   unsigned VN = VNI->id;
818
819   // If the VN has already been computed, just return it.
820   if (ThisValNoAssignments[VN] >= 0)
821     return ThisValNoAssignments[VN];
822 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
823
824   // If this val is not a copy from the other val, then it must be a new value
825   // number in the destination.
826   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
827   if (I == ThisFromOther.end()) {
828     NewVNInfo.push_back(VNI);
829     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
830   }
831   VNInfo *OtherValNo = I->second;
832
833   // Otherwise, this *is* a copy from the RHS.  If the other side has already
834   // been computed, return it.
835   if (OtherValNoAssignments[OtherValNo->id] >= 0)
836     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
837   
838   // Mark this value number as currently being computed, then ask what the
839   // ultimate value # of the other value is.
840   ThisValNoAssignments[VN] = -2;
841   unsigned UltimateVN =
842     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
843                       OtherValNoAssignments, ThisValNoAssignments);
844   return ThisValNoAssignments[VN] = UltimateVN;
845 }
846
847 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
848   return std::find(V.begin(), V.end(), Val) != V.end();
849 }
850
851 /// SimpleJoin - Attempt to joint the specified interval into this one. The
852 /// caller of this method must guarantee that the RHS only contains a single
853 /// value number and that the RHS is not defined by a copy from this
854 /// interval.  This returns false if the intervals are not joinable, or it
855 /// joins them and returns true.
856 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
857   assert(RHS.containsOneValue());
858   
859   // Some number (potentially more than one) value numbers in the current
860   // interval may be defined as copies from the RHS.  Scan the overlapping
861   // portions of the LHS and RHS, keeping track of this and looking for
862   // overlapping live ranges that are NOT defined as copies.  If these exist, we
863   // cannot coalesce.
864   
865   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
866   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
867   
868   if (LHSIt->start < RHSIt->start) {
869     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
870     if (LHSIt != LHS.begin()) --LHSIt;
871   } else if (RHSIt->start < LHSIt->start) {
872     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
873     if (RHSIt != RHS.begin()) --RHSIt;
874   }
875   
876   SmallVector<VNInfo*, 8> EliminatedLHSVals;
877   
878   while (1) {
879     // Determine if these live intervals overlap.
880     bool Overlaps = false;
881     if (LHSIt->start <= RHSIt->start)
882       Overlaps = LHSIt->end > RHSIt->start;
883     else
884       Overlaps = RHSIt->end > LHSIt->start;
885     
886     // If the live intervals overlap, there are two interesting cases: if the
887     // LHS interval is defined by a copy from the RHS, it's ok and we record
888     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
889     // coalesce these live ranges and we bail out.
890     if (Overlaps) {
891       // If we haven't already recorded that this value # is safe, check it.
892       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
893         // Copy from the RHS?
894         unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
895         if (SrcReg != RHS.reg)
896           return false;    // Nope, bail out.
897         
898         EliminatedLHSVals.push_back(LHSIt->valno);
899       }
900       
901       // We know this entire LHS live range is okay, so skip it now.
902       if (++LHSIt == LHSEnd) break;
903       continue;
904     }
905     
906     if (LHSIt->end < RHSIt->end) {
907       if (++LHSIt == LHSEnd) break;
908     } else {
909       // One interesting case to check here.  It's possible that we have
910       // something like "X3 = Y" which defines a new value number in the LHS,
911       // and is the last use of this liverange of the RHS.  In this case, we
912       // want to notice this copy (so that it gets coalesced away) even though
913       // the live ranges don't actually overlap.
914       if (LHSIt->start == RHSIt->end) {
915         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
916           // We already know that this value number is going to be merged in
917           // if coalescing succeeds.  Just skip the liverange.
918           if (++LHSIt == LHSEnd) break;
919         } else {
920           // Otherwise, if this is a copy from the RHS, mark it as being merged
921           // in.
922           if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
923             EliminatedLHSVals.push_back(LHSIt->valno);
924
925             // We know this entire LHS live range is okay, so skip it now.
926             if (++LHSIt == LHSEnd) break;
927           }
928         }
929       }
930       
931       if (++RHSIt == RHSEnd) break;
932     }
933   }
934   
935   // If we got here, we know that the coalescing will be successful and that
936   // the value numbers in EliminatedLHSVals will all be merged together.  Since
937   // the most common case is that EliminatedLHSVals has a single number, we
938   // optimize for it: if there is more than one value, we merge them all into
939   // the lowest numbered one, then handle the interval as if we were merging
940   // with one value number.
941   VNInfo *LHSValNo;
942   if (EliminatedLHSVals.size() > 1) {
943     // Loop through all the equal value numbers merging them into the smallest
944     // one.
945     VNInfo *Smallest = EliminatedLHSVals[0];
946     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
947       if (EliminatedLHSVals[i]->id < Smallest->id) {
948         // Merge the current notion of the smallest into the smaller one.
949         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
950         Smallest = EliminatedLHSVals[i];
951       } else {
952         // Merge into the smallest.
953         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
954       }
955     }
956     LHSValNo = Smallest;
957   } else {
958     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
959     LHSValNo = EliminatedLHSVals[0];
960   }
961   
962   // Okay, now that there is a single LHS value number that we're merging the
963   // RHS into, update the value number info for the LHS to indicate that the
964   // value number is defined where the RHS value number was.
965   const VNInfo *VNI = RHS.getValNumInfo(0);
966   LHSValNo->def  = VNI->def;
967   LHSValNo->copy = VNI->copy;
968   
969   // Okay, the final step is to loop over the RHS live intervals, adding them to
970   // the LHS.
971   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
972   LHS.addKills(LHSValNo, VNI->kills);
973   LHS.MergeRangesInAsValue(RHS, LHSValNo);
974   LHS.weight += RHS.weight;
975   if (RHS.preference && !LHS.preference)
976     LHS.preference = RHS.preference;
977   
978   return true;
979 }
980
981 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
982 /// returns false.  Otherwise, if one of the intervals being joined is a
983 /// physreg, this method always canonicalizes LHS to be it.  The output
984 /// "RHS" will not have been modified, so we can use this information
985 /// below to update aliases.
986 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
987                                              LiveInterval &RHS, bool &Swapped) {
988   // Compute the final value assignment, assuming that the live ranges can be
989   // coalesced.
990   SmallVector<int, 16> LHSValNoAssignments;
991   SmallVector<int, 16> RHSValNoAssignments;
992   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
993   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
994   SmallVector<VNInfo*, 16> NewVNInfo;
995                           
996   // If a live interval is a physical register, conservatively check if any
997   // of its sub-registers is overlapping the live interval of the virtual
998   // register. If so, do not coalesce.
999   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1000       *tri_->getSubRegisters(LHS.reg)) {
1001     for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1002       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1003         DOUT << "Interfere with sub-register ";
1004         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1005         return false;
1006       }
1007   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1008              *tri_->getSubRegisters(RHS.reg)) {
1009     for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1010       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1011         DOUT << "Interfere with sub-register ";
1012         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1013         return false;
1014       }
1015   }
1016                           
1017   // Compute ultimate value numbers for the LHS and RHS values.
1018   if (RHS.containsOneValue()) {
1019     // Copies from a liveinterval with a single value are simple to handle and
1020     // very common, handle the special case here.  This is important, because
1021     // often RHS is small and LHS is large (e.g. a physreg).
1022     
1023     // Find out if the RHS is defined as a copy from some value in the LHS.
1024     int RHSVal0DefinedFromLHS = -1;
1025     int RHSValID = -1;
1026     VNInfo *RHSValNoInfo = NULL;
1027     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1028     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1029     if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1030       // If RHS is not defined as a copy from the LHS, we can use simpler and
1031       // faster checks to see if the live ranges are coalescable.  This joiner
1032       // can't swap the LHS/RHS intervals though.
1033       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1034         return SimpleJoin(LHS, RHS);
1035       } else {
1036         RHSValNoInfo = RHSValNoInfo0;
1037       }
1038     } else {
1039       // It was defined as a copy from the LHS, find out what value # it is.
1040       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1041       RHSValID = RHSValNoInfo->id;
1042       RHSVal0DefinedFromLHS = RHSValID;
1043     }
1044     
1045     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1046     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1047     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1048     
1049     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1050     // should now get updated.
1051     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1052          i != e; ++i) {
1053       VNInfo *VNI = *i;
1054       unsigned VN = VNI->id;
1055       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1056         if (LHSSrcReg != RHS.reg) {
1057           // If this is not a copy from the RHS, its value number will be
1058           // unmodified by the coalescing.
1059           NewVNInfo[VN] = VNI;
1060           LHSValNoAssignments[VN] = VN;
1061         } else if (RHSValID == -1) {
1062           // Otherwise, it is a copy from the RHS, and we don't already have a
1063           // value# for it.  Keep the current value number, but remember it.
1064           LHSValNoAssignments[VN] = RHSValID = VN;
1065           NewVNInfo[VN] = RHSValNoInfo;
1066           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1067         } else {
1068           // Otherwise, use the specified value #.
1069           LHSValNoAssignments[VN] = RHSValID;
1070           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1071             NewVNInfo[VN] = RHSValNoInfo;
1072             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1073           }
1074         }
1075       } else {
1076         NewVNInfo[VN] = VNI;
1077         LHSValNoAssignments[VN] = VN;
1078       }
1079     }
1080     
1081     assert(RHSValID != -1 && "Didn't find value #?");
1082     RHSValNoAssignments[0] = RHSValID;
1083     if (RHSVal0DefinedFromLHS != -1) {
1084       // This path doesn't go through ComputeUltimateVN so just set
1085       // it to anything.
1086       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1087     }
1088   } else {
1089     // Loop over the value numbers of the LHS, seeing if any are defined from
1090     // the RHS.
1091     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1092          i != e; ++i) {
1093       VNInfo *VNI = *i;
1094       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1095         continue;
1096       
1097       // DstReg is known to be a register in the LHS interval.  If the src is
1098       // from the RHS interval, we can use its value #.
1099       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1100         continue;
1101       
1102       // Figure out the value # from the RHS.
1103       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1104     }
1105     
1106     // Loop over the value numbers of the RHS, seeing if any are defined from
1107     // the LHS.
1108     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1109          i != e; ++i) {
1110       VNInfo *VNI = *i;
1111       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1112         continue;
1113       
1114       // DstReg is known to be a register in the RHS interval.  If the src is
1115       // from the LHS interval, we can use its value #.
1116       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1117         continue;
1118       
1119       // Figure out the value # from the LHS.
1120       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1121     }
1122     
1123     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1124     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1125     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1126     
1127     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1128          i != e; ++i) {
1129       VNInfo *VNI = *i;
1130       unsigned VN = VNI->id;
1131       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1132         continue;
1133       ComputeUltimateVN(VNI, NewVNInfo,
1134                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1135                         LHSValNoAssignments, RHSValNoAssignments);
1136     }
1137     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1138          i != e; ++i) {
1139       VNInfo *VNI = *i;
1140       unsigned VN = VNI->id;
1141       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1142         continue;
1143       // If this value number isn't a copy from the LHS, it's a new number.
1144       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1145         NewVNInfo.push_back(VNI);
1146         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1147         continue;
1148       }
1149       
1150       ComputeUltimateVN(VNI, NewVNInfo,
1151                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1152                         RHSValNoAssignments, LHSValNoAssignments);
1153     }
1154   }
1155   
1156   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1157   // interval lists to see if these intervals are coalescable.
1158   LiveInterval::const_iterator I = LHS.begin();
1159   LiveInterval::const_iterator IE = LHS.end();
1160   LiveInterval::const_iterator J = RHS.begin();
1161   LiveInterval::const_iterator JE = RHS.end();
1162   
1163   // Skip ahead until the first place of potential sharing.
1164   if (I->start < J->start) {
1165     I = std::upper_bound(I, IE, J->start);
1166     if (I != LHS.begin()) --I;
1167   } else if (J->start < I->start) {
1168     J = std::upper_bound(J, JE, I->start);
1169     if (J != RHS.begin()) --J;
1170   }
1171   
1172   while (1) {
1173     // Determine if these two live ranges overlap.
1174     bool Overlaps;
1175     if (I->start < J->start) {
1176       Overlaps = I->end > J->start;
1177     } else {
1178       Overlaps = J->end > I->start;
1179     }
1180
1181     // If so, check value # info to determine if they are really different.
1182     if (Overlaps) {
1183       // If the live range overlap will map to the same value number in the
1184       // result liverange, we can still coalesce them.  If not, we can't.
1185       if (LHSValNoAssignments[I->valno->id] !=
1186           RHSValNoAssignments[J->valno->id])
1187         return false;
1188     }
1189     
1190     if (I->end < J->end) {
1191       ++I;
1192       if (I == IE) break;
1193     } else {
1194       ++J;
1195       if (J == JE) break;
1196     }
1197   }
1198
1199   // Update kill info. Some live ranges are extended due to copy coalescing.
1200   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1201          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1202     VNInfo *VNI = I->first;
1203     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1204     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1205     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1206     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1207   }
1208
1209   // Update kill info. Some live ranges are extended due to copy coalescing.
1210   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1211          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1212     VNInfo *VNI = I->first;
1213     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1214     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1215     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1216     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1217   }
1218
1219   // If we get here, we know that we can coalesce the live ranges.  Ask the
1220   // intervals to coalesce themselves now.
1221   if ((RHS.ranges.size() > LHS.ranges.size() &&
1222       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1223       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1224     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1225     Swapped = true;
1226   } else {
1227     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1228     Swapped = false;
1229   }
1230   return true;
1231 }
1232
1233 namespace {
1234   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1235   // depth of the basic block (the unsigned), and then on the MBB number.
1236   struct DepthMBBCompare {
1237     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1238     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1239       if (LHS.first > RHS.first) return true;   // Deeper loops first
1240       return LHS.first == RHS.first &&
1241         LHS.second->getNumber() < RHS.second->getNumber();
1242     }
1243   };
1244 }
1245
1246 /// getRepIntervalSize - Returns the size of the interval that represents the
1247 /// specified register.
1248 template<class SF>
1249 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1250   return Rc->getRepIntervalSize(Reg);
1251 }
1252
1253 /// CopyRecSort::operator - Join priority queue sorting function.
1254 ///
1255 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1256   // Inner loops first.
1257   if (left.LoopDepth > right.LoopDepth)
1258     return false;
1259   else if (left.LoopDepth == right.LoopDepth)
1260     if (left.isBackEdge && !right.isBackEdge)
1261       return false;
1262   return true;
1263 }
1264
1265 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1266                                                std::vector<CopyRec> &TryAgain) {
1267   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1268
1269   std::vector<CopyRec> VirtCopies;
1270   std::vector<CopyRec> PhysCopies;
1271   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1272   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1273        MII != E;) {
1274     MachineInstr *Inst = MII++;
1275     
1276     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1277     unsigned SrcReg, DstReg;
1278     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1279       DstReg = Inst->getOperand(0).getReg();
1280       SrcReg = Inst->getOperand(1).getReg();
1281     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1282       continue;
1283
1284     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1285     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1286     if (NewHeuristic) {
1287       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1288     } else {
1289       if (SrcIsPhys || DstIsPhys)
1290         PhysCopies.push_back(CopyRec(Inst, 0, false));
1291       else
1292         VirtCopies.push_back(CopyRec(Inst, 0, false));
1293     }
1294   }
1295
1296   if (NewHeuristic)
1297     return;
1298
1299   // Try coalescing physical register + virtual register first.
1300   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1301     CopyRec &TheCopy = PhysCopies[i];
1302     bool Again = false;
1303     if (!JoinCopy(TheCopy, Again))
1304       if (Again)
1305         TryAgain.push_back(TheCopy);
1306   }
1307   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1308     CopyRec &TheCopy = VirtCopies[i];
1309     bool Again = false;
1310     if (!JoinCopy(TheCopy, Again))
1311       if (Again)
1312         TryAgain.push_back(TheCopy);
1313   }
1314 }
1315
1316 void SimpleRegisterCoalescing::joinIntervals() {
1317   DOUT << "********** JOINING INTERVALS ***********\n";
1318
1319   if (NewHeuristic)
1320     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1321
1322   std::vector<CopyRec> TryAgainList;
1323   if (loopInfo->begin() == loopInfo->end()) {
1324     // If there are no loops in the function, join intervals in function order.
1325     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1326          I != E; ++I)
1327       CopyCoalesceInMBB(I, TryAgainList);
1328   } else {
1329     // Otherwise, join intervals in inner loops before other intervals.
1330     // Unfortunately we can't just iterate over loop hierarchy here because
1331     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1332
1333     // Join intervals in the function prolog first. We want to join physical
1334     // registers with virtual registers before the intervals got too long.
1335     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1336     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1337       MachineBasicBlock *MBB = I;
1338       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1339     }
1340
1341     // Sort by loop depth.
1342     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1343
1344     // Finally, join intervals in loop nest order.
1345     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1346       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1347   }
1348   
1349   // Joining intervals can allow other intervals to be joined.  Iteratively join
1350   // until we make no progress.
1351   if (NewHeuristic) {
1352     SmallVector<CopyRec, 16> TryAgain;
1353     bool ProgressMade = true;
1354     while (ProgressMade) {
1355       ProgressMade = false;
1356       while (!JoinQueue->empty()) {
1357         CopyRec R = JoinQueue->pop();
1358         bool Again = false;
1359         bool Success = JoinCopy(R, Again);
1360         if (Success)
1361           ProgressMade = true;
1362         else if (Again)
1363           TryAgain.push_back(R);
1364       }
1365
1366       if (ProgressMade) {
1367         while (!TryAgain.empty()) {
1368           JoinQueue->push(TryAgain.back());
1369           TryAgain.pop_back();
1370         }
1371       }
1372     }
1373   } else {
1374     bool ProgressMade = true;
1375     while (ProgressMade) {
1376       ProgressMade = false;
1377
1378       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1379         CopyRec &TheCopy = TryAgainList[i];
1380         if (TheCopy.MI) {
1381           bool Again = false;
1382           bool Success = JoinCopy(TheCopy, Again);
1383           if (Success || !Again) {
1384             TheCopy.MI = 0;   // Mark this one as done.
1385             ProgressMade = true;
1386           }
1387         }
1388       }
1389     }
1390   }
1391
1392   if (NewHeuristic)
1393     delete JoinQueue;  
1394 }
1395
1396 /// Return true if the two specified registers belong to different register
1397 /// classes.  The registers may be either phys or virt regs.
1398 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1399                                                         unsigned RegB) const {
1400
1401   // Get the register classes for the first reg.
1402   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1403     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1404            "Shouldn't consider two physregs!");
1405     return !mri_->getRegClass(RegB)->contains(RegA);
1406   }
1407
1408   // Compare against the regclass for the second reg.
1409   const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1410   if (TargetRegisterInfo::isVirtualRegister(RegB))
1411     return RegClass != mri_->getRegClass(RegB);
1412   else
1413     return !RegClass->contains(RegB);
1414 }
1415
1416 /// lastRegisterUse - Returns the last use of the specific register between
1417 /// cycles Start and End or NULL if there are no uses.
1418 MachineOperand *
1419 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1420                                           unsigned Reg, unsigned &UseIdx) const{
1421   UseIdx = 0;
1422   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1423     MachineOperand *LastUse = NULL;
1424     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1425            E = mri_->use_end(); I != E; ++I) {
1426       MachineOperand &Use = I.getOperand();
1427       MachineInstr *UseMI = Use.getParent();
1428       unsigned Idx = li_->getInstructionIndex(UseMI);
1429       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1430         LastUse = &Use;
1431         UseIdx = Idx;
1432       }
1433     }
1434     return LastUse;
1435   }
1436
1437   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1438   int s = Start;
1439   while (e >= s) {
1440     // Skip deleted instructions
1441     MachineInstr *MI = li_->getInstructionFromIndex(e);
1442     while ((e - InstrSlots::NUM) >= s && !MI) {
1443       e -= InstrSlots::NUM;
1444       MI = li_->getInstructionFromIndex(e);
1445     }
1446     if (e < s || MI == NULL)
1447       return NULL;
1448
1449     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1450       MachineOperand &Use = MI->getOperand(i);
1451       if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1452           tri_->regsOverlap(Use.getReg(), Reg)) {
1453         UseIdx = e;
1454         return &Use;
1455       }
1456     }
1457
1458     e -= InstrSlots::NUM;
1459   }
1460
1461   return NULL;
1462 }
1463
1464
1465 /// findDefOperand - Returns the MachineOperand that is a def of the specific
1466 /// register. It returns NULL if the def is not found.
1467 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI,
1468                                                          unsigned Reg) const {
1469   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1470     MachineOperand &MO = MI->getOperand(i);
1471     if (MO.isRegister() && MO.isDef() &&
1472         tri_->regsOverlap(MO.getReg(), Reg))
1473       return &MO;
1474   }
1475   return NULL;
1476 }
1477
1478 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
1479 /// between cycles Start and End.
1480 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1481                                                   unsigned Reg) {
1482   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1483   int s = Start;
1484   while (e >= s) {
1485     // Skip deleted instructions
1486     MachineInstr *MI = li_->getInstructionFromIndex(e);
1487     while ((e - InstrSlots::NUM) >= s && !MI) {
1488       e -= InstrSlots::NUM;
1489       MI = li_->getInstructionFromIndex(e);
1490     }
1491     if (e < s || MI == NULL)
1492       return;
1493
1494     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1495       MachineOperand &MO = MI->getOperand(i);
1496       if (MO.isRegister() && MO.isKill() && MO.getReg() &&
1497           tri_->regsOverlap(MO.getReg(), Reg)) {
1498         MO.setIsKill(false);
1499       }
1500     }
1501
1502     e -= InstrSlots::NUM;
1503   }
1504 }
1505
1506 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1507   if (TargetRegisterInfo::isPhysicalRegister(reg))
1508     cerr << tri_->getName(reg);
1509   else
1510     cerr << "%reg" << reg;
1511 }
1512
1513 void SimpleRegisterCoalescing::releaseMemory() {
1514   JoinedCopies.clear();
1515 }
1516
1517 static bool isZeroLengthInterval(LiveInterval *li) {
1518   for (LiveInterval::Ranges::const_iterator
1519          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1520     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1521       return false;
1522   return true;
1523 }
1524
1525 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1526   mf_ = &fn;
1527   mri_ = &fn.getRegInfo();
1528   tm_ = &fn.getTarget();
1529   tri_ = tm_->getRegisterInfo();
1530   tii_ = tm_->getInstrInfo();
1531   li_ = &getAnalysis<LiveIntervals>();
1532   lv_ = &getAnalysis<LiveVariables>();
1533   loopInfo = &getAnalysis<MachineLoopInfo>();
1534
1535   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1536        << "********** Function: "
1537        << ((Value*)mf_->getFunction())->getName() << '\n';
1538
1539   allocatableRegs_ = tri_->getAllocatableSet(fn);
1540   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1541          E = tri_->regclass_end(); I != E; ++I)
1542     allocatableRCRegs_.insert(std::make_pair(*I,
1543                                              tri_->getAllocatableSet(fn, *I)));
1544
1545   // Join (coalesce) intervals if requested.
1546   if (EnableJoining) {
1547     joinIntervals();
1548     DOUT << "********** INTERVALS POST JOINING **********\n";
1549     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1550       I->second.print(DOUT, tri_);
1551       DOUT << "\n";
1552     }
1553
1554     // Delete all coalesced copies.
1555     for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1556            E = JoinedCopies.end(); I != E; ++I) {
1557       li_->RemoveMachineInstrFromMaps(*I);
1558       (*I)->eraseFromParent();
1559       ++numPeep;
1560     }
1561   }
1562
1563   // Perform a final pass over the instructions and compute spill weights
1564   // and remove identity moves.
1565   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1566        mbbi != mbbe; ++mbbi) {
1567     MachineBasicBlock* mbb = mbbi;
1568     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1569
1570     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1571          mii != mie; ) {
1572       // if the move will be an identity move delete it
1573       unsigned srcReg, dstReg;
1574       if (tii_->isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
1575         // remove from def list
1576         LiveInterval &RegInt = li_->getOrCreateInterval(srcReg);
1577         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1578         // If def of this move instruction is dead, remove its live range from
1579         // the dstination register's live interval.
1580         if (MO->isDead()) {
1581           unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1582           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1583           RegInt.removeRange(MLR->start, MoveIdx+1, true);
1584           if (RegInt.empty())
1585             li_->removeInterval(srcReg);
1586         }
1587         li_->RemoveMachineInstrFromMaps(mii);
1588         mii = mbbi->erase(mii);
1589         ++numPeep;
1590       } else {
1591         SmallSet<unsigned, 4> UniqueUses;
1592         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1593           const MachineOperand &mop = mii->getOperand(i);
1594           if (mop.isRegister() && mop.getReg() &&
1595               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1596             unsigned reg = mop.getReg();
1597             // Multiple uses of reg by the same instruction. It should not
1598             // contribute to spill weight again.
1599             if (UniqueUses.count(reg) != 0)
1600               continue;
1601             LiveInterval &RegInt = li_->getInterval(reg);
1602             RegInt.weight +=
1603               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1604             UniqueUses.insert(reg);
1605           }
1606         }
1607         ++mii;
1608       }
1609     }
1610   }
1611
1612   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1613     LiveInterval &LI = I->second;
1614     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1615       // If the live interval length is essentially zero, i.e. in every live
1616       // range the use follows def immediately, it doesn't make sense to spill
1617       // it and hope it will be easier to allocate for this li.
1618       if (isZeroLengthInterval(&LI))
1619         LI.weight = HUGE_VALF;
1620       else {
1621         bool isLoad = false;
1622         if (li_->isReMaterializable(LI, isLoad)) {
1623           // If all of the definitions of the interval are re-materializable,
1624           // it is a preferred candidate for spilling. If non of the defs are
1625           // loads, then it's potentially very cheap to re-materialize.
1626           // FIXME: this gets much more complicated once we support non-trivial
1627           // re-materialization.
1628           if (isLoad)
1629             LI.weight *= 0.9F;
1630           else
1631             LI.weight *= 0.5F;
1632         }
1633       }
1634
1635       // Slightly prefer live interval that has been assigned a preferred reg.
1636       if (LI.preference)
1637         LI.weight *= 1.01F;
1638
1639       // Divide the weight of the interval by its size.  This encourages 
1640       // spilling of intervals that are large and have few uses, and
1641       // discourages spilling of small intervals with many uses.
1642       LI.weight /= LI.getSize();
1643     }
1644   }
1645
1646   DEBUG(dump());
1647   return true;
1648 }
1649
1650 /// print - Implement the dump method.
1651 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1652    li_->print(O, m);
1653 }
1654
1655 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1656   return new SimpleRegisterCoalescing();
1657 }
1658
1659 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1660 DEFINING_FILE_FOR(SimpleRegisterCoalescing)