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