More tweaks to improve compile time.
[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                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
416                                   DenseMap<VNInfo*, VNInfo*> &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   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
429   if (I == ThisFromOther.end()) {
430     NewVNInfo.push_back(VNI);
431     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
432   }
433   VNInfo *OtherValNo = I->second;
434
435   // Otherwise, this *is* a copy from the RHS.  If the other side has already
436   // been computed, return it.
437   if (OtherValNoAssignments[OtherValNo->id] >= 0)
438     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
439   
440   // Mark this value number as currently being computed, then ask what the
441   // ultimate value # of the other value is.
442   ThisValNoAssignments[VN] = -2;
443   unsigned UltimateVN =
444     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
445                       OtherValNoAssignments, ThisValNoAssignments);
446   return ThisValNoAssignments[VN] = UltimateVN;
447 }
448
449 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
450   return std::find(V.begin(), V.end(), Val) != V.end();
451 }
452
453 /// SimpleJoin - Attempt to joint the specified interval into this one. The
454 /// caller of this method must guarantee that the RHS only contains a single
455 /// value number and that the RHS is not defined by a copy from this
456 /// interval.  This returns false if the intervals are not joinable, or it
457 /// joins them and returns true.
458 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
459   assert(RHS.containsOneValue());
460   
461   // Some number (potentially more than one) value numbers in the current
462   // interval may be defined as copies from the RHS.  Scan the overlapping
463   // portions of the LHS and RHS, keeping track of this and looking for
464   // overlapping live ranges that are NOT defined as copies.  If these exist, we
465   // cannot coalesce.
466   
467   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
468   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
469   
470   if (LHSIt->start < RHSIt->start) {
471     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
472     if (LHSIt != LHS.begin()) --LHSIt;
473   } else if (RHSIt->start < LHSIt->start) {
474     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
475     if (RHSIt != RHS.begin()) --RHSIt;
476   }
477   
478   SmallVector<VNInfo*, 8> EliminatedLHSVals;
479   
480   while (1) {
481     // Determine if these live intervals overlap.
482     bool Overlaps = false;
483     if (LHSIt->start <= RHSIt->start)
484       Overlaps = LHSIt->end > RHSIt->start;
485     else
486       Overlaps = RHSIt->end > LHSIt->start;
487     
488     // If the live intervals overlap, there are two interesting cases: if the
489     // LHS interval is defined by a copy from the RHS, it's ok and we record
490     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
491     // coalesce these live ranges and we bail out.
492     if (Overlaps) {
493       // If we haven't already recorded that this value # is safe, check it.
494       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
495         // Copy from the RHS?
496         unsigned SrcReg = LHSIt->valno->reg;
497         if (rep(SrcReg) != RHS.reg)
498           return false;    // Nope, bail out.
499         
500         EliminatedLHSVals.push_back(LHSIt->valno);
501       }
502       
503       // We know this entire LHS live range is okay, so skip it now.
504       if (++LHSIt == LHSEnd) break;
505       continue;
506     }
507     
508     if (LHSIt->end < RHSIt->end) {
509       if (++LHSIt == LHSEnd) break;
510     } else {
511       // One interesting case to check here.  It's possible that we have
512       // something like "X3 = Y" which defines a new value number in the LHS,
513       // and is the last use of this liverange of the RHS.  In this case, we
514       // want to notice this copy (so that it gets coalesced away) even though
515       // the live ranges don't actually overlap.
516       if (LHSIt->start == RHSIt->end) {
517         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
518           // We already know that this value number is going to be merged in
519           // if coalescing succeeds.  Just skip the liverange.
520           if (++LHSIt == LHSEnd) break;
521         } else {
522           // Otherwise, if this is a copy from the RHS, mark it as being merged
523           // in.
524           if (rep(LHSIt->valno->reg) == RHS.reg) {
525             EliminatedLHSVals.push_back(LHSIt->valno);
526
527             // We know this entire LHS live range is okay, so skip it now.
528             if (++LHSIt == LHSEnd) break;
529           }
530         }
531       }
532       
533       if (++RHSIt == RHSEnd) break;
534     }
535   }
536   
537   // If we got here, we know that the coalescing will be successful and that
538   // the value numbers in EliminatedLHSVals will all be merged together.  Since
539   // the most common case is that EliminatedLHSVals has a single number, we
540   // optimize for it: if there is more than one value, we merge them all into
541   // the lowest numbered one, then handle the interval as if we were merging
542   // with one value number.
543   VNInfo *LHSValNo;
544   if (EliminatedLHSVals.size() > 1) {
545     // Loop through all the equal value numbers merging them into the smallest
546     // one.
547     VNInfo *Smallest = EliminatedLHSVals[0];
548     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
549       if (EliminatedLHSVals[i]->id < Smallest->id) {
550         // Merge the current notion of the smallest into the smaller one.
551         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
552         Smallest = EliminatedLHSVals[i];
553       } else {
554         // Merge into the smallest.
555         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
556       }
557     }
558     LHSValNo = Smallest;
559   } else {
560     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
561     LHSValNo = EliminatedLHSVals[0];
562   }
563   
564   // Okay, now that there is a single LHS value number that we're merging the
565   // RHS into, update the value number info for the LHS to indicate that the
566   // value number is defined where the RHS value number was.
567   const VNInfo *VNI = RHS.getFirstValNumInfo();
568   LHSValNo->def = VNI->def;
569   LHSValNo->reg = VNI->reg;
570   
571   // Okay, the final step is to loop over the RHS live intervals, adding them to
572   // the LHS.
573   LHS.addKills(*LHSValNo, VNI->kills);
574   LHS.MergeRangesInAsValue(RHS, LHSValNo);
575   LHS.weight += RHS.weight;
576   if (RHS.preference && !LHS.preference)
577     LHS.preference = RHS.preference;
578   
579   return true;
580 }
581
582 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
583 /// returns false.  Otherwise, if one of the intervals being joined is a
584 /// physreg, this method always canonicalizes LHS to be it.  The output
585 /// "RHS" will not have been modified, so we can use this information
586 /// below to update aliases.
587 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
588                                              LiveInterval &RHS, bool &Swapped) {
589   // Compute the final value assignment, assuming that the live ranges can be
590   // coalesced.
591   SmallVector<int, 16> LHSValNoAssignments;
592   SmallVector<int, 16> RHSValNoAssignments;
593   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
594   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
595   SmallVector<VNInfo*, 16> NewVNInfo;
596                           
597   // If a live interval is a physical register, conservatively check if any
598   // of its sub-registers is overlapping the live interval of the virtual
599   // register. If so, do not coalesce.
600   if (MRegisterInfo::isPhysicalRegister(LHS.reg) &&
601       *mri_->getSubRegisters(LHS.reg)) {
602     for (const unsigned* SR = mri_->getSubRegisters(LHS.reg); *SR; ++SR)
603       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
604         DOUT << "Interfere with sub-register ";
605         DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
606         return false;
607       }
608   } else if (MRegisterInfo::isPhysicalRegister(RHS.reg) &&
609              *mri_->getSubRegisters(RHS.reg)) {
610     for (const unsigned* SR = mri_->getSubRegisters(RHS.reg); *SR; ++SR)
611       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
612         DOUT << "Interfere with sub-register ";
613         DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
614         return false;
615       }
616   }
617                           
618   // Compute ultimate value numbers for the LHS and RHS values.
619   if (RHS.containsOneValue()) {
620     // Copies from a liveinterval with a single value are simple to handle and
621     // very common, handle the special case here.  This is important, because
622     // often RHS is small and LHS is large (e.g. a physreg).
623     
624     // Find out if the RHS is defined as a copy from some value in the LHS.
625     int RHSVal0DefinedFromLHS = -1;
626     int RHSValID = -1;
627     VNInfo *RHSValNoInfo = NULL;
628     VNInfo *RHSValNoInfo0 = RHS.getFirstValNumInfo();
629     unsigned RHSSrcReg = RHSValNoInfo0->reg;
630     if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
631       // If RHS is not defined as a copy from the LHS, we can use simpler and
632       // faster checks to see if the live ranges are coalescable.  This joiner
633       // can't swap the LHS/RHS intervals though.
634       if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
635         return SimpleJoin(LHS, RHS);
636       } else {
637         RHSValNoInfo = RHSValNoInfo0;
638       }
639     } else {
640       // It was defined as a copy from the LHS, find out what value # it is.
641       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
642       RHSValID = RHSValNoInfo->id;
643       RHSVal0DefinedFromLHS = RHSValID;
644     }
645     
646     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
647     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
648     NewVNInfo.resize(LHS.getNumValNums(), NULL);
649     
650     // Okay, *all* of the values in LHS that are defined as a copy from RHS
651     // should now get updated.
652     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
653          i != e; ++i) {
654       VNInfo *VNI = *i;
655       unsigned VN = VNI->id;
656       if (unsigned LHSSrcReg = VNI->reg) {
657         if (rep(LHSSrcReg) != RHS.reg) {
658           // If this is not a copy from the RHS, its value number will be
659           // unmodified by the coalescing.
660           NewVNInfo[VN] = VNI;
661           LHSValNoAssignments[VN] = VN;
662         } else if (RHSValID == -1) {
663           // Otherwise, it is a copy from the RHS, and we don't already have a
664           // value# for it.  Keep the current value number, but remember it.
665           LHSValNoAssignments[VN] = RHSValID = VN;
666           NewVNInfo[VN] = RHSValNoInfo;
667           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
668         } else {
669           // Otherwise, use the specified value #.
670           LHSValNoAssignments[VN] = RHSValID;
671           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
672             NewVNInfo[VN] = RHSValNoInfo;
673             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
674           }
675         }
676       } else {
677         NewVNInfo[VN] = VNI;
678         LHSValNoAssignments[VN] = VN;
679       }
680     }
681     
682     assert(RHSValID != -1 && "Didn't find value #?");
683     RHSValNoAssignments[0] = RHSValID;
684     if (RHSVal0DefinedFromLHS != -1) {
685       // This path doesn't go through ComputeUltimateVN so just set
686       // it to anything.
687       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
688     }
689   } else {
690     // Loop over the value numbers of the LHS, seeing if any are defined from
691     // the RHS.
692     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
693          i != e; ++i) {
694       VNInfo *VNI = *i;
695       unsigned ValSrcReg = VNI->reg;
696       if (ValSrcReg == 0)  // Src not defined by a copy?
697         continue;
698       
699       // DstReg is known to be a register in the LHS interval.  If the src is
700       // from the RHS interval, we can use its value #.
701       if (rep(ValSrcReg) != RHS.reg)
702         continue;
703       
704       // Figure out the value # from the RHS.
705       LHSValsDefinedFromRHS[VNI] = RHS.getLiveRangeContaining(VNI->def-1)->valno;
706     }
707     
708     // Loop over the value numbers of the RHS, seeing if any are defined from
709     // the LHS.
710     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
711          i != e; ++i) {
712       VNInfo *VNI = *i;
713       unsigned ValSrcReg = VNI->reg;
714       if (ValSrcReg == 0)  // Src not defined by a copy?
715         continue;
716       
717       // DstReg is known to be a register in the RHS interval.  If the src is
718       // from the LHS interval, we can use its value #.
719       if (rep(ValSrcReg) != LHS.reg)
720         continue;
721       
722       // Figure out the value # from the LHS.
723       RHSValsDefinedFromLHS[VNI]= LHS.getLiveRangeContaining(VNI->def-1)->valno;
724     }
725     
726     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
727     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
728     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
729     
730     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
731          i != e; ++i) {
732       VNInfo *VNI = *i;
733       unsigned VN = VNI->id;
734       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
735         continue;
736       ComputeUltimateVN(VNI, NewVNInfo,
737                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
738                         LHSValNoAssignments, RHSValNoAssignments);
739     }
740     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
741          i != e; ++i) {
742       VNInfo *VNI = *i;
743       unsigned VN = VNI->id;
744       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
745         continue;
746       // If this value number isn't a copy from the LHS, it's a new number.
747       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
748         NewVNInfo.push_back(VNI);
749         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
750         continue;
751       }
752       
753       ComputeUltimateVN(VNI, NewVNInfo,
754                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
755                         RHSValNoAssignments, LHSValNoAssignments);
756     }
757   }
758   
759   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
760   // interval lists to see if these intervals are coalescable.
761   LiveInterval::const_iterator I = LHS.begin();
762   LiveInterval::const_iterator IE = LHS.end();
763   LiveInterval::const_iterator J = RHS.begin();
764   LiveInterval::const_iterator JE = RHS.end();
765   
766   // Skip ahead until the first place of potential sharing.
767   if (I->start < J->start) {
768     I = std::upper_bound(I, IE, J->start);
769     if (I != LHS.begin()) --I;
770   } else if (J->start < I->start) {
771     J = std::upper_bound(J, JE, I->start);
772     if (J != RHS.begin()) --J;
773   }
774   
775   while (1) {
776     // Determine if these two live ranges overlap.
777     bool Overlaps;
778     if (I->start < J->start) {
779       Overlaps = I->end > J->start;
780     } else {
781       Overlaps = J->end > I->start;
782     }
783
784     // If so, check value # info to determine if they are really different.
785     if (Overlaps) {
786       // If the live range overlap will map to the same value number in the
787       // result liverange, we can still coalesce them.  If not, we can't.
788       if (LHSValNoAssignments[I->valno->id] !=
789           RHSValNoAssignments[J->valno->id])
790         return false;
791     }
792     
793     if (I->end < J->end) {
794       ++I;
795       if (I == IE) break;
796     } else {
797       ++J;
798       if (J == JE) break;
799     }
800   }
801
802   // If we get here, we know that we can coalesce the live ranges.  Ask the
803   // intervals to coalesce themselves now.
804   if ((RHS.ranges.size() > LHS.ranges.size() &&
805       MRegisterInfo::isVirtualRegister(LHS.reg)) ||
806       MRegisterInfo::isPhysicalRegister(RHS.reg)) {
807     // Update kill info. Some live ranges are extended due to copy coalescing.
808     for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
809            E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
810       VNInfo *VNI = I->first;
811       unsigned LHSValID = LHSValNoAssignments[VNI->id];
812       LiveInterval::removeKill(*NewVNInfo[LHSValID], VNI->def);
813       RHS.addKills(*NewVNInfo[LHSValID], VNI->kills);
814     }
815
816     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
817     Swapped = true;
818   } else {
819     // Update kill info. Some live ranges are extended due to copy coalescing.
820     for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
821            E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
822       VNInfo *VNI = I->first;
823       unsigned RHSValID = RHSValNoAssignments[VNI->id];
824       LiveInterval::removeKill(*NewVNInfo[RHSValID], VNI->def);
825       LHS.addKills(*NewVNInfo[RHSValID], VNI->kills);
826     }
827
828     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
829     Swapped = false;
830   }
831   return true;
832 }
833
834 namespace {
835   // DepthMBBCompare - Comparison predicate that sort first based on the loop
836   // depth of the basic block (the unsigned), and then on the MBB number.
837   struct DepthMBBCompare {
838     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
839     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
840       if (LHS.first > RHS.first) return true;   // Deeper loops first
841       return LHS.first == RHS.first &&
842         LHS.second->getNumber() < RHS.second->getNumber();
843     }
844   };
845 }
846
847 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
848                                 std::vector<CopyRec> *TryAgain, bool PhysOnly) {
849   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
850   
851   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
852        MII != E;) {
853     MachineInstr *Inst = MII++;
854     
855     // If this isn't a copy, we can't join intervals.
856     unsigned SrcReg, DstReg;
857     if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
858     
859     if (TryAgain && !JoinCopy(Inst, SrcReg, DstReg, PhysOnly))
860       TryAgain->push_back(getCopyRec(Inst, SrcReg, DstReg));
861   }
862 }
863
864 void SimpleRegisterCoalescing::joinIntervals() {
865   DOUT << "********** JOINING INTERVALS ***********\n";
866
867   JoinedLIs.resize(li_->getNumIntervals());
868   JoinedLIs.reset();
869
870   std::vector<CopyRec> TryAgainList;
871   const LoopInfo &LI = getAnalysis<LoopInfo>();
872   if (LI.begin() == LI.end()) {
873     // If there are no loops in the function, join intervals in function order.
874     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
875          I != E; ++I)
876       CopyCoalesceInMBB(I, &TryAgainList);
877   } else {
878     // Otherwise, join intervals in inner loops before other intervals.
879     // Unfortunately we can't just iterate over loop hierarchy here because
880     // there may be more MBB's than BB's.  Collect MBB's for sorting.
881
882     // Join intervals in the function prolog first. We want to join physical
883     // registers with virtual registers before the intervals got too long.
884     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
885     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); I != E;++I)
886       MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
887
888     // Sort by loop depth.
889     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
890
891     // Finally, join intervals in loop nest order.
892     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
893       CopyCoalesceInMBB(MBBs[i].second, NULL, true);
894     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
895       CopyCoalesceInMBB(MBBs[i].second, &TryAgainList, false);
896   }
897   
898   // Joining intervals can allow other intervals to be joined.  Iteratively join
899   // until we make no progress.
900   bool ProgressMade = true;
901   while (ProgressMade) {
902     ProgressMade = false;
903
904     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
905       CopyRec &TheCopy = TryAgainList[i];
906       if (TheCopy.MI &&
907           JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
908         TheCopy.MI = 0;   // Mark this one as done.
909         ProgressMade = true;
910       }
911     }
912   }
913
914   // Some live range has been lengthened due to colaescing, eliminate the
915   // unnecessary kills.
916   int RegNum = JoinedLIs.find_first();
917   while (RegNum != -1) {
918     unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
919     unsigned repReg = rep(Reg);
920     LiveInterval &LI = li_->getInterval(repReg);
921     LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
922     for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
923       MachineInstr *Kill = svi.Kills[i];
924       // Suppose vr1 = op vr2, x
925       // and vr1 and vr2 are coalesced. vr2 should still be marked kill
926       // unless it is a two-address operand.
927       if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
928         continue;
929       if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
930         unsetRegisterKill(Kill, repReg);
931     }
932     RegNum = JoinedLIs.find_next(RegNum);
933   }
934   
935   DOUT << "*** Register mapping ***\n";
936   for (int i = 0, e = r2rMap_.size(); i != e; ++i)
937     if (r2rMap_[i]) {
938       DOUT << "  reg " << i << " -> ";
939       DEBUG(printRegName(r2rMap_[i]));
940       DOUT << "\n";
941     }
942 }
943
944 /// Return true if the two specified registers belong to different register
945 /// classes.  The registers may be either phys or virt regs.
946 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
947                                              unsigned RegB) const {
948
949   // Get the register classes for the first reg.
950   if (MRegisterInfo::isPhysicalRegister(RegA)) {
951     assert(MRegisterInfo::isVirtualRegister(RegB) &&
952            "Shouldn't consider two physregs!");
953     return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
954   }
955
956   // Compare against the regclass for the second reg.
957   const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
958   if (MRegisterInfo::isVirtualRegister(RegB))
959     return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
960   else
961     return !RegClass->contains(RegB);
962 }
963
964 /// lastRegisterUse - Returns the last use of the specific register between
965 /// cycles Start and End. It also returns the use operand by reference. It
966 /// returns NULL if there are no uses.
967 MachineInstr *
968 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
969                                MachineOperand *&MOU) {
970   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
971   int s = Start;
972   while (e >= s) {
973     // Skip deleted instructions
974     MachineInstr *MI = li_->getInstructionFromIndex(e);
975     while ((e - InstrSlots::NUM) >= s && !MI) {
976       e -= InstrSlots::NUM;
977       MI = li_->getInstructionFromIndex(e);
978     }
979     if (e < s || MI == NULL)
980       return NULL;
981
982     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
983       MachineOperand &MO = MI->getOperand(i);
984       if (MO.isReg() && MO.isUse() && MO.getReg() &&
985           mri_->regsOverlap(rep(MO.getReg()), Reg)) {
986         MOU = &MO;
987         return MI;
988       }
989     }
990
991     e -= InstrSlots::NUM;
992   }
993
994   return NULL;
995 }
996
997
998 /// findDefOperand - Returns the MachineOperand that is a def of the specific
999 /// register. It returns NULL if the def is not found.
1000 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI, unsigned Reg) {
1001   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1002     MachineOperand &MO = MI->getOperand(i);
1003     if (MO.isReg() && MO.isDef() &&
1004         mri_->regsOverlap(rep(MO.getReg()), Reg))
1005       return &MO;
1006   }
1007   return NULL;
1008 }
1009
1010 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
1011 /// of the specific instruction.
1012 void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1013   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1014     MachineOperand &MO = MI->getOperand(i);
1015     if (MO.isReg() && MO.isKill() && MO.getReg() &&
1016         mri_->regsOverlap(rep(MO.getReg()), Reg))
1017       MO.unsetIsKill();
1018   }
1019 }
1020
1021 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
1022 /// between cycles Start and End.
1023 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1024                                        unsigned Reg) {
1025   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1026   int s = Start;
1027   while (e >= s) {
1028     // Skip deleted instructions
1029     MachineInstr *MI = li_->getInstructionFromIndex(e);
1030     while ((e - InstrSlots::NUM) >= s && !MI) {
1031       e -= InstrSlots::NUM;
1032       MI = li_->getInstructionFromIndex(e);
1033     }
1034     if (e < s || MI == NULL)
1035       return;
1036
1037     for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1038       MachineOperand &MO = MI->getOperand(i);
1039       if (MO.isReg() && MO.isKill() && MO.getReg() &&
1040           mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1041         MO.unsetIsKill();
1042       }
1043     }
1044
1045     e -= InstrSlots::NUM;
1046   }
1047 }
1048
1049 /// hasRegisterDef - True if the instruction defines the specific register.
1050 ///
1051 bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1052   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1053     MachineOperand &MO = MI->getOperand(i);
1054     if (MO.isReg() && MO.isDef() &&
1055         mri_->regsOverlap(rep(MO.getReg()), Reg))
1056       return true;
1057   }
1058   return false;
1059 }
1060
1061 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1062   if (MRegisterInfo::isPhysicalRegister(reg))
1063     cerr << mri_->getName(reg);
1064   else
1065     cerr << "%reg" << reg;
1066 }
1067
1068 void SimpleRegisterCoalescing::releaseMemory() {
1069    r2rMap_.clear();
1070    JoinedLIs.clear();
1071 }
1072
1073 static bool isZeroLengthInterval(LiveInterval *li) {
1074   for (LiveInterval::Ranges::const_iterator
1075          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1076     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1077       return false;
1078   return true;
1079 }
1080
1081 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1082   mf_ = &fn;
1083   tm_ = &fn.getTarget();
1084   mri_ = tm_->getRegisterInfo();
1085   tii_ = tm_->getInstrInfo();
1086   li_ = &getAnalysis<LiveIntervals>();
1087   lv_ = &getAnalysis<LiveVariables>();
1088
1089   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1090        << "********** Function: "
1091        << ((Value*)mf_->getFunction())->getName() << '\n';
1092
1093   allocatableRegs_ = mri_->getAllocatableSet(fn);
1094   for (MRegisterInfo::regclass_iterator I = mri_->regclass_begin(),
1095          E = mri_->regclass_end(); I != E; ++I)
1096     allocatableRCRegs_.insert(std::make_pair(*I,mri_->getAllocatableSet(fn, *I)));
1097
1098   r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
1099
1100   // Join (coalesce) intervals if requested.
1101   if (EnableJoining) {
1102     joinIntervals();
1103     DOUT << "********** INTERVALS POST JOINING **********\n";
1104     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1105       I->second.print(DOUT, mri_);
1106       DOUT << "\n";
1107     }
1108   }
1109
1110   // perform a final pass over the instructions and compute spill
1111   // weights, coalesce virtual registers and remove identity moves.
1112   const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
1113
1114   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1115        mbbi != mbbe; ++mbbi) {
1116     MachineBasicBlock* mbb = mbbi;
1117     unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
1118
1119     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1120          mii != mie; ) {
1121       // if the move will be an identity move delete it
1122       unsigned srcReg, dstReg, RegRep;
1123       if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1124           (RegRep = rep(srcReg)) == rep(dstReg)) {
1125         // remove from def list
1126         LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1127         MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1128         // If def of this move instruction is dead, remove its live range from
1129         // the dstination register's live interval.
1130         if (MO->isDead()) {
1131           unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1132           LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1133           RegInt.removeRange(MLR->start, MoveIdx+1);
1134           if (RegInt.empty())
1135             li_->removeInterval(RegRep);
1136         }
1137         li_->RemoveMachineInstrFromMaps(mii);
1138         mii = mbbi->erase(mii);
1139         ++numPeep;
1140       } else {
1141         SmallSet<unsigned, 4> UniqueUses;
1142         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1143           const MachineOperand &mop = mii->getOperand(i);
1144           if (mop.isRegister() && mop.getReg() &&
1145               MRegisterInfo::isVirtualRegister(mop.getReg())) {
1146             // replace register with representative register
1147             unsigned reg = rep(mop.getReg());
1148             mii->getOperand(i).setReg(reg);
1149
1150             // Multiple uses of reg by the same instruction. It should not
1151             // contribute to spill weight again.
1152             if (UniqueUses.count(reg) != 0)
1153               continue;
1154             LiveInterval &RegInt = li_->getInterval(reg);
1155             float w = (mop.isUse()+mop.isDef()) * powf(10.0F, (float)loopDepth);
1156             RegInt.weight += w;
1157             UniqueUses.insert(reg);
1158           }
1159         }
1160         ++mii;
1161       }
1162     }
1163   }
1164
1165   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1166     LiveInterval &LI = I->second;
1167     if (MRegisterInfo::isVirtualRegister(LI.reg)) {
1168       // If the live interval length is essentially zero, i.e. in every live
1169       // range the use follows def immediately, it doesn't make sense to spill
1170       // it and hope it will be easier to allocate for this li.
1171       if (isZeroLengthInterval(&LI))
1172         LI.weight = HUGE_VALF;
1173
1174       // Slightly prefer live interval that has been assigned a preferred reg.
1175       if (LI.preference)
1176         LI.weight *= 1.01F;
1177
1178       // Divide the weight of the interval by its size.  This encourages 
1179       // spilling of intervals that are large and have few uses, and
1180       // discourages spilling of small intervals with many uses.
1181       LI.weight /= LI.getSize();
1182     }
1183   }
1184
1185   DEBUG(dump());
1186   return true;
1187 }
1188
1189 /// print - Implement the dump method.
1190 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1191    li_->print(O, m);
1192 }