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