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