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