703f9ffd45771e5e9545b192c880fa89b3f8d143
[oota-llvm.git] / lib / CodeGen / SimpleRegisterCoalescing.cpp
1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "llvm/CodeGen/SimpleRegisterCoalescing.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "VirtRegMap.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.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(numPeep     , "Number of identity moves eliminated after coalescing");
40 STATISTIC(numAborts   , "Number of times interval joining aborted");
41
42 char SimpleRegisterCoalescing::ID = 0;
43 namespace {
44   static cl::opt<bool>
45   EnableJoining("join-liveintervals",
46                 cl::desc("Coalesce copies (default=true)"),
47                 cl::init(true));
48
49   RegisterPass<SimpleRegisterCoalescing> 
50   X("simple-register-coalescing", "Simple Register Coalescing");
51 }
52
53 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
54
55 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
56    //AU.addPreserved<LiveVariables>();
57   AU.addPreserved<LiveIntervals>();
58   AU.addPreservedID(PHIEliminationID);
59   AU.addPreservedID(TwoAddressInstructionPassID);
60   AU.addRequired<LiveVariables>();
61   AU.addRequired<LiveIntervals>();
62   AU.addRequired<LoopInfo>();
63   MachineFunctionPass::getAnalysisUsage(AU);
64 }
65
66 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
67 /// being the source and IntB being the dest, thus this defines a value number
68 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
69 /// see if we can merge these two pieces of B into a single value number,
70 /// eliminating a copy.  For example:
71 ///
72 ///  A3 = B0
73 ///    ...
74 ///  B1 = A3      <- this copy
75 ///
76 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
77 /// value number to be replaced with B0 (which simplifies the B liveinterval).
78 ///
79 /// This returns true if an interval was modified.
80 ///
81 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
82                                          MachineInstr *CopyMI) {
83   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
84
85   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
86   // the example above.
87   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
88   VNInfo *BValNo = BLR->valno;
89   
90   // Get the location that B is defined at.  Two options: either this value has
91   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
92   // can't process it.
93   if (!BValNo->reg) return false;
94   assert(BValNo->def == CopyIdx &&
95          "Copy doesn't define the value?");
96   
97   // AValNo is the value number in A that defines the copy, A0 in the example.
98   LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
99   VNInfo *AValNo = AValLR->valno;
100   
101   // If AValNo is defined as a copy from IntB, we can potentially process this.
102   
103   // Get the instruction that defines this value number.
104   unsigned SrcReg = AValNo->reg;
105   if (!SrcReg) return false;  // Not defined by a copy.
106     
107   // If the value number is not defined by a copy instruction, ignore it.
108     
109   // If the source register comes from an interval other than IntB, we can't
110   // handle this.
111   if (rep(SrcReg) != IntB.reg) return false;
112   
113   // Get the LiveRange in IntB that this value number starts with.
114   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
115   
116   // Make sure that the end of the live range is inside the same block as
117   // CopyMI.
118   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
119   if (!ValLREndInst || 
120       ValLREndInst->getParent() != CopyMI->getParent()) return false;
121
122   // Okay, we now know that ValLR ends in the same block that the CopyMI
123   // live-range starts.  If there are no intervening live ranges between them in
124   // IntB, we can merge them.
125   if (ValLR+1 != BLR) return false;
126
127   // If a live interval is a physical register, conservatively check if any
128   // of its sub-registers is overlapping the live interval of the virtual
129   // register. If so, do not coalesce.
130   if (MRegisterInfo::isPhysicalRegister(IntB.reg) &&
131       *mri_->getSubRegisters(IntB.reg)) {
132     for (const unsigned* SR = mri_->getSubRegisters(IntB.reg); *SR; ++SR)
133       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
134         DOUT << "Interfere with sub-register ";
135         DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
136         return false;
137       }
138   }
139   
140   DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
141   
142   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
143   // We are about to delete CopyMI, so need to remove it as the 'instruction
144   // that defines this value #'. Update the the valnum with the new defining
145   // instruction #.
146   BValNo->def = FillerStart;
147   BValNo->reg = 0;
148   
149   // Okay, we can merge them.  We need to insert a new liverange:
150   // [ValLR.end, BLR.begin) of either value number, then we merge the
151   // two value numbers.
152   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
153
154   // If the IntB live range is assigned to a physical register, and if that
155   // physreg has aliases, 
156   if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
157     // Update the liveintervals of sub-registers.
158     for (const unsigned *AS = mri_->getSubRegisters(IntB.reg); *AS; ++AS) {
159       LiveInterval &AliasLI = li_->getInterval(*AS);
160       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
161                                  AliasLI.getNextValue(FillerStart, 0)));
162     }
163   }
164
165   // Okay, merge "B1" into the same value number as "B0".
166   if (BValNo != ValLR->valno)
167     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
168   DOUT << "   result = "; IntB.print(DOUT, mri_);
169   DOUT << "\n";
170
171   // If the source instruction was killing the source register before the
172   // merge, unset the isKill marker given the live range has been extended.
173   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
174   if (UIdx != -1)
175     ValLREndInst->getOperand(UIdx).unsetIsKill();
176   
177   // Finally, delete the copy instruction.
178   li_->RemoveMachineInstrFromMaps(CopyMI);
179   CopyMI->eraseFromParent();
180   ++numPeep;
181   return true;
182 }
183
184 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
185 /// which are the src/dst of the copy instruction CopyMI.  This returns true
186 /// if the copy was successfully coalesced away, or if it is never possible
187 /// to coalesce this copy, due to register constraints.  It returns
188 /// false if it is not currently possible to coalesce this interval, but
189 /// it may be possible if other things get coalesced.
190 bool SimpleRegisterCoalescing::JoinCopy(MachineInstr *CopyMI,
191                              unsigned SrcReg, unsigned DstReg, bool PhysOnly) {
192   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
193
194   // Get representative registers.
195   unsigned repSrcReg = rep(SrcReg);
196   unsigned repDstReg = rep(DstReg);
197   
198   // If they are already joined we continue.
199   if (repSrcReg == repDstReg) {
200     DOUT << "\tCopy already coalesced.\n";
201     return true;  // Not coalescable.
202   }
203   
204   bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
205   bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
206   if (PhysOnly && !SrcIsPhys && !DstIsPhys)
207     // Only joining physical registers with virtual registers in this round.
208     return true;
209
210   // If they are both physical registers, we cannot join them.
211   if (SrcIsPhys && DstIsPhys) {
212     DOUT << "\tCan not coalesce physregs.\n";
213     return true;  // Not coalescable.
214   }
215   
216   // We only join virtual registers with allocatable physical registers.
217   if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
218     DOUT << "\tSrc reg is unallocatable physreg.\n";
219     return true;  // Not coalescable.
220   }
221   if (DstIsPhys && !allocatableRegs_[repDstReg]) {
222     DOUT << "\tDst reg is unallocatable physreg.\n";
223     return true;  // Not coalescable.
224   }
225   
226   // If they are not of the same register class, we cannot join them.
227   if (differingRegisterClasses(repSrcReg, repDstReg)) {
228     DOUT << "\tSrc/Dest are different register classes.\n";
229     return true;  // Not coalescable.
230   }
231   
232   LiveInterval &SrcInt = li_->getInterval(repSrcReg);
233   LiveInterval &DstInt = li_->getInterval(repDstReg);
234   assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
235          "Register mapping is horribly broken!");
236
237   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
238   DOUT << " and "; DstInt.print(DOUT, mri_);
239   DOUT << ": ";
240
241   // Check if it is necessary to propagate "isDead" property before intervals
242   // are joined.
243   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
244   bool isDead = mopd->isDead();
245   bool isShorten = false;
246   unsigned SrcStart = 0, RemoveStart = 0;
247   unsigned SrcEnd = 0, RemoveEnd = 0;
248   if (isDead) {
249     unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
250     LiveInterval::iterator SrcLR =
251       SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
252     RemoveStart = SrcStart = SrcLR->start;
253     RemoveEnd   = SrcEnd   = SrcLR->end;
254     // The instruction which defines the src is only truly dead if there are
255     // no intermediate uses and there isn't a use beyond the copy.
256     // FIXME: find the last use, mark is kill and shorten the live range.
257     if (SrcEnd > li_->getDefIndex(CopyIdx)) {
258       isDead = false;
259     } else {
260       MachineOperand *MOU;
261       MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
262       if (LastUse) {
263         // Shorten the liveinterval to the end of last use.
264         MOU->setIsKill();
265         isDead = false;
266         isShorten = true;
267         RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
268         RemoveEnd   = SrcEnd;
269       } else {
270         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
271         if (SrcMI) {
272           MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
273           if (mops)
274             // A dead def should have a single cycle interval.
275             ++RemoveStart;
276         }
277       }
278     }
279   }
280
281   // We need to be careful about coalescing a source physical register with a
282   // virtual register. Once the coalescing is done, it cannot be broken and
283   // these are not spillable! If the destination interval uses are far away,
284   // think twice about coalescing them!
285   if (!mopd->isDead() && (SrcIsPhys || DstIsPhys)) {
286     LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
287     unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
288     unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
289     const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(JoinVReg);
290     unsigned Threshold = allocatableRCRegs_[RC].count();
291
292     // If the virtual register live interval is long has it has low use desity,
293     // do not join them, instead mark the physical register as its allocation
294     // preference.
295     unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
296     LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
297     if (Length > Threshold &&
298         (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
299       JoinVInt.preference = JoinPReg;
300       ++numAborts;
301       DOUT << "\tMay tie down a physical register, abort!\n";
302       return false;
303     }
304   }
305
306   // Okay, attempt to join these two intervals.  On failure, this returns false.
307   // Otherwise, if one of the intervals being joined is a physreg, this method
308   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
309   // been modified, so we can use this information below to update aliases.
310   bool Swapped = false;
311   if (JoinIntervals(DstInt, SrcInt, Swapped)) {
312     if (isDead) {
313       // Result of the copy is dead. Propagate this property.
314       if (SrcStart == 0) {
315         assert(MRegisterInfo::isPhysicalRegister(repSrcReg) &&
316                "Live-in must be a physical register!");
317         // Live-in to the function but dead. Remove it from entry live-in set.
318         // JoinIntervals may end up swapping the two intervals.
319         mf_->begin()->removeLiveIn(repSrcReg);
320       } else {
321         MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
322         if (SrcMI) {
323           MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
324           if (mops)
325             mops->setIsDead();
326         }
327       }
328     }
329
330     if (isShorten || isDead) {
331       // Shorten the destination live interval.
332       if (Swapped)
333         SrcInt.removeRange(RemoveStart, RemoveEnd);
334     }
335   } else {
336     // Coalescing failed.
337     
338     // If we can eliminate the copy without merging the live ranges, do so now.
339     if (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI))
340       return true;
341
342     // Otherwise, we are unable to join the intervals.
343     DOUT << "Interference!\n";
344     return false;
345   }
346
347   LiveInterval *ResSrcInt = &SrcInt;
348   LiveInterval *ResDstInt = &DstInt;
349   if (Swapped) {
350     std::swap(repSrcReg, repDstReg);
351     std::swap(ResSrcInt, ResDstInt);
352   }
353   assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
354          "LiveInterval::join didn't work right!");
355                                
356   // If we're about to merge live ranges into a physical register live range,
357   // we have to update any aliased register's live ranges to indicate that they
358   // have clobbered values for this range.
359   if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
360     // Unset unnecessary kills.
361     if (!ResDstInt->containsOneValue()) {
362       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
363              E = ResSrcInt->end(); I != E; ++I)
364         unsetRegisterKills(I->start, I->end, repDstReg);
365     }
366
367     // Update the liveintervals of sub-registers.
368     for (const unsigned *AS = mri_->getSubRegisters(repDstReg); *AS; ++AS)
369       li_->getInterval(*AS).MergeInClobberRanges(*ResSrcInt);
370   } else {
371     // Merge use info if the destination is a virtual register.
372     LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
373     LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
374     dVI.NumUses += sVI.NumUses;
375   }
376
377   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, mri_);
378   DOUT << "\n";
379
380   // Remember these liveintervals have been joined.
381   JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
382   if (MRegisterInfo::isVirtualRegister(repDstReg))
383     JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
384
385   // repSrcReg is guarateed to be the register whose live interval that is
386   // being merged.
387   li_->removeInterval(repSrcReg);
388   r2rMap_[repSrcReg] = repDstReg;
389
390   // Finally, delete the copy instruction.
391   li_->RemoveMachineInstrFromMaps(CopyMI);
392   CopyMI->eraseFromParent();
393   ++numPeep;
394   ++numJoins;
395   return true;
396 }
397
398 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
399 /// compute what the resultant value numbers for each value in the input two
400 /// ranges will be.  This is complicated by copies between the two which can
401 /// and will commonly cause multiple value numbers to be merged into one.
402 ///
403 /// VN is the value number that we're trying to resolve.  InstDefiningValue
404 /// keeps track of the new InstDefiningValue assignment for the result
405 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
406 /// whether a value in this or other is a copy from the opposite set.
407 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
408 /// already been assigned.
409 ///
410 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
411 /// contains the value number the copy is from.
412 ///
413 static unsigned ComputeUltimateVN(VNInfo *VNI,
414                                   SmallVector<VNInfo*, 16> &NewVNInfo,
415                                   SmallVector<VNInfo*, 16> &ThisFromOther,
416                                   SmallVector<VNInfo*, 16> &OtherFromThis,
417                                   SmallVector<int, 16> &ThisValNoAssignments,
418                                   SmallVector<int, 16> &OtherValNoAssignments) {
419   unsigned VN = VNI->id;
420
421   // If the VN has already been computed, just return it.
422   if (ThisValNoAssignments[VN] >= 0)
423     return ThisValNoAssignments[VN];
424 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
425
426   // If this val is not a copy from the other val, then it must be a new value
427   // number in the destination.
428   VNInfo *OtherValNo = ThisFromOther[VN];
429   if (!OtherValNo) {
430     NewVNInfo.push_back(VNI);
431     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
432   }
433
434   // Otherwise, this *is* a copy from the RHS.  If the other side has already
435   // been computed, return it.
436   if (OtherValNoAssignments[OtherValNo->id] >= 0)
437     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
438   
439   // Mark this value number as currently being computed, then ask what the
440   // ultimate value # of the other value is.
441   ThisValNoAssignments[VN] = -2;
442   unsigned UltimateVN =
443     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
444                       OtherValNoAssignments, ThisValNoAssignments);
445   return ThisValNoAssignments[VN] = UltimateVN;
446 }
447
448 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
449   return std::find(V.begin(), V.end(), Val) != V.end();
450 }
451
452 /// SimpleJoin - Attempt to joint the specified interval into this one. The
453 /// caller of this method must guarantee that the RHS only contains a single
454 /// value number and that the RHS is not defined by a copy from this
455 /// interval.  This returns false if the intervals are not joinable, or it
456 /// joins them and returns true.
457 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
458   assert(RHS.containsOneValue());
459   
460   // Some number (potentially more than one) value numbers in the current
461   // interval may be defined as copies from the RHS.  Scan the overlapping
462   // portions of the LHS and RHS, keeping track of this and looking for
463   // overlapping live ranges that are NOT defined as copies.  If these exist, we
464   // cannot coalesce.
465   
466   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
467   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
468   
469   if (LHSIt->start < RHSIt->start) {
470     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
471     if (LHSIt != LHS.begin()) --LHSIt;
472   } else if (RHSIt->start < LHSIt->start) {
473     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
474     if (RHSIt != RHS.begin()) --RHSIt;
475   }
476   
477   SmallVector<VNInfo*, 8> EliminatedLHSVals;
478   
479   while (1) {
480     // Determine if these live intervals overlap.
481     bool Overlaps = false;
482     if (LHSIt->start <= RHSIt->start)
483       Overlaps = LHSIt->end > RHSIt->start;
484     else
485       Overlaps = RHSIt->end > LHSIt->start;
486     
487     // If the live intervals overlap, there are two interesting cases: if the
488     // LHS interval is defined by a copy from the RHS, it's ok and we record
489     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
490     // coalesce these live ranges and we bail out.
491     if (Overlaps) {
492       // If we haven't already recorded that this value # is safe, check it.
493       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
494         // Copy from the RHS?
495         unsigned SrcReg = LHSIt->valno->reg;
496         if (rep(SrcReg) != RHS.reg)
497           return false;    // Nope, bail out.
498         
499         EliminatedLHSVals.push_back(LHSIt->valno);
500       }
501       
502       // We know this entire LHS live range is okay, so skip it now.
503       if (++LHSIt == LHSEnd) break;
504       continue;
505     }
506     
507     if (LHSIt->end < RHSIt->end) {
508       if (++LHSIt == LHSEnd) break;
509     } else {
510       // One interesting case to check here.  It's possible that we have
511       // something like "X3 = Y" which defines a new value number in the LHS,
512       // and is the last use of this liverange of the RHS.  In this case, we
513       // want to notice this copy (so that it gets coalesced away) even though
514       // the live ranges don't actually overlap.
515       if (LHSIt->start == RHSIt->end) {
516         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
517           // We already know that this value number is going to be merged in
518           // if coalescing succeeds.  Just skip the liverange.
519           if (++LHSIt == LHSEnd) break;
520         } else {
521           // Otherwise, if this is a copy from the RHS, mark it as being merged
522           // in.
523           if (rep(LHSIt->valno->reg) == RHS.reg) {
524             EliminatedLHSVals.push_back(LHSIt->valno);
525
526             // We know this entire LHS live range is okay, so skip it now.
527             if (++LHSIt == LHSEnd) break;
528           }
529         }
530       }
531       
532       if (++RHSIt == RHSEnd) break;
533     }
534   }
535   
536   // If we got here, we know that the coalescing will be successful and that
537   // the value numbers in EliminatedLHSVals will all be merged together.  Since
538   // the most common case is that EliminatedLHSVals has a single number, we
539   // optimize for it: if there is more than one value, we merge them all into
540   // the lowest numbered one, then handle the interval as if we were merging
541   // with one value number.
542   VNInfo *LHSValNo;
543   if (EliminatedLHSVals.size() > 1) {
544     // Loop through all the equal value numbers merging them into the smallest
545     // one.
546     VNInfo *Smallest = EliminatedLHSVals[0];
547     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
548       if (EliminatedLHSVals[i]->id < Smallest->id) {
549         // Merge the current notion of the smallest into the smaller one.
550         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
551         Smallest = EliminatedLHSVals[i];
552       } else {
553         // Merge into the smallest.
554         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
555       }
556     }
557     LHSValNo = Smallest;
558   } else {
559     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
560     LHSValNo = EliminatedLHSVals[0];
561   }
562   
563   // Okay, now that there is a single LHS value number that we're merging the
564   // RHS into, update the value number info for the LHS to indicate that the
565   // value number is defined where the RHS value number was.
566   const VNInfo *VNI = RHS.getFirstValNumInfo();
567   LHSValNo->def = VNI->def;
568   LHSValNo->reg = VNI->reg;
569   
570   // Okay, the final step is to loop over the RHS live intervals, adding them to
571   // the LHS.
572   LHS.addKills(*LHSValNo, VNI->kills);
573   LHS.MergeRangesInAsValue(RHS, LHSValNo);
574   LHS.weight += RHS.weight;
575   if (RHS.preference && !LHS.preference)
576     LHS.preference = RHS.preference;
577   
578   return true;
579 }
580
581 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
582 /// returns false.  Otherwise, if one of the intervals being joined is a
583 /// physreg, this method always canonicalizes LHS to be it.  The output
584 /// "RHS" will not have been modified, so we can use this information
585 /// below to update aliases.
586 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
587                                              LiveInterval &RHS, bool &Swapped) {
588   // Compute the final value assignment, assuming that the live ranges can be
589   // coalesced.
590   SmallVector<int, 16> LHSValNoAssignments;
591   SmallVector<int, 16> RHSValNoAssignments;
592   SmallVector<VNInfo*, 16> LHSValsDefinedFromRHS;
593   SmallVector<VNInfo*, 16> RHSValsDefinedFromLHS;
594   SmallVector<VNInfo*, 16> NewVNInfo;
595                           
596   // If a live interval is a physical register, conservatively check if any
597   // of its sub-registers is overlapping the live interval of the virtual
598   // register. If so, do not coalesce.
599   if (MRegisterInfo::isPhysicalRegister(LHS.reg) &&
600       *mri_->getSubRegisters(LHS.reg)) {
601     for (const unsigned* SR = mri_->getSubRegisters(LHS.reg); *SR; ++SR)
602       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
603         DOUT << "Interfere with sub-register ";
604         DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
605         return false;
606       }
607   } else if (MRegisterInfo::isPhysicalRegister(RHS.reg) &&
608              *mri_->getSubRegisters(RHS.reg)) {
609     for (const unsigned* SR = mri_->getSubRegisters(RHS.reg); *SR; ++SR)
610       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
611         DOUT << "Interfere with sub-register ";
612         DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
613         return false;
614       }
615   }
616                           
617   LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), NULL);
618   RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), NULL);
619
620   // Compute ultimate value numbers for the LHS and RHS values.
621   if (RHS.containsOneValue()) {
622     // Copies from a liveinterval with a single value are simple to handle and
623     // very common, handle the special case here.  This is important, because
624     // often RHS is small and LHS is large (e.g. a physreg).
625     
626     // Find out if the RHS is defined as a copy from some value in the LHS.
627     int RHSVal0DefinedFromLHS = -1;
628     int RHSValID = -1;
629     VNInfo *RHSValNoInfo = NULL;
630     unsigned RHSSrcReg = RHS.getFirstValNumInfo()->reg;
631     if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
632       // If RHS is not defined as a copy from the LHS, we can use simpler and
633       // faster checks to see if the live ranges are coalescable.  This joiner
634       // can't swap the LHS/RHS intervals though.
635       if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
636         return SimpleJoin(LHS, RHS);
637       } else {
638         RHSValNoInfo = RHS.getFirstValNumInfo();
639       }
640     } else {
641       // It was defined as a copy from the LHS, find out what value # it is.
642       const VNInfo *VNI = RHS.getFirstValNumInfo();
643       RHSValNoInfo = LHS.getLiveRangeContaining(VNI->def-1)->valno;
644       RHSValID = RHSValNoInfo->id;
645       RHSVal0DefinedFromLHS = RHSValID;
646     }
647     
648     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
649     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
650     NewVNInfo.resize(LHS.getNumValNums(), NULL);
651     
652     // Okay, *all* of the values in LHS that are defined as a copy from RHS
653     // should now get updated.
654     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
655          i != e; ++i) {
656       VNInfo *VNI = *i;
657       unsigned VN = VNI->id;
658       if (unsigned LHSSrcReg = VNI->reg) {
659         if (rep(LHSSrcReg) != RHS.reg) {
660           // If this is not a copy from the RHS, its value number will be
661           // unmodified by the coalescing.
662           NewVNInfo[VN] = VNI;
663           LHSValNoAssignments[VN] = VN;
664         } else if (RHSValID == -1) {
665           // Otherwise, it is a copy from the RHS, and we don't already have a
666           // value# for it.  Keep the current value number, but remember it.
667           LHSValNoAssignments[VN] = RHSValID = VN;
668           NewVNInfo[VN] = RHSValNoInfo;
669           LHSValsDefinedFromRHS[VN] = VNI;
670         } else {
671           // Otherwise, use the specified value #.
672           LHSValNoAssignments[VN] = RHSValID;
673           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
674             NewVNInfo[VN] = RHSValNoInfo;
675             LHSValsDefinedFromRHS[VN] = VNI;
676           }
677         }
678       } else {
679         NewVNInfo[VN] = VNI;
680         LHSValNoAssignments[VN] = VN;
681       }
682     }
683     
684     assert(RHSValID != -1 && "Didn't find value #?");
685     RHSValNoAssignments[0] = RHSValID;
686     if (RHSVal0DefinedFromLHS != -1) {
687       const VNInfo *VNI = RHS.getFirstValNumInfo();
688       RHSValsDefinedFromLHS[0] = LHS.getLiveRangeContaining(VNI->def-1)->valno;
689     }
690   } else {
691     // Loop over the value numbers of the LHS, seeing if any are defined from
692     // the RHS.
693     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
694          i != e; ++i) {
695       VNInfo *VNI = *i;
696       unsigned VN = VNI->id;
697       unsigned ValSrcReg = VNI->reg;
698       if (ValSrcReg == 0)  // Src not defined by a copy?
699         continue;
700       
701       // DstReg is known to be a register in the LHS interval.  If the src is
702       // from the RHS interval, we can use its value #.
703       if (rep(ValSrcReg) != RHS.reg)
704         continue;
705       
706       // Figure out the value # from the RHS.
707       LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(VNI->def-1)->valno;
708     }
709     
710     // Loop over the value numbers of the RHS, seeing if any are defined from
711     // the LHS.
712     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
713          i != e; ++i) {
714       VNInfo *VNI = *i;
715       unsigned VN = VNI->id;
716       unsigned ValSrcReg = VNI->reg;
717       if (ValSrcReg == 0)  // Src not defined by a copy?
718         continue;
719       
720       // DstReg is known to be a register in the RHS interval.  If the src is
721       // from the LHS interval, we can use its value #.
722       if (rep(ValSrcReg) != LHS.reg)
723         continue;
724       
725       // Figure out the value # from the LHS.
726       RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(VNI->def-1)->valno;
727     }
728     
729     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
730     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
731     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
732     
733     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
734          i != e; ++i) {
735       VNInfo *VNI = *i;
736       unsigned VN = VNI->id;
737       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
738         continue;
739       ComputeUltimateVN(VNI, NewVNInfo,
740                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
741                         LHSValNoAssignments, RHSValNoAssignments);
742     }
743     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
744          i != e; ++i) {
745       VNInfo *VNI = *i;
746       unsigned VN = VNI->id;
747       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
748         continue;
749       // If this value number isn't a copy from the LHS, it's a new number.
750       if (!RHSValsDefinedFromLHS[VN]) {
751         NewVNInfo.push_back(VNI);
752         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
753         continue;
754       }
755       
756       ComputeUltimateVN(VNI, NewVNInfo,
757                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
758                         RHSValNoAssignments, LHSValNoAssignments);
759     }
760   }
761   
762   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
763   // interval lists to see if these intervals are coalescable.
764   LiveInterval::const_iterator I = LHS.begin();
765   LiveInterval::const_iterator IE = LHS.end();
766   LiveInterval::const_iterator J = RHS.begin();
767   LiveInterval::const_iterator JE = RHS.end();
768   
769   // Skip ahead until the first place of potential sharing.
770   if (I->start < J->start) {
771     I = std::upper_bound(I, IE, J->start);
772     if (I != LHS.begin()) --I;
773   } else if (J->start < I->start) {
774     J = std::upper_bound(J, JE, I->start);
775     if (J != RHS.begin()) --J;
776   }
777   
778   while (1) {
779     // Determine if these two live ranges overlap.
780     bool Overlaps;
781     if (I->start < J->start) {
782       Overlaps = I->end > J->start;
783     } else {
784       Overlaps = J->end > I->start;
785     }
786
787     // If so, check value # info to determine if they are really different.
788     if (Overlaps) {
789       // If the live range overlap will map to the same value number in the
790       // result liverange, we can still coalesce them.  If not, we can't.
791       if (LHSValNoAssignments[I->valno->id] !=
792           RHSValNoAssignments[J->valno->id])
793         return false;
794     }
795     
796     if (I->end < J->end) {
797       ++I;
798       if (I == IE) break;
799     } else {
800       ++J;
801       if (J == JE) break;
802     }
803   }
804
805   // Update kill info. Some live ranges are extended due to copy coalescing.
806   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
807        i != e; ++i) {
808     VNInfo *VNI = *i;
809     unsigned VN = VNI->id;
810     if (VN >= RHSValsDefinedFromLHS.size() || !RHSValsDefinedFromLHS[VN])
811       continue;
812     unsigned RHSValID = RHSValNoAssignments[VN];
813     LiveInterval::removeKill(*NewVNInfo[RHSValID], VNI->def);
814     LHS.addKills(*NewVNInfo[RHSValID], VNI->kills);
815   }
816   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
817        i != e; ++i) {
818     VNInfo *VNI = *i;
819     unsigned VN = VNI->id;
820     if (VN >= LHSValsDefinedFromRHS.size() || !LHSValsDefinedFromRHS[VN])
821       continue;
822     unsigned LHSValID = LHSValNoAssignments[VN];
823     LiveInterval::removeKill(*NewVNInfo[LHSValID], VNI->def);
824     RHS.addKills(*NewVNInfo[LHSValID], VNI->kills);
825   }
826
827   // If we get here, we know that we can coalesce the live ranges.  Ask the
828   // intervals to coalesce themselves now.
829   if ((RHS.ranges.size() > LHS.ranges.size() &&
830       MRegisterInfo::isVirtualRegister(LHS.reg)) ||
831       MRegisterInfo::isPhysicalRegister(RHS.reg)) {
832     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
833     Swapped = true;
834   } else {
835     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
836     Swapped = false;
837   }
838   return true;
839 }
840
841 namespace {
842   // DepthMBBCompare - Comparison predicate that sort first based on the loop
843   // depth of the basic block (the unsigned), and then on the MBB number.
844   struct DepthMBBCompare {
845     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
846     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
847       if (LHS.first > RHS.first) return true;   // Deeper loops first
848       return LHS.first == RHS.first &&
849         LHS.second->getNumber() < RHS.second->getNumber();
850     }
851   };
852 }
853
854 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
855                                 std::vector<CopyRec> *TryAgain, bool PhysOnly) {
856   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
857   
858   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
859        MII != E;) {
860     MachineInstr *Inst = MII++;
861     
862     // If this isn't a copy, we can't join intervals.
863     unsigned SrcReg, DstReg;
864     if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
865     
866     if (TryAgain && !JoinCopy(Inst, SrcReg, DstReg, PhysOnly))
867       TryAgain->push_back(getCopyRec(Inst, SrcReg, DstReg));
868   }
869 }
870
871 void SimpleRegisterCoalescing::joinIntervals() {
872   DOUT << "********** JOINING INTERVALS ***********\n";
873
874   JoinedLIs.resize(li_->getNumIntervals());
875   JoinedLIs.reset();
876
877   std::vector<CopyRec> TryAgainList;
878   const LoopInfo &LI = getAnalysis<LoopInfo>();
879   if (LI.begin() == LI.end()) {
880     // If there are no loops in the function, join intervals in function order.
881     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
882          I != E; ++I)
883       CopyCoalesceInMBB(I, &TryAgainList);
884   } else {
885     // Otherwise, join intervals in inner loops before other intervals.
886     // Unfortunately we can't just iterate over loop hierarchy here because
887     // there may be more MBB's than BB's.  Collect MBB's for sorting.
888
889     // Join intervals in the function prolog first. We want to join physical
890     // registers with virtual registers before the intervals got too long.
891     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
892     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); I != E;++I)
893       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
894
895     // Sort by loop depth.
896     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
897
898     // Finally, join intervals in loop nest order.
899     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
900       CopyCoalesceInMBB(MBBs[i].second, NULL, true);
901     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
902       CopyCoalesceInMBB(MBBs[i].second, &TryAgainList, false);
903   }
904   
905   // Joining intervals can allow other intervals to be joined.  Iteratively join
906   // until we make no progress.
907   bool ProgressMade = true;
908   while (ProgressMade) {
909     ProgressMade = false;
910
911     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
912       CopyRec &TheCopy = TryAgainList[i];
913       if (TheCopy.MI &&
914           JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
915         TheCopy.MI = 0;   // Mark this one as done.
916         ProgressMade = true;
917       }
918     }
919   }
920
921   // Some live range has been lengthened due to colaescing, eliminate the
922   // unnecessary kills.
923   int RegNum = JoinedLIs.find_first();
924   while (RegNum != -1) {
925     unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
926     unsigned repReg = rep(Reg);
927     LiveInterval &LI = li_->getInterval(repReg);
928     LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
929     for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
930       MachineInstr *Kill = svi.Kills[i];
931       // Suppose vr1 = op vr2, x
932       // and vr1 and vr2 are coalesced. vr2 should still be marked kill
933       // unless it is a two-address operand.
934       if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
935         continue;
936       if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
937         unsetRegisterKill(Kill, repReg);
938     }
939     RegNum = JoinedLIs.find_next(RegNum);
940   }
941   
942   DOUT << "*** Register mapping ***\n";
943   for (int i = 0, e = r2rMap_.size(); i != e; ++i)
944     if (r2rMap_[i]) {
945       DOUT << "  reg " << i << " -> ";
946       DEBUG(printRegName(r2rMap_[i]));
947       DOUT << "\n";
948     }
949 }
950
951 /// Return true if the two specified registers belong to different register
952 /// classes.  The registers may be either phys or virt regs.
953 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
954                                              unsigned RegB) const {
955
956   // Get the register classes for the first reg.
957   if (MRegisterInfo::isPhysicalRegister(RegA)) {
958     assert(MRegisterInfo::isVirtualRegister(RegB) &&
959            "Shouldn't consider two physregs!");
960     return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
961   }
962
963   // Compare against the regclass for the second reg.
964   const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
965   if (MRegisterInfo::isVirtualRegister(RegB))
966     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
967   else
968     return !RegClass->contains(RegB);
969 }
970
971 /// lastRegisterUse - Returns the last use of the specific register between
972 /// cycles Start and End. It also returns the use operand by reference. It
973 /// returns NULL if there are no uses.
974 MachineInstr *
975 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
976                                MachineOperand *&MOU) {
977   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
978   int s = Start;
979   while (e >= s) {
980     // Skip deleted instructions
981     MachineInstr *MI = li_->getInstructionFromIndex(e);
982     while ((e - InstrSlots::NUM) >= s && !MI) {
983       e -= InstrSlots::NUM;
984       MI = li_->getInstructionFromIndex(e);
985     }
986     if (e < s || MI == NULL)
987       return NULL;
988
989     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
990       MachineOperand &MO = MI->getOperand(i);
991       if (MO.isReg() && MO.isUse() && MO.getReg() &&
992           mri_->regsOverlap(rep(MO.getReg()), Reg)) {
993         MOU = &MO;
994         return MI;
995       }
996     }
997
998     e -= InstrSlots::NUM;
999   }
1000
1001   return NULL;
1002 }
1003
1004
1005 /// findDefOperand - Returns the MachineOperand that is a def of the specific
1006 /// register. It returns NULL if the def is not found.
1007 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI, unsigned Reg) {
1008   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1009     MachineOperand &MO = MI->getOperand(i);
1010     if (MO.isReg() && MO.isDef() &&
1011         mri_->regsOverlap(rep(MO.getReg()), Reg))
1012       return &MO;
1013   }
1014   return NULL;
1015 }
1016
1017 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
1018 /// of the specific instruction.
1019 void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1020   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1021     MachineOperand &MO = MI->getOperand(i);
1022     if (MO.isReg() && MO.isKill() && MO.getReg() &&
1023         mri_->regsOverlap(rep(MO.getReg()), Reg))
1024       MO.unsetIsKill();
1025   }
1026 }
1027
1028 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
1029 /// between cycles Start and End.
1030 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1031                                        unsigned Reg) {
1032   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1033   int s = Start;
1034   while (e >= s) {
1035     // Skip deleted instructions
1036     MachineInstr *MI = li_->getInstructionFromIndex(e);
1037     while ((e - InstrSlots::NUM) >= s && !MI) {
1038       e -= InstrSlots::NUM;
1039       MI = li_->getInstructionFromIndex(e);
1040     }
1041     if (e < s || MI == NULL)
1042       return;
1043
1044     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1045       MachineOperand &MO = MI->getOperand(i);
1046       if (MO.isReg() && MO.isKill() && MO.getReg() &&
1047           mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1048         MO.unsetIsKill();
1049       }
1050     }
1051
1052     e -= InstrSlots::NUM;
1053   }
1054 }
1055
1056 /// hasRegisterDef - True if the instruction defines the specific register.
1057 ///
1058 bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1059   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1060     MachineOperand &MO = MI->getOperand(i);
1061     if (MO.isReg() && MO.isDef() &&
1062         mri_->regsOverlap(rep(MO.getReg()), Reg))
1063       return true;
1064   }
1065   return false;
1066 }
1067
1068 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1069   if (MRegisterInfo::isPhysicalRegister(reg))
1070     cerr << mri_->getName(reg);
1071   else
1072     cerr << "%reg" << reg;
1073 }
1074
1075 void SimpleRegisterCoalescing::releaseMemory() {
1076    r2rMap_.clear();
1077    JoinedLIs.clear();
1078 }
1079
1080 static bool isZeroLengthInterval(LiveInterval *li) {
1081   for (LiveInterval::Ranges::const_iterator
1082          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1083     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1084       return false;
1085   return true;
1086 }
1087
1088 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1089   mf_ = &fn;
1090   tm_ = &fn.getTarget();
1091   mri_ = tm_->getRegisterInfo();
1092   tii_ = tm_->getInstrInfo();
1093   li_ = &getAnalysis<LiveIntervals>();
1094   lv_ = &getAnalysis<LiveVariables>();
1095
1096   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1097        << "********** Function: "
1098        << ((Value*)mf_->getFunction())->getName() << '\n';
1099
1100   allocatableRegs_ = mri_->getAllocatableSet(fn);
1101   for (MRegisterInfo::regclass_iterator I = mri_->regclass_begin(),
1102          E = mri_->regclass_end(); I != E; ++I)
1103     allocatableRCRegs_.insert(std::make_pair(*I,mri_->getAllocatableSet(fn, *I)));
1104
1105   r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
1106
1107   // Join (coalesce) intervals if requested.
1108   if (EnableJoining) {
1109     joinIntervals();
1110     DOUT << "********** INTERVALS POST JOINING **********\n";
1111     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1112       I->second.print(DOUT, mri_);
1113       DOUT << "\n";
1114     }
1115   }
1116
1117   // perform a final pass over the instructions and compute spill
1118   // weights, coalesce virtual registers and remove identity moves.
1119   const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
1120
1121   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1122        mbbi != mbbe; ++mbbi) {
1123     MachineBasicBlock* mbb = mbbi;
1124     unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
1125
1126     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1127          mii != mie; ) {
1128       // if the move will be an identity move delete it
1129       unsigned srcReg, dstReg, RegRep;
1130       if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1131           (RegRep = rep(srcReg)) == rep(dstReg)) {
1132         // remove from def list
1133         LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1134         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1135         // If def of this move instruction is dead, remove its live range from
1136         // the dstination register's live interval.
1137         if (MO->isDead()) {
1138           unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1139           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1140           RegInt.removeRange(MLR->start, MoveIdx+1);
1141           if (RegInt.empty())
1142             li_->removeInterval(RegRep);
1143         }
1144         li_->RemoveMachineInstrFromMaps(mii);
1145         mii = mbbi->erase(mii);
1146         ++numPeep;
1147       } else {
1148         SmallSet<unsigned, 4> UniqueUses;
1149         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1150           const MachineOperand &mop = mii->getOperand(i);
1151           if (mop.isRegister() && mop.getReg() &&
1152               MRegisterInfo::isVirtualRegister(mop.getReg())) {
1153             // replace register with representative register
1154             unsigned reg = rep(mop.getReg());
1155             mii->getOperand(i).setReg(reg);
1156
1157             // Multiple uses of reg by the same instruction. It should not
1158             // contribute to spill weight again.
1159             if (UniqueUses.count(reg) != 0)
1160               continue;
1161             LiveInterval &RegInt = li_->getInterval(reg);
1162             float w = (mop.isUse()+mop.isDef()) * powf(10.0F, (float)loopDepth);
1163             RegInt.weight += w;
1164             UniqueUses.insert(reg);
1165           }
1166         }
1167         ++mii;
1168       }
1169     }
1170   }
1171
1172   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1173     LiveInterval &LI = I->second;
1174     if (MRegisterInfo::isVirtualRegister(LI.reg)) {
1175       // If the live interval length is essentially zero, i.e. in every live
1176       // range the use follows def immediately, it doesn't make sense to spill
1177       // it and hope it will be easier to allocate for this li.
1178       if (isZeroLengthInterval(&LI))
1179         LI.weight = HUGE_VALF;
1180
1181       // Slightly prefer live interval that has been assigned a preferred reg.
1182       if (LI.preference)
1183         LI.weight *= 1.01F;
1184
1185       // Divide the weight of the interval by its size.  This encourages 
1186       // spilling of intervals that are large and have few uses, and
1187       // discourages spilling of small intervals with many uses.
1188       LI.weight /= LI.getSize();
1189     }
1190   }
1191
1192   DEBUG(dump());
1193   return true;
1194 }
1195
1196 /// print - Implement the dump method.
1197 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1198    li_->print(O, m);
1199 }