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