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