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