Enable exception handling int JIT
[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/LiveVariables.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.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(numCommutes , "Number of instruction commuting performed");
40 STATISTIC(numExtends  , "Number of copies extended");
41 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
42 STATISTIC(numAborts   , "Number of times interval joining aborted");
43
44 char SimpleRegisterCoalescing::ID = 0;
45 namespace {
46   static cl::opt<bool>
47   EnableJoining("join-liveintervals",
48                 cl::desc("Coalesce copies (default=true)"),
49                 cl::init(true));
50
51   static cl::opt<bool>
52   NewHeuristic("new-coalescer-heuristic",
53                 cl::desc("Use new coalescer heuristic"),
54                 cl::init(false));
55
56   static cl::opt<bool>
57   CommuteDef("coalescer-commute-instrs",
58              cl::init(false), cl::Hidden);
59
60   RegisterPass<SimpleRegisterCoalescing> 
61   X("simple-register-coalescing", "Simple Register Coalescing");
62
63   // Declare that we implement the RegisterCoalescer interface
64   RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
65 }
66
67 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
68
69 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
70   AU.addPreserved<LiveIntervals>();
71   AU.addPreserved<MachineLoopInfo>();
72   AU.addPreservedID(MachineDominatorsID);
73   AU.addPreservedID(PHIEliminationID);
74   AU.addPreservedID(TwoAddressInstructionPassID);
75   AU.addRequired<LiveVariables>();
76   AU.addRequired<LiveIntervals>();
77   AU.addRequired<MachineLoopInfo>();
78   MachineFunctionPass::getAnalysisUsage(AU);
79 }
80
81 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
82 /// being the source and IntB being the dest, thus this defines a value number
83 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
84 /// see if we can merge these two pieces of B into a single value number,
85 /// eliminating a copy.  For example:
86 ///
87 ///  A3 = B0
88 ///    ...
89 ///  B1 = A3      <- this copy
90 ///
91 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
92 /// value number to be replaced with B0 (which simplifies the B liveinterval).
93 ///
94 /// This returns true if an interval was modified.
95 ///
96 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
97                                                     LiveInterval &IntB,
98                                                     MachineInstr *CopyMI) {
99   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
100
101   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
102   // the example above.
103   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
104   VNInfo *BValNo = BLR->valno;
105   
106   // Get the location that B is defined at.  Two options: either this value has
107   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
108   // can't process it.
109   if (!BValNo->reg) return false;
110   assert(BValNo->def == CopyIdx &&
111          "Copy doesn't define the value?");
112   
113   // AValNo is the value number in A that defines the copy, A3 in the example.
114   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
115   VNInfo *AValNo = ALR->valno;
116   
117   // If AValNo is defined as a copy from IntB, we can potentially process this.  
118   // Get the instruction that defines this value number.
119   unsigned SrcReg = AValNo->reg;
120   if (!SrcReg) return false;  // Not defined by a copy.
121     
122   // If the value number is not defined by a copy instruction, ignore it.
123     
124   // If the source register comes from an interval other than IntB, we can't
125   // handle this.
126   if (rep(SrcReg) != IntB.reg) return false;
127   
128   // Get the LiveRange in IntB that this value number starts with.
129   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
130   
131   // Make sure that the end of the live range is inside the same block as
132   // CopyMI.
133   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
134   if (!ValLREndInst || 
135       ValLREndInst->getParent() != CopyMI->getParent()) return false;
136
137   // Okay, we now know that ValLR ends in the same block that the CopyMI
138   // live-range starts.  If there are no intervening live ranges between them in
139   // IntB, we can merge them.
140   if (ValLR+1 != BLR) return false;
141
142   // If a live interval is a physical register, conservatively check if any
143   // of its sub-registers is overlapping the live interval of the virtual
144   // register. If so, do not coalesce.
145   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
146       *tri_->getSubRegisters(IntB.reg)) {
147     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
148       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
149         DOUT << "Interfere with sub-register ";
150         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
151         return false;
152       }
153   }
154   
155   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
156   
157   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
158   // We are about to delete CopyMI, so need to remove it as the 'instruction
159   // that defines this value #'. Update the the valnum with the new defining
160   // instruction #.
161   BValNo->def = FillerStart;
162   BValNo->reg = 0;
163   
164   // Okay, we can merge them.  We need to insert a new liverange:
165   // [ValLR.end, BLR.begin) of either value number, then we merge the
166   // two value numbers.
167   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
168
169   // If the IntB live range is assigned to a physical register, and if that
170   // physreg has aliases, 
171   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
172     // Update the liveintervals of sub-registers.
173     for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
174       LiveInterval &AliasLI = li_->getInterval(*AS);
175       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
176               AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
177     }
178   }
179
180   // Okay, merge "B1" into the same value number as "B0".
181   if (BValNo != ValLR->valno)
182     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
183   DOUT << "   result = "; IntB.print(DOUT, tri_);
184   DOUT << "\n";
185
186   // If the source instruction was killing the source register before the
187   // merge, unset the isKill marker given the live range has been extended.
188   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
189   if (UIdx != -1)
190     ValLREndInst->getOperand(UIdx).setIsKill(false);
191
192   ++numExtends;
193   return true;
194 }
195
196 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
197 /// being the source and IntB being the dest, thus this defines a value number
198 /// in IntB.  If the source value number (in IntA) is defined by a commutable
199 /// instruction and its other operand is coalesced to the copy dest register,
200 /// see if we can transform the copy into a noop by commuting the definition. For
201 /// example,
202 ///
203 ///  A3 = op A2 B0<kill>
204 ///    ...
205 ///  B1 = A3      <- this copy
206 ///    ...
207 ///     = op A3   <- more uses
208 ///
209 /// ==>
210 ///
211 ///  B2 = op B0 A2<kill>
212 ///    ...
213 ///  B1 = B2      <- now an identify copy
214 ///    ...
215 ///     = op B2   <- more uses
216 ///
217 /// This returns true if an interval was modified.
218 ///
219 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
220                                                         LiveInterval &IntB,
221                                                         MachineInstr *CopyMI) {
222   if (!CommuteDef) return false;
223
224   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
225
226   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
227   // the example above.
228   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
229   VNInfo *BValNo = BLR->valno;
230   
231   // Get the location that B is defined at.  Two options: either this value has
232   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
233   // can't process it.
234   if (!BValNo->reg) return false;
235   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
236   
237   // AValNo is the value number in A that defines the copy, A3 in the example.
238   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
239   VNInfo *AValNo = ALR->valno;
240   // If other defs can reach uses of this def, then it's not safe to perform
241   // the optimization.
242   if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
243     return false;
244   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
245   const TargetInstrDesc &TID = DefMI->getDesc();
246   if (!TID.isCommutable())
247     return false;
248   int Idx = -1;
249   for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
250     MachineOperand &MO = DefMI->getOperand(i);
251     if (!MO.isRegister()) continue;
252     unsigned Reg = MO.getReg();
253     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
254       if (rep(Reg) == IntA.reg) {
255         // If the dest register comes from an interval other than IntA, we
256         // can't handle this.
257         if (Reg != IntA.reg)
258           return false;
259         continue;
260       }
261       if (Idx != -1)
262         // FIXME: Being overly careful here. We just need to figure out the
263         // which register operand will become the new def.
264         return false;
265       Idx = i;
266     }
267   }
268   if (Idx == -1)
269     // Something like %reg1024 = add %reg1024, %reg1024
270     return false;
271
272   MachineOperand &MO = DefMI->getOperand(Idx);
273   unsigned NewReg = MO.getReg();
274   if (rep(NewReg) != IntB.reg || !MO.isKill())
275     return false;
276
277   // Make sure there are no other definitions of IntB that would reach the
278   // uses which the new definition can reach.
279   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
280        AI != AE; ++AI) {
281     if (AI->valno != AValNo) continue;
282     LiveInterval::Ranges::iterator BI =
283       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
284     if (BI != IntB.ranges.begin())
285       --BI;
286     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
287       if (BI->valno == BLR->valno)
288         continue;
289       if (BI->start <= AI->start && BI->end > AI->start)
290         return false;
291       if (BI->start > AI->start && BI->start < AI->end)
292         return false;
293     }
294   }
295
296   // At this point we have decided that it is legal to do this
297   // transformation.  Start by commuting the instruction.
298   MachineBasicBlock *MBB = DefMI->getParent();
299   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
300   if (NewMI != DefMI) {
301     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
302     MBB->insert(DefMI, NewMI);
303     MBB->erase(DefMI);
304   }
305   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg);
306   NewMI->getOperand(OpIdx).setIsKill();
307
308   // Update uses of IntA of the specific Val# with IntB.
309   bool BHasPHIKill = BValNo->hasPHIKill;
310   SmallVector<VNInfo*, 4> BDeadValNos;
311   SmallVector<unsigned, 4> BKills;
312   std::map<unsigned, unsigned> BExtend;
313   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
314          UE = mri_->use_end(); UI != UE;) {
315     MachineOperand &UseMO = UI.getOperand();
316     MachineInstr *UseMI = &*UI;
317     ++UI;
318     if (JoinedCopies.count(UseMI))
319       continue;
320     unsigned UseIdx = li_->getInstructionIndex(UseMI);
321     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
322     if (ULR->valno != AValNo)
323       continue;
324     UseMO.setReg(NewReg);
325     if (UseMO.isKill())
326       BKills.push_back(li_->getUseIndex(UseIdx)+1);
327     if (UseMI == CopyMI)
328       continue;
329     unsigned SrcReg, DstReg;
330     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
331       continue;
332     unsigned repDstReg = rep(DstReg);
333     if (repDstReg != IntB.reg) {
334       // Update dst register interval val# since its source register has
335       // changed.
336       LiveInterval &DLI = li_->getInterval(repDstReg);
337       LiveInterval::iterator DLR =
338         DLI.FindLiveRangeContaining(li_->getDefIndex(UseIdx));
339       DLR->valno->reg = NewReg;
340       ChangedCopies.insert(UseMI);
341     } else {
342       // This copy will become a noop. If it's defining a new val#,
343       // remove that val# as well. However this live range is being
344       // extended to the end of the existing live range defined by the copy.
345       unsigned DefIdx = li_->getDefIndex(UseIdx);
346       LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
347       BHasPHIKill |= DLR->valno->hasPHIKill;
348       assert(DLR->valno->def == DefIdx);
349       BDeadValNos.push_back(DLR->valno);
350       BExtend[DLR->start] = DLR->end;
351       JoinedCopies.insert(UseMI);
352       // If this is a kill but it's going to be removed, the last use
353       // of the same val# is the new kill.
354       if (UseMO.isKill()) {
355         BKills.pop_back();
356       }
357     }
358   }
359
360   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
361   // simply extend BLR if CopyMI doesn't end the range.
362   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
363
364   IntB.removeValNo(BValNo);
365   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
366     IntB.removeValNo(BDeadValNos[i]);
367   VNInfo *ValNo = IntB.getNextValue(ALR->start, 0, li_->getVNInfoAllocator());
368   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
369        AI != AE; ++AI) {
370     if (AI->valno != AValNo) continue;
371     unsigned End = AI->end;
372     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
373     if (EI != BExtend.end())
374       End = EI->second;
375     IntB.addRange(LiveRange(AI->start, End, ValNo));
376   }
377   IntB.addKills(ValNo, BKills);
378   ValNo->hasPHIKill = BHasPHIKill;
379
380   DOUT << "   result = "; IntB.print(DOUT, tri_);
381   DOUT << "\n";
382
383   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
384   IntA.removeValNo(AValNo);
385   DOUT << "   result = "; IntA.print(DOUT, tri_);
386   DOUT << "\n";
387
388   ++numCommutes;
389   return true;
390 }
391
392 /// AddSubRegIdxPairs - Recursively mark all the registers represented by the
393 /// specified register as sub-registers. The recursion level is expected to be
394 /// shallow.
395 void SimpleRegisterCoalescing::AddSubRegIdxPairs(unsigned Reg, unsigned SubIdx) {
396   std::vector<unsigned> &JoinedRegs = r2rRevMap_[Reg];
397   for (unsigned i = 0, e = JoinedRegs.size(); i != e; ++i) {
398     SubRegIdxes.push_back(std::make_pair(JoinedRegs[i], SubIdx));
399     AddSubRegIdxPairs(JoinedRegs[i], SubIdx);
400   }
401 }
402
403 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
404 ///
405 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
406                                               unsigned DstReg) {
407   MachineBasicBlock *MBB = CopyMI->getParent();
408   const MachineLoop *L = loopInfo->getLoopFor(MBB);
409   if (!L)
410     return false;
411   if (MBB != L->getLoopLatch())
412     return false;
413
414   DstReg = rep(DstReg);
415   LiveInterval &LI = li_->getInterval(DstReg);
416   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
417   LiveInterval::const_iterator DstLR =
418     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
419   if (DstLR == LI.end())
420     return false;
421   unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
422   if (DstLR->valno->kills.size() == 1 &&
423       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
424     return true;
425   return false;
426 }
427
428 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
429 /// which are the src/dst of the copy instruction CopyMI.  This returns true
430 /// if the copy was successfully coalesced away. If it is not currently
431 /// possible to coalesce this interval, but it may be possible if other
432 /// things get coalesced, then it returns true by reference in 'Again'.
433 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
434   MachineInstr *CopyMI = TheCopy.MI;
435
436   Again = false;
437   if (JoinedCopies.count(CopyMI))
438     return false; // Already done.
439
440   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
441
442   // Get representative registers.
443   unsigned SrcReg = TheCopy.SrcReg;
444   unsigned DstReg = TheCopy.DstReg;
445
446   // CopyMI has been modified due to commuting.
447   if (ChangedCopies.count(CopyMI)) {
448     if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
449         ;
450     else if (CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
451       DstReg = CopyMI->getOperand(0).getReg();
452       SrcReg = CopyMI->getOperand(1).getReg();
453     } else
454       assert(0 && "Unrecognized move instruction!");
455     TheCopy.SrcReg = SrcReg;
456     TheCopy.DstReg = DstReg;
457     ChangedCopies.erase(CopyMI);
458   }
459
460   unsigned repSrcReg = rep(SrcReg);
461   unsigned repDstReg = rep(DstReg);
462   
463   // If they are already joined we continue.
464   if (repSrcReg == repDstReg) {
465     DOUT << "\tCopy already coalesced.\n";
466     return false;  // Not coalescable.
467   }
468   
469   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(repSrcReg);
470   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(repDstReg);
471
472   // If they are both physical registers, we cannot join them.
473   if (SrcIsPhys && DstIsPhys) {
474     DOUT << "\tCan not coalesce physregs.\n";
475     return false;  // Not coalescable.
476   }
477   
478   // We only join virtual registers with allocatable physical registers.
479   if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
480     DOUT << "\tSrc reg is unallocatable physreg.\n";
481     return false;  // Not coalescable.
482   }
483   if (DstIsPhys && !allocatableRegs_[repDstReg]) {
484     DOUT << "\tDst reg is unallocatable physreg.\n";
485     return false;  // Not coalescable.
486   }
487
488   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
489   unsigned RealDstReg = 0;
490   if (isExtSubReg) {
491     unsigned SubIdx = CopyMI->getOperand(2).getImm();
492     if (SrcIsPhys)
493       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
494       // coalesced with AX.
495       repSrcReg = tri_->getSubReg(repSrcReg, SubIdx);
496     else if (DstIsPhys) {
497       // If this is a extract_subreg where dst is a physical register, e.g.
498       // cl = EXTRACT_SUBREG reg1024, 1
499       // then create and update the actual physical register allocated to RHS.
500       const TargetRegisterClass *RC = mri_->getRegClass(repSrcReg);
501       for (const unsigned *SRs = tri_->getSuperRegisters(repDstReg);
502            unsigned SR = *SRs; ++SRs) {
503         if (repDstReg == tri_->getSubReg(SR, SubIdx) &&
504             RC->contains(SR)) {
505           RealDstReg = SR;
506           break;
507         }
508       }
509       assert(RealDstReg && "Invalid extra_subreg instruction!");
510
511       // For this type of EXTRACT_SUBREG, conservatively
512       // check if the live interval of the source register interfere with the
513       // actual super physical register we are trying to coalesce with.
514       LiveInterval &RHS = li_->getInterval(repSrcReg);
515       if (li_->hasInterval(RealDstReg) &&
516           RHS.overlaps(li_->getInterval(RealDstReg))) {
517         DOUT << "Interfere with register ";
518         DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
519         return false; // Not coalescable
520       }
521       for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
522         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
523           DOUT << "Interfere with sub-register ";
524           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
525           return false; // Not coalescable
526         }
527     } else {
528       unsigned SrcSize= li_->getInterval(repSrcReg).getSize() / InstrSlots::NUM;
529       unsigned DstSize= li_->getInterval(repDstReg).getSize() / InstrSlots::NUM;
530       const TargetRegisterClass *RC=mf_->getRegInfo().getRegClass(repDstReg);
531       unsigned Threshold = allocatableRCRegs_[RC].count();
532       // Be conservative. If both sides are virtual registers, do not coalesce
533       // if this will cause a high use density interval to target a smaller set
534       // of registers.
535       if (DstSize > Threshold || SrcSize > Threshold) {
536         LiveVariables::VarInfo &svi = lv_->getVarInfo(repSrcReg);
537         LiveVariables::VarInfo &dvi = lv_->getVarInfo(repDstReg);
538         if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
539           Again = true;  // May be possible to coalesce later.
540           return false;
541         }
542       }
543     }
544   } else if (differingRegisterClasses(repSrcReg, repDstReg)) {
545     // If they are not of the same register class, we cannot join them.
546     DOUT << "\tSrc/Dest are different register classes.\n";
547     // Allow the coalescer to try again in case either side gets coalesced to
548     // a physical register that's compatible with the other side. e.g.
549     // r1024 = MOV32to32_ r1025
550     // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
551     Again = true;  // May be possible to coalesce later.
552     return false;
553   }
554   
555   LiveInterval &SrcInt = li_->getInterval(repSrcReg);
556   LiveInterval &DstInt = li_->getInterval(repDstReg);
557   assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
558          "Register mapping is horribly broken!");
559
560   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
561   DOUT << " and "; DstInt.print(DOUT, tri_);
562   DOUT << ": ";
563
564   // Check if it is necessary to propagate "isDead" property before intervals
565   // are joined.
566   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
567   bool isDead = mopd->isDead();
568   bool isShorten = false;
569   unsigned SrcStart = 0, RemoveStart = 0;
570   unsigned SrcEnd = 0, RemoveEnd = 0;
571   if (isDead) {
572     unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
573     LiveInterval::iterator SrcLR =
574       SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
575     RemoveStart = SrcStart = SrcLR->start;
576     RemoveEnd   = SrcEnd   = SrcLR->end;
577     // The instruction which defines the src is only truly dead if there are
578     // no intermediate uses and there isn't a use beyond the copy.
579     // FIXME: find the last use, mark is kill and shorten the live range.
580     if (SrcEnd > li_->getDefIndex(CopyIdx)) {
581       isDead = false;
582     } else {
583       MachineOperand *MOU;
584       MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
585       if (LastUse) {
586         // Shorten the liveinterval to the end of last use.
587         MOU->setIsKill();
588         isDead = false;
589         isShorten = true;
590         RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
591         RemoveEnd   = SrcEnd;
592       } else {
593         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
594         if (SrcMI) {
595           MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
596           if (mops)
597             // A dead def should have a single cycle interval.
598             ++RemoveStart;
599         }
600       }
601     }
602   }
603
604   // We need to be careful about coalescing a source physical register with a
605   // virtual register. Once the coalescing is done, it cannot be broken and
606   // these are not spillable! If the destination interval uses are far away,
607   // think twice about coalescing them!
608   if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
609     LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
610     unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
611     unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
612     const TargetRegisterClass *RC = mf_->getRegInfo().getRegClass(JoinVReg);
613     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
614     if (TheCopy.isBackEdge)
615       Threshold *= 2; // Favors back edge copies.
616
617     // If the virtual register live interval is long but it has low use desity,
618     // do not join them, instead mark the physical register as its allocation
619     // preference.
620     unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
621     LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
622     if (Length > Threshold &&
623         (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
624       JoinVInt.preference = JoinPReg;
625       ++numAborts;
626       DOUT << "\tMay tie down a physical register, abort!\n";
627       Again = true;  // May be possible to coalesce later.
628       return false;
629     }
630   }
631
632   // Okay, attempt to join these two intervals.  On failure, this returns false.
633   // Otherwise, if one of the intervals being joined is a physreg, this method
634   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
635   // been modified, so we can use this information below to update aliases.
636   bool Swapped = false;
637   if (JoinIntervals(DstInt, SrcInt, Swapped)) {
638     if (isDead) {
639       // Result of the copy is dead. Propagate this property.
640       if (SrcStart == 0) {
641         assert(TargetRegisterInfo::isPhysicalRegister(repSrcReg) &&
642                "Live-in must be a physical register!");
643         // Live-in to the function but dead. Remove it from entry live-in set.
644         // JoinIntervals may end up swapping the two intervals.
645         mf_->begin()->removeLiveIn(repSrcReg);
646       } else {
647         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
648         if (SrcMI) {
649           MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
650           if (mops)
651             mops->setIsDead();
652         }
653       }
654     }
655
656     if (isShorten || isDead) {
657       // Shorten the destination live interval.
658       if (Swapped)
659         SrcInt.removeRange(RemoveStart, RemoveEnd, true);
660     }
661   } else {
662     // Coalescing failed.
663     
664     // If we can eliminate the copy without merging the live ranges, do so now.
665     if (!isExtSubReg &&
666         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
667          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
668       JoinedCopies.insert(CopyMI);
669       return true;
670     }
671     
672
673     // Otherwise, we are unable to join the intervals.
674     DOUT << "Interference!\n";
675     Again = true;  // May be possible to coalesce later.
676     return false;
677   }
678
679   LiveInterval *ResSrcInt = &SrcInt;
680   LiveInterval *ResDstInt = &DstInt;
681   if (Swapped) {
682     std::swap(repSrcReg, repDstReg);
683     std::swap(ResSrcInt, ResDstInt);
684   }
685   assert(TargetRegisterInfo::isVirtualRegister(repSrcReg) &&
686          "LiveInterval::join didn't work right!");
687                                
688   // If we're about to merge live ranges into a physical register live range,
689   // we have to update any aliased register's live ranges to indicate that they
690   // have clobbered values for this range.
691   if (TargetRegisterInfo::isPhysicalRegister(repDstReg)) {
692     // Unset unnecessary kills.
693     if (!ResDstInt->containsOneValue()) {
694       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
695              E = ResSrcInt->end(); I != E; ++I)
696         unsetRegisterKills(I->start, I->end, repDstReg);
697     }
698
699     // If this is a extract_subreg where dst is a physical register, e.g.
700     // cl = EXTRACT_SUBREG reg1024, 1
701     // then create and update the actual physical register allocated to RHS.
702     if (RealDstReg) {
703       LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
704       SmallSet<const VNInfo*, 4> CopiedValNos;
705       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
706              E = ResSrcInt->ranges.end(); I != E; ++I) {
707         LiveInterval::const_iterator DstLR =
708           ResDstInt->FindLiveRangeContaining(I->start);
709         assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
710         const VNInfo *DstValNo = DstLR->valno;
711         if (CopiedValNos.insert(DstValNo)) {
712           VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->reg,
713                                                   li_->getVNInfoAllocator());
714           ValNo->hasPHIKill = DstValNo->hasPHIKill;
715           RealDstInt.addKills(ValNo, DstValNo->kills);
716           RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
717         }
718       }
719       repDstReg = RealDstReg;
720     }
721
722     // Update the liveintervals of sub-registers.
723     for (const unsigned *AS = tri_->getSubRegisters(repDstReg); *AS; ++AS)
724       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
725                                                  li_->getVNInfoAllocator());
726   } else {
727     // Merge use info if the destination is a virtual register.
728     LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
729     LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
730     dVI.NumUses += sVI.NumUses;
731   }
732
733   // Remember these liveintervals have been joined.
734   JoinedLIs.set(repSrcReg - TargetRegisterInfo::FirstVirtualRegister);
735   if (TargetRegisterInfo::isVirtualRegister(repDstReg))
736     JoinedLIs.set(repDstReg - TargetRegisterInfo::FirstVirtualRegister);
737
738   if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
739     if (!Swapped) {
740       // Make sure we allocate the larger super-register.
741       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
742       std::swap(repSrcReg, repDstReg);
743       std::swap(ResSrcInt, ResDstInt);
744     }
745     unsigned SubIdx = CopyMI->getOperand(2).getImm();
746     SubRegIdxes.push_back(std::make_pair(repSrcReg, SubIdx));
747     AddSubRegIdxPairs(repSrcReg, SubIdx);
748   }
749
750   if (NewHeuristic) {
751     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
752            e = ResSrcInt->vni_end(); i != e; ++i) {
753       const VNInfo *vni = *i;
754       if (vni->def && vni->def != ~1U && vni->def != ~0U) {
755         MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
756         unsigned SrcReg, DstReg;
757         if (CopyMI &&
758             JoinedCopies.count(CopyMI) == 0 &&
759             tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
760           unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
761           JoinQueue->push(CopyRec(CopyMI, SrcReg, DstReg, LoopDepth,
762                                   isBackEdgeCopy(CopyMI, DstReg)));
763         }
764       }
765     }
766   }
767
768   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
769   DOUT << "\n";
770
771   // repSrcReg is guarateed to be the register whose live interval that is
772   // being merged.
773   li_->removeInterval(repSrcReg);
774   r2rMap_[repSrcReg] = repDstReg;
775   r2rRevMap_[repDstReg].push_back(repSrcReg);
776
777   // Finally, delete the copy instruction.
778   JoinedCopies.insert(CopyMI);
779   ++numJoins;
780   return true;
781 }
782
783 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
784 /// compute what the resultant value numbers for each value in the input two
785 /// ranges will be.  This is complicated by copies between the two which can
786 /// and will commonly cause multiple value numbers to be merged into one.
787 ///
788 /// VN is the value number that we're trying to resolve.  InstDefiningValue
789 /// keeps track of the new InstDefiningValue assignment for the result
790 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
791 /// whether a value in this or other is a copy from the opposite set.
792 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
793 /// already been assigned.
794 ///
795 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
796 /// contains the value number the copy is from.
797 ///
798 static unsigned ComputeUltimateVN(VNInfo *VNI,
799                                   SmallVector<VNInfo*, 16> &NewVNInfo,
800                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
801                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
802                                   SmallVector<int, 16> &ThisValNoAssignments,
803                                   SmallVector<int, 16> &OtherValNoAssignments) {
804   unsigned VN = VNI->id;
805
806   // If the VN has already been computed, just return it.
807   if (ThisValNoAssignments[VN] >= 0)
808     return ThisValNoAssignments[VN];
809 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
810
811   // If this val is not a copy from the other val, then it must be a new value
812   // number in the destination.
813   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
814   if (I == ThisFromOther.end()) {
815     NewVNInfo.push_back(VNI);
816     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
817   }
818   VNInfo *OtherValNo = I->second;
819
820   // Otherwise, this *is* a copy from the RHS.  If the other side has already
821   // been computed, return it.
822   if (OtherValNoAssignments[OtherValNo->id] >= 0)
823     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
824   
825   // Mark this value number as currently being computed, then ask what the
826   // ultimate value # of the other value is.
827   ThisValNoAssignments[VN] = -2;
828   unsigned UltimateVN =
829     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
830                       OtherValNoAssignments, ThisValNoAssignments);
831   return ThisValNoAssignments[VN] = UltimateVN;
832 }
833
834 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
835   return std::find(V.begin(), V.end(), Val) != V.end();
836 }
837
838 /// SimpleJoin - Attempt to joint the specified interval into this one. The
839 /// caller of this method must guarantee that the RHS only contains a single
840 /// value number and that the RHS is not defined by a copy from this
841 /// interval.  This returns false if the intervals are not joinable, or it
842 /// joins them and returns true.
843 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
844   assert(RHS.containsOneValue());
845   
846   // Some number (potentially more than one) value numbers in the current
847   // interval may be defined as copies from the RHS.  Scan the overlapping
848   // portions of the LHS and RHS, keeping track of this and looking for
849   // overlapping live ranges that are NOT defined as copies.  If these exist, we
850   // cannot coalesce.
851   
852   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
853   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
854   
855   if (LHSIt->start < RHSIt->start) {
856     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
857     if (LHSIt != LHS.begin()) --LHSIt;
858   } else if (RHSIt->start < LHSIt->start) {
859     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
860     if (RHSIt != RHS.begin()) --RHSIt;
861   }
862   
863   SmallVector<VNInfo*, 8> EliminatedLHSVals;
864   
865   while (1) {
866     // Determine if these live intervals overlap.
867     bool Overlaps = false;
868     if (LHSIt->start <= RHSIt->start)
869       Overlaps = LHSIt->end > RHSIt->start;
870     else
871       Overlaps = RHSIt->end > LHSIt->start;
872     
873     // If the live intervals overlap, there are two interesting cases: if the
874     // LHS interval is defined by a copy from the RHS, it's ok and we record
875     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
876     // coalesce these live ranges and we bail out.
877     if (Overlaps) {
878       // If we haven't already recorded that this value # is safe, check it.
879       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
880         // Copy from the RHS?
881         unsigned SrcReg = LHSIt->valno->reg;
882         if (rep(SrcReg) != RHS.reg)
883           return false;    // Nope, bail out.
884         
885         EliminatedLHSVals.push_back(LHSIt->valno);
886       }
887       
888       // We know this entire LHS live range is okay, so skip it now.
889       if (++LHSIt == LHSEnd) break;
890       continue;
891     }
892     
893     if (LHSIt->end < RHSIt->end) {
894       if (++LHSIt == LHSEnd) break;
895     } else {
896       // One interesting case to check here.  It's possible that we have
897       // something like "X3 = Y" which defines a new value number in the LHS,
898       // and is the last use of this liverange of the RHS.  In this case, we
899       // want to notice this copy (so that it gets coalesced away) even though
900       // the live ranges don't actually overlap.
901       if (LHSIt->start == RHSIt->end) {
902         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
903           // We already know that this value number is going to be merged in
904           // if coalescing succeeds.  Just skip the liverange.
905           if (++LHSIt == LHSEnd) break;
906         } else {
907           // Otherwise, if this is a copy from the RHS, mark it as being merged
908           // in.
909           if (rep(LHSIt->valno->reg) == RHS.reg) {
910             EliminatedLHSVals.push_back(LHSIt->valno);
911
912             // We know this entire LHS live range is okay, so skip it now.
913             if (++LHSIt == LHSEnd) break;
914           }
915         }
916       }
917       
918       if (++RHSIt == RHSEnd) break;
919     }
920   }
921   
922   // If we got here, we know that the coalescing will be successful and that
923   // the value numbers in EliminatedLHSVals will all be merged together.  Since
924   // the most common case is that EliminatedLHSVals has a single number, we
925   // optimize for it: if there is more than one value, we merge them all into
926   // the lowest numbered one, then handle the interval as if we were merging
927   // with one value number.
928   VNInfo *LHSValNo;
929   if (EliminatedLHSVals.size() > 1) {
930     // Loop through all the equal value numbers merging them into the smallest
931     // one.
932     VNInfo *Smallest = EliminatedLHSVals[0];
933     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
934       if (EliminatedLHSVals[i]->id < Smallest->id) {
935         // Merge the current notion of the smallest into the smaller one.
936         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
937         Smallest = EliminatedLHSVals[i];
938       } else {
939         // Merge into the smallest.
940         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
941       }
942     }
943     LHSValNo = Smallest;
944   } else {
945     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
946     LHSValNo = EliminatedLHSVals[0];
947   }
948   
949   // Okay, now that there is a single LHS value number that we're merging the
950   // RHS into, update the value number info for the LHS to indicate that the
951   // value number is defined where the RHS value number was.
952   const VNInfo *VNI = RHS.getValNumInfo(0);
953   LHSValNo->def = VNI->def;
954   LHSValNo->reg = VNI->reg;
955   
956   // Okay, the final step is to loop over the RHS live intervals, adding them to
957   // the LHS.
958   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
959   LHS.addKills(LHSValNo, VNI->kills);
960   LHS.MergeRangesInAsValue(RHS, LHSValNo);
961   LHS.weight += RHS.weight;
962   if (RHS.preference && !LHS.preference)
963     LHS.preference = RHS.preference;
964   
965   return true;
966 }
967
968 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
969 /// returns false.  Otherwise, if one of the intervals being joined is a
970 /// physreg, this method always canonicalizes LHS to be it.  The output
971 /// "RHS" will not have been modified, so we can use this information
972 /// below to update aliases.
973 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
974                                              LiveInterval &RHS, bool &Swapped) {
975   // Compute the final value assignment, assuming that the live ranges can be
976   // coalesced.
977   SmallVector<int, 16> LHSValNoAssignments;
978   SmallVector<int, 16> RHSValNoAssignments;
979   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
980   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
981   SmallVector<VNInfo*, 16> NewVNInfo;
982                           
983   // If a live interval is a physical register, conservatively check if any
984   // of its sub-registers is overlapping the live interval of the virtual
985   // register. If so, do not coalesce.
986   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
987       *tri_->getSubRegisters(LHS.reg)) {
988     for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
989       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
990         DOUT << "Interfere with sub-register ";
991         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
992         return false;
993       }
994   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
995              *tri_->getSubRegisters(RHS.reg)) {
996     for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
997       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
998         DOUT << "Interfere with sub-register ";
999         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1000         return false;
1001       }
1002   }
1003                           
1004   // Compute ultimate value numbers for the LHS and RHS values.
1005   if (RHS.containsOneValue()) {
1006     // Copies from a liveinterval with a single value are simple to handle and
1007     // very common, handle the special case here.  This is important, because
1008     // often RHS is small and LHS is large (e.g. a physreg).
1009     
1010     // Find out if the RHS is defined as a copy from some value in the LHS.
1011     int RHSVal0DefinedFromLHS = -1;
1012     int RHSValID = -1;
1013     VNInfo *RHSValNoInfo = NULL;
1014     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1015     unsigned RHSSrcReg = RHSValNoInfo0->reg;
1016     if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1017       // If RHS is not defined as a copy from the LHS, we can use simpler and
1018       // faster checks to see if the live ranges are coalescable.  This joiner
1019       // can't swap the LHS/RHS intervals though.
1020       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1021         return SimpleJoin(LHS, RHS);
1022       } else {
1023         RHSValNoInfo = RHSValNoInfo0;
1024       }
1025     } else {
1026       // It was defined as a copy from the LHS, find out what value # it is.
1027       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1028       RHSValID = RHSValNoInfo->id;
1029       RHSVal0DefinedFromLHS = RHSValID;
1030     }
1031     
1032     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1033     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1034     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1035     
1036     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1037     // should now get updated.
1038     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1039          i != e; ++i) {
1040       VNInfo *VNI = *i;
1041       unsigned VN = VNI->id;
1042       if (unsigned LHSSrcReg = VNI->reg) {
1043         if (rep(LHSSrcReg) != RHS.reg) {
1044           // If this is not a copy from the RHS, its value number will be
1045           // unmodified by the coalescing.
1046           NewVNInfo[VN] = VNI;
1047           LHSValNoAssignments[VN] = VN;
1048         } else if (RHSValID == -1) {
1049           // Otherwise, it is a copy from the RHS, and we don't already have a
1050           // value# for it.  Keep the current value number, but remember it.
1051           LHSValNoAssignments[VN] = RHSValID = VN;
1052           NewVNInfo[VN] = RHSValNoInfo;
1053           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1054         } else {
1055           // Otherwise, use the specified value #.
1056           LHSValNoAssignments[VN] = RHSValID;
1057           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1058             NewVNInfo[VN] = RHSValNoInfo;
1059             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1060           }
1061         }
1062       } else {
1063         NewVNInfo[VN] = VNI;
1064         LHSValNoAssignments[VN] = VN;
1065       }
1066     }
1067     
1068     assert(RHSValID != -1 && "Didn't find value #?");
1069     RHSValNoAssignments[0] = RHSValID;
1070     if (RHSVal0DefinedFromLHS != -1) {
1071       // This path doesn't go through ComputeUltimateVN so just set
1072       // it to anything.
1073       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1074     }
1075   } else {
1076     // Loop over the value numbers of the LHS, seeing if any are defined from
1077     // the RHS.
1078     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1079          i != e; ++i) {
1080       VNInfo *VNI = *i;
1081       unsigned ValSrcReg = VNI->reg;
1082       if (VNI->def == ~1U ||ValSrcReg == 0)  // Src not defined by a copy?
1083         continue;
1084       
1085       // DstReg is known to be a register in the LHS interval.  If the src is
1086       // from the RHS interval, we can use its value #.
1087       if (rep(ValSrcReg) != RHS.reg)
1088         continue;
1089       
1090       // Figure out the value # from the RHS.
1091       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1092     }
1093     
1094     // Loop over the value numbers of the RHS, seeing if any are defined from
1095     // the LHS.
1096     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1097          i != e; ++i) {
1098       VNInfo *VNI = *i;
1099       unsigned ValSrcReg = VNI->reg;
1100       if (VNI->def == ~1U || ValSrcReg == 0)  // Src not defined by a copy?
1101         continue;
1102       
1103       // DstReg is known to be a register in the RHS interval.  If the src is
1104       // from the LHS interval, we can use its value #.
1105       if (rep(ValSrcReg) != LHS.reg)
1106         continue;
1107       
1108       // Figure out the value # from the LHS.
1109       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1110     }
1111     
1112     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1113     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1114     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1115     
1116     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1117          i != e; ++i) {
1118       VNInfo *VNI = *i;
1119       unsigned VN = VNI->id;
1120       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1121         continue;
1122       ComputeUltimateVN(VNI, NewVNInfo,
1123                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1124                         LHSValNoAssignments, RHSValNoAssignments);
1125     }
1126     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1127          i != e; ++i) {
1128       VNInfo *VNI = *i;
1129       unsigned VN = VNI->id;
1130       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1131         continue;
1132       // If this value number isn't a copy from the LHS, it's a new number.
1133       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1134         NewVNInfo.push_back(VNI);
1135         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1136         continue;
1137       }
1138       
1139       ComputeUltimateVN(VNI, NewVNInfo,
1140                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1141                         RHSValNoAssignments, LHSValNoAssignments);
1142     }
1143   }
1144   
1145   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1146   // interval lists to see if these intervals are coalescable.
1147   LiveInterval::const_iterator I = LHS.begin();
1148   LiveInterval::const_iterator IE = LHS.end();
1149   LiveInterval::const_iterator J = RHS.begin();
1150   LiveInterval::const_iterator JE = RHS.end();
1151   
1152   // Skip ahead until the first place of potential sharing.
1153   if (I->start < J->start) {
1154     I = std::upper_bound(I, IE, J->start);
1155     if (I != LHS.begin()) --I;
1156   } else if (J->start < I->start) {
1157     J = std::upper_bound(J, JE, I->start);
1158     if (J != RHS.begin()) --J;
1159   }
1160   
1161   while (1) {
1162     // Determine if these two live ranges overlap.
1163     bool Overlaps;
1164     if (I->start < J->start) {
1165       Overlaps = I->end > J->start;
1166     } else {
1167       Overlaps = J->end > I->start;
1168     }
1169
1170     // If so, check value # info to determine if they are really different.
1171     if (Overlaps) {
1172       // If the live range overlap will map to the same value number in the
1173       // result liverange, we can still coalesce them.  If not, we can't.
1174       if (LHSValNoAssignments[I->valno->id] !=
1175           RHSValNoAssignments[J->valno->id])
1176         return false;
1177     }
1178     
1179     if (I->end < J->end) {
1180       ++I;
1181       if (I == IE) break;
1182     } else {
1183       ++J;
1184       if (J == JE) break;
1185     }
1186   }
1187
1188   // Update kill info. Some live ranges are extended due to copy coalescing.
1189   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1190          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1191     VNInfo *VNI = I->first;
1192     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1193     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1194     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1195     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1196   }
1197
1198   // Update kill info. Some live ranges are extended due to copy coalescing.
1199   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1200          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1201     VNInfo *VNI = I->first;
1202     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1203     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1204     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1205     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1206   }
1207
1208   // If we get here, we know that we can coalesce the live ranges.  Ask the
1209   // intervals to coalesce themselves now.
1210   if ((RHS.ranges.size() > LHS.ranges.size() &&
1211       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1212       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1213     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1214     Swapped = true;
1215   } else {
1216     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1217     Swapped = false;
1218   }
1219   return true;
1220 }
1221
1222 namespace {
1223   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1224   // depth of the basic block (the unsigned), and then on the MBB number.
1225   struct DepthMBBCompare {
1226     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1227     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1228       if (LHS.first > RHS.first) return true;   // Deeper loops first
1229       return LHS.first == RHS.first &&
1230         LHS.second->getNumber() < RHS.second->getNumber();
1231     }
1232   };
1233 }
1234
1235 /// getRepIntervalSize - Returns the size of the interval that represents the
1236 /// specified register.
1237 template<class SF>
1238 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1239   return Rc->getRepIntervalSize(Reg);
1240 }
1241
1242 /// CopyRecSort::operator - Join priority queue sorting function.
1243 ///
1244 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1245   // Inner loops first.
1246   if (left.LoopDepth > right.LoopDepth)
1247     return false;
1248   else if (left.LoopDepth == right.LoopDepth) {
1249     if (left.isBackEdge && !right.isBackEdge)
1250       return false;
1251     else if (left.isBackEdge == right.isBackEdge) {
1252       // Join virtuals to physical registers first.
1253       bool LDstIsPhys = TargetRegisterInfo::isPhysicalRegister(left.DstReg);
1254       bool LSrcIsPhys = TargetRegisterInfo::isPhysicalRegister(left.SrcReg);
1255       bool LIsPhys = LDstIsPhys || LSrcIsPhys;
1256       bool RDstIsPhys = TargetRegisterInfo::isPhysicalRegister(right.DstReg);
1257       bool RSrcIsPhys = TargetRegisterInfo::isPhysicalRegister(right.SrcReg);
1258       bool RIsPhys = RDstIsPhys || RSrcIsPhys;
1259       if (LIsPhys && !RIsPhys)
1260         return false;
1261       else if (LIsPhys == RIsPhys) {
1262         // Join shorter intervals first.
1263         unsigned LSize = 0;
1264         unsigned RSize = 0;
1265         if (LIsPhys) {
1266           LSize =  LDstIsPhys ? 0 : JPQ->getRepIntervalSize(left.DstReg);
1267           LSize += LSrcIsPhys ? 0 : JPQ->getRepIntervalSize(left.SrcReg);
1268           RSize =  RDstIsPhys ? 0 : JPQ->getRepIntervalSize(right.DstReg);
1269           RSize += RSrcIsPhys ? 0 : JPQ->getRepIntervalSize(right.SrcReg);
1270         } else {
1271           LSize =  std::min(JPQ->getRepIntervalSize(left.DstReg),
1272                             JPQ->getRepIntervalSize(left.SrcReg));
1273           RSize =  std::min(JPQ->getRepIntervalSize(right.DstReg),
1274                             JPQ->getRepIntervalSize(right.SrcReg));
1275         }
1276         if (LSize < RSize)
1277           return false;
1278       }
1279     }
1280   }
1281   return true;
1282 }
1283
1284 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1285                                                std::vector<CopyRec> &TryAgain) {
1286   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1287
1288   std::vector<CopyRec> VirtCopies;
1289   std::vector<CopyRec> PhysCopies;
1290   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1291   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1292        MII != E;) {
1293     MachineInstr *Inst = MII++;
1294     
1295     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1296     unsigned SrcReg, DstReg;
1297     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1298       DstReg = Inst->getOperand(0).getReg();
1299       SrcReg = Inst->getOperand(1).getReg();
1300     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1301       continue;
1302
1303     unsigned repSrcReg = rep(SrcReg);
1304     unsigned repDstReg = rep(DstReg);
1305     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(repSrcReg);
1306     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(repDstReg);
1307     if (NewHeuristic) {
1308       JoinQueue->push(CopyRec(Inst, SrcReg, DstReg, LoopDepth,
1309                               isBackEdgeCopy(Inst, DstReg)));
1310     } else {
1311       if (SrcIsPhys || DstIsPhys)
1312         PhysCopies.push_back(CopyRec(Inst, SrcReg, DstReg, 0, false));
1313       else
1314         VirtCopies.push_back(CopyRec(Inst, SrcReg, DstReg, 0, false));
1315     }
1316   }
1317
1318   if (NewHeuristic)
1319     return;
1320
1321   // Try coalescing physical register + virtual register first.
1322   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1323     CopyRec &TheCopy = PhysCopies[i];
1324     bool Again = false;
1325     if (!JoinCopy(TheCopy, Again))
1326       if (Again)
1327         TryAgain.push_back(TheCopy);
1328   }
1329   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1330     CopyRec &TheCopy = VirtCopies[i];
1331     bool Again = false;
1332     if (!JoinCopy(TheCopy, Again))
1333       if (Again)
1334         TryAgain.push_back(TheCopy);
1335   }
1336 }
1337
1338 void SimpleRegisterCoalescing::joinIntervals() {
1339   DOUT << "********** JOINING INTERVALS ***********\n";
1340
1341   if (NewHeuristic)
1342     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1343
1344   JoinedLIs.resize(li_->getNumIntervals());
1345   JoinedLIs.reset();
1346
1347   std::vector<CopyRec> TryAgainList;
1348   if (loopInfo->begin() == loopInfo->end()) {
1349     // If there are no loops in the function, join intervals in function order.
1350     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1351          I != E; ++I)
1352       CopyCoalesceInMBB(I, TryAgainList);
1353   } else {
1354     // Otherwise, join intervals in inner loops before other intervals.
1355     // Unfortunately we can't just iterate over loop hierarchy here because
1356     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1357
1358     // Join intervals in the function prolog first. We want to join physical
1359     // registers with virtual registers before the intervals got too long.
1360     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1361     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1362       MachineBasicBlock *MBB = I;
1363       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1364     }
1365
1366     // Sort by loop depth.
1367     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1368
1369     // Finally, join intervals in loop nest order.
1370     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1371       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1372   }
1373   
1374   // Joining intervals can allow other intervals to be joined.  Iteratively join
1375   // until we make no progress.
1376   if (NewHeuristic) {
1377     SmallVector<CopyRec, 16> TryAgain;
1378     bool ProgressMade = true;
1379     while (ProgressMade) {
1380       ProgressMade = false;
1381       while (!JoinQueue->empty()) {
1382         CopyRec R = JoinQueue->pop();
1383         bool Again = false;
1384         bool Success = JoinCopy(R, Again);
1385         if (Success)
1386           ProgressMade = true;
1387         else if (Again)
1388           TryAgain.push_back(R);
1389       }
1390
1391       if (ProgressMade) {
1392         while (!TryAgain.empty()) {
1393           JoinQueue->push(TryAgain.back());
1394           TryAgain.pop_back();
1395         }
1396       }
1397     }
1398   } else {
1399     bool ProgressMade = true;
1400     while (ProgressMade) {
1401       ProgressMade = false;
1402
1403       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1404         CopyRec &TheCopy = TryAgainList[i];
1405         if (TheCopy.MI) {
1406           bool Again = false;
1407           bool Success = JoinCopy(TheCopy, Again);
1408           if (Success || !Again) {
1409             TheCopy.MI = 0;   // Mark this one as done.
1410             ProgressMade = true;
1411           }
1412         }
1413       }
1414     }
1415   }
1416
1417   // Some live range has been lengthened due to colaescing, eliminate the
1418   // unnecessary kills.
1419   int RegNum = JoinedLIs.find_first();
1420   while (RegNum != -1) {
1421     unsigned Reg = RegNum + TargetRegisterInfo::FirstVirtualRegister;
1422     unsigned repReg = rep(Reg);
1423     LiveInterval &LI = li_->getInterval(repReg);
1424     LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
1425     for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
1426       MachineInstr *Kill = svi.Kills[i];
1427       // Suppose vr1 = op vr2, x
1428       // and vr1 and vr2 are coalesced. vr2 should still be marked kill
1429       // unless it is a two-address operand.
1430       if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
1431         continue;
1432       if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
1433         unsetRegisterKill(Kill, repReg);
1434     }
1435     RegNum = JoinedLIs.find_next(RegNum);
1436   }
1437
1438   if (NewHeuristic)
1439     delete JoinQueue;
1440   
1441   DOUT << "*** Register mapping ***\n";
1442   for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
1443     if (r2rMap_[i]) {
1444       DOUT << "  reg " << i << " -> ";
1445       DEBUG(printRegName(r2rMap_[i]));
1446       DOUT << "\n";
1447     }
1448 }
1449
1450 /// Return true if the two specified registers belong to different register
1451 /// classes.  The registers may be either phys or virt regs.
1452 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1453                                                         unsigned RegB) const {
1454
1455   // Get the register classes for the first reg.
1456   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1457     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1458            "Shouldn't consider two physregs!");
1459     return !mf_->getRegInfo().getRegClass(RegB)->contains(RegA);
1460   }
1461
1462   // Compare against the regclass for the second reg.
1463   const TargetRegisterClass *RegClass = mf_->getRegInfo().getRegClass(RegA);
1464   if (TargetRegisterInfo::isVirtualRegister(RegB))
1465     return RegClass != mf_->getRegInfo().getRegClass(RegB);
1466   else
1467     return !RegClass->contains(RegB);
1468 }
1469
1470 /// FIXME: Make use MachineRegisterInfo use information for virtual registers.
1471 /// lastRegisterUse - Returns the last use of the specific register between
1472 /// cycles Start and End. It also returns the use operand by reference. It
1473 /// returns NULL if there are no uses.
1474 MachineInstr *
1475 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1476                                           unsigned Reg, MachineOperand *&MOU) {
1477   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1478   int s = Start;
1479   while (e >= s) {
1480     // Skip deleted instructions
1481     MachineInstr *MI = li_->getInstructionFromIndex(e);
1482     while ((e - InstrSlots::NUM) >= s && !MI) {
1483       e -= InstrSlots::NUM;
1484       MI = li_->getInstructionFromIndex(e);
1485     }
1486     if (e < s || MI == NULL)
1487       return NULL;
1488
1489     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1490       MachineOperand &MO = MI->getOperand(i);
1491       if (MO.isRegister() && MO.isUse() && MO.getReg() &&
1492           tri_->regsOverlap(rep(MO.getReg()), Reg)) {
1493         MOU = &MO;
1494         return MI;
1495       }
1496     }
1497
1498     e -= InstrSlots::NUM;
1499   }
1500
1501   return NULL;
1502 }
1503
1504
1505 /// findDefOperand - Returns the MachineOperand that is a def of the specific
1506 /// register. It returns NULL if the def is not found.
1507 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI,
1508                                                          unsigned Reg) {
1509   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1510     MachineOperand &MO = MI->getOperand(i);
1511     if (MO.isRegister() && MO.isDef() &&
1512         tri_->regsOverlap(rep(MO.getReg()), Reg))
1513       return &MO;
1514   }
1515   return NULL;
1516 }
1517
1518 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
1519 /// of the specific instruction.
1520 void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI,
1521                                                  unsigned Reg) {
1522   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1523     MachineOperand &MO = MI->getOperand(i);
1524     if (MO.isRegister() && MO.isKill() && MO.getReg() &&
1525         tri_->regsOverlap(rep(MO.getReg()), Reg))
1526       MO.setIsKill(false);
1527   }
1528 }
1529
1530 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
1531 /// between cycles Start and End.
1532 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1533                                                   unsigned Reg) {
1534   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1535   int s = Start;
1536   while (e >= s) {
1537     // Skip deleted instructions
1538     MachineInstr *MI = li_->getInstructionFromIndex(e);
1539     while ((e - InstrSlots::NUM) >= s && !MI) {
1540       e -= InstrSlots::NUM;
1541       MI = li_->getInstructionFromIndex(e);
1542     }
1543     if (e < s || MI == NULL)
1544       return;
1545
1546     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1547       MachineOperand &MO = MI->getOperand(i);
1548       if (MO.isRegister() && MO.isKill() && MO.getReg() &&
1549           tri_->regsOverlap(rep(MO.getReg()), Reg)) {
1550         MO.setIsKill(false);
1551       }
1552     }
1553
1554     e -= InstrSlots::NUM;
1555   }
1556 }
1557
1558 /// hasRegisterDef - True if the instruction defines the specific register.
1559 ///
1560 bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1561   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1562     MachineOperand &MO = MI->getOperand(i);
1563     if (MO.isRegister() && MO.isDef() &&
1564         tri_->regsOverlap(rep(MO.getReg()), Reg))
1565       return true;
1566   }
1567   return false;
1568 }
1569
1570 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1571   if (TargetRegisterInfo::isPhysicalRegister(reg))
1572     cerr << tri_->getName(reg);
1573   else
1574     cerr << "%reg" << reg;
1575 }
1576
1577 void SimpleRegisterCoalescing::releaseMemory() {
1578   for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
1579     r2rRevMap_[i].clear();
1580   r2rRevMap_.clear();
1581   r2rMap_.clear();
1582   JoinedLIs.clear();
1583   SubRegIdxes.clear();
1584   JoinedCopies.clear();
1585   ChangedCopies.clear();
1586 }
1587
1588 static bool isZeroLengthInterval(LiveInterval *li) {
1589   for (LiveInterval::Ranges::const_iterator
1590          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1591     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1592       return false;
1593   return true;
1594 }
1595
1596 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1597   mf_ = &fn;
1598   mri_ = &fn.getRegInfo();
1599   tm_ = &fn.getTarget();
1600   tri_ = tm_->getRegisterInfo();
1601   tii_ = tm_->getInstrInfo();
1602   li_ = &getAnalysis<LiveIntervals>();
1603   lv_ = &getAnalysis<LiveVariables>();
1604   loopInfo = &getAnalysis<MachineLoopInfo>();
1605
1606   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1607        << "********** Function: "
1608        << ((Value*)mf_->getFunction())->getName() << '\n';
1609
1610   allocatableRegs_ = tri_->getAllocatableSet(fn);
1611   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1612          E = tri_->regclass_end(); I != E; ++I)
1613     allocatableRCRegs_.insert(std::make_pair(*I,
1614                                              tri_->getAllocatableSet(fn, *I)));
1615
1616   MachineRegisterInfo &RegInfo = mf_->getRegInfo();
1617   r2rMap_.grow(RegInfo.getLastVirtReg());
1618   r2rRevMap_.grow(RegInfo.getLastVirtReg());
1619
1620   // Join (coalesce) intervals if requested.
1621   IndexedMap<unsigned, VirtReg2IndexFunctor> RegSubIdxMap;
1622   if (EnableJoining) {
1623     joinIntervals();
1624     DOUT << "********** INTERVALS POST JOINING **********\n";
1625     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1626       I->second.print(DOUT, tri_);
1627       DOUT << "\n";
1628     }
1629
1630     // Delete all coalesced copies.
1631     for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1632            E = JoinedCopies.end(); I != E; ++I) {
1633       li_->RemoveMachineInstrFromMaps(*I);
1634       (*I)->eraseFromParent();
1635       ++numPeep;
1636     }
1637
1638     // Transfer sub-registers info to MachineRegisterInfo now that coalescing
1639     // information is complete.
1640     RegSubIdxMap.grow(RegInfo.getLastVirtReg()+1);
1641     while (!SubRegIdxes.empty()) {
1642       std::pair<unsigned, unsigned> RI = SubRegIdxes.back();
1643       SubRegIdxes.pop_back();
1644       RegSubIdxMap[RI.first] = RI.second;
1645     }
1646   }
1647
1648   // perform a final pass over the instructions and compute spill
1649   // weights, coalesce virtual registers and remove identity moves.
1650   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1651        mbbi != mbbe; ++mbbi) {
1652     MachineBasicBlock* mbb = mbbi;
1653     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1654
1655     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1656          mii != mie; ) {
1657       // if the move will be an identity move delete it
1658       unsigned srcReg, dstReg, RegRep;
1659       if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1660           (RegRep = rep(srcReg)) == rep(dstReg)) {
1661         // remove from def list
1662         LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1663         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1664         // If def of this move instruction is dead, remove its live range from
1665         // the dstination register's live interval.
1666         if (MO->isDead()) {
1667           unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1668           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1669           RegInt.removeRange(MLR->start, MoveIdx+1, true);
1670           if (RegInt.empty())
1671             li_->removeInterval(RegRep);
1672         }
1673         li_->RemoveMachineInstrFromMaps(mii);
1674         mii = mbbi->erase(mii);
1675         ++numPeep;
1676       } else {
1677         SmallSet<unsigned, 4> UniqueUses;
1678         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1679           const MachineOperand &mop = mii->getOperand(i);
1680           if (mop.isRegister() && mop.getReg() &&
1681               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1682             // replace register with representative register
1683             unsigned OrigReg = mop.getReg();
1684             unsigned reg = rep(OrigReg);
1685             unsigned SubIdx = RegSubIdxMap[OrigReg];
1686             if (SubIdx && TargetRegisterInfo::isPhysicalRegister(reg))
1687               mii->getOperand(i).setReg(tri_->getSubReg(reg, SubIdx));
1688             else {
1689               mii->getOperand(i).setReg(reg);
1690               mii->getOperand(i).setSubReg(SubIdx);
1691             }
1692
1693             // Multiple uses of reg by the same instruction. It should not
1694             // contribute to spill weight again.
1695             if (UniqueUses.count(reg) != 0)
1696               continue;
1697             LiveInterval &RegInt = li_->getInterval(reg);
1698             RegInt.weight +=
1699               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1700             UniqueUses.insert(reg);
1701           }
1702         }
1703         ++mii;
1704       }
1705     }
1706   }
1707
1708   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1709     LiveInterval &LI = I->second;
1710     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1711       // If the live interval length is essentially zero, i.e. in every live
1712       // range the use follows def immediately, it doesn't make sense to spill
1713       // it and hope it will be easier to allocate for this li.
1714       if (isZeroLengthInterval(&LI))
1715         LI.weight = HUGE_VALF;
1716       else {
1717         bool isLoad = false;
1718         if (li_->isReMaterializable(LI, isLoad)) {
1719           // If all of the definitions of the interval are re-materializable,
1720           // it is a preferred candidate for spilling. If non of the defs are
1721           // loads, then it's potentially very cheap to re-materialize.
1722           // FIXME: this gets much more complicated once we support non-trivial
1723           // re-materialization.
1724           if (isLoad)
1725             LI.weight *= 0.9F;
1726           else
1727             LI.weight *= 0.5F;
1728         }
1729       }
1730
1731       // Slightly prefer live interval that has been assigned a preferred reg.
1732       if (LI.preference)
1733         LI.weight *= 1.01F;
1734
1735       // Divide the weight of the interval by its size.  This encourages 
1736       // spilling of intervals that are large and have few uses, and
1737       // discourages spilling of small intervals with many uses.
1738       LI.weight /= LI.getSize();
1739     }
1740   }
1741
1742   DEBUG(dump());
1743   return true;
1744 }
1745
1746 /// print - Implement the dump method.
1747 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1748    li_->print(O, m);
1749 }
1750
1751 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1752   return new SimpleRegisterCoalescing();
1753 }
1754
1755 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1756 DEFINING_FILE_FOR(SimpleRegisterCoalescing)