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