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