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