Two coalescer fixes in one.
[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/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.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(numCrossRCs , "Number of cross class joins performed");
40 STATISTIC(numCommutes , "Number of instruction commuting performed");
41 STATISTIC(numExtends  , "Number of copies extended");
42 STATISTIC(NumReMats   , "Number of instructions re-materialized");
43 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
44 STATISTIC(numAborts   , "Number of times interval joining aborted");
45 STATISTIC(numDeadValNo, "Number of valno def marked dead");
46
47 char SimpleRegisterCoalescing::ID = 0;
48 static cl::opt<bool>
49 EnableJoining("join-liveintervals",
50               cl::desc("Coalesce copies (default=true)"),
51               cl::init(true));
52
53 static cl::opt<bool>
54 NewHeuristic("new-coalescer-heuristic",
55              cl::desc("Use new coalescer heuristic"),
56              cl::init(false), cl::Hidden);
57
58 static cl::opt<bool>
59 CrossClassJoin("join-cross-class-copies",
60                cl::desc("Coalesce cross register class copies"),
61                cl::init(false), cl::Hidden);
62
63 static RegisterPass<SimpleRegisterCoalescing> 
64 X("simple-register-coalescing", "Simple Register Coalescing");
65
66 // Declare that we implement the RegisterCoalescer interface
67 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
68
69 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
70
71 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
72   AU.addRequired<LiveIntervals>();
73   AU.addPreserved<LiveIntervals>();
74   AU.addRequired<MachineLoopInfo>();
75   AU.addPreserved<MachineLoopInfo>();
76   AU.addPreservedID(MachineDominatorsID);
77   if (StrongPHIElim)
78     AU.addPreservedID(StrongPHIEliminationID);
79   else
80     AU.addPreservedID(PHIEliminationID);
81   AU.addPreservedID(TwoAddressInstructionPassID);
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   assert(BLR != IntB.end() && "Live range not found!");
109   VNInfo *BValNo = BLR->valno;
110   
111   // Get the location that B is defined at.  Two options: either this value has
112   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
113   // can't process it.
114   if (!BValNo->copy) return false;
115   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
116   
117   // AValNo is the value number in A that defines the copy, A3 in the example.
118   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
119   assert(ALR != IntA.end() && "Live range not found!");
120   VNInfo *AValNo = ALR->valno;
121   // If it's re-defined by an early clobber somewhere in the live range, then
122   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
123   // See PR3149:
124   // 172     %ECX<def> = MOV32rr %reg1039<kill>
125   // 180     INLINEASM <es:subl $5,$1
126   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
127   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
128   // 188     %EAX<def> = MOV32rr %EAX<kill>
129   // 196     %ECX<def> = MOV32rr %ECX<kill>
130   // 204     %ECX<def> = MOV32rr %ECX<kill>
131   // 212     %EAX<def> = MOV32rr %EAX<kill>
132   // 220     %EAX<def> = MOV32rr %EAX
133   // 228     %reg1039<def> = MOV32rr %ECX<kill>
134   // The early clobber operand ties ECX input to the ECX def.
135   //
136   // The live interval of ECX is represented as this:
137   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
138   // The coalescer has no idea there was a def in the middle of [174,230].
139   if (AValNo->redefByEC)
140     return false;
141   
142   // If AValNo is defined as a copy from IntB, we can potentially process this.  
143   // Get the instruction that defines this value number.
144   unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
145   if (!SrcReg) return false;  // Not defined by a copy.
146     
147   // If the value number is not defined by a copy instruction, ignore it.
148
149   // If the source register comes from an interval other than IntB, we can't
150   // handle this.
151   if (SrcReg != IntB.reg) return false;
152   
153   // Get the LiveRange in IntB that this value number starts with.
154   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
155   assert(ValLR != IntB.end() && "Live range not found!");
156   
157   // Make sure that the end of the live range is inside the same block as
158   // CopyMI.
159   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
160   if (!ValLREndInst || 
161       ValLREndInst->getParent() != CopyMI->getParent()) return false;
162
163   // Okay, we now know that ValLR ends in the same block that the CopyMI
164   // live-range starts.  If there are no intervening live ranges between them in
165   // IntB, we can merge them.
166   if (ValLR+1 != BLR) return false;
167
168   // If a live interval is a physical register, conservatively check if any
169   // of its sub-registers is overlapping the live interval of the virtual
170   // register. If so, do not coalesce.
171   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
172       *tri_->getSubRegisters(IntB.reg)) {
173     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
174       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
175         DOUT << "Interfere with sub-register ";
176         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
177         return false;
178       }
179   }
180   
181   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
182   
183   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
184   // We are about to delete CopyMI, so need to remove it as the 'instruction
185   // that defines this value #'. Update the the valnum with the new defining
186   // instruction #.
187   BValNo->def  = FillerStart;
188   BValNo->copy = NULL;
189   
190   // Okay, we can merge them.  We need to insert a new liverange:
191   // [ValLR.end, BLR.begin) of either value number, then we merge the
192   // two value numbers.
193   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
194
195   // If the IntB live range is assigned to a physical register, and if that
196   // physreg has sub-registers, update their live intervals as well. 
197   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
198     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
199       LiveInterval &SRLI = li_->getInterval(*SR);
200       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
201                  SRLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
202     }
203   }
204
205   // Okay, merge "B1" into the same value number as "B0".
206   if (BValNo != ValLR->valno) {
207     IntB.addKills(ValLR->valno, BValNo->kills);
208     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
209   }
210   DOUT << "   result = "; IntB.print(DOUT, tri_);
211   DOUT << "\n";
212
213   // If the source instruction was killing the source register before the
214   // merge, unset the isKill marker given the live range has been extended.
215   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
216   if (UIdx != -1) {
217     ValLREndInst->getOperand(UIdx).setIsKill(false);
218     IntB.removeKill(ValLR->valno, FillerStart);
219   }
220
221   ++numExtends;
222   return true;
223 }
224
225 /// HasOtherReachingDefs - Return true if there are definitions of IntB
226 /// other than BValNo val# that can reach uses of AValno val# of IntA.
227 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
228                                                     LiveInterval &IntB,
229                                                     VNInfo *AValNo,
230                                                     VNInfo *BValNo) {
231   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
232        AI != AE; ++AI) {
233     if (AI->valno != AValNo) continue;
234     LiveInterval::Ranges::iterator BI =
235       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
236     if (BI != IntB.ranges.begin())
237       --BI;
238     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
239       if (BI->valno == BValNo)
240         continue;
241       if (BI->start <= AI->start && BI->end > AI->start)
242         return true;
243       if (BI->start > AI->start && BI->start < AI->end)
244         return true;
245     }
246   }
247   return false;
248 }
249
250 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
251 /// being the source and IntB being the dest, thus this defines a value number
252 /// in IntB.  If the source value number (in IntA) is defined by a commutable
253 /// instruction and its other operand is coalesced to the copy dest register,
254 /// see if we can transform the copy into a noop by commuting the definition. For
255 /// example,
256 ///
257 ///  A3 = op A2 B0<kill>
258 ///    ...
259 ///  B1 = A3      <- this copy
260 ///    ...
261 ///     = op A3   <- more uses
262 ///
263 /// ==>
264 ///
265 ///  B2 = op B0 A2<kill>
266 ///    ...
267 ///  B1 = B2      <- now an identify copy
268 ///    ...
269 ///     = op B2   <- more uses
270 ///
271 /// This returns true if an interval was modified.
272 ///
273 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
274                                                         LiveInterval &IntB,
275                                                         MachineInstr *CopyMI) {
276   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
277
278   // FIXME: For now, only eliminate the copy by commuting its def when the
279   // source register is a virtual register. We want to guard against cases
280   // where the copy is a back edge copy and commuting the def lengthen the
281   // live interval of the source register to the entire loop.
282   if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
283     return false;
284
285   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
286   // the example above.
287   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
288   assert(BLR != IntB.end() && "Live range not found!");
289   VNInfo *BValNo = BLR->valno;
290   
291   // Get the location that B is defined at.  Two options: either this value has
292   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
293   // can't process it.
294   if (!BValNo->copy) return false;
295   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
296   
297   // AValNo is the value number in A that defines the copy, A3 in the example.
298   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
299   assert(ALR != IntA.end() && "Live range not found!");
300   VNInfo *AValNo = ALR->valno;
301   // If other defs can reach uses of this def, then it's not safe to perform
302   // the optimization.
303   if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
304     return false;
305   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
306   const TargetInstrDesc &TID = DefMI->getDesc();
307   unsigned NewDstIdx;
308   if (!TID.isCommutable() ||
309       !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
310     return false;
311
312   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
313   unsigned NewReg = NewDstMO.getReg();
314   if (NewReg != IntB.reg || !NewDstMO.isKill())
315     return false;
316
317   // Make sure there are no other definitions of IntB that would reach the
318   // uses which the new definition can reach.
319   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
320     return false;
321
322   // If some of the uses of IntA.reg is already coalesced away, return false.
323   // It's not possible to determine whether it's safe to perform the coalescing.
324   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
325          UE = mri_->use_end(); UI != UE; ++UI) {
326     MachineInstr *UseMI = &*UI;
327     unsigned UseIdx = li_->getInstructionIndex(UseMI);
328     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
329     if (ULR == IntA.end())
330       continue;
331     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
332       return false;
333   }
334
335   // At this point we have decided that it is legal to do this
336   // transformation.  Start by commuting the instruction.
337   MachineBasicBlock *MBB = DefMI->getParent();
338   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
339   if (!NewMI)
340     return false;
341   if (NewMI != DefMI) {
342     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
343     MBB->insert(DefMI, NewMI);
344     MBB->erase(DefMI);
345   }
346   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
347   NewMI->getOperand(OpIdx).setIsKill();
348
349   bool BHasPHIKill = BValNo->hasPHIKill;
350   SmallVector<VNInfo*, 4> BDeadValNos;
351   SmallVector<unsigned, 4> BKills;
352   std::map<unsigned, unsigned> BExtend;
353
354   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
355   // A = or A, B
356   // ...
357   // B = A
358   // ...
359   // C = A<kill>
360   // ...
361   //   = B
362   //
363   // then do not add kills of A to the newly created B interval.
364   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
365   if (Extended)
366     BExtend[ALR->end] = BLR->end;
367
368   // Update uses of IntA of the specific Val# with IntB.
369   bool BHasSubRegs = false;
370   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
371     BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
372   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
373          UE = mri_->use_end(); UI != UE;) {
374     MachineOperand &UseMO = UI.getOperand();
375     MachineInstr *UseMI = &*UI;
376     ++UI;
377     if (JoinedCopies.count(UseMI))
378       continue;
379     unsigned UseIdx = li_->getInstructionIndex(UseMI);
380     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
381     if (ULR == IntA.end() || ULR->valno != AValNo)
382       continue;
383     UseMO.setReg(NewReg);
384     if (UseMI == CopyMI)
385       continue;
386     if (UseMO.isKill()) {
387       if (Extended)
388         UseMO.setIsKill(false);
389       else
390         BKills.push_back(li_->getUseIndex(UseIdx)+1);
391     }
392     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
393     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
394       continue;
395     if (DstReg == IntB.reg) {
396       // This copy will become a noop. If it's defining a new val#,
397       // remove that val# as well. However this live range is being
398       // extended to the end of the existing live range defined by the copy.
399       unsigned DefIdx = li_->getDefIndex(UseIdx);
400       const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
401       BHasPHIKill |= DLR->valno->hasPHIKill;
402       assert(DLR->valno->def == DefIdx);
403       if (BHasSubRegs)
404         // Don't know how to update sub-register live intervals.
405         return false;
406       BDeadValNos.push_back(DLR->valno);
407       BExtend[DLR->start] = DLR->end;
408       JoinedCopies.insert(UseMI);
409       // If this is a kill but it's going to be removed, the last use
410       // of the same val# is the new kill.
411       if (UseMO.isKill())
412         BKills.pop_back();
413     }
414   }
415
416   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
417   // simply extend BLR if CopyMI doesn't end the range.
418   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
419
420   // Remove val#'s defined by copies that will be coalesced away.
421   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
422     IntB.removeValNo(BDeadValNos[i]);
423
424   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
425   // is updated. Kills are also updated.
426   VNInfo *ValNo = BValNo;
427   ValNo->def = AValNo->def;
428   ValNo->copy = NULL;
429   for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
430     unsigned Kill = ValNo->kills[j];
431     if (Kill != BLR->end)
432       BKills.push_back(Kill);
433   }
434   ValNo->kills.clear();
435   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
436        AI != AE; ++AI) {
437     if (AI->valno != AValNo) continue;
438     unsigned End = AI->end;
439     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
440     if (EI != BExtend.end())
441       End = EI->second;
442     IntB.addRange(LiveRange(AI->start, End, ValNo));
443
444     // If the IntB live range is assigned to a physical register, and if that
445     // physreg has sub-registers, update their live intervals as well. 
446     if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
447       for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
448         LiveInterval &SRLI = li_->getInterval(*SR);
449         SRLI.MergeInClobberRange(AI->start, End, li_->getVNInfoAllocator());
450       }
451     }
452   }
453   IntB.addKills(ValNo, BKills);
454   ValNo->hasPHIKill = BHasPHIKill;
455
456   DOUT << "   result = "; IntB.print(DOUT, tri_);
457   DOUT << "\n";
458
459   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
460   IntA.removeValNo(AValNo);
461   DOUT << "   result = "; IntA.print(DOUT, tri_);
462   DOUT << "\n";
463
464   ++numCommutes;
465   return true;
466 }
467
468 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
469 /// fallthoughs to SuccMBB.
470 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
471                                   MachineBasicBlock *SuccMBB,
472                                   const TargetInstrInfo *tii_) {
473   if (MBB == SuccMBB)
474     return true;
475   MachineBasicBlock *TBB = 0, *FBB = 0;
476   SmallVector<MachineOperand, 4> Cond;
477   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
478     MBB->isSuccessor(SuccMBB);
479 }
480
481 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
482 /// from a physical register live interval as well as from the live intervals
483 /// of its sub-registers.
484 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
485                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
486   li.removeRange(Start, End, true);
487   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
488     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
489       if (!li_->hasInterval(*SR))
490         continue;
491       LiveInterval &sli = li_->getInterval(*SR);
492       unsigned RemoveEnd = Start;
493       while (RemoveEnd != End) {
494         LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
495         if (LR == sli.end())
496           break;
497         RemoveEnd = (LR->end < End) ? LR->end : End;
498         sli.removeRange(Start, RemoveEnd, true);
499         Start = RemoveEnd;
500       }
501     }
502   }
503 }
504
505 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
506 /// as the copy instruction, trim the live interval to the last use and return
507 /// true.
508 bool
509 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(unsigned CopyIdx,
510                                                     MachineBasicBlock *CopyMBB,
511                                                     LiveInterval &li,
512                                                     const LiveRange *LR) {
513   unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
514   unsigned LastUseIdx;
515   MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
516                                             LastUseIdx);
517   if (LastUse) {
518     MachineInstr *LastUseMI = LastUse->getParent();
519     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
520       // r1024 = op
521       // ...
522       // BB1:
523       //       = r1024
524       //
525       // BB2:
526       // r1025<dead> = r1024<kill>
527       if (MBBStart < LR->end)
528         removeRange(li, MBBStart, LR->end, li_, tri_);
529       return true;
530     }
531
532     // There are uses before the copy, just shorten the live range to the end
533     // of last use.
534     LastUse->setIsKill();
535     removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
536     li.addKill(LR->valno, LastUseIdx+1);
537     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
538     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
539         DstReg == li.reg) {
540       // Last use is itself an identity code.
541       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
542       LastUseMI->getOperand(DeadIdx).setIsDead();
543     }
544     return true;
545   }
546
547   // Is it livein?
548   if (LR->start <= MBBStart && LR->end > MBBStart) {
549     if (LR->start == 0) {
550       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
551       // Live-in to the function but dead. Remove it from entry live-in set.
552       mf_->begin()->removeLiveIn(li.reg);
553     }
554     // FIXME: Shorten intervals in BBs that reaches this BB.
555   }
556
557   return false;
558 }
559
560 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
561 /// computation, replace the copy by rematerialize the definition.
562 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
563                                                        unsigned DstReg,
564                                                        MachineInstr *CopyMI) {
565   unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
566   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
567   assert(SrcLR != SrcInt.end() && "Live range not found!");
568   VNInfo *ValNo = SrcLR->valno;
569   // If other defs can reach uses of this def, then it's not safe to perform
570   // the optimization.
571   if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
572     return false;
573   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
574   const TargetInstrDesc &TID = DefMI->getDesc();
575   if (!TID.isAsCheapAsAMove())
576     return false;
577   if (!DefMI->getDesc().isRematerializable() ||
578       !tii_->isTriviallyReMaterializable(DefMI))
579     return false;
580   bool SawStore = false;
581   if (!DefMI->isSafeToMove(tii_, SawStore))
582     return false;
583
584   unsigned DefIdx = li_->getDefIndex(CopyIdx);
585   const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
586   DLR->valno->copy = NULL;
587   // Don't forget to update sub-register intervals.
588   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
589     for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
590       if (!li_->hasInterval(*SR))
591         continue;
592       DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
593       if (DLR && DLR->valno->copy == CopyMI)
594         DLR->valno->copy = NULL;
595     }
596   }
597
598   // If copy kills the source register, find the last use and propagate
599   // kill.
600   MachineBasicBlock *MBB = CopyMI->getParent();
601   if (CopyMI->killsRegister(SrcInt.reg))
602     TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR);
603
604   MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
605   CopyMI->removeFromParent();
606   tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
607   MachineInstr *NewMI = prior(MII);
608   // CopyMI may have implicit operands, transfer them over to the newly
609   // rematerialized instruction. And update implicit def interval valnos.
610   for (unsigned i = CopyMI->getDesc().getNumOperands(),
611          e = CopyMI->getNumOperands(); i != e; ++i) {
612     MachineOperand &MO = CopyMI->getOperand(i);
613     if (MO.isReg() && MO.isImplicit())
614       NewMI->addOperand(MO);
615     if (MO.isDef() && li_->hasInterval(MO.getReg())) {
616       unsigned Reg = MO.getReg();
617       DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
618       if (DLR && DLR->valno->copy == CopyMI)
619         DLR->valno->copy = NULL;
620     }
621   }
622
623   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
624   MBB->getParent()->DeleteMachineInstr(CopyMI);
625   ReMatCopies.insert(CopyMI);
626   ReMatDefs.insert(DefMI);
627   ++NumReMats;
628   return true;
629 }
630
631 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
632 ///
633 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
634                                               unsigned DstReg) const {
635   MachineBasicBlock *MBB = CopyMI->getParent();
636   const MachineLoop *L = loopInfo->getLoopFor(MBB);
637   if (!L)
638     return false;
639   if (MBB != L->getLoopLatch())
640     return false;
641
642   LiveInterval &LI = li_->getInterval(DstReg);
643   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
644   LiveInterval::const_iterator DstLR =
645     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
646   if (DstLR == LI.end())
647     return false;
648   unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
649   if (DstLR->valno->kills.size() == 1 &&
650       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
651     return true;
652   return false;
653 }
654
655 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
656 /// update the subregister number if it is not zero. If DstReg is a
657 /// physical register and the existing subregister number of the def / use
658 /// being updated is not zero, make sure to set it to the correct physical
659 /// subregister.
660 void
661 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
662                                             unsigned SubIdx) {
663   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
664   if (DstIsPhys && SubIdx) {
665     // Figure out the real physical register we are updating with.
666     DstReg = tri_->getSubReg(DstReg, SubIdx);
667     SubIdx = 0;
668   }
669
670   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
671          E = mri_->reg_end(); I != E; ) {
672     MachineOperand &O = I.getOperand();
673     MachineInstr *UseMI = &*I;
674     ++I;
675     unsigned OldSubIdx = O.getSubReg();
676     if (DstIsPhys) {
677       unsigned UseDstReg = DstReg;
678       if (OldSubIdx)
679           UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
680
681       unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
682       if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
683                             CopySrcSubIdx, CopyDstSubIdx) &&
684           CopySrcReg != CopyDstReg &&
685           CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
686         // If the use is a copy and it won't be coalesced away, and its source
687         // is defined by a trivial computation, try to rematerialize it instead.
688         if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
689           continue;
690       }
691
692       O.setReg(UseDstReg);
693       O.setSubReg(0);
694       continue;
695     }
696
697     // Sub-register indexes goes from small to large. e.g.
698     // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
699     // EAX: 1 -> AL, 2 -> AX
700     // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
701     // sub-register 2 is also AX.
702     if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
703       assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
704     else if (SubIdx)
705       O.setSubReg(SubIdx);
706     // Remove would-be duplicated kill marker.
707     if (O.isKill() && UseMI->killsRegister(DstReg))
708       O.setIsKill(false);
709     O.setReg(DstReg);
710
711     // After updating the operand, check if the machine instruction has
712     // become a copy. If so, update its val# information.
713     const TargetInstrDesc &TID = UseMI->getDesc();
714     unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
715     if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
716         tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
717                           CopySrcSubIdx, CopyDstSubIdx) &&
718         CopySrcReg != CopyDstReg &&
719         (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
720          allocatableRegs_[CopyDstReg])) {
721       LiveInterval &LI = li_->getInterval(CopyDstReg);
722       unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
723       const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
724       if (DLR->valno->def == DefIdx)
725         DLR->valno->copy = UseMI;
726     }
727   }
728 }
729
730 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
731 /// registers due to insert_subreg coalescing. e.g.
732 /// r1024 = op
733 /// r1025 = implicit_def
734 /// r1025 = insert_subreg r1025, r1024
735 ///       = op r1025
736 /// =>
737 /// r1025 = op
738 /// r1025 = implicit_def
739 /// r1025 = insert_subreg r1025, r1025
740 ///       = op r1025
741 void
742 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
743   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
744          E = mri_->reg_end(); I != E; ) {
745     MachineOperand &O = I.getOperand();
746     MachineInstr *DefMI = &*I;
747     ++I;
748     if (!O.isDef())
749       continue;
750     if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
751       continue;
752     if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
753       continue;
754     li_->RemoveMachineInstrFromMaps(DefMI);
755     DefMI->eraseFromParent();
756   }
757 }
758
759 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
760 /// due to live range lengthening as the result of coalescing.
761 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
762                                                       LiveInterval &LI) {
763   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
764          UE = mri_->use_end(); UI != UE; ++UI) {
765     MachineOperand &UseMO = UI.getOperand();
766     if (UseMO.isKill()) {
767       MachineInstr *UseMI = UseMO.getParent();
768       unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
769       if (JoinedCopies.count(UseMI))
770         continue;
771       const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
772       if (!UI || !LI.isKill(UI->valno, UseIdx+1))
773         UseMO.setIsKill(false);
774     }
775   }
776 }
777
778 /// removeIntervalIfEmpty - Check if the live interval of a physical register
779 /// is empty, if so remove it and also remove the empty intervals of its
780 /// sub-registers. Return true if live interval is removed.
781 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
782                                   const TargetRegisterInfo *tri_) {
783   if (li.empty()) {
784     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
785       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
786         if (!li_->hasInterval(*SR))
787           continue;
788         LiveInterval &sli = li_->getInterval(*SR);
789         if (sli.empty())
790           li_->removeInterval(*SR);
791       }
792     li_->removeInterval(li.reg);
793     return true;
794   }
795   return false;
796 }
797
798 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
799 /// Return true if live interval is removed.
800 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
801                                                         MachineInstr *CopyMI) {
802   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
803   LiveInterval::iterator MLR =
804     li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
805   if (MLR == li.end())
806     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
807   unsigned RemoveStart = MLR->start;
808   unsigned RemoveEnd = MLR->end;
809   // Remove the liverange that's defined by this.
810   if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
811     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
812     return removeIntervalIfEmpty(li, li_, tri_);
813   }
814   return false;
815 }
816
817 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
818 /// the val# it defines. If the live interval becomes empty, remove it as well.
819 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
820                                              MachineInstr *DefMI) {
821   unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
822   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
823   if (DefIdx != MLR->valno->def)
824     return false;
825   li.removeValNo(MLR->valno);
826   return removeIntervalIfEmpty(li, li_, tri_);
827 }
828
829 /// PropagateDeadness - Propagate the dead marker to the instruction which
830 /// defines the val#.
831 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
832                               unsigned &LRStart, LiveIntervals *li_,
833                               const TargetRegisterInfo* tri_) {
834   MachineInstr *DefMI =
835     li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
836   if (DefMI && DefMI != CopyMI) {
837     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
838     if (DeadIdx != -1) {
839       DefMI->getOperand(DeadIdx).setIsDead();
840       // A dead def should have a single cycle interval.
841       ++LRStart;
842     }
843   }
844 }
845
846 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
847 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
848 /// ends the live range there. If there isn't another use, then this live range
849 /// is dead. Return true if live interval is removed.
850 bool
851 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
852                                                       MachineInstr *CopyMI) {
853   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
854   if (CopyIdx == 0) {
855     // FIXME: special case: function live in. It can be a general case if the
856     // first instruction index starts at > 0 value.
857     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
858     // Live-in to the function but dead. Remove it from entry live-in set.
859     if (mf_->begin()->isLiveIn(li.reg))
860       mf_->begin()->removeLiveIn(li.reg);
861     const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
862     removeRange(li, LR->start, LR->end, li_, tri_);
863     return removeIntervalIfEmpty(li, li_, tri_);
864   }
865
866   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
867   if (LR == li.end())
868     // Livein but defined by a phi.
869     return false;
870
871   unsigned RemoveStart = LR->start;
872   unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
873   if (LR->end > RemoveEnd)
874     // More uses past this copy? Nothing to do.
875     return false;
876
877   // If there is a last use in the same bb, we can't remove the live range.
878   // Shorten the live interval and return.
879   MachineBasicBlock *CopyMBB = CopyMI->getParent();
880   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
881     return false;
882
883   MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
884   if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
885     // If the live range starts in another mbb and the copy mbb is not a fall
886     // through mbb, then we can only cut the range from the beginning of the
887     // copy mbb.
888     RemoveStart = li_->getMBBStartIdx(CopyMBB) + 1;
889
890   if (LR->valno->def == RemoveStart) {
891     // If the def MI defines the val# and this copy is the only kill of the
892     // val#, then propagate the dead marker.
893     if (li.isOnlyLROfValNo(LR)) {
894       PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
895       ++numDeadValNo;
896     }
897     if (li.isKill(LR->valno, RemoveEnd))
898       li.removeKill(LR->valno, RemoveEnd);
899   }
900
901   removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
902   return removeIntervalIfEmpty(li, li_, tri_);
903 }
904
905 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
906 /// from an implicit def to another register can be coalesced away.
907 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
908                                                      LiveInterval &li,
909                                                      LiveInterval &ImpLi) const{
910   if (!CopyMI->killsRegister(ImpLi.reg))
911     return false;
912   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
913   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
914   if (LR == li.end())
915     return false;
916   if (LR->valno->hasPHIKill)
917     return false;
918   if (LR->valno->def != CopyIdx)
919     return false;
920   // Make sure all of val# uses are copies.
921   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
922          UE = mri_->use_end(); UI != UE;) {
923     MachineInstr *UseMI = &*UI;
924     ++UI;
925     if (JoinedCopies.count(UseMI))
926       continue;
927     unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
928     LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
929     if (ULR == li.end() || ULR->valno != LR->valno)
930       continue;
931     // If the use is not a use, then it's not safe to coalesce the move.
932     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
933     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
934       if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
935           UseMI->getOperand(1).getReg() == li.reg)
936         continue;
937       return false;
938     }
939   }
940   return true;
941 }
942
943
944 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
945 /// def and it is being removed. Turn all copies from this value# into
946 /// identity copies so they will be removed.
947 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
948                                                      VNInfo *VNI) {
949   SmallVector<MachineInstr*, 4> ImpDefs;
950   MachineOperand *LastUse = NULL;
951   unsigned LastUseIdx = li_->getUseIndex(VNI->def);
952   for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
953          RE = mri_->reg_end(); RI != RE;) {
954     MachineOperand *MO = &RI.getOperand();
955     MachineInstr *MI = &*RI;
956     ++RI;
957     if (MO->isDef()) {
958       if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
959         ImpDefs.push_back(MI);
960       }
961       continue;
962     }
963     if (JoinedCopies.count(MI))
964       continue;
965     unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
966     LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
967     if (ULR == li.end() || ULR->valno != VNI)
968       continue;
969     // If the use is a copy, turn it into an identity copy.
970     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
971     if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
972         SrcReg == li.reg) {
973       // Each use MI may have multiple uses of this register. Change them all.
974       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
975         MachineOperand &MO = MI->getOperand(i);
976         if (MO.isReg() && MO.getReg() == li.reg)
977           MO.setReg(DstReg);
978       }
979       JoinedCopies.insert(MI);
980     } else if (UseIdx > LastUseIdx) {
981       LastUseIdx = UseIdx;
982       LastUse = MO;
983     }
984   }
985   if (LastUse) {
986     LastUse->setIsKill();
987     li.addKill(VNI, LastUseIdx+1);
988   } else {
989     // Remove dead implicit_def's.
990     while (!ImpDefs.empty()) {
991       MachineInstr *ImpDef = ImpDefs.back();
992       ImpDefs.pop_back();
993       li_->RemoveMachineInstrFromMaps(ImpDef);
994       ImpDef->eraseFromParent();
995     }
996   }
997 }
998
999 /// getMatchingSuperReg - Return a super-register of the specified register
1000 /// Reg so its sub-register of index SubIdx is Reg.
1001 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx, 
1002                                     const TargetRegisterClass *RC,
1003                                     const TargetRegisterInfo* TRI) {
1004   for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
1005        unsigned SR = *SRs; ++SRs)
1006     if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
1007       return SR;
1008   return 0;
1009 }
1010
1011 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1012 /// two virtual registers from different register classes.
1013 bool
1014 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1015                                                 unsigned SmallReg,
1016                                                 unsigned Threshold) {
1017   // Then make sure the intervals are *short*.
1018   LiveInterval &LargeInt = li_->getInterval(LargeReg);
1019   LiveInterval &SmallInt = li_->getInterval(SmallReg);
1020   unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1021   unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1022   if (SmallSize > Threshold || LargeSize > Threshold)
1023     if ((float)std::distance(mri_->use_begin(SmallReg),
1024                              mri_->use_end()) / SmallSize <
1025         (float)std::distance(mri_->use_begin(LargeReg),
1026                              mri_->use_end()) / LargeSize)
1027       return false;
1028   return true;
1029 }
1030
1031 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1032 /// register with a physical register, check if any of the virtual register
1033 /// operand is a sub-register use or def. If so, make sure it won't result
1034 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1035 /// vr1024 = extract_subreg vr1025, 1
1036 /// ...
1037 /// vr1024 = mov8rr AH
1038 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1039 /// AH does not have a super-reg whose sub-register 1 is AH.
1040 bool
1041 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1042                                                       unsigned VirtReg,
1043                                                       unsigned PhysReg) {
1044   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1045          E = mri_->reg_end(); I != E; ++I) {
1046     MachineOperand &O = I.getOperand();
1047     MachineInstr *MI = &*I;
1048     if (MI == CopyMI || JoinedCopies.count(MI))
1049       continue;
1050     unsigned SubIdx = O.getSubReg();
1051     if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1052       return true;
1053     if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1054       SubIdx = MI->getOperand(2).getImm();
1055       if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1056         return true;
1057       if (O.isDef()) {
1058         unsigned SrcReg = MI->getOperand(1).getReg();
1059         const TargetRegisterClass *RC =
1060           TargetRegisterInfo::isPhysicalRegister(SrcReg)
1061           ? tri_->getPhysicalRegisterRegClass(SrcReg)
1062           : mri_->getRegClass(SrcReg);
1063         if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1064           return true;
1065       }
1066     }
1067     if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1068       SubIdx = MI->getOperand(3).getImm();
1069       if (VirtReg == MI->getOperand(0).getReg()) {
1070         if (!tri_->getSubReg(PhysReg, SubIdx))
1071           return true;
1072       } else {
1073         unsigned DstReg = MI->getOperand(0).getReg();
1074         const TargetRegisterClass *RC =
1075           TargetRegisterInfo::isPhysicalRegister(DstReg)
1076           ? tri_->getPhysicalRegisterRegClass(DstReg)
1077           : mri_->getRegClass(DstReg);
1078         if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1079           return true;
1080       }
1081     }
1082   }
1083   return false;
1084 }
1085
1086
1087 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1088 /// an extract_subreg where dst is a physical register, e.g.
1089 /// cl = EXTRACT_SUBREG reg1024, 1
1090 bool
1091 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1092                                                unsigned SrcReg, unsigned SubIdx,
1093                                                unsigned &RealDstReg) {
1094   const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1095   RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
1096   assert(RealDstReg && "Invalid extract_subreg instruction!");
1097
1098   // For this type of EXTRACT_SUBREG, conservatively
1099   // check if the live interval of the source register interfere with the
1100   // actual super physical register we are trying to coalesce with.
1101   LiveInterval &RHS = li_->getInterval(SrcReg);
1102   if (li_->hasInterval(RealDstReg) &&
1103       RHS.overlaps(li_->getInterval(RealDstReg))) {
1104     DOUT << "Interfere with register ";
1105     DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
1106     return false; // Not coalescable
1107   }
1108   for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1109     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1110       DOUT << "Interfere with sub-register ";
1111       DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1112       return false; // Not coalescable
1113     }
1114   return true;
1115 }
1116
1117 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1118 /// an insert_subreg where src is a physical register, e.g.
1119 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1120 bool
1121 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1122                                                unsigned SrcReg, unsigned SubIdx,
1123                                                unsigned &RealSrcReg) {
1124   const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1125   RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
1126   assert(RealSrcReg && "Invalid extract_subreg instruction!");
1127
1128   LiveInterval &RHS = li_->getInterval(DstReg);
1129   if (li_->hasInterval(RealSrcReg) &&
1130       RHS.overlaps(li_->getInterval(RealSrcReg))) {
1131     DOUT << "Interfere with register ";
1132     DEBUG(li_->getInterval(RealSrcReg).print(DOUT, tri_));
1133     return false; // Not coalescable
1134   }
1135   for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1136     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1137       DOUT << "Interfere with sub-register ";
1138       DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1139       return false; // Not coalescable
1140     }
1141   return true;
1142 }
1143
1144 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1145 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1146 /// if the copy was successfully coalesced away. If it is not currently
1147 /// possible to coalesce this interval, but it may be possible if other
1148 /// things get coalesced, then it returns true by reference in 'Again'.
1149 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1150   MachineInstr *CopyMI = TheCopy.MI;
1151
1152   Again = false;
1153   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1154     return false; // Already done.
1155
1156   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1157
1158   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1159   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1160   bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1161   unsigned SubIdx = 0;
1162   if (isExtSubReg) {
1163     DstReg = CopyMI->getOperand(0).getReg();
1164     SrcReg = CopyMI->getOperand(1).getReg();
1165   } else if (isInsSubReg) {
1166     if (CopyMI->getOperand(2).getSubReg()) {
1167       DOUT << "\tSource of insert_subreg is already coalesced "
1168            << "to another register.\n";
1169       return false;  // Not coalescable.
1170     }
1171     DstReg = CopyMI->getOperand(0).getReg();
1172     SrcReg = CopyMI->getOperand(2).getReg();
1173   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1174     assert(0 && "Unrecognized copy instruction!");
1175     return false;
1176   }
1177
1178   // If they are already joined we continue.
1179   if (SrcReg == DstReg) {
1180     DOUT << "\tCopy already coalesced.\n";
1181     return false;  // Not coalescable.
1182   }
1183   
1184   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1185   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1186
1187   // If they are both physical registers, we cannot join them.
1188   if (SrcIsPhys && DstIsPhys) {
1189     DOUT << "\tCan not coalesce physregs.\n";
1190     return false;  // Not coalescable.
1191   }
1192   
1193   // We only join virtual registers with allocatable physical registers.
1194   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1195     DOUT << "\tSrc reg is unallocatable physreg.\n";
1196     return false;  // Not coalescable.
1197   }
1198   if (DstIsPhys && !allocatableRegs_[DstReg]) {
1199     DOUT << "\tDst reg is unallocatable physreg.\n";
1200     return false;  // Not coalescable.
1201   }
1202
1203   // Should be non-null only when coalescing to a sub-register class.
1204   bool CrossRC = false;
1205   const TargetRegisterClass *NewRC = NULL;
1206   MachineBasicBlock *CopyMBB = CopyMI->getParent();
1207   unsigned RealDstReg = 0;
1208   unsigned RealSrcReg = 0;
1209   if (isExtSubReg || isInsSubReg) {
1210     SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1211     if (SrcIsPhys && isExtSubReg) {
1212       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1213       // coalesced with AX.
1214       unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1215       if (DstSubIdx) {
1216         // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1217         // coalesced to a larger register so the subreg indices cancel out.
1218         if (DstSubIdx != SubIdx) {
1219           DOUT << "\t Sub-register indices mismatch.\n";
1220           return false; // Not coalescable.
1221         }
1222       } else
1223         SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1224       SubIdx = 0;
1225     } else if (DstIsPhys && isInsSubReg) {
1226       // EAX = INSERT_SUBREG EAX, r1024, 0
1227       unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1228       if (SrcSubIdx) {
1229         // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1230         // coalesced to a larger register so the subreg indices cancel out.
1231         if (SrcSubIdx != SubIdx) {
1232           DOUT << "\t Sub-register indices mismatch.\n";
1233           return false; // Not coalescable.
1234         }
1235       } else
1236         DstReg = tri_->getSubReg(DstReg, SubIdx);
1237       SubIdx = 0;
1238     } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
1239       if (CopyMI->getOperand(1).getSubReg()) {
1240         DOUT << "\tSrc of extract_subreg already coalesced with reg"
1241              << " of a super-class.\n";
1242         return false; // Not coalescable.
1243       }
1244
1245       if (isExtSubReg) {
1246         if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1247           return false; // Not coalescable
1248       } else {
1249         if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1250           return false; // Not coalescable
1251       }
1252       SubIdx = 0;
1253     } else {
1254       unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1255         : CopyMI->getOperand(2).getSubReg();
1256       if (OldSubIdx) {
1257         if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1258           // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1259           // coalesced to a larger register so the subreg indices cancel out.
1260           // Also check if the other larger register is of the same register
1261           // class as the would be resulting register.
1262           SubIdx = 0;
1263         else {
1264           DOUT << "\t Sub-register indices mismatch.\n";
1265           return false; // Not coalescable.
1266         }
1267       }
1268       if (SubIdx) {
1269         unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1270         unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1271         unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1272         if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1273           Again = true;  // May be possible to coalesce later.
1274           return false;
1275         }
1276       }
1277     }
1278   } else if (differingRegisterClasses(SrcReg, DstReg)) {
1279     if (!CrossClassJoin)
1280       return false;
1281     CrossRC = true;
1282
1283     // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1284     // with another? If it's the resulting destination register, then
1285     // the subidx must be propagated to uses (but only those defined
1286     // by the EXTRACT_SUBREG). If it's being coalesced into another
1287     // register, it should be safe because register is assumed to have
1288     // the register class of the super-register.
1289
1290     // Process moves where one of the registers have a sub-register index.
1291     MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1292     if (DstMO->getSubReg())
1293       // FIXME: Can we handle this?
1294       return false;
1295     MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1296     SubIdx = SrcMO->getSubReg();
1297     if (SubIdx) {
1298       // This is not a extract_subreg but it looks like one.
1299       // e.g. %cl = MOV16rr %reg1024:2
1300       isExtSubReg = true;
1301       if (DstIsPhys) {
1302         if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1303           return false; // Not coalescable
1304         SubIdx = 0;
1305       }
1306     }
1307
1308     const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1309     const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1310     unsigned LargeReg = SrcReg;
1311     unsigned SmallReg = DstReg;
1312     unsigned Limit = 0;
1313
1314     // Now determine the register class of the joined register.
1315     if (isExtSubReg) {
1316       if (SubIdx && DstRC && DstRC->isASubClass()) {
1317         // This is a move to a sub-register class. However, the source is a
1318         // sub-register of a larger register class. We don't know what should
1319         // the register class be. FIXME.
1320         Again = true;
1321         return false;
1322       }
1323       Limit = allocatableRCRegs_[DstRC].count();
1324     } else if (!SrcIsPhys && !SrcIsPhys) {
1325       unsigned SrcSize = SrcRC->getSize();
1326       unsigned DstSize = DstRC->getSize();
1327       if (SrcSize < DstSize)
1328         // For example X86::MOVSD2PDrr copies from FR64 to VR128.
1329         NewRC = DstRC;
1330       else if (DstSize > SrcSize) {
1331         NewRC = SrcRC;
1332         std::swap(LargeReg, SmallReg);
1333       } else {
1334         unsigned SrcNumRegs = SrcRC->getNumRegs();
1335         unsigned DstNumRegs = DstRC->getNumRegs();
1336         if (DstNumRegs < SrcNumRegs)
1337           // Sub-register class?
1338           NewRC = DstRC;
1339         else if (SrcNumRegs < DstNumRegs) {
1340           NewRC = SrcRC;
1341           std::swap(LargeReg, SmallReg);
1342         } else
1343           // No idea what's the right register class to use.
1344           return false;
1345       }
1346     }
1347
1348     // If we are joining two virtual registers and the resulting register
1349     // class is more restrictive (fewer register, smaller size). Check if it's
1350     // worth doing the merge.
1351     if (!SrcIsPhys && !DstIsPhys &&
1352         (isExtSubReg || DstRC->isASubClass()) &&
1353         !isWinToJoinCrossClass(LargeReg, SmallReg,
1354                                allocatableRCRegs_[NewRC].count())) {
1355       DOUT << "\tSrc/Dest are different register classes.\n";
1356       // Allow the coalescer to try again in case either side gets coalesced to
1357       // a physical register that's compatible with the other side. e.g.
1358       // r1024 = MOV32to32_ r1025
1359       // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1360       Again = true;  // May be possible to coalesce later.
1361       return false;
1362     }
1363   }
1364
1365   // Will it create illegal extract_subreg / insert_subreg?
1366   if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1367     return false;
1368   if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1369     return false;
1370   
1371   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1372   LiveInterval &DstInt = li_->getInterval(DstReg);
1373   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1374          "Register mapping is horribly broken!");
1375
1376   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1377   DOUT << " and "; DstInt.print(DOUT, tri_);
1378   DOUT << ": ";
1379
1380   // Save a copy of the virtual register live interval. We'll manually
1381   // merge this into the "real" physical register live interval this is
1382   // coalesced with.
1383   LiveInterval *SavedLI = 0;
1384   if (RealDstReg)
1385     SavedLI = li_->dupInterval(&SrcInt);
1386   else if (RealSrcReg)
1387     SavedLI = li_->dupInterval(&DstInt);
1388
1389   // Check if it is necessary to propagate "isDead" property.
1390   if (!isExtSubReg && !isInsSubReg) {
1391     MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1392     bool isDead = mopd->isDead();
1393
1394     // We need to be careful about coalescing a source physical register with a
1395     // virtual register. Once the coalescing is done, it cannot be broken and
1396     // these are not spillable! If the destination interval uses are far away,
1397     // think twice about coalescing them!
1398     if (!isDead && (SrcIsPhys || DstIsPhys)) {
1399       LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1400       unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1401       unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1402       const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1403       unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1404       if (TheCopy.isBackEdge)
1405         Threshold *= 2; // Favors back edge copies.
1406
1407       // If the virtual register live interval is long but it has low use desity,
1408       // do not join them, instead mark the physical register as its allocation
1409       // preference.
1410       unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1411       if (Length > Threshold &&
1412           (((float)std::distance(mri_->use_begin(JoinVReg), mri_->use_end())
1413             / Length) < (1.0 / Threshold))) {
1414         JoinVInt.preference = JoinPReg;
1415         ++numAborts;
1416         DOUT << "\tMay tie down a physical register, abort!\n";
1417         Again = true;  // May be possible to coalesce later.
1418         return false;
1419       }
1420     }
1421   }
1422
1423   // Okay, attempt to join these two intervals.  On failure, this returns false.
1424   // Otherwise, if one of the intervals being joined is a physreg, this method
1425   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1426   // been modified, so we can use this information below to update aliases.
1427   bool Swapped = false;
1428   // If SrcInt is implicitly defined, it's safe to coalesce.
1429   bool isEmpty = SrcInt.empty();
1430   if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1431     // Only coalesce an empty interval (defined by implicit_def) with
1432     // another interval which has a valno defined by the CopyMI and the CopyMI
1433     // is a kill of the implicit def.
1434     DOUT << "Not profitable!\n";
1435     return false;
1436   }
1437
1438   if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1439     // Coalescing failed.
1440
1441     // If definition of source is defined by trivial computation, try
1442     // rematerializing it.
1443     if (!isExtSubReg && !isInsSubReg &&
1444         ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1445       return true;
1446     
1447     // If we can eliminate the copy without merging the live ranges, do so now.
1448     if (!isExtSubReg && !isInsSubReg &&
1449         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1450          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1451       JoinedCopies.insert(CopyMI);
1452       return true;
1453     }
1454     
1455     // Otherwise, we are unable to join the intervals.
1456     DOUT << "Interference!\n";
1457     Again = true;  // May be possible to coalesce later.
1458     return false;
1459   }
1460
1461   LiveInterval *ResSrcInt = &SrcInt;
1462   LiveInterval *ResDstInt = &DstInt;
1463   if (Swapped) {
1464     std::swap(SrcReg, DstReg);
1465     std::swap(ResSrcInt, ResDstInt);
1466   }
1467   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1468          "LiveInterval::join didn't work right!");
1469                                
1470   // If we're about to merge live ranges into a physical register live interval,
1471   // we have to update any aliased register's live ranges to indicate that they
1472   // have clobbered values for this range.
1473   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1474     // If this is a extract_subreg where dst is a physical register, e.g.
1475     // cl = EXTRACT_SUBREG reg1024, 1
1476     // then create and update the actual physical register allocated to RHS.
1477     if (RealDstReg || RealSrcReg) {
1478       LiveInterval &RealInt =
1479         li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1480       for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1481              E = SavedLI->vni_end(); I != E; ++I) {
1482         const VNInfo *ValNo = *I;
1483         VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->copy,
1484                                                 li_->getVNInfoAllocator());
1485         NewValNo->hasPHIKill = ValNo->hasPHIKill;
1486         NewValNo->redefByEC = ValNo->redefByEC;
1487         RealInt.addKills(NewValNo, ValNo->kills);
1488         RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1489       }
1490       RealInt.weight += SavedLI->weight;      
1491       DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1492     }
1493
1494     // Update the liveintervals of sub-registers.
1495     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1496       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1497                                                  li_->getVNInfoAllocator());
1498   }
1499
1500   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1501   // larger super-register.
1502   if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1503     if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1504       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1505       std::swap(SrcReg, DstReg);
1506       std::swap(ResSrcInt, ResDstInt);
1507     }
1508   }
1509
1510   // Coalescing to a virtual register that is of a sub-register class of the
1511   // other. Make sure the resulting register is set to the right register class.
1512   if (CrossRC) {
1513       ++numCrossRCs;
1514     if (NewRC)
1515       mri_->setRegClass(DstReg, NewRC);
1516   }
1517
1518   if (NewHeuristic) {
1519     // Add all copies that define val# in the source interval into the queue.
1520     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1521            e = ResSrcInt->vni_end(); i != e; ++i) {
1522       const VNInfo *vni = *i;
1523       if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1524         continue;
1525       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1526       unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx;
1527       if (CopyMI &&
1528           JoinedCopies.count(CopyMI) == 0 &&
1529           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg,
1530                             NewSrcSubIdx, NewDstSubIdx)) {
1531         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1532         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1533                                 isBackEdgeCopy(CopyMI, DstReg)));
1534       }
1535     }
1536   }
1537
1538   // Remember to delete the copy instruction.
1539   JoinedCopies.insert(CopyMI);
1540
1541   // Some live range has been lengthened due to colaescing, eliminate the
1542   // unnecessary kills.
1543   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1544   if (TargetRegisterInfo::isVirtualRegister(DstReg))
1545     RemoveUnnecessaryKills(DstReg, *ResDstInt);
1546
1547   if (isInsSubReg)
1548     // Avoid:
1549     // r1024 = op
1550     // r1024 = implicit_def
1551     // ...
1552     //       = r1024
1553     RemoveDeadImpDef(DstReg, *ResDstInt);
1554   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1555
1556   // SrcReg is guarateed to be the register whose live interval that is
1557   // being merged.
1558   li_->removeInterval(SrcReg);
1559
1560   // Manually deleted the live interval copy.
1561   if (SavedLI) {
1562     SavedLI->clear();
1563     delete SavedLI;
1564   }
1565
1566   if (isEmpty) {
1567     // Now the copy is being coalesced away, the val# previously defined
1568     // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1569     // length interval. Remove the val#.
1570     unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1571     const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1572     VNInfo *ImpVal = LR->valno;
1573     assert(ImpVal->def == CopyIdx);
1574     unsigned NextDef = LR->end;
1575     RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1576     ResDstInt->removeValNo(ImpVal);
1577     LR = ResDstInt->FindLiveRangeContaining(NextDef);
1578     if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1579       // Special case: vr1024 = implicit_def
1580       //               vr1024 = insert_subreg vr1024, vr1025, c
1581       // The insert_subreg becomes a "copy" that defines a val# which can itself
1582       // be coalesced away.
1583       MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1584       if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1585         LR->valno->copy = DefMI;
1586     }
1587   }
1588
1589   // If resulting interval has a preference that no longer fits because of subreg
1590   // coalescing, just clear the preference.
1591   if (ResDstInt->preference && (isExtSubReg || isInsSubReg) &&
1592       TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1593     const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1594     if (!RC->contains(ResDstInt->preference))
1595       ResDstInt->preference = 0;
1596   }
1597
1598   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
1599   DOUT << "\n";
1600
1601   ++numJoins;
1602   return true;
1603 }
1604
1605 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1606 /// compute what the resultant value numbers for each value in the input two
1607 /// ranges will be.  This is complicated by copies between the two which can
1608 /// and will commonly cause multiple value numbers to be merged into one.
1609 ///
1610 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1611 /// keeps track of the new InstDefiningValue assignment for the result
1612 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1613 /// whether a value in this or other is a copy from the opposite set.
1614 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1615 /// already been assigned.
1616 ///
1617 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1618 /// contains the value number the copy is from.
1619 ///
1620 static unsigned ComputeUltimateVN(VNInfo *VNI,
1621                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1622                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1623                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1624                                   SmallVector<int, 16> &ThisValNoAssignments,
1625                                   SmallVector<int, 16> &OtherValNoAssignments) {
1626   unsigned VN = VNI->id;
1627
1628   // If the VN has already been computed, just return it.
1629   if (ThisValNoAssignments[VN] >= 0)
1630     return ThisValNoAssignments[VN];
1631 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1632
1633   // If this val is not a copy from the other val, then it must be a new value
1634   // number in the destination.
1635   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1636   if (I == ThisFromOther.end()) {
1637     NewVNInfo.push_back(VNI);
1638     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1639   }
1640   VNInfo *OtherValNo = I->second;
1641
1642   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1643   // been computed, return it.
1644   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1645     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1646   
1647   // Mark this value number as currently being computed, then ask what the
1648   // ultimate value # of the other value is.
1649   ThisValNoAssignments[VN] = -2;
1650   unsigned UltimateVN =
1651     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1652                       OtherValNoAssignments, ThisValNoAssignments);
1653   return ThisValNoAssignments[VN] = UltimateVN;
1654 }
1655
1656 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1657   return std::find(V.begin(), V.end(), Val) != V.end();
1658 }
1659
1660 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1661 /// the specified live interval is defined by a copy from the specified
1662 /// register.
1663 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1664                                                            LiveRange *LR,
1665                                                            unsigned Reg) {
1666   unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1667   if (SrcReg == Reg)
1668     return true;
1669   if (LR->valno->def == ~0U &&
1670       TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1671       *tri_->getSuperRegisters(li.reg)) {
1672     // It's a sub-register live interval, we may not have precise information.
1673     // Re-compute it.
1674     MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1675     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1676     if (DefMI &&
1677         tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1678         DstReg == li.reg && SrcReg == Reg) {
1679       // Cache computed info.
1680       LR->valno->def  = LR->start;
1681       LR->valno->copy = DefMI;
1682       return true;
1683     }
1684   }
1685   return false;
1686 }
1687
1688 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1689 /// caller of this method must guarantee that the RHS only contains a single
1690 /// value number and that the RHS is not defined by a copy from this
1691 /// interval.  This returns false if the intervals are not joinable, or it
1692 /// joins them and returns true.
1693 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1694   assert(RHS.containsOneValue());
1695   
1696   // Some number (potentially more than one) value numbers in the current
1697   // interval may be defined as copies from the RHS.  Scan the overlapping
1698   // portions of the LHS and RHS, keeping track of this and looking for
1699   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1700   // cannot coalesce.
1701   
1702   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1703   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1704   
1705   if (LHSIt->start < RHSIt->start) {
1706     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1707     if (LHSIt != LHS.begin()) --LHSIt;
1708   } else if (RHSIt->start < LHSIt->start) {
1709     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1710     if (RHSIt != RHS.begin()) --RHSIt;
1711   }
1712   
1713   SmallVector<VNInfo*, 8> EliminatedLHSVals;
1714   
1715   while (1) {
1716     // Determine if these live intervals overlap.
1717     bool Overlaps = false;
1718     if (LHSIt->start <= RHSIt->start)
1719       Overlaps = LHSIt->end > RHSIt->start;
1720     else
1721       Overlaps = RHSIt->end > LHSIt->start;
1722     
1723     // If the live intervals overlap, there are two interesting cases: if the
1724     // LHS interval is defined by a copy from the RHS, it's ok and we record
1725     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1726     // coalesce these live ranges and we bail out.
1727     if (Overlaps) {
1728       // If we haven't already recorded that this value # is safe, check it.
1729       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1730         // Copy from the RHS?
1731         if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1732           return false;    // Nope, bail out.
1733
1734         if (LHSIt->contains(RHSIt->valno->def))
1735           // Here is an interesting situation:
1736           // BB1:
1737           //   vr1025 = copy vr1024
1738           //   ..
1739           // BB2:
1740           //   vr1024 = op 
1741           //          = vr1025
1742           // Even though vr1025 is copied from vr1024, it's not safe to
1743           // coalesced them since live range of vr1025 intersects the
1744           // def of vr1024. This happens because vr1025 is assigned the
1745           // value of the previous iteration of vr1024.
1746           return false;
1747         EliminatedLHSVals.push_back(LHSIt->valno);
1748       }
1749       
1750       // We know this entire LHS live range is okay, so skip it now.
1751       if (++LHSIt == LHSEnd) break;
1752       continue;
1753     }
1754     
1755     if (LHSIt->end < RHSIt->end) {
1756       if (++LHSIt == LHSEnd) break;
1757     } else {
1758       // One interesting case to check here.  It's possible that we have
1759       // something like "X3 = Y" which defines a new value number in the LHS,
1760       // and is the last use of this liverange of the RHS.  In this case, we
1761       // want to notice this copy (so that it gets coalesced away) even though
1762       // the live ranges don't actually overlap.
1763       if (LHSIt->start == RHSIt->end) {
1764         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1765           // We already know that this value number is going to be merged in
1766           // if coalescing succeeds.  Just skip the liverange.
1767           if (++LHSIt == LHSEnd) break;
1768         } else {
1769           // Otherwise, if this is a copy from the RHS, mark it as being merged
1770           // in.
1771           if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1772             if (LHSIt->contains(RHSIt->valno->def))
1773               // Here is an interesting situation:
1774               // BB1:
1775               //   vr1025 = copy vr1024
1776               //   ..
1777               // BB2:
1778               //   vr1024 = op 
1779               //          = vr1025
1780               // Even though vr1025 is copied from vr1024, it's not safe to
1781               // coalesced them since live range of vr1025 intersects the
1782               // def of vr1024. This happens because vr1025 is assigned the
1783               // value of the previous iteration of vr1024.
1784               return false;
1785             EliminatedLHSVals.push_back(LHSIt->valno);
1786
1787             // We know this entire LHS live range is okay, so skip it now.
1788             if (++LHSIt == LHSEnd) break;
1789           }
1790         }
1791       }
1792       
1793       if (++RHSIt == RHSEnd) break;
1794     }
1795   }
1796   
1797   // If we got here, we know that the coalescing will be successful and that
1798   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1799   // the most common case is that EliminatedLHSVals has a single number, we
1800   // optimize for it: if there is more than one value, we merge them all into
1801   // the lowest numbered one, then handle the interval as if we were merging
1802   // with one value number.
1803   VNInfo *LHSValNo = NULL;
1804   if (EliminatedLHSVals.size() > 1) {
1805     // Loop through all the equal value numbers merging them into the smallest
1806     // one.
1807     VNInfo *Smallest = EliminatedLHSVals[0];
1808     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1809       if (EliminatedLHSVals[i]->id < Smallest->id) {
1810         // Merge the current notion of the smallest into the smaller one.
1811         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1812         Smallest = EliminatedLHSVals[i];
1813       } else {
1814         // Merge into the smallest.
1815         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1816       }
1817     }
1818     LHSValNo = Smallest;
1819   } else if (EliminatedLHSVals.empty()) {
1820     if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1821         *tri_->getSuperRegisters(LHS.reg))
1822       // Imprecise sub-register information. Can't handle it.
1823       return false;
1824     assert(0 && "No copies from the RHS?");
1825   } else {
1826     LHSValNo = EliminatedLHSVals[0];
1827   }
1828   
1829   // Okay, now that there is a single LHS value number that we're merging the
1830   // RHS into, update the value number info for the LHS to indicate that the
1831   // value number is defined where the RHS value number was.
1832   const VNInfo *VNI = RHS.getValNumInfo(0);
1833   LHSValNo->def  = VNI->def;
1834   LHSValNo->copy = VNI->copy;
1835   
1836   // Okay, the final step is to loop over the RHS live intervals, adding them to
1837   // the LHS.
1838   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1839   LHS.addKills(LHSValNo, VNI->kills);
1840   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1841   LHS.weight += RHS.weight;
1842   if (RHS.preference && !LHS.preference)
1843     LHS.preference = RHS.preference;
1844   
1845   return true;
1846 }
1847
1848 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1849 /// returns false.  Otherwise, if one of the intervals being joined is a
1850 /// physreg, this method always canonicalizes LHS to be it.  The output
1851 /// "RHS" will not have been modified, so we can use this information
1852 /// below to update aliases.
1853 bool
1854 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
1855                                         bool &Swapped) {
1856   // Compute the final value assignment, assuming that the live ranges can be
1857   // coalesced.
1858   SmallVector<int, 16> LHSValNoAssignments;
1859   SmallVector<int, 16> RHSValNoAssignments;
1860   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1861   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1862   SmallVector<VNInfo*, 16> NewVNInfo;
1863
1864   // If a live interval is a physical register, conservatively check if any
1865   // of its sub-registers is overlapping the live interval of the virtual
1866   // register. If so, do not coalesce.
1867   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1868       *tri_->getSubRegisters(LHS.reg)) {
1869     // If it's coalescing a virtual register to a physical register, estimate
1870     // its live interval length. This is the *cost* of scanning an entire live
1871     // interval. If the cost is low, we'll do an exhaustive check instead.
1872
1873     // If this is something like this:
1874     // BB1:
1875     // v1024 = op
1876     // ...
1877     // BB2:
1878     // ...
1879     // RAX   = v1024
1880     //
1881     // That is, the live interval of v1024 crosses a bb. Then we can't rely on
1882     // less conservative check. It's possible a sub-register is defined before
1883     // v1024 (or live in) and live out of BB1.
1884     if (RHS.containsOneValue() &&
1885         li_->intervalIsInOneMBB(RHS) &&
1886         li_->getApproximateInstructionCount(RHS) <= 10) {
1887       // Perform a more exhaustive check for some common cases.
1888       if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
1889         return false;
1890     } else {
1891       for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1892         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1893           DOUT << "Interfere with sub-register ";
1894           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1895           return false;
1896         }
1897     }
1898   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1899              *tri_->getSubRegisters(RHS.reg)) {
1900     if (LHS.containsOneValue() &&
1901         li_->getApproximateInstructionCount(LHS) <= 10) {
1902       // Perform a more exhaustive check for some common cases.
1903       if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
1904         return false;
1905     } else {
1906       for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1907         if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1908           DOUT << "Interfere with sub-register ";
1909           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1910           return false;
1911         }
1912     }
1913   }
1914                           
1915   // Compute ultimate value numbers for the LHS and RHS values.
1916   if (RHS.containsOneValue()) {
1917     // Copies from a liveinterval with a single value are simple to handle and
1918     // very common, handle the special case here.  This is important, because
1919     // often RHS is small and LHS is large (e.g. a physreg).
1920     
1921     // Find out if the RHS is defined as a copy from some value in the LHS.
1922     int RHSVal0DefinedFromLHS = -1;
1923     int RHSValID = -1;
1924     VNInfo *RHSValNoInfo = NULL;
1925     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1926     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1927     if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
1928       // If RHS is not defined as a copy from the LHS, we can use simpler and
1929       // faster checks to see if the live ranges are coalescable.  This joiner
1930       // can't swap the LHS/RHS intervals though.
1931       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1932         return SimpleJoin(LHS, RHS);
1933       } else {
1934         RHSValNoInfo = RHSValNoInfo0;
1935       }
1936     } else {
1937       // It was defined as a copy from the LHS, find out what value # it is.
1938       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1939       RHSValID = RHSValNoInfo->id;
1940       RHSVal0DefinedFromLHS = RHSValID;
1941     }
1942     
1943     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1944     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1945     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1946     
1947     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1948     // should now get updated.
1949     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1950          i != e; ++i) {
1951       VNInfo *VNI = *i;
1952       unsigned VN = VNI->id;
1953       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1954         if (LHSSrcReg != RHS.reg) {
1955           // If this is not a copy from the RHS, its value number will be
1956           // unmodified by the coalescing.
1957           NewVNInfo[VN] = VNI;
1958           LHSValNoAssignments[VN] = VN;
1959         } else if (RHSValID == -1) {
1960           // Otherwise, it is a copy from the RHS, and we don't already have a
1961           // value# for it.  Keep the current value number, but remember it.
1962           LHSValNoAssignments[VN] = RHSValID = VN;
1963           NewVNInfo[VN] = RHSValNoInfo;
1964           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1965         } else {
1966           // Otherwise, use the specified value #.
1967           LHSValNoAssignments[VN] = RHSValID;
1968           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1969             NewVNInfo[VN] = RHSValNoInfo;
1970             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1971           }
1972         }
1973       } else {
1974         NewVNInfo[VN] = VNI;
1975         LHSValNoAssignments[VN] = VN;
1976       }
1977     }
1978     
1979     assert(RHSValID != -1 && "Didn't find value #?");
1980     RHSValNoAssignments[0] = RHSValID;
1981     if (RHSVal0DefinedFromLHS != -1) {
1982       // This path doesn't go through ComputeUltimateVN so just set
1983       // it to anything.
1984       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1985     }
1986   } else {
1987     // Loop over the value numbers of the LHS, seeing if any are defined from
1988     // the RHS.
1989     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1990          i != e; ++i) {
1991       VNInfo *VNI = *i;
1992       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1993         continue;
1994       
1995       // DstReg is known to be a register in the LHS interval.  If the src is
1996       // from the RHS interval, we can use its value #.
1997       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1998         continue;
1999       
2000       // Figure out the value # from the RHS.
2001       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
2002     }
2003     
2004     // Loop over the value numbers of the RHS, seeing if any are defined from
2005     // the LHS.
2006     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2007          i != e; ++i) {
2008       VNInfo *VNI = *i;
2009       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
2010         continue;
2011       
2012       // DstReg is known to be a register in the RHS interval.  If the src is
2013       // from the LHS interval, we can use its value #.
2014       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2015         continue;
2016       
2017       // Figure out the value # from the LHS.
2018       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
2019     }
2020     
2021     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2022     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2023     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2024     
2025     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2026          i != e; ++i) {
2027       VNInfo *VNI = *i;
2028       unsigned VN = VNI->id;
2029       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
2030         continue;
2031       ComputeUltimateVN(VNI, NewVNInfo,
2032                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2033                         LHSValNoAssignments, RHSValNoAssignments);
2034     }
2035     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2036          i != e; ++i) {
2037       VNInfo *VNI = *i;
2038       unsigned VN = VNI->id;
2039       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
2040         continue;
2041       // If this value number isn't a copy from the LHS, it's a new number.
2042       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2043         NewVNInfo.push_back(VNI);
2044         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2045         continue;
2046       }
2047       
2048       ComputeUltimateVN(VNI, NewVNInfo,
2049                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2050                         RHSValNoAssignments, LHSValNoAssignments);
2051     }
2052   }
2053   
2054   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2055   // interval lists to see if these intervals are coalescable.
2056   LiveInterval::const_iterator I = LHS.begin();
2057   LiveInterval::const_iterator IE = LHS.end();
2058   LiveInterval::const_iterator J = RHS.begin();
2059   LiveInterval::const_iterator JE = RHS.end();
2060   
2061   // Skip ahead until the first place of potential sharing.
2062   if (I->start < J->start) {
2063     I = std::upper_bound(I, IE, J->start);
2064     if (I != LHS.begin()) --I;
2065   } else if (J->start < I->start) {
2066     J = std::upper_bound(J, JE, I->start);
2067     if (J != RHS.begin()) --J;
2068   }
2069   
2070   while (1) {
2071     // Determine if these two live ranges overlap.
2072     bool Overlaps;
2073     if (I->start < J->start) {
2074       Overlaps = I->end > J->start;
2075     } else {
2076       Overlaps = J->end > I->start;
2077     }
2078
2079     // If so, check value # info to determine if they are really different.
2080     if (Overlaps) {
2081       // If the live range overlap will map to the same value number in the
2082       // result liverange, we can still coalesce them.  If not, we can't.
2083       if (LHSValNoAssignments[I->valno->id] !=
2084           RHSValNoAssignments[J->valno->id])
2085         return false;
2086     }
2087     
2088     if (I->end < J->end) {
2089       ++I;
2090       if (I == IE) break;
2091     } else {
2092       ++J;
2093       if (J == JE) break;
2094     }
2095   }
2096
2097   // Update kill info. Some live ranges are extended due to copy coalescing.
2098   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2099          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2100     VNInfo *VNI = I->first;
2101     unsigned LHSValID = LHSValNoAssignments[VNI->id];
2102     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
2103     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
2104     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2105   }
2106
2107   // Update kill info. Some live ranges are extended due to copy coalescing.
2108   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2109          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2110     VNInfo *VNI = I->first;
2111     unsigned RHSValID = RHSValNoAssignments[VNI->id];
2112     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
2113     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
2114     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2115   }
2116
2117   // If we get here, we know that we can coalesce the live ranges.  Ask the
2118   // intervals to coalesce themselves now.
2119   if ((RHS.ranges.size() > LHS.ranges.size() &&
2120       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2121       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2122     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
2123     Swapped = true;
2124   } else {
2125     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
2126     Swapped = false;
2127   }
2128   return true;
2129 }
2130
2131 namespace {
2132   // DepthMBBCompare - Comparison predicate that sort first based on the loop
2133   // depth of the basic block (the unsigned), and then on the MBB number.
2134   struct DepthMBBCompare {
2135     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2136     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2137       if (LHS.first > RHS.first) return true;   // Deeper loops first
2138       return LHS.first == RHS.first &&
2139         LHS.second->getNumber() < RHS.second->getNumber();
2140     }
2141   };
2142 }
2143
2144 /// getRepIntervalSize - Returns the size of the interval that represents the
2145 /// specified register.
2146 template<class SF>
2147 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2148   return Rc->getRepIntervalSize(Reg);
2149 }
2150
2151 /// CopyRecSort::operator - Join priority queue sorting function.
2152 ///
2153 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2154   // Inner loops first.
2155   if (left.LoopDepth > right.LoopDepth)
2156     return false;
2157   else if (left.LoopDepth == right.LoopDepth)
2158     if (left.isBackEdge && !right.isBackEdge)
2159       return false;
2160   return true;
2161 }
2162
2163 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2164                                                std::vector<CopyRec> &TryAgain) {
2165   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
2166
2167   std::vector<CopyRec> VirtCopies;
2168   std::vector<CopyRec> PhysCopies;
2169   std::vector<CopyRec> ImpDefCopies;
2170   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
2171   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2172        MII != E;) {
2173     MachineInstr *Inst = MII++;
2174     
2175     // If this isn't a copy nor a extract_subreg, we can't join intervals.
2176     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2177     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2178       DstReg = Inst->getOperand(0).getReg();
2179       SrcReg = Inst->getOperand(1).getReg();
2180     } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
2181       DstReg = Inst->getOperand(0).getReg();
2182       SrcReg = Inst->getOperand(2).getReg();
2183     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2184       continue;
2185
2186     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2187     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2188     if (NewHeuristic) {
2189       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
2190     } else {
2191       if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2192         ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2193       else if (SrcIsPhys || DstIsPhys)
2194         PhysCopies.push_back(CopyRec(Inst, 0, false));
2195       else
2196         VirtCopies.push_back(CopyRec(Inst, 0, false));
2197     }
2198   }
2199
2200   if (NewHeuristic)
2201     return;
2202
2203   // Try coalescing implicit copies first, followed by copies to / from
2204   // physical registers, then finally copies from virtual registers to
2205   // virtual registers.
2206   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2207     CopyRec &TheCopy = ImpDefCopies[i];
2208     bool Again = false;
2209     if (!JoinCopy(TheCopy, Again))
2210       if (Again)
2211         TryAgain.push_back(TheCopy);
2212   }
2213   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2214     CopyRec &TheCopy = PhysCopies[i];
2215     bool Again = false;
2216     if (!JoinCopy(TheCopy, Again))
2217       if (Again)
2218         TryAgain.push_back(TheCopy);
2219   }
2220   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2221     CopyRec &TheCopy = VirtCopies[i];
2222     bool Again = false;
2223     if (!JoinCopy(TheCopy, Again))
2224       if (Again)
2225         TryAgain.push_back(TheCopy);
2226   }
2227 }
2228
2229 void SimpleRegisterCoalescing::joinIntervals() {
2230   DOUT << "********** JOINING INTERVALS ***********\n";
2231
2232   if (NewHeuristic)
2233     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2234
2235   std::vector<CopyRec> TryAgainList;
2236   if (loopInfo->empty()) {
2237     // If there are no loops in the function, join intervals in function order.
2238     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2239          I != E; ++I)
2240       CopyCoalesceInMBB(I, TryAgainList);
2241   } else {
2242     // Otherwise, join intervals in inner loops before other intervals.
2243     // Unfortunately we can't just iterate over loop hierarchy here because
2244     // there may be more MBB's than BB's.  Collect MBB's for sorting.
2245
2246     // Join intervals in the function prolog first. We want to join physical
2247     // registers with virtual registers before the intervals got too long.
2248     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2249     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2250       MachineBasicBlock *MBB = I;
2251       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2252     }
2253
2254     // Sort by loop depth.
2255     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2256
2257     // Finally, join intervals in loop nest order.
2258     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2259       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2260   }
2261   
2262   // Joining intervals can allow other intervals to be joined.  Iteratively join
2263   // until we make no progress.
2264   if (NewHeuristic) {
2265     SmallVector<CopyRec, 16> TryAgain;
2266     bool ProgressMade = true;
2267     while (ProgressMade) {
2268       ProgressMade = false;
2269       while (!JoinQueue->empty()) {
2270         CopyRec R = JoinQueue->pop();
2271         bool Again = false;
2272         bool Success = JoinCopy(R, Again);
2273         if (Success)
2274           ProgressMade = true;
2275         else if (Again)
2276           TryAgain.push_back(R);
2277       }
2278
2279       if (ProgressMade) {
2280         while (!TryAgain.empty()) {
2281           JoinQueue->push(TryAgain.back());
2282           TryAgain.pop_back();
2283         }
2284       }
2285     }
2286   } else {
2287     bool ProgressMade = true;
2288     while (ProgressMade) {
2289       ProgressMade = false;
2290
2291       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2292         CopyRec &TheCopy = TryAgainList[i];
2293         if (TheCopy.MI) {
2294           bool Again = false;
2295           bool Success = JoinCopy(TheCopy, Again);
2296           if (Success || !Again) {
2297             TheCopy.MI = 0;   // Mark this one as done.
2298             ProgressMade = true;
2299           }
2300         }
2301       }
2302     }
2303   }
2304
2305   if (NewHeuristic)
2306     delete JoinQueue;  
2307 }
2308
2309 /// Return true if the two specified registers belong to different register
2310 /// classes.  The registers may be either phys or virt regs.
2311 bool
2312 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2313                                                    unsigned RegB) const {
2314   // Get the register classes for the first reg.
2315   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2316     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2317            "Shouldn't consider two physregs!");
2318     return !mri_->getRegClass(RegB)->contains(RegA);
2319   }
2320
2321   // Compare against the regclass for the second reg.
2322   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2323   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2324     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2325     return RegClassA != RegClassB;
2326   }
2327   return !RegClassA->contains(RegB);
2328 }
2329
2330 /// lastRegisterUse - Returns the last use of the specific register between
2331 /// cycles Start and End or NULL if there are no uses.
2332 MachineOperand *
2333 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
2334                                           unsigned Reg, unsigned &UseIdx) const{
2335   UseIdx = 0;
2336   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2337     MachineOperand *LastUse = NULL;
2338     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2339            E = mri_->use_end(); I != E; ++I) {
2340       MachineOperand &Use = I.getOperand();
2341       MachineInstr *UseMI = Use.getParent();
2342       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2343       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2344           SrcReg == DstReg)
2345         // Ignore identity copies.
2346         continue;
2347       unsigned Idx = li_->getInstructionIndex(UseMI);
2348       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2349         LastUse = &Use;
2350         UseIdx = li_->getUseIndex(Idx);
2351       }
2352     }
2353     return LastUse;
2354   }
2355
2356   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2357   int s = Start;
2358   while (e >= s) {
2359     // Skip deleted instructions
2360     MachineInstr *MI = li_->getInstructionFromIndex(e);
2361     while ((e - InstrSlots::NUM) >= s && !MI) {
2362       e -= InstrSlots::NUM;
2363       MI = li_->getInstructionFromIndex(e);
2364     }
2365     if (e < s || MI == NULL)
2366       return NULL;
2367
2368     // Ignore identity copies.
2369     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2370     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2371           SrcReg == DstReg))
2372       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2373         MachineOperand &Use = MI->getOperand(i);
2374         if (Use.isReg() && Use.isUse() && Use.getReg() &&
2375             tri_->regsOverlap(Use.getReg(), Reg)) {
2376           UseIdx = li_->getUseIndex(e);
2377           return &Use;
2378         }
2379       }
2380
2381     e -= InstrSlots::NUM;
2382   }
2383
2384   return NULL;
2385 }
2386
2387
2388 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2389   if (TargetRegisterInfo::isPhysicalRegister(reg))
2390     cerr << tri_->getName(reg);
2391   else
2392     cerr << "%reg" << reg;
2393 }
2394
2395 void SimpleRegisterCoalescing::releaseMemory() {
2396   JoinedCopies.clear();
2397   ReMatCopies.clear();
2398   ReMatDefs.clear();
2399 }
2400
2401 static bool isZeroLengthInterval(LiveInterval *li) {
2402   for (LiveInterval::Ranges::const_iterator
2403          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2404     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2405       return false;
2406   return true;
2407 }
2408
2409 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2410 /// turn the copy into an implicit def.
2411 bool
2412 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2413                                              MachineBasicBlock *MBB,
2414                                              unsigned DstReg, unsigned SrcReg) {
2415   MachineInstr *CopyMI = &*I;
2416   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2417   if (!li_->hasInterval(SrcReg))
2418     return false;
2419   LiveInterval &SrcInt = li_->getInterval(SrcReg);
2420   if (!SrcInt.empty())
2421     return false;
2422   if (!li_->hasInterval(DstReg))
2423     return false;
2424   LiveInterval &DstInt = li_->getInterval(DstReg);
2425   const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
2426   DstInt.removeValNo(DstLR->valno);
2427   CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2428   for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2429     CopyMI->RemoveOperand(i);
2430   bool NoUse = mri_->use_empty(SrcReg);
2431   if (NoUse) {
2432     for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2433            E = mri_->reg_end(); I != E; ) {
2434       assert(I.getOperand().isDef());
2435       MachineInstr *DefMI = &*I;
2436       ++I;
2437       // The implicit_def source has no other uses, delete it.
2438       assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2439       li_->RemoveMachineInstrFromMaps(DefMI);
2440       DefMI->eraseFromParent();
2441     }
2442   }
2443   ++I;
2444   return true;
2445 }
2446
2447
2448 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2449   mf_ = &fn;
2450   mri_ = &fn.getRegInfo();
2451   tm_ = &fn.getTarget();
2452   tri_ = tm_->getRegisterInfo();
2453   tii_ = tm_->getInstrInfo();
2454   li_ = &getAnalysis<LiveIntervals>();
2455   loopInfo = &getAnalysis<MachineLoopInfo>();
2456
2457   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2458        << "********** Function: "
2459        << ((Value*)mf_->getFunction())->getName() << '\n';
2460
2461   allocatableRegs_ = tri_->getAllocatableSet(fn);
2462   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2463          E = tri_->regclass_end(); I != E; ++I)
2464     allocatableRCRegs_.insert(std::make_pair(*I,
2465                                              tri_->getAllocatableSet(fn, *I)));
2466
2467   // Join (coalesce) intervals if requested.
2468   if (EnableJoining) {
2469     joinIntervals();
2470     DEBUG({
2471         DOUT << "********** INTERVALS POST JOINING **********\n";
2472         for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2473           I->second->print(DOUT, tri_);
2474           DOUT << "\n";
2475         }
2476       });
2477   }
2478
2479   // Perform a final pass over the instructions and compute spill weights
2480   // and remove identity moves.
2481   SmallVector<unsigned, 4> DeadDefs;
2482   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2483        mbbi != mbbe; ++mbbi) {
2484     MachineBasicBlock* mbb = mbbi;
2485     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2486
2487     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2488          mii != mie; ) {
2489       MachineInstr *MI = mii;
2490       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2491       if (JoinedCopies.count(MI)) {
2492         // Delete all coalesced copies.
2493         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2494           assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2495                   MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2496                  "Unrecognized copy instruction");
2497           DstReg = MI->getOperand(0).getReg();
2498         }
2499         if (MI->registerDefIsDead(DstReg)) {
2500           LiveInterval &li = li_->getInterval(DstReg);
2501           if (!ShortenDeadCopySrcLiveRange(li, MI))
2502             ShortenDeadCopyLiveRange(li, MI);
2503         }
2504         li_->RemoveMachineInstrFromMaps(MI);
2505         mii = mbbi->erase(mii);
2506         ++numPeep;
2507         continue;
2508       }
2509
2510       // Now check if this is a remat'ed def instruction which is now dead.
2511       if (ReMatDefs.count(MI)) {
2512         bool isDead = true;
2513         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2514           const MachineOperand &MO = MI->getOperand(i);
2515           if (!MO.isReg())
2516             continue;
2517           unsigned Reg = MO.getReg();
2518           if (!Reg)
2519             continue;
2520           if (TargetRegisterInfo::isVirtualRegister(Reg))
2521             DeadDefs.push_back(Reg);
2522           if (MO.isDead())
2523             continue;
2524           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2525               !mri_->use_empty(Reg)) {
2526             isDead = false;
2527             break;
2528           }
2529         }
2530         if (isDead) {
2531           while (!DeadDefs.empty()) {
2532             unsigned DeadDef = DeadDefs.back();
2533             DeadDefs.pop_back();
2534             RemoveDeadDef(li_->getInterval(DeadDef), MI);
2535           }
2536           li_->RemoveMachineInstrFromMaps(mii);
2537           mii = mbbi->erase(mii);
2538           continue;
2539         } else
2540           DeadDefs.clear();
2541       }
2542
2543       // If the move will be an identity move delete it
2544       bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2545       if (isMove && SrcReg == DstReg) {
2546         if (li_->hasInterval(SrcReg)) {
2547           LiveInterval &RegInt = li_->getInterval(SrcReg);
2548           // If def of this move instruction is dead, remove its live range
2549           // from the dstination register's live interval.
2550           if (MI->registerDefIsDead(DstReg)) {
2551             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2552               ShortenDeadCopyLiveRange(RegInt, MI);
2553           }
2554         }
2555         li_->RemoveMachineInstrFromMaps(MI);
2556         mii = mbbi->erase(mii);
2557         ++numPeep;
2558       } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2559         SmallSet<unsigned, 4> UniqueUses;
2560         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2561           const MachineOperand &mop = MI->getOperand(i);
2562           if (mop.isReg() && mop.getReg() &&
2563               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2564             unsigned reg = mop.getReg();
2565             // Multiple uses of reg by the same instruction. It should not
2566             // contribute to spill weight again.
2567             if (UniqueUses.count(reg) != 0)
2568               continue;
2569             LiveInterval &RegInt = li_->getInterval(reg);
2570             RegInt.weight +=
2571               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2572             UniqueUses.insert(reg);
2573           }
2574         }
2575         ++mii;
2576       }
2577     }
2578   }
2579
2580   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2581     LiveInterval &LI = *I->second;
2582     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2583       // If the live interval length is essentially zero, i.e. in every live
2584       // range the use follows def immediately, it doesn't make sense to spill
2585       // it and hope it will be easier to allocate for this li.
2586       if (isZeroLengthInterval(&LI))
2587         LI.weight = HUGE_VALF;
2588       else {
2589         bool isLoad = false;
2590         SmallVector<LiveInterval*, 4> SpillIs;
2591         if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2592           // If all of the definitions of the interval are re-materializable,
2593           // it is a preferred candidate for spilling. If non of the defs are
2594           // loads, then it's potentially very cheap to re-materialize.
2595           // FIXME: this gets much more complicated once we support non-trivial
2596           // re-materialization.
2597           if (isLoad)
2598             LI.weight *= 0.9F;
2599           else
2600             LI.weight *= 0.5F;
2601         }
2602       }
2603
2604       // Slightly prefer live interval that has been assigned a preferred reg.
2605       if (LI.preference)
2606         LI.weight *= 1.01F;
2607
2608       // Divide the weight of the interval by its size.  This encourages 
2609       // spilling of intervals that are large and have few uses, and
2610       // discourages spilling of small intervals with many uses.
2611       LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2612     }
2613   }
2614
2615   DEBUG(dump());
2616   return true;
2617 }
2618
2619 /// print - Implement the dump method.
2620 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2621    li_->print(O, m);
2622 }
2623
2624 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2625   return new SimpleRegisterCoalescing();
2626 }
2627
2628 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2629 DEFINING_FILE_FOR(SimpleRegisterCoalescing)