Un-tabify.
[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), mri_->use_end())
1280             / 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 interval,
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 = NULL;
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
1716 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
1717                                         bool &Swapped) {
1718   // Compute the final value assignment, assuming that the live ranges can be
1719   // coalesced.
1720   SmallVector<int, 16> LHSValNoAssignments;
1721   SmallVector<int, 16> RHSValNoAssignments;
1722   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1723   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1724   SmallVector<VNInfo*, 16> NewVNInfo;
1725
1726   // If a live interval is a physical register, conservatively check if any
1727   // of its sub-registers is overlapping the live interval of the virtual
1728   // register. If so, do not coalesce.
1729   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1730       *tri_->getSubRegisters(LHS.reg)) {
1731     // If it's coalescing a virtual register to a physical register, estimate
1732     // its live interval length. This is the *cost* of scanning an entire live
1733     // interval. If the cost is low, we'll do an exhaustive check instead.
1734
1735     // If this is something like this:
1736     // BB1:
1737     // v1024 = op
1738     // ...
1739     // BB2:
1740     // ...
1741     // RAX   = v1024
1742     //
1743     // That is, the live interval of v1024 crosses a bb. Then we can't rely on
1744     // less conservative check. It's possible a sub-register is defined before
1745     // v1024 (or live in) and live out of BB1.
1746     if (RHS.containsOneValue() &&
1747         li_->intervalIsInOneMBB(RHS) &&
1748         li_->getApproximateInstructionCount(RHS) <= 10) {
1749       // Perform a more exhaustive check for some common cases.
1750       if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
1751         return false;
1752     } else {
1753       for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1754         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1755           DOUT << "Interfere with sub-register ";
1756           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1757           return false;
1758         }
1759     }
1760   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1761              *tri_->getSubRegisters(RHS.reg)) {
1762     if (LHS.containsOneValue() &&
1763         li_->getApproximateInstructionCount(LHS) <= 10) {
1764       // Perform a more exhaustive check for some common cases.
1765       if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
1766         return false;
1767     } else {
1768       for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1769         if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1770           DOUT << "Interfere with sub-register ";
1771           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1772           return false;
1773         }
1774     }
1775   }
1776                           
1777   // Compute ultimate value numbers for the LHS and RHS values.
1778   if (RHS.containsOneValue()) {
1779     // Copies from a liveinterval with a single value are simple to handle and
1780     // very common, handle the special case here.  This is important, because
1781     // often RHS is small and LHS is large (e.g. a physreg).
1782     
1783     // Find out if the RHS is defined as a copy from some value in the LHS.
1784     int RHSVal0DefinedFromLHS = -1;
1785     int RHSValID = -1;
1786     VNInfo *RHSValNoInfo = NULL;
1787     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1788     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1789     if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
1790       // If RHS is not defined as a copy from the LHS, we can use simpler and
1791       // faster checks to see if the live ranges are coalescable.  This joiner
1792       // can't swap the LHS/RHS intervals though.
1793       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1794         return SimpleJoin(LHS, RHS);
1795       } else {
1796         RHSValNoInfo = RHSValNoInfo0;
1797       }
1798     } else {
1799       // It was defined as a copy from the LHS, find out what value # it is.
1800       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1801       RHSValID = RHSValNoInfo->id;
1802       RHSVal0DefinedFromLHS = RHSValID;
1803     }
1804     
1805     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1806     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1807     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1808     
1809     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1810     // should now get updated.
1811     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1812          i != e; ++i) {
1813       VNInfo *VNI = *i;
1814       unsigned VN = VNI->id;
1815       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1816         if (LHSSrcReg != RHS.reg) {
1817           // If this is not a copy from the RHS, its value number will be
1818           // unmodified by the coalescing.
1819           NewVNInfo[VN] = VNI;
1820           LHSValNoAssignments[VN] = VN;
1821         } else if (RHSValID == -1) {
1822           // Otherwise, it is a copy from the RHS, and we don't already have a
1823           // value# for it.  Keep the current value number, but remember it.
1824           LHSValNoAssignments[VN] = RHSValID = VN;
1825           NewVNInfo[VN] = RHSValNoInfo;
1826           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1827         } else {
1828           // Otherwise, use the specified value #.
1829           LHSValNoAssignments[VN] = RHSValID;
1830           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1831             NewVNInfo[VN] = RHSValNoInfo;
1832             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1833           }
1834         }
1835       } else {
1836         NewVNInfo[VN] = VNI;
1837         LHSValNoAssignments[VN] = VN;
1838       }
1839     }
1840     
1841     assert(RHSValID != -1 && "Didn't find value #?");
1842     RHSValNoAssignments[0] = RHSValID;
1843     if (RHSVal0DefinedFromLHS != -1) {
1844       // This path doesn't go through ComputeUltimateVN so just set
1845       // it to anything.
1846       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1847     }
1848   } else {
1849     // Loop over the value numbers of the LHS, seeing if any are defined from
1850     // the RHS.
1851     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1852          i != e; ++i) {
1853       VNInfo *VNI = *i;
1854       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1855         continue;
1856       
1857       // DstReg is known to be a register in the LHS interval.  If the src is
1858       // from the RHS interval, we can use its value #.
1859       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1860         continue;
1861       
1862       // Figure out the value # from the RHS.
1863       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1864     }
1865     
1866     // Loop over the value numbers of the RHS, seeing if any are defined from
1867     // the LHS.
1868     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1869          i != e; ++i) {
1870       VNInfo *VNI = *i;
1871       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1872         continue;
1873       
1874       // DstReg is known to be a register in the RHS interval.  If the src is
1875       // from the LHS interval, we can use its value #.
1876       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1877         continue;
1878       
1879       // Figure out the value # from the LHS.
1880       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1881     }
1882     
1883     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1884     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1885     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1886     
1887     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1888          i != e; ++i) {
1889       VNInfo *VNI = *i;
1890       unsigned VN = VNI->id;
1891       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1892         continue;
1893       ComputeUltimateVN(VNI, NewVNInfo,
1894                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1895                         LHSValNoAssignments, RHSValNoAssignments);
1896     }
1897     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1898          i != e; ++i) {
1899       VNInfo *VNI = *i;
1900       unsigned VN = VNI->id;
1901       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1902         continue;
1903       // If this value number isn't a copy from the LHS, it's a new number.
1904       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1905         NewVNInfo.push_back(VNI);
1906         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1907         continue;
1908       }
1909       
1910       ComputeUltimateVN(VNI, NewVNInfo,
1911                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1912                         RHSValNoAssignments, LHSValNoAssignments);
1913     }
1914   }
1915   
1916   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1917   // interval lists to see if these intervals are coalescable.
1918   LiveInterval::const_iterator I = LHS.begin();
1919   LiveInterval::const_iterator IE = LHS.end();
1920   LiveInterval::const_iterator J = RHS.begin();
1921   LiveInterval::const_iterator JE = RHS.end();
1922   
1923   // Skip ahead until the first place of potential sharing.
1924   if (I->start < J->start) {
1925     I = std::upper_bound(I, IE, J->start);
1926     if (I != LHS.begin()) --I;
1927   } else if (J->start < I->start) {
1928     J = std::upper_bound(J, JE, I->start);
1929     if (J != RHS.begin()) --J;
1930   }
1931   
1932   while (1) {
1933     // Determine if these two live ranges overlap.
1934     bool Overlaps;
1935     if (I->start < J->start) {
1936       Overlaps = I->end > J->start;
1937     } else {
1938       Overlaps = J->end > I->start;
1939     }
1940
1941     // If so, check value # info to determine if they are really different.
1942     if (Overlaps) {
1943       // If the live range overlap will map to the same value number in the
1944       // result liverange, we can still coalesce them.  If not, we can't.
1945       if (LHSValNoAssignments[I->valno->id] !=
1946           RHSValNoAssignments[J->valno->id])
1947         return false;
1948     }
1949     
1950     if (I->end < J->end) {
1951       ++I;
1952       if (I == IE) break;
1953     } else {
1954       ++J;
1955       if (J == JE) break;
1956     }
1957   }
1958
1959   // Update kill info. Some live ranges are extended due to copy coalescing.
1960   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1961          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1962     VNInfo *VNI = I->first;
1963     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1964     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1965     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1966     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1967   }
1968
1969   // Update kill info. Some live ranges are extended due to copy coalescing.
1970   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1971          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1972     VNInfo *VNI = I->first;
1973     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1974     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1975     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1976     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1977   }
1978
1979   // If we get here, we know that we can coalesce the live ranges.  Ask the
1980   // intervals to coalesce themselves now.
1981   if ((RHS.ranges.size() > LHS.ranges.size() &&
1982       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1983       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1984     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1985     Swapped = true;
1986   } else {
1987     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1988     Swapped = false;
1989   }
1990   return true;
1991 }
1992
1993 namespace {
1994   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1995   // depth of the basic block (the unsigned), and then on the MBB number.
1996   struct DepthMBBCompare {
1997     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1998     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1999       if (LHS.first > RHS.first) return true;   // Deeper loops first
2000       return LHS.first == RHS.first &&
2001         LHS.second->getNumber() < RHS.second->getNumber();
2002     }
2003   };
2004 }
2005
2006 /// getRepIntervalSize - Returns the size of the interval that represents the
2007 /// specified register.
2008 template<class SF>
2009 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2010   return Rc->getRepIntervalSize(Reg);
2011 }
2012
2013 /// CopyRecSort::operator - Join priority queue sorting function.
2014 ///
2015 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2016   // Inner loops first.
2017   if (left.LoopDepth > right.LoopDepth)
2018     return false;
2019   else if (left.LoopDepth == right.LoopDepth)
2020     if (left.isBackEdge && !right.isBackEdge)
2021       return false;
2022   return true;
2023 }
2024
2025 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2026                                                std::vector<CopyRec> &TryAgain) {
2027   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
2028
2029   std::vector<CopyRec> VirtCopies;
2030   std::vector<CopyRec> PhysCopies;
2031   std::vector<CopyRec> ImpDefCopies;
2032   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
2033   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2034        MII != E;) {
2035     MachineInstr *Inst = MII++;
2036     
2037     // If this isn't a copy nor a extract_subreg, we can't join intervals.
2038     unsigned SrcReg, DstReg;
2039     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2040       DstReg = Inst->getOperand(0).getReg();
2041       SrcReg = Inst->getOperand(1).getReg();
2042     } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
2043       DstReg = Inst->getOperand(0).getReg();
2044       SrcReg = Inst->getOperand(2).getReg();
2045     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
2046       continue;
2047
2048     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2049     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2050     if (NewHeuristic) {
2051       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
2052     } else {
2053       if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2054         ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2055       else if (SrcIsPhys || DstIsPhys)
2056         PhysCopies.push_back(CopyRec(Inst, 0, false));
2057       else
2058         VirtCopies.push_back(CopyRec(Inst, 0, false));
2059     }
2060   }
2061
2062   if (NewHeuristic)
2063     return;
2064
2065   // Try coalescing implicit copies first, followed by copies to / from
2066   // physical registers, then finally copies from virtual registers to
2067   // virtual registers.
2068   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2069     CopyRec &TheCopy = ImpDefCopies[i];
2070     bool Again = false;
2071     if (!JoinCopy(TheCopy, Again))
2072       if (Again)
2073         TryAgain.push_back(TheCopy);
2074   }
2075   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2076     CopyRec &TheCopy = PhysCopies[i];
2077     bool Again = false;
2078     if (!JoinCopy(TheCopy, Again))
2079       if (Again)
2080         TryAgain.push_back(TheCopy);
2081   }
2082   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2083     CopyRec &TheCopy = VirtCopies[i];
2084     bool Again = false;
2085     if (!JoinCopy(TheCopy, Again))
2086       if (Again)
2087         TryAgain.push_back(TheCopy);
2088   }
2089 }
2090
2091 void SimpleRegisterCoalescing::joinIntervals() {
2092   DOUT << "********** JOINING INTERVALS ***********\n";
2093
2094   if (NewHeuristic)
2095     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2096
2097   std::vector<CopyRec> TryAgainList;
2098   if (loopInfo->empty()) {
2099     // If there are no loops in the function, join intervals in function order.
2100     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2101          I != E; ++I)
2102       CopyCoalesceInMBB(I, TryAgainList);
2103   } else {
2104     // Otherwise, join intervals in inner loops before other intervals.
2105     // Unfortunately we can't just iterate over loop hierarchy here because
2106     // there may be more MBB's than BB's.  Collect MBB's for sorting.
2107
2108     // Join intervals in the function prolog first. We want to join physical
2109     // registers with virtual registers before the intervals got too long.
2110     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2111     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2112       MachineBasicBlock *MBB = I;
2113       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2114     }
2115
2116     // Sort by loop depth.
2117     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2118
2119     // Finally, join intervals in loop nest order.
2120     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2121       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2122   }
2123   
2124   // Joining intervals can allow other intervals to be joined.  Iteratively join
2125   // until we make no progress.
2126   if (NewHeuristic) {
2127     SmallVector<CopyRec, 16> TryAgain;
2128     bool ProgressMade = true;
2129     while (ProgressMade) {
2130       ProgressMade = false;
2131       while (!JoinQueue->empty()) {
2132         CopyRec R = JoinQueue->pop();
2133         bool Again = false;
2134         bool Success = JoinCopy(R, Again);
2135         if (Success)
2136           ProgressMade = true;
2137         else if (Again)
2138           TryAgain.push_back(R);
2139       }
2140
2141       if (ProgressMade) {
2142         while (!TryAgain.empty()) {
2143           JoinQueue->push(TryAgain.back());
2144           TryAgain.pop_back();
2145         }
2146       }
2147     }
2148   } else {
2149     bool ProgressMade = true;
2150     while (ProgressMade) {
2151       ProgressMade = false;
2152
2153       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2154         CopyRec &TheCopy = TryAgainList[i];
2155         if (TheCopy.MI) {
2156           bool Again = false;
2157           bool Success = JoinCopy(TheCopy, Again);
2158           if (Success || !Again) {
2159             TheCopy.MI = 0;   // Mark this one as done.
2160             ProgressMade = true;
2161           }
2162         }
2163       }
2164     }
2165   }
2166
2167   if (NewHeuristic)
2168     delete JoinQueue;  
2169 }
2170
2171 /// Return true if the two specified registers belong to different register
2172 /// classes.  The registers may be either phys or virt regs. In the
2173 /// case where both registers are virtual registers, it would also returns
2174 /// true by reference the RegB register class in SubRC if it is a subset of
2175 /// RegA's register class.
2176 bool
2177 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, unsigned RegB,
2178                                       const TargetRegisterClass *&SubRC) const {
2179
2180   // Get the register classes for the first reg.
2181   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2182     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2183            "Shouldn't consider two physregs!");
2184     return !mri_->getRegClass(RegB)->contains(RegA);
2185   }
2186
2187   // Compare against the regclass for the second reg.
2188   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2189   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2190     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2191     if (RegClassA == RegClassB)
2192       return false;
2193     SubRC = (RegClassA->hasSubClass(RegClassB)) ? RegClassB : NULL;
2194     return true;
2195   }
2196   return !RegClassA->contains(RegB);
2197 }
2198
2199 /// lastRegisterUse - Returns the last use of the specific register between
2200 /// cycles Start and End or NULL if there are no uses.
2201 MachineOperand *
2202 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
2203                                           unsigned Reg, unsigned &UseIdx) const{
2204   UseIdx = 0;
2205   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2206     MachineOperand *LastUse = NULL;
2207     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2208            E = mri_->use_end(); I != E; ++I) {
2209       MachineOperand &Use = I.getOperand();
2210       MachineInstr *UseMI = Use.getParent();
2211       unsigned SrcReg, DstReg;
2212       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
2213         // Ignore identity copies.
2214         continue;
2215       unsigned Idx = li_->getInstructionIndex(UseMI);
2216       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2217         LastUse = &Use;
2218         UseIdx = Idx;
2219       }
2220     }
2221     return LastUse;
2222   }
2223
2224   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2225   int s = Start;
2226   while (e >= s) {
2227     // Skip deleted instructions
2228     MachineInstr *MI = li_->getInstructionFromIndex(e);
2229     while ((e - InstrSlots::NUM) >= s && !MI) {
2230       e -= InstrSlots::NUM;
2231       MI = li_->getInstructionFromIndex(e);
2232     }
2233     if (e < s || MI == NULL)
2234       return NULL;
2235
2236     // Ignore identity copies.
2237     unsigned SrcReg, DstReg;
2238     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
2239       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2240         MachineOperand &Use = MI->getOperand(i);
2241         if (Use.isReg() && Use.isUse() && Use.getReg() &&
2242             tri_->regsOverlap(Use.getReg(), Reg)) {
2243           UseIdx = e;
2244           return &Use;
2245         }
2246       }
2247
2248     e -= InstrSlots::NUM;
2249   }
2250
2251   return NULL;
2252 }
2253
2254
2255 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2256   if (TargetRegisterInfo::isPhysicalRegister(reg))
2257     cerr << tri_->getName(reg);
2258   else
2259     cerr << "%reg" << reg;
2260 }
2261
2262 void SimpleRegisterCoalescing::releaseMemory() {
2263   JoinedCopies.clear();
2264   ReMatCopies.clear();
2265   ReMatDefs.clear();
2266 }
2267
2268 static bool isZeroLengthInterval(LiveInterval *li) {
2269   for (LiveInterval::Ranges::const_iterator
2270          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2271     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2272       return false;
2273   return true;
2274 }
2275
2276 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2277 /// turn the copy into an implicit def.
2278 bool
2279 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2280                                              MachineBasicBlock *MBB,
2281                                              unsigned DstReg, unsigned SrcReg) {
2282   MachineInstr *CopyMI = &*I;
2283   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2284   if (!li_->hasInterval(SrcReg))
2285     return false;
2286   LiveInterval &SrcInt = li_->getInterval(SrcReg);
2287   if (!SrcInt.empty())
2288     return false;
2289   if (!li_->hasInterval(DstReg))
2290     return false;
2291   LiveInterval &DstInt = li_->getInterval(DstReg);
2292   const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
2293   DstInt.removeValNo(DstLR->valno);
2294   CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2295   for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2296     CopyMI->RemoveOperand(i);
2297   bool NoUse = mri_->use_empty(SrcReg);
2298   if (NoUse) {
2299     for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2300            E = mri_->reg_end(); I != E; ) {
2301       assert(I.getOperand().isDef());
2302       MachineInstr *DefMI = &*I;
2303       ++I;
2304       // The implicit_def source has no other uses, delete it.
2305       assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2306       li_->RemoveMachineInstrFromMaps(DefMI);
2307       DefMI->eraseFromParent();
2308     }
2309   }
2310   ++I;
2311   return true;
2312 }
2313
2314
2315 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2316   mf_ = &fn;
2317   mri_ = &fn.getRegInfo();
2318   tm_ = &fn.getTarget();
2319   tri_ = tm_->getRegisterInfo();
2320   tii_ = tm_->getInstrInfo();
2321   li_ = &getAnalysis<LiveIntervals>();
2322   loopInfo = &getAnalysis<MachineLoopInfo>();
2323
2324   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2325        << "********** Function: "
2326        << ((Value*)mf_->getFunction())->getName() << '\n';
2327
2328   allocatableRegs_ = tri_->getAllocatableSet(fn);
2329   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2330          E = tri_->regclass_end(); I != E; ++I)
2331     allocatableRCRegs_.insert(std::make_pair(*I,
2332                                              tri_->getAllocatableSet(fn, *I)));
2333
2334   // Join (coalesce) intervals if requested.
2335   if (EnableJoining) {
2336     joinIntervals();
2337     DEBUG({
2338         DOUT << "********** INTERVALS POST JOINING **********\n";
2339         for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2340           I->second->print(DOUT, tri_);
2341           DOUT << "\n";
2342         }
2343       });
2344   }
2345
2346   // Perform a final pass over the instructions and compute spill weights
2347   // and remove identity moves.
2348   SmallVector<unsigned, 4> DeadDefs;
2349   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2350        mbbi != mbbe; ++mbbi) {
2351     MachineBasicBlock* mbb = mbbi;
2352     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2353
2354     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2355          mii != mie; ) {
2356       MachineInstr *MI = mii;
2357       unsigned SrcReg, DstReg;
2358       if (JoinedCopies.count(MI)) {
2359         // Delete all coalesced copies.
2360         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2361           assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2362                   MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2363                  "Unrecognized copy instruction");
2364           DstReg = MI->getOperand(0).getReg();
2365         }
2366         if (MI->registerDefIsDead(DstReg)) {
2367           LiveInterval &li = li_->getInterval(DstReg);
2368           if (!ShortenDeadCopySrcLiveRange(li, MI))
2369             ShortenDeadCopyLiveRange(li, MI);
2370         }
2371         li_->RemoveMachineInstrFromMaps(MI);
2372         mii = mbbi->erase(mii);
2373         ++numPeep;
2374         continue;
2375       }
2376
2377       // Now check if this is a remat'ed def instruction which is now dead.
2378       if (ReMatDefs.count(MI)) {
2379         bool isDead = true;
2380         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2381           const MachineOperand &MO = MI->getOperand(i);
2382           if (!MO.isReg())
2383             continue;
2384           unsigned Reg = MO.getReg();
2385           if (TargetRegisterInfo::isVirtualRegister(Reg))
2386             DeadDefs.push_back(Reg);
2387           if (MO.isDead())
2388             continue;
2389           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2390               !mri_->use_empty(Reg)) {
2391             isDead = false;
2392             break;
2393           }
2394         }
2395         if (isDead) {
2396           while (!DeadDefs.empty()) {
2397             unsigned DeadDef = DeadDefs.back();
2398             DeadDefs.pop_back();
2399             RemoveDeadDef(li_->getInterval(DeadDef), MI);
2400           }
2401           li_->RemoveMachineInstrFromMaps(mii);
2402           mii = mbbi->erase(mii);
2403           continue;
2404         } else
2405           DeadDefs.clear();
2406       }
2407
2408       // If the move will be an identity move delete it
2409       bool isMove = tii_->isMoveInstr(*MI, SrcReg, DstReg);
2410       if (isMove && SrcReg == DstReg) {
2411         if (li_->hasInterval(SrcReg)) {
2412           LiveInterval &RegInt = li_->getInterval(SrcReg);
2413           // If def of this move instruction is dead, remove its live range
2414           // from the dstination register's live interval.
2415           if (MI->registerDefIsDead(DstReg)) {
2416             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2417               ShortenDeadCopyLiveRange(RegInt, MI);
2418           }
2419         }
2420         li_->RemoveMachineInstrFromMaps(MI);
2421         mii = mbbi->erase(mii);
2422         ++numPeep;
2423       } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2424         SmallSet<unsigned, 4> UniqueUses;
2425         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2426           const MachineOperand &mop = MI->getOperand(i);
2427           if (mop.isReg() && mop.getReg() &&
2428               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2429             unsigned reg = mop.getReg();
2430             // Multiple uses of reg by the same instruction. It should not
2431             // contribute to spill weight again.
2432             if (UniqueUses.count(reg) != 0)
2433               continue;
2434             LiveInterval &RegInt = li_->getInterval(reg);
2435             RegInt.weight +=
2436               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2437             UniqueUses.insert(reg);
2438           }
2439         }
2440         ++mii;
2441       }
2442     }
2443   }
2444
2445   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2446     LiveInterval &LI = *I->second;
2447     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2448       // If the live interval length is essentially zero, i.e. in every live
2449       // range the use follows def immediately, it doesn't make sense to spill
2450       // it and hope it will be easier to allocate for this li.
2451       if (isZeroLengthInterval(&LI))
2452         LI.weight = HUGE_VALF;
2453       else {
2454         bool isLoad = false;
2455         SmallVector<LiveInterval*, 4> SpillIs;
2456         if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2457           // If all of the definitions of the interval are re-materializable,
2458           // it is a preferred candidate for spilling. If non of the defs are
2459           // loads, then it's potentially very cheap to re-materialize.
2460           // FIXME: this gets much more complicated once we support non-trivial
2461           // re-materialization.
2462           if (isLoad)
2463             LI.weight *= 0.9F;
2464           else
2465             LI.weight *= 0.5F;
2466         }
2467       }
2468
2469       // Slightly prefer live interval that has been assigned a preferred reg.
2470       if (LI.preference)
2471         LI.weight *= 1.01F;
2472
2473       // Divide the weight of the interval by its size.  This encourages 
2474       // spilling of intervals that are large and have few uses, and
2475       // discourages spilling of small intervals with many uses.
2476       LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2477     }
2478   }
2479
2480   DEBUG(dump());
2481   return true;
2482 }
2483
2484 /// print - Implement the dump method.
2485 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2486    li_->print(O, m);
2487 }
2488
2489 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2490   return new SimpleRegisterCoalescing();
2491 }
2492
2493 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2494 DEFINING_FILE_FOR(SimpleRegisterCoalescing)