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