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