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