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