Rename a variable to make MSVC happy.
[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/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include <algorithm>
37 #include <cmath>
38 using namespace llvm;
39
40 STATISTIC(numJoins    , "Number of interval joins performed");
41 STATISTIC(numCrossRCs , "Number of cross class joins performed");
42 STATISTIC(numCommutes , "Number of instruction commuting performed");
43 STATISTIC(numExtends  , "Number of copies extended");
44 STATISTIC(NumReMats   , "Number of instructions re-materialized");
45 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
46 STATISTIC(numAborts   , "Number of times interval joining aborted");
47 STATISTIC(numDeadValNo, "Number of valno def marked dead");
48
49 char SimpleRegisterCoalescing::ID = 0;
50 static cl::opt<bool>
51 EnableJoining("join-liveintervals",
52               cl::desc("Coalesce copies (default=true)"),
53               cl::init(true));
54
55 static cl::opt<bool>
56 NewHeuristic("new-coalescer-heuristic",
57              cl::desc("Use new coalescer heuristic"),
58              cl::init(false), cl::Hidden);
59
60 static cl::opt<bool>
61 DisableCrossClassJoin("disable-cross-class-join",
62                cl::desc("Avoid coalescing cross register class copies"),
63                cl::init(false), cl::Hidden);
64
65 static cl::opt<bool>
66 PhysJoinTweak("tweak-phys-join-heuristics",
67                cl::desc("Tweak heuristics for joining phys reg with vr"),
68                cl::init(false), cl::Hidden);
69
70 static RegisterPass<SimpleRegisterCoalescing> 
71 X("simple-register-coalescing", "Simple Register Coalescing");
72
73 // Declare that we implement the RegisterCoalescer interface
74 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
75
76 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
77
78 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
79   AU.setPreservesCFG();
80   AU.addRequired<LiveIntervals>();
81   AU.addPreserved<LiveIntervals>();
82   AU.addRequired<MachineLoopInfo>();
83   AU.addPreserved<MachineLoopInfo>();
84   AU.addPreservedID(MachineDominatorsID);
85   if (StrongPHIElim)
86     AU.addPreservedID(StrongPHIEliminationID);
87   else
88     AU.addPreservedID(PHIEliminationID);
89   AU.addPreservedID(TwoAddressInstructionPassID);
90   MachineFunctionPass::getAnalysisUsage(AU);
91 }
92
93 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
94 /// being the source and IntB being the dest, thus this defines a value number
95 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
96 /// see if we can merge these two pieces of B into a single value number,
97 /// eliminating a copy.  For example:
98 ///
99 ///  A3 = B0
100 ///    ...
101 ///  B1 = A3      <- this copy
102 ///
103 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
104 /// value number to be replaced with B0 (which simplifies the B liveinterval).
105 ///
106 /// This returns true if an interval was modified.
107 ///
108 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
109                                                     LiveInterval &IntB,
110                                                     MachineInstr *CopyMI) {
111   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
112
113   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
114   // the example above.
115   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
116   assert(BLR != IntB.end() && "Live range not found!");
117   VNInfo *BValNo = BLR->valno;
118   
119   // Get the location that B is defined at.  Two options: either this value has
120   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
121   // can't process it.
122   if (!BValNo->copy) return false;
123   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
124   
125   // AValNo is the value number in A that defines the copy, A3 in the example.
126   unsigned CopyUseIdx = li_->getUseIndex(CopyIdx);
127   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
128   assert(ALR != IntA.end() && "Live range not found!");
129   VNInfo *AValNo = ALR->valno;
130   // If it's re-defined by an early clobber somewhere in the live range, then
131   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
132   // See PR3149:
133   // 172     %ECX<def> = MOV32rr %reg1039<kill>
134   // 180     INLINEASM <es:subl $5,$1
135   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
136   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
137   // 188     %EAX<def> = MOV32rr %EAX<kill>
138   // 196     %ECX<def> = MOV32rr %ECX<kill>
139   // 204     %ECX<def> = MOV32rr %ECX<kill>
140   // 212     %EAX<def> = MOV32rr %EAX<kill>
141   // 220     %EAX<def> = MOV32rr %EAX
142   // 228     %reg1039<def> = MOV32rr %ECX<kill>
143   // The early clobber operand ties ECX input to the ECX def.
144   //
145   // The live interval of ECX is represented as this:
146   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
147   // The coalescer has no idea there was a def in the middle of [174,230].
148   if (AValNo->hasRedefByEC())
149     return false;
150   
151   // If AValNo is defined as a copy from IntB, we can potentially process this.  
152   // Get the instruction that defines this value number.
153   unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
154   if (!SrcReg) return false;  // Not defined by a copy.
155     
156   // If the value number is not defined by a copy instruction, ignore it.
157
158   // If the source register comes from an interval other than IntB, we can't
159   // handle this.
160   if (SrcReg != IntB.reg) return false;
161   
162   // Get the LiveRange in IntB that this value number starts with.
163   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
164   assert(ValLR != IntB.end() && "Live range not found!");
165   
166   // Make sure that the end of the live range is inside the same block as
167   // CopyMI.
168   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
169   if (!ValLREndInst || 
170       ValLREndInst->getParent() != CopyMI->getParent()) return false;
171
172   // Okay, we now know that ValLR ends in the same block that the CopyMI
173   // live-range starts.  If there are no intervening live ranges between them in
174   // IntB, we can merge them.
175   if (ValLR+1 != BLR) return false;
176
177   // If a live interval is a physical register, conservatively check if any
178   // of its sub-registers is overlapping the live interval of the virtual
179   // register. If so, do not coalesce.
180   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
181       *tri_->getSubRegisters(IntB.reg)) {
182     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
183       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
184         DOUT << "Interfere with sub-register ";
185         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
186         return false;
187       }
188   }
189   
190   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
191   
192   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
193   // We are about to delete CopyMI, so need to remove it as the 'instruction
194   // that defines this value #'. Update the the valnum with the new defining
195   // instruction #.
196   BValNo->def  = FillerStart;
197   BValNo->copy = NULL;
198   
199   // Okay, we can merge them.  We need to insert a new liverange:
200   // [ValLR.end, BLR.begin) of either value number, then we merge the
201   // two value numbers.
202   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
203
204   // If the IntB live range is assigned to a physical register, and if that
205   // physreg has sub-registers, update their live intervals as well. 
206   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
207     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
208       LiveInterval &SRLI = li_->getInterval(*SR);
209       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
210                               SRLI.getNextValue(FillerStart, 0, true,
211                                                 li_->getVNInfoAllocator())));
212     }
213   }
214
215   // Okay, merge "B1" into the same value number as "B0".
216   if (BValNo != ValLR->valno) {
217     IntB.addKills(ValLR->valno, BValNo->kills);
218     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
219   }
220   DOUT << "   result = "; IntB.print(DOUT, tri_);
221   DOUT << "\n";
222
223   // If the source instruction was killing the source register before the
224   // merge, unset the isKill marker given the live range has been extended.
225   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
226   if (UIdx != -1) {
227     ValLREndInst->getOperand(UIdx).setIsKill(false);
228     IntB.removeKill(ValLR->valno, FillerStart);
229   }
230
231   // If the copy instruction was killing the destination register before the
232   // merge, find the last use and trim the live range. That will also add the
233   // isKill marker.
234   if (CopyMI->killsRegister(IntA.reg))
235     TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
236
237   ++numExtends;
238   return true;
239 }
240
241 /// HasOtherReachingDefs - Return true if there are definitions of IntB
242 /// other than BValNo val# that can reach uses of AValno val# of IntA.
243 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
244                                                     LiveInterval &IntB,
245                                                     VNInfo *AValNo,
246                                                     VNInfo *BValNo) {
247   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
248        AI != AE; ++AI) {
249     if (AI->valno != AValNo) continue;
250     LiveInterval::Ranges::iterator BI =
251       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
252     if (BI != IntB.ranges.begin())
253       --BI;
254     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
255       if (BI->valno == BValNo)
256         continue;
257       if (BI->start <= AI->start && BI->end > AI->start)
258         return true;
259       if (BI->start > AI->start && BI->start < AI->end)
260         return true;
261     }
262   }
263   return false;
264 }
265
266 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
267 /// being the source and IntB being the dest, thus this defines a value number
268 /// in IntB.  If the source value number (in IntA) is defined by a commutable
269 /// instruction and its other operand is coalesced to the copy dest register,
270 /// see if we can transform the copy into a noop by commuting the definition. For
271 /// example,
272 ///
273 ///  A3 = op A2 B0<kill>
274 ///    ...
275 ///  B1 = A3      <- this copy
276 ///    ...
277 ///     = op A3   <- more uses
278 ///
279 /// ==>
280 ///
281 ///  B2 = op B0 A2<kill>
282 ///    ...
283 ///  B1 = B2      <- now an identify copy
284 ///    ...
285 ///     = op B2   <- more uses
286 ///
287 /// This returns true if an interval was modified.
288 ///
289 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
290                                                         LiveInterval &IntB,
291                                                         MachineInstr *CopyMI) {
292   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
293
294   // FIXME: For now, only eliminate the copy by commuting its def when the
295   // source register is a virtual register. We want to guard against cases
296   // where the copy is a back edge copy and commuting the def lengthen the
297   // live interval of the source register to the entire loop.
298   if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
299     return false;
300
301   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
302   // the example above.
303   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
304   assert(BLR != IntB.end() && "Live range not found!");
305   VNInfo *BValNo = BLR->valno;
306   
307   // Get the location that B is defined at.  Two options: either this value has
308   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
309   // can't process it.
310   if (!BValNo->copy) return false;
311   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
312   
313   // AValNo is the value number in A that defines the copy, A3 in the example.
314   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
315   assert(ALR != IntA.end() && "Live range not found!");
316   VNInfo *AValNo = ALR->valno;
317   // If other defs can reach uses of this def, then it's not safe to perform
318   // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
319   // tested?
320   if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
321       AValNo->isUnused() || AValNo->hasPHIKill())
322     return false;
323   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
324   const TargetInstrDesc &TID = DefMI->getDesc();
325   if (!TID.isCommutable())
326     return false;
327   // If DefMI is a two-address instruction then commuting it will change the
328   // destination register.
329   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
330   assert(DefIdx != -1);
331   unsigned UseOpIdx;
332   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
333     return false;
334   unsigned Op1, Op2, NewDstIdx;
335   if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
336     return false;
337   if (Op1 == UseOpIdx)
338     NewDstIdx = Op2;
339   else if (Op2 == UseOpIdx)
340     NewDstIdx = Op1;
341   else
342     return false;
343
344   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
345   unsigned NewReg = NewDstMO.getReg();
346   if (NewReg != IntB.reg || !NewDstMO.isKill())
347     return false;
348
349   // Make sure there are no other definitions of IntB that would reach the
350   // uses which the new definition can reach.
351   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
352     return false;
353
354   // If some of the uses of IntA.reg is already coalesced away, return false.
355   // It's not possible to determine whether it's safe to perform the coalescing.
356   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
357          UE = mri_->use_end(); UI != UE; ++UI) {
358     MachineInstr *UseMI = &*UI;
359     unsigned UseIdx = li_->getInstructionIndex(UseMI);
360     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
361     if (ULR == IntA.end())
362       continue;
363     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
364       return false;
365   }
366
367   // At this point we have decided that it is legal to do this
368   // transformation.  Start by commuting the instruction.
369   MachineBasicBlock *MBB = DefMI->getParent();
370   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
371   if (!NewMI)
372     return false;
373   if (NewMI != DefMI) {
374     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
375     MBB->insert(DefMI, NewMI);
376     MBB->erase(DefMI);
377   }
378   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
379   NewMI->getOperand(OpIdx).setIsKill();
380
381   bool BHasPHIKill = BValNo->hasPHIKill();
382   SmallVector<VNInfo*, 4> BDeadValNos;
383   VNInfo::KillSet BKills;
384   std::map<unsigned, unsigned> BExtend;
385
386   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
387   // A = or A, B
388   // ...
389   // B = A
390   // ...
391   // C = A<kill>
392   // ...
393   //   = B
394   //
395   // then do not add kills of A to the newly created B interval.
396   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
397   if (Extended)
398     BExtend[ALR->end] = BLR->end;
399
400   // Update uses of IntA of the specific Val# with IntB.
401   bool BHasSubRegs = false;
402   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
403     BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
404   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
405          UE = mri_->use_end(); UI != UE;) {
406     MachineOperand &UseMO = UI.getOperand();
407     MachineInstr *UseMI = &*UI;
408     ++UI;
409     if (JoinedCopies.count(UseMI))
410       continue;
411     unsigned UseIdx = li_->getInstructionIndex(UseMI);
412     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
413     if (ULR == IntA.end() || ULR->valno != AValNo)
414       continue;
415     UseMO.setReg(NewReg);
416     if (UseMI == CopyMI)
417       continue;
418     if (UseMO.isKill()) {
419       if (Extended)
420         UseMO.setIsKill(false);
421       else
422         BKills.push_back(VNInfo::KillInfo(false, li_->getUseIndex(UseIdx)+1));
423     }
424     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
425     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
426       continue;
427     if (DstReg == IntB.reg) {
428       // This copy will become a noop. If it's defining a new val#,
429       // remove that val# as well. However this live range is being
430       // extended to the end of the existing live range defined by the copy.
431       unsigned DefIdx = li_->getDefIndex(UseIdx);
432       const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
433       BHasPHIKill |= DLR->valno->hasPHIKill();
434       assert(DLR->valno->def == DefIdx);
435       BDeadValNos.push_back(DLR->valno);
436       BExtend[DLR->start] = DLR->end;
437       JoinedCopies.insert(UseMI);
438       // If this is a kill but it's going to be removed, the last use
439       // of the same val# is the new kill.
440       if (UseMO.isKill())
441         BKills.pop_back();
442     }
443   }
444
445   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
446   // simply extend BLR if CopyMI doesn't end the range.
447   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
448
449   // Remove val#'s defined by copies that will be coalesced away.
450   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
451     VNInfo *DeadVNI = BDeadValNos[i];
452     if (BHasSubRegs) {
453       for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
454         LiveInterval &SRLI = li_->getInterval(*SR);
455         const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
456         SRLI.removeValNo(SRLR->valno);
457       }
458     }
459     IntB.removeValNo(BDeadValNos[i]);
460   }
461
462   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
463   // is updated. Kills are also updated.
464   VNInfo *ValNo = BValNo;
465   ValNo->def = AValNo->def;
466   ValNo->copy = NULL;
467   for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
468     unsigned Kill = ValNo->kills[j].killIdx;
469     if (Kill != BLR->end)
470       BKills.push_back(VNInfo::KillInfo(ValNo->kills[j].isPHIKill, Kill));
471   }
472   ValNo->kills.clear();
473   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
474        AI != AE; ++AI) {
475     if (AI->valno != AValNo) continue;
476     unsigned End = AI->end;
477     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
478     if (EI != BExtend.end())
479       End = EI->second;
480     IntB.addRange(LiveRange(AI->start, End, ValNo));
481
482     // If the IntB live range is assigned to a physical register, and if that
483     // physreg has sub-registers, update their live intervals as well. 
484     if (BHasSubRegs) {
485       for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
486         LiveInterval &SRLI = li_->getInterval(*SR);
487         SRLI.MergeInClobberRange(AI->start, End, li_->getVNInfoAllocator());
488       }
489     }
490   }
491   IntB.addKills(ValNo, BKills);
492   ValNo->setHasPHIKill(BHasPHIKill);
493
494   DOUT << "   result = "; IntB.print(DOUT, tri_);
495   DOUT << "\n";
496
497   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
498   IntA.removeValNo(AValNo);
499   DOUT << "   result = "; IntA.print(DOUT, tri_);
500   DOUT << "\n";
501
502   ++numCommutes;
503   return true;
504 }
505
506 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
507 /// fallthoughs to SuccMBB.
508 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
509                                   MachineBasicBlock *SuccMBB,
510                                   const TargetInstrInfo *tii_) {
511   if (MBB == SuccMBB)
512     return true;
513   MachineBasicBlock *TBB = 0, *FBB = 0;
514   SmallVector<MachineOperand, 4> Cond;
515   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
516     MBB->isSuccessor(SuccMBB);
517 }
518
519 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
520 /// from a physical register live interval as well as from the live intervals
521 /// of its sub-registers.
522 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
523                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
524   li.removeRange(Start, End, true);
525   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
526     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
527       if (!li_->hasInterval(*SR))
528         continue;
529       LiveInterval &sli = li_->getInterval(*SR);
530       unsigned RemoveEnd = Start;
531       while (RemoveEnd != End) {
532         LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
533         if (LR == sli.end())
534           break;
535         RemoveEnd = (LR->end < End) ? LR->end : End;
536         sli.removeRange(Start, RemoveEnd, true);
537         Start = RemoveEnd;
538       }
539     }
540   }
541 }
542
543 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
544 /// as the copy instruction, trim the live interval to the last use and return
545 /// true.
546 bool
547 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(unsigned CopyIdx,
548                                                     MachineBasicBlock *CopyMBB,
549                                                     LiveInterval &li,
550                                                     const LiveRange *LR) {
551   unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
552   unsigned LastUseIdx;
553   MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
554                                             LastUseIdx);
555   if (LastUse) {
556     MachineInstr *LastUseMI = LastUse->getParent();
557     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
558       // r1024 = op
559       // ...
560       // BB1:
561       //       = r1024
562       //
563       // BB2:
564       // r1025<dead> = r1024<kill>
565       if (MBBStart < LR->end)
566         removeRange(li, MBBStart, LR->end, li_, tri_);
567       return true;
568     }
569
570     // There are uses before the copy, just shorten the live range to the end
571     // of last use.
572     LastUse->setIsKill();
573     removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
574     li.addKill(LR->valno, LastUseIdx+1, false);
575     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
576     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
577         DstReg == li.reg) {
578       // Last use is itself an identity code.
579       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
580       LastUseMI->getOperand(DeadIdx).setIsDead();
581     }
582     return true;
583   }
584
585   // Is it livein?
586   if (LR->start <= MBBStart && LR->end > MBBStart) {
587     if (LR->start == 0) {
588       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
589       // Live-in to the function but dead. Remove it from entry live-in set.
590       mf_->begin()->removeLiveIn(li.reg);
591     }
592     // FIXME: Shorten intervals in BBs that reaches this BB.
593   }
594
595   return false;
596 }
597
598 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
599 /// computation, replace the copy by rematerialize the definition.
600 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
601                                                        unsigned DstReg,
602                                                        unsigned DstSubIdx,
603                                                        MachineInstr *CopyMI) {
604   unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
605   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
606   assert(SrcLR != SrcInt.end() && "Live range not found!");
607   VNInfo *ValNo = SrcLR->valno;
608   // If other defs can reach uses of this def, then it's not safe to perform
609   // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
610   // tested?
611   if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
612       ValNo->isUnused() || ValNo->hasPHIKill())
613     return false;
614   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
615   const TargetInstrDesc &TID = DefMI->getDesc();
616   if (!TID.isAsCheapAsAMove())
617     return false;
618   if (!DefMI->getDesc().isRematerializable() ||
619       !tii_->isTriviallyReMaterializable(DefMI))
620     return false;
621   bool SawStore = false;
622   if (!DefMI->isSafeToMove(tii_, SawStore))
623     return false;
624   if (TID.getNumDefs() != 1)
625     return false;
626   if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) {
627     // Make sure the copy destination register class fits the instruction
628     // definition register class. The mismatch can happen as a result of earlier
629     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
630     const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
631     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
632       if (mri_->getRegClass(DstReg) != RC)
633         return false;
634     } else if (!RC->contains(DstReg))
635       return false;
636   }
637
638   unsigned DefIdx = li_->getDefIndex(CopyIdx);
639   const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
640   DLR->valno->copy = NULL;
641   // Don't forget to update sub-register intervals.
642   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
643     for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
644       if (!li_->hasInterval(*SR))
645         continue;
646       DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
647       if (DLR && DLR->valno->copy == CopyMI)
648         DLR->valno->copy = NULL;
649     }
650   }
651
652   // If copy kills the source register, find the last use and propagate
653   // kill.
654   bool checkForDeadDef = false;
655   MachineBasicBlock *MBB = CopyMI->getParent();
656   if (CopyMI->killsRegister(SrcInt.reg))
657     if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
658       checkForDeadDef = true;
659     }
660
661   MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
662   tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI);
663   MachineInstr *NewMI = prior(MII);
664
665   if (checkForDeadDef) {
666     // PR4090 fix: Trim interval failed because there was no use of the
667     // source interval in this MBB. If the def is in this MBB too then we
668     // should mark it dead:
669     if (DefMI->getParent() == MBB) {
670       DefMI->addRegisterDead(SrcInt.reg, tri_);
671       SrcLR->end = SrcLR->start + 1;
672     }
673   }
674
675   // CopyMI may have implicit operands, transfer them over to the newly
676   // rematerialized instruction. And update implicit def interval valnos.
677   for (unsigned i = CopyMI->getDesc().getNumOperands(),
678          e = CopyMI->getNumOperands(); i != e; ++i) {
679     MachineOperand &MO = CopyMI->getOperand(i);
680     if (MO.isReg() && MO.isImplicit())
681       NewMI->addOperand(MO);
682     if (MO.isDef() && li_->hasInterval(MO.getReg())) {
683       unsigned Reg = MO.getReg();
684       DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
685       if (DLR && DLR->valno->copy == CopyMI)
686         DLR->valno->copy = NULL;
687     }
688   }
689
690   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
691   CopyMI->eraseFromParent();
692   ReMatCopies.insert(CopyMI);
693   ReMatDefs.insert(DefMI);
694   ++NumReMats;
695   return true;
696 }
697
698 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
699 ///
700 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
701                                               unsigned DstReg) const {
702   MachineBasicBlock *MBB = CopyMI->getParent();
703   const MachineLoop *L = loopInfo->getLoopFor(MBB);
704   if (!L)
705     return false;
706   if (MBB != L->getLoopLatch())
707     return false;
708
709   LiveInterval &LI = li_->getInterval(DstReg);
710   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
711   LiveInterval::const_iterator DstLR =
712     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
713   if (DstLR == LI.end())
714     return false;
715   if (DstLR->valno->kills.size() == 1 && DstLR->valno->kills[0].isPHIKill)
716     return true;
717   return false;
718 }
719
720 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
721 /// update the subregister number if it is not zero. If DstReg is a
722 /// physical register and the existing subregister number of the def / use
723 /// being updated is not zero, make sure to set it to the correct physical
724 /// subregister.
725 void
726 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
727                                             unsigned SubIdx) {
728   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
729   if (DstIsPhys && SubIdx) {
730     // Figure out the real physical register we are updating with.
731     DstReg = tri_->getSubReg(DstReg, SubIdx);
732     SubIdx = 0;
733   }
734
735   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
736          E = mri_->reg_end(); I != E; ) {
737     MachineOperand &O = I.getOperand();
738     MachineInstr *UseMI = &*I;
739     ++I;
740     unsigned OldSubIdx = O.getSubReg();
741     if (DstIsPhys) {
742       unsigned UseDstReg = DstReg;
743       if (OldSubIdx)
744           UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
745
746       unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
747       if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
748                             CopySrcSubIdx, CopyDstSubIdx) &&
749           CopySrcReg != CopyDstReg &&
750           CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
751         // If the use is a copy and it won't be coalesced away, and its source
752         // is defined by a trivial computation, try to rematerialize it instead.
753         if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
754                                     CopyDstSubIdx, UseMI))
755           continue;
756       }
757
758       O.setReg(UseDstReg);
759       O.setSubReg(0);
760       continue;
761     }
762
763     // Sub-register indexes goes from small to large. e.g.
764     // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
765     // EAX: 1 -> AL, 2 -> AX
766     // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
767     // sub-register 2 is also AX.
768     if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
769       assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
770     else if (SubIdx)
771       O.setSubReg(SubIdx);
772     // Remove would-be duplicated kill marker.
773     if (O.isKill() && UseMI->killsRegister(DstReg))
774       O.setIsKill(false);
775     O.setReg(DstReg);
776
777     // After updating the operand, check if the machine instruction has
778     // become a copy. If so, update its val# information.
779     if (JoinedCopies.count(UseMI))
780       continue;
781
782     const TargetInstrDesc &TID = UseMI->getDesc();
783     unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
784     if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
785         tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
786                           CopySrcSubIdx, CopyDstSubIdx) &&
787         CopySrcReg != CopyDstReg &&
788         (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
789          allocatableRegs_[CopyDstReg])) {
790       LiveInterval &LI = li_->getInterval(CopyDstReg);
791       unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
792       if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
793         if (DLR->valno->def == DefIdx)
794           DLR->valno->copy = UseMI;
795       }
796     }
797   }
798 }
799
800 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
801 /// due to live range lengthening as the result of coalescing.
802 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
803                                                       LiveInterval &LI) {
804   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
805          UE = mri_->use_end(); UI != UE; ++UI) {
806     MachineOperand &UseMO = UI.getOperand();
807     if (!UseMO.isKill())
808       continue;
809     MachineInstr *UseMI = UseMO.getParent();
810     unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
811     const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
812     if (!LR || !LI.isKill(LR->valno, UseIdx+1)) {
813       if (LR->valno->def != UseIdx+1) {
814         // Interesting problem. After coalescing reg1027's def and kill are both
815         // at the same point:  %reg1027,0.000000e+00 = [56,814:0)  0@70-(814)
816         //
817         // bb5:
818         // 60   %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
819         // 68   %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
820         // 76   t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
821         // 84   %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
822         // 96   t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
823         //
824         // Do not remove the kill marker on t2LDRi12.
825         UseMO.setIsKill(false);
826       }
827     }
828   }
829 }
830
831 /// removeIntervalIfEmpty - Check if the live interval of a physical register
832 /// is empty, if so remove it and also remove the empty intervals of its
833 /// sub-registers. Return true if live interval is removed.
834 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
835                                   const TargetRegisterInfo *tri_) {
836   if (li.empty()) {
837     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
838       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
839         if (!li_->hasInterval(*SR))
840           continue;
841         LiveInterval &sli = li_->getInterval(*SR);
842         if (sli.empty())
843           li_->removeInterval(*SR);
844       }
845     li_->removeInterval(li.reg);
846     return true;
847   }
848   return false;
849 }
850
851 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
852 /// Return true if live interval is removed.
853 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
854                                                         MachineInstr *CopyMI) {
855   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
856   LiveInterval::iterator MLR =
857     li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
858   if (MLR == li.end())
859     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
860   unsigned RemoveStart = MLR->start;
861   unsigned RemoveEnd = MLR->end;
862   unsigned DefIdx = li_->getDefIndex(CopyIdx);
863   // Remove the liverange that's defined by this.
864   if (RemoveStart == DefIdx && RemoveEnd == DefIdx+1) {
865     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
866     return removeIntervalIfEmpty(li, li_, tri_);
867   }
868   return false;
869 }
870
871 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
872 /// the val# it defines. If the live interval becomes empty, remove it as well.
873 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
874                                              MachineInstr *DefMI) {
875   unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
876   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
877   if (DefIdx != MLR->valno->def)
878     return false;
879   li.removeValNo(MLR->valno);
880   return removeIntervalIfEmpty(li, li_, tri_);
881 }
882
883 /// PropagateDeadness - Propagate the dead marker to the instruction which
884 /// defines the val#.
885 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
886                               unsigned &LRStart, LiveIntervals *li_,
887                               const TargetRegisterInfo* tri_) {
888   MachineInstr *DefMI =
889     li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
890   if (DefMI && DefMI != CopyMI) {
891     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
892     if (DeadIdx != -1) {
893       DefMI->getOperand(DeadIdx).setIsDead();
894       // A dead def should have a single cycle interval.
895       ++LRStart;
896     }
897   }
898 }
899
900 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
901 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
902 /// ends the live range there. If there isn't another use, then this live range
903 /// is dead. Return true if live interval is removed.
904 bool
905 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
906                                                       MachineInstr *CopyMI) {
907   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
908   if (CopyIdx == 0) {
909     // FIXME: special case: function live in. It can be a general case if the
910     // first instruction index starts at > 0 value.
911     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
912     // Live-in to the function but dead. Remove it from entry live-in set.
913     if (mf_->begin()->isLiveIn(li.reg))
914       mf_->begin()->removeLiveIn(li.reg);
915     const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
916     removeRange(li, LR->start, LR->end, li_, tri_);
917     return removeIntervalIfEmpty(li, li_, tri_);
918   }
919
920   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
921   if (LR == li.end())
922     // Livein but defined by a phi.
923     return false;
924
925   unsigned RemoveStart = LR->start;
926   unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
927   if (LR->end > RemoveEnd)
928     // More uses past this copy? Nothing to do.
929     return false;
930
931   // If there is a last use in the same bb, we can't remove the live range.
932   // Shorten the live interval and return.
933   MachineBasicBlock *CopyMBB = CopyMI->getParent();
934   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
935     return false;
936
937   // There are other kills of the val#. Nothing to do.
938   if (!li.isOnlyLROfValNo(LR))
939     return false;
940
941   MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
942   if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
943     // If the live range starts in another mbb and the copy mbb is not a fall
944     // through mbb, then we can only cut the range from the beginning of the
945     // copy mbb.
946     RemoveStart = li_->getMBBStartIdx(CopyMBB) + 1;
947
948   if (LR->valno->def == RemoveStart) {
949     // If the def MI defines the val# and this copy is the only kill of the
950     // val#, then propagate the dead marker.
951     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
952     ++numDeadValNo;
953
954     if (li.isKill(LR->valno, RemoveEnd))
955       li.removeKill(LR->valno, RemoveEnd);
956   }
957
958   removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
959   return removeIntervalIfEmpty(li, li_, tri_);
960 }
961
962 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
963 /// from an implicit def to another register can be coalesced away.
964 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
965                                                      LiveInterval &li,
966                                                      LiveInterval &ImpLi) const{
967   if (!CopyMI->killsRegister(ImpLi.reg))
968     return false;
969   // Make sure this is the only use.
970   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
971          UE = mri_->use_end(); UI != UE;) {
972     MachineInstr *UseMI = &*UI;
973     ++UI;
974     if (CopyMI == UseMI || JoinedCopies.count(UseMI))
975       continue;
976     return false;
977   }
978   return true;
979 }
980
981
982 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
983 /// a virtual destination register with physical source register.
984 bool
985 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
986                                                      MachineBasicBlock *CopyMBB,
987                                                      LiveInterval &DstInt,
988                                                      LiveInterval &SrcInt) {
989   // If the virtual register live interval is long but it has low use desity,
990   // do not join them, instead mark the physical register as its allocation
991   // preference.
992   const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
993   unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
994   unsigned Length = li_->getApproximateInstructionCount(DstInt);
995   if (Length > Threshold &&
996       (((float)std::distance(mri_->use_begin(DstInt.reg),
997                              mri_->use_end()) / Length) < (1.0 / Threshold)))
998     return false;
999
1000   // If the virtual register live interval extends into a loop, turn down
1001   // aggressiveness.
1002   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1003   const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1004   if (!L) {
1005     // Let's see if the virtual register live interval extends into the loop.
1006     LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1007     assert(DLR != DstInt.end() && "Live range not found!");
1008     DLR = DstInt.FindLiveRangeContaining(DLR->end+1);
1009     if (DLR != DstInt.end()) {
1010       CopyMBB = li_->getMBBFromIndex(DLR->start);
1011       L = loopInfo->getLoopFor(CopyMBB);
1012     }
1013   }
1014
1015   if (!L || Length <= Threshold)
1016     return true;
1017
1018   unsigned UseIdx = li_->getUseIndex(CopyIdx);
1019   LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1020   MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1021   if (loopInfo->getLoopFor(SMBB) != L) {
1022     if (!loopInfo->isLoopHeader(CopyMBB))
1023       return false;
1024     // If vr's live interval extends pass the loop header, do not join.
1025     for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1026            SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1027       MachineBasicBlock *SuccMBB = *SI;
1028       if (SuccMBB == CopyMBB)
1029         continue;
1030       if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1031                           li_->getMBBEndIdx(SuccMBB)+1))
1032         return false;
1033     }
1034   }
1035   return true;
1036 }
1037
1038 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1039 /// copy from a virtual source register to a physical destination register.
1040 bool
1041 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1042                                                      MachineBasicBlock *CopyMBB,
1043                                                      LiveInterval &DstInt,
1044                                                      LiveInterval &SrcInt) {
1045   // If the virtual register live interval is long but it has low use desity,
1046   // do not join them, instead mark the physical register as its allocation
1047   // preference.
1048   const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1049   unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1050   unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1051   if (Length > Threshold &&
1052       (((float)std::distance(mri_->use_begin(SrcInt.reg),
1053                              mri_->use_end()) / Length) < (1.0 / Threshold)))
1054     return false;
1055
1056   if (SrcInt.empty())
1057     // Must be implicit_def.
1058     return false;
1059
1060   // If the virtual register live interval is defined or cross a loop, turn
1061   // down aggressiveness.
1062   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1063   unsigned UseIdx = li_->getUseIndex(CopyIdx);
1064   LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1065   assert(SLR != SrcInt.end() && "Live range not found!");
1066   SLR = SrcInt.FindLiveRangeContaining(SLR->start-1);
1067   if (SLR == SrcInt.end())
1068     return true;
1069   MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1070   const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1071
1072   if (!L || Length <= Threshold)
1073     return true;
1074
1075   if (loopInfo->getLoopFor(CopyMBB) != L) {
1076     if (SMBB != L->getLoopLatch())
1077       return false;
1078     // If vr's live interval is extended from before the loop latch, do not
1079     // join.
1080     for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1081            PE = SMBB->pred_end(); PI != PE; ++PI) {
1082       MachineBasicBlock *PredMBB = *PI;
1083       if (PredMBB == SMBB)
1084         continue;
1085       if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1086                           li_->getMBBEndIdx(PredMBB)+1))
1087         return false;
1088     }
1089   }
1090   return true;
1091 }
1092
1093 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1094 /// two virtual registers from different register classes.
1095 bool
1096 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1097                                                 unsigned SmallReg,
1098                                                 unsigned Threshold) {
1099   // Then make sure the intervals are *short*.
1100   LiveInterval &LargeInt = li_->getInterval(LargeReg);
1101   LiveInterval &SmallInt = li_->getInterval(SmallReg);
1102   unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1103   unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1104   if (SmallSize > Threshold || LargeSize > Threshold)
1105     if ((float)std::distance(mri_->use_begin(SmallReg),
1106                              mri_->use_end()) / SmallSize <
1107         (float)std::distance(mri_->use_begin(LargeReg),
1108                              mri_->use_end()) / LargeSize)
1109       return false;
1110   return true;
1111 }
1112
1113 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1114 /// register with a physical register, check if any of the virtual register
1115 /// operand is a sub-register use or def. If so, make sure it won't result
1116 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1117 /// vr1024 = extract_subreg vr1025, 1
1118 /// ...
1119 /// vr1024 = mov8rr AH
1120 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1121 /// AH does not have a super-reg whose sub-register 1 is AH.
1122 bool
1123 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1124                                                       unsigned VirtReg,
1125                                                       unsigned PhysReg) {
1126   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1127          E = mri_->reg_end(); I != E; ++I) {
1128     MachineOperand &O = I.getOperand();
1129     MachineInstr *MI = &*I;
1130     if (MI == CopyMI || JoinedCopies.count(MI))
1131       continue;
1132     unsigned SubIdx = O.getSubReg();
1133     if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1134       return true;
1135     if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1136       SubIdx = MI->getOperand(2).getImm();
1137       if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1138         return true;
1139       if (O.isDef()) {
1140         unsigned SrcReg = MI->getOperand(1).getReg();
1141         const TargetRegisterClass *RC =
1142           TargetRegisterInfo::isPhysicalRegister(SrcReg)
1143           ? tri_->getPhysicalRegisterRegClass(SrcReg)
1144           : mri_->getRegClass(SrcReg);
1145         if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1146           return true;
1147       }
1148     }
1149     if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1150         MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
1151       SubIdx = MI->getOperand(3).getImm();
1152       if (VirtReg == MI->getOperand(0).getReg()) {
1153         if (!tri_->getSubReg(PhysReg, SubIdx))
1154           return true;
1155       } else {
1156         unsigned DstReg = MI->getOperand(0).getReg();
1157         const TargetRegisterClass *RC =
1158           TargetRegisterInfo::isPhysicalRegister(DstReg)
1159           ? tri_->getPhysicalRegisterRegClass(DstReg)
1160           : mri_->getRegClass(DstReg);
1161         if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1162           return true;
1163       }
1164     }
1165   }
1166   return false;
1167 }
1168
1169
1170 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1171 /// an extract_subreg where dst is a physical register, e.g.
1172 /// cl = EXTRACT_SUBREG reg1024, 1
1173 bool
1174 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1175                                                unsigned SrcReg, unsigned SubIdx,
1176                                                unsigned &RealDstReg) {
1177   const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1178   RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1179   assert(RealDstReg && "Invalid extract_subreg instruction!");
1180
1181   // For this type of EXTRACT_SUBREG, conservatively
1182   // check if the live interval of the source register interfere with the
1183   // actual super physical register we are trying to coalesce with.
1184   LiveInterval &RHS = li_->getInterval(SrcReg);
1185   if (li_->hasInterval(RealDstReg) &&
1186       RHS.overlaps(li_->getInterval(RealDstReg))) {
1187     DOUT << "Interfere with register ";
1188     DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
1189     return false; // Not coalescable
1190   }
1191   for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1192     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1193       DOUT << "Interfere with sub-register ";
1194       DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1195       return false; // Not coalescable
1196     }
1197   return true;
1198 }
1199
1200 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1201 /// an insert_subreg where src is a physical register, e.g.
1202 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1203 bool
1204 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1205                                                unsigned SrcReg, unsigned SubIdx,
1206                                                unsigned &RealSrcReg) {
1207   const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1208   RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1209   assert(RealSrcReg && "Invalid extract_subreg instruction!");
1210
1211   LiveInterval &RHS = li_->getInterval(DstReg);
1212   if (li_->hasInterval(RealSrcReg) &&
1213       RHS.overlaps(li_->getInterval(RealSrcReg))) {
1214     DOUT << "Interfere with register ";
1215     DEBUG(li_->getInterval(RealSrcReg).print(DOUT, tri_));
1216     return false; // Not coalescable
1217   }
1218   for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1219     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1220       DOUT << "Interfere with sub-register ";
1221       DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1222       return false; // Not coalescable
1223     }
1224   return true;
1225 }
1226
1227 /// getRegAllocPreference - Return register allocation preference register.
1228 ///
1229 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1230                                       MachineRegisterInfo *MRI,
1231                                       const TargetRegisterInfo *TRI) {
1232   if (TargetRegisterInfo::isPhysicalRegister(Reg))
1233     return 0;
1234   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1235   return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1236 }
1237
1238 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1239 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1240 /// if the copy was successfully coalesced away. If it is not currently
1241 /// possible to coalesce this interval, but it may be possible if other
1242 /// things get coalesced, then it returns true by reference in 'Again'.
1243 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1244   MachineInstr *CopyMI = TheCopy.MI;
1245
1246   Again = false;
1247   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1248     return false; // Already done.
1249
1250   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1251
1252   unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1253   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1254   bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1255   bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
1256   unsigned SubIdx = 0;
1257   if (isExtSubReg) {
1258     DstReg    = CopyMI->getOperand(0).getReg();
1259     DstSubIdx = CopyMI->getOperand(0).getSubReg();
1260     SrcReg    = CopyMI->getOperand(1).getReg();
1261     SrcSubIdx = CopyMI->getOperand(2).getImm();
1262   } else if (isInsSubReg || isSubRegToReg) {
1263     DstReg    = CopyMI->getOperand(0).getReg();
1264     DstSubIdx = CopyMI->getOperand(3).getImm();
1265     SrcReg    = CopyMI->getOperand(2).getReg();
1266     SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1267     if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1268       // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1269       // coalesced to a larger register so the subreg indices cancel out.
1270       DOUT << "\tSource of insert_subreg is already coalesced "
1271            << "to another register.\n";
1272       return false;  // Not coalescable.
1273     }
1274   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1275     llvm_unreachable("Unrecognized copy instruction!");
1276   }
1277
1278   // If they are already joined we continue.
1279   if (SrcReg == DstReg) {
1280     DOUT << "\tCopy already coalesced.\n";
1281     return false;  // Not coalescable.
1282   }
1283   
1284   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1285   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1286
1287   // If they are both physical registers, we cannot join them.
1288   if (SrcIsPhys && DstIsPhys) {
1289     DOUT << "\tCan not coalesce physregs.\n";
1290     return false;  // Not coalescable.
1291   }
1292   
1293   // We only join virtual registers with allocatable physical registers.
1294   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1295     DOUT << "\tSrc reg is unallocatable physreg.\n";
1296     return false;  // Not coalescable.
1297   }
1298   if (DstIsPhys && !allocatableRegs_[DstReg]) {
1299     DOUT << "\tDst reg is unallocatable physreg.\n";
1300     return false;  // Not coalescable.
1301   }
1302
1303   // Check that a physical source register is compatible with dst regclass
1304   if (SrcIsPhys) {
1305     unsigned SrcSubReg = SrcSubIdx ?
1306       tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1307     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1308     const TargetRegisterClass *DstSubRC = DstRC;
1309     if (DstSubIdx)
1310       DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1311     assert(DstSubRC && "Illegal subregister index");
1312     if (!DstSubRC->contains(SrcSubReg)) {
1313       DEBUG(errs() << "\tIncompatible destination regclass: "
1314             << tri_->getName(SrcSubReg) << " not in " << DstSubRC->getName()
1315             << ".\n");
1316       return false;             // Not coalescable.
1317     }
1318   }
1319
1320   // Check that a physical dst register is compatible with source regclass
1321   if (DstIsPhys) {
1322     unsigned DstSubReg = DstSubIdx ?
1323       tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1324     const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1325     const TargetRegisterClass *SrcSubRC = SrcRC;
1326     if (SrcSubIdx)
1327       SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1328     assert(SrcSubRC && "Illegal subregister index");
1329     if (!SrcSubRC->contains(DstReg)) {
1330       DEBUG(errs() << "\tIncompatible source regclass: "
1331             << tri_->getName(DstSubReg) << " not in " << SrcSubRC->getName()
1332             << ".\n");
1333       (void)DstSubReg;
1334       return false;             // Not coalescable.
1335     }
1336   }
1337
1338   // Should be non-null only when coalescing to a sub-register class.
1339   bool CrossRC = false;
1340   const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1341   const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1342   const TargetRegisterClass *NewRC = NULL;
1343   MachineBasicBlock *CopyMBB = CopyMI->getParent();
1344   unsigned RealDstReg = 0;
1345   unsigned RealSrcReg = 0;
1346   if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1347     SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1348     if (SrcIsPhys && isExtSubReg) {
1349       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1350       // coalesced with AX.
1351       unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1352       if (DstSubIdx) {
1353         // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1354         // coalesced to a larger register so the subreg indices cancel out.
1355         if (DstSubIdx != SubIdx) {
1356           DOUT << "\t Sub-register indices mismatch.\n";
1357           return false; // Not coalescable.
1358         }
1359       } else
1360         SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1361       SubIdx = 0;
1362     } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1363       // EAX = INSERT_SUBREG EAX, r1024, 0
1364       unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1365       if (SrcSubIdx) {
1366         // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1367         // coalesced to a larger register so the subreg indices cancel out.
1368         if (SrcSubIdx != SubIdx) {
1369           DOUT << "\t Sub-register indices mismatch.\n";
1370           return false; // Not coalescable.
1371         }
1372       } else
1373         DstReg = tri_->getSubReg(DstReg, SubIdx);
1374       SubIdx = 0;
1375     } else if ((DstIsPhys && isExtSubReg) ||
1376                (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1377       if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1378         DOUT << "\tSrc of extract_subreg already coalesced with reg"
1379              << " of a super-class.\n";
1380         return false; // Not coalescable.
1381       }
1382
1383       if (isExtSubReg) {
1384         if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1385           return false; // Not coalescable
1386       } else {
1387         if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1388           return false; // Not coalescable
1389       }
1390       SubIdx = 0;
1391     } else {
1392       unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1393         : CopyMI->getOperand(2).getSubReg();
1394       if (OldSubIdx) {
1395         if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1396           // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1397           // coalesced to a larger register so the subreg indices cancel out.
1398           // Also check if the other larger register is of the same register
1399           // class as the would be resulting register.
1400           SubIdx = 0;
1401         else {
1402           DOUT << "\t Sub-register indices mismatch.\n";
1403           return false; // Not coalescable.
1404         }
1405       }
1406       if (SubIdx) {
1407         if (!DstIsPhys && !SrcIsPhys) {
1408           if (isInsSubReg || isSubRegToReg) {
1409             NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1410           } else // extract_subreg {
1411             NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1412           }
1413         if (!NewRC) {
1414           DOUT << "\t Conflicting sub-register indices.\n";
1415           return false;  // Not coalescable
1416         }
1417
1418         unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1419         unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1420         unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1421         if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1422           Again = true;  // May be possible to coalesce later.
1423           return false;
1424         }
1425       }
1426     }
1427   } else if (differingRegisterClasses(SrcReg, DstReg)) {
1428     if (DisableCrossClassJoin)
1429       return false;
1430     CrossRC = true;
1431
1432     // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1433     // with another? If it's the resulting destination register, then
1434     // the subidx must be propagated to uses (but only those defined
1435     // by the EXTRACT_SUBREG). If it's being coalesced into another
1436     // register, it should be safe because register is assumed to have
1437     // the register class of the super-register.
1438
1439     // Process moves where one of the registers have a sub-register index.
1440     MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1441     MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1442     SubIdx = DstMO->getSubReg();
1443     if (SubIdx) {
1444       if (SrcMO->getSubReg())
1445         // FIXME: can we handle this?
1446         return false;
1447       // This is not an insert_subreg but it looks like one.
1448       // e.g. %reg1024:4 = MOV32rr %EAX
1449       isInsSubReg = true;
1450       if (SrcIsPhys) {
1451         if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1452           return false; // Not coalescable
1453         SubIdx = 0;
1454       }
1455     } else {
1456       SubIdx = SrcMO->getSubReg();
1457       if (SubIdx) {
1458         // This is not a extract_subreg but it looks like one.
1459         // e.g. %cl = MOV16rr %reg1024:1
1460         isExtSubReg = true;
1461         if (DstIsPhys) {
1462           if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1463             return false; // Not coalescable
1464           SubIdx = 0;
1465         }
1466       }
1467     }
1468
1469     unsigned LargeReg = SrcReg;
1470     unsigned SmallReg = DstReg;
1471
1472     // Now determine the register class of the joined register.
1473     if (isExtSubReg) {
1474       if (SubIdx && DstRC && DstRC->isASubClass()) {
1475         // This is a move to a sub-register class. However, the source is a
1476         // sub-register of a larger register class. We don't know what should
1477         // the register class be. FIXME.
1478         Again = true;
1479         return false;
1480       }
1481       if (!DstIsPhys && !SrcIsPhys)
1482         NewRC = SrcRC;
1483     } else if (!SrcIsPhys && !DstIsPhys) {
1484       NewRC = getCommonSubClass(SrcRC, DstRC);
1485       if (!NewRC) {
1486         DEBUG(errs() << "\tDisjoint regclasses: "
1487               << SrcRC->getName() << ", "
1488               << DstRC->getName() << ".\n");
1489         return false;           // Not coalescable.
1490       }
1491       if (DstRC->getSize() > SrcRC->getSize())
1492         std::swap(LargeReg, SmallReg);
1493     }
1494
1495     // If we are joining two virtual registers and the resulting register
1496     // class is more restrictive (fewer register, smaller size). Check if it's
1497     // worth doing the merge.
1498     if (!SrcIsPhys && !DstIsPhys &&
1499         (isExtSubReg || DstRC->isASubClass()) &&
1500         !isWinToJoinCrossClass(LargeReg, SmallReg,
1501                                allocatableRCRegs_[NewRC].count())) {
1502       DOUT << "\tSrc/Dest are different register classes.\n";
1503       // Allow the coalescer to try again in case either side gets coalesced to
1504       // a physical register that's compatible with the other side. e.g.
1505       // r1024 = MOV32to32_ r1025
1506       // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1507       Again = true;  // May be possible to coalesce later.
1508       return false;
1509     }
1510   }
1511
1512   // Will it create illegal extract_subreg / insert_subreg?
1513   if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1514     return false;
1515   if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1516     return false;
1517   
1518   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1519   LiveInterval &DstInt = li_->getInterval(DstReg);
1520   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1521          "Register mapping is horribly broken!");
1522
1523   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1524   DOUT << " and "; DstInt.print(DOUT, tri_);
1525   DOUT << ": ";
1526
1527   // Save a copy of the virtual register live interval. We'll manually
1528   // merge this into the "real" physical register live interval this is
1529   // coalesced with.
1530   LiveInterval *SavedLI = 0;
1531   if (RealDstReg)
1532     SavedLI = li_->dupInterval(&SrcInt);
1533   else if (RealSrcReg)
1534     SavedLI = li_->dupInterval(&DstInt);
1535
1536   // Check if it is necessary to propagate "isDead" property.
1537   if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1538     MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1539     bool isDead = mopd->isDead();
1540
1541     // We need to be careful about coalescing a source physical register with a
1542     // virtual register. Once the coalescing is done, it cannot be broken and
1543     // these are not spillable! If the destination interval uses are far away,
1544     // think twice about coalescing them!
1545     if (!isDead && (SrcIsPhys || DstIsPhys)) {
1546       // If the copy is in a loop, take care not to coalesce aggressively if the
1547       // src is coming in from outside the loop (or the dst is out of the loop).
1548       // If it's not in a loop, then determine whether to join them base purely
1549       // by the length of the interval.
1550       if (PhysJoinTweak) {
1551         if (SrcIsPhys) {
1552           if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1553             mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1554             ++numAborts;
1555             DOUT << "\tMay tie down a physical register, abort!\n";
1556             Again = true;  // May be possible to coalesce later.
1557             return false;
1558           }
1559         } else {
1560           if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1561             mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1562             ++numAborts;
1563             DOUT << "\tMay tie down a physical register, abort!\n";
1564             Again = true;  // May be possible to coalesce later.
1565             return false;
1566           }
1567         }
1568       } else {
1569         // If the virtual register live interval is long but it has low use desity,
1570         // do not join them, instead mark the physical register as its allocation
1571         // preference.
1572         LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1573         unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1574         unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1575         const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1576         unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1577         if (TheCopy.isBackEdge)
1578           Threshold *= 2; // Favors back edge copies.
1579
1580         unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1581         float Ratio = 1.0 / Threshold;
1582         if (Length > Threshold &&
1583             (((float)std::distance(mri_->use_begin(JoinVReg),
1584                                    mri_->use_end()) / Length) < Ratio)) {
1585           mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1586           ++numAborts;
1587           DOUT << "\tMay tie down a physical register, abort!\n";
1588           Again = true;  // May be possible to coalesce later.
1589           return false;
1590         }
1591       }
1592     }
1593   }
1594
1595   // Okay, attempt to join these two intervals.  On failure, this returns false.
1596   // Otherwise, if one of the intervals being joined is a physreg, this method
1597   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1598   // been modified, so we can use this information below to update aliases.
1599   bool Swapped = false;
1600   // If SrcInt is implicitly defined, it's safe to coalesce.
1601   bool isEmpty = SrcInt.empty();
1602   if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1603     // Only coalesce an empty interval (defined by implicit_def) with
1604     // another interval which has a valno defined by the CopyMI and the CopyMI
1605     // is a kill of the implicit def.
1606     DOUT << "Not profitable!\n";
1607     return false;
1608   }
1609
1610   if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1611     // Coalescing failed.
1612
1613     // If definition of source is defined by trivial computation, try
1614     // rematerializing it.
1615     if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1616         ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1617       return true;
1618     
1619     // If we can eliminate the copy without merging the live ranges, do so now.
1620     if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1621         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1622          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1623       JoinedCopies.insert(CopyMI);
1624       return true;
1625     }
1626     
1627     // Otherwise, we are unable to join the intervals.
1628     DOUT << "Interference!\n";
1629     Again = true;  // May be possible to coalesce later.
1630     return false;
1631   }
1632
1633   LiveInterval *ResSrcInt = &SrcInt;
1634   LiveInterval *ResDstInt = &DstInt;
1635   if (Swapped) {
1636     std::swap(SrcReg, DstReg);
1637     std::swap(ResSrcInt, ResDstInt);
1638   }
1639   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1640          "LiveInterval::join didn't work right!");
1641                                
1642   // If we're about to merge live ranges into a physical register live interval,
1643   // we have to update any aliased register's live ranges to indicate that they
1644   // have clobbered values for this range.
1645   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1646     // If this is a extract_subreg where dst is a physical register, e.g.
1647     // cl = EXTRACT_SUBREG reg1024, 1
1648     // then create and update the actual physical register allocated to RHS.
1649     if (RealDstReg || RealSrcReg) {
1650       LiveInterval &RealInt =
1651         li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1652       for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1653              E = SavedLI->vni_end(); I != E; ++I) {
1654         const VNInfo *ValNo = *I;
1655         VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->copy,
1656                                                 false, // updated at *
1657                                                 li_->getVNInfoAllocator());
1658         NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1659         RealInt.addKills(NewValNo, ValNo->kills);
1660         RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1661       }
1662       RealInt.weight += SavedLI->weight;      
1663       DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1664     }
1665
1666     // Update the liveintervals of sub-registers.
1667     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1668       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1669                                                  li_->getVNInfoAllocator());
1670   }
1671
1672   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1673   // larger super-register.
1674   if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1675       !SrcIsPhys && !DstIsPhys) {
1676     if ((isExtSubReg && !Swapped) ||
1677         ((isInsSubReg || isSubRegToReg) && Swapped)) {
1678       ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1679       std::swap(SrcReg, DstReg);
1680       std::swap(ResSrcInt, ResDstInt);
1681     }
1682   }
1683
1684   // Coalescing to a virtual register that is of a sub-register class of the
1685   // other. Make sure the resulting register is set to the right register class.
1686   if (CrossRC)
1687     ++numCrossRCs;
1688
1689   // This may happen even if it's cross-rc coalescing. e.g.
1690   // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1691   // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1692   // be allocate a register from GR64_ABCD.
1693   if (NewRC)
1694     mri_->setRegClass(DstReg, NewRC);
1695
1696   if (NewHeuristic) {
1697     // Add all copies that define val# in the source interval into the queue.
1698     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1699            e = ResSrcInt->vni_end(); i != e; ++i) {
1700       const VNInfo *vni = *i;
1701       // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1702       if (!vni->def || vni->isUnused() || vni->isPHIDef() || !vni->isDefAccurate())
1703         continue;
1704       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1705       unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx;
1706       if (CopyMI &&
1707           JoinedCopies.count(CopyMI) == 0 &&
1708           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg,
1709                             NewSrcSubIdx, NewDstSubIdx)) {
1710         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1711         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1712                                 isBackEdgeCopy(CopyMI, DstReg)));
1713       }
1714     }
1715   }
1716
1717   // Remember to delete the copy instruction.
1718   JoinedCopies.insert(CopyMI);
1719
1720   // Some live range has been lengthened due to colaescing, eliminate the
1721   // unnecessary kills.
1722   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1723   if (TargetRegisterInfo::isVirtualRegister(DstReg))
1724     RemoveUnnecessaryKills(DstReg, *ResDstInt);
1725
1726   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1727
1728   // SrcReg is guarateed to be the register whose live interval that is
1729   // being merged.
1730   li_->removeInterval(SrcReg);
1731
1732   // Update regalloc hint.
1733   tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1734
1735   // Manually deleted the live interval copy.
1736   if (SavedLI) {
1737     SavedLI->clear();
1738     delete SavedLI;
1739   }
1740
1741   // If resulting interval has a preference that no longer fits because of subreg
1742   // coalescing, just clear the preference.
1743   unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1744   if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1745       TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1746     const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1747     if (!RC->contains(Preference))
1748       mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1749   }
1750
1751   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
1752   DOUT << "\n";
1753
1754   ++numJoins;
1755   return true;
1756 }
1757
1758 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1759 /// compute what the resultant value numbers for each value in the input two
1760 /// ranges will be.  This is complicated by copies between the two which can
1761 /// and will commonly cause multiple value numbers to be merged into one.
1762 ///
1763 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1764 /// keeps track of the new InstDefiningValue assignment for the result
1765 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1766 /// whether a value in this or other is a copy from the opposite set.
1767 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1768 /// already been assigned.
1769 ///
1770 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1771 /// contains the value number the copy is from.
1772 ///
1773 static unsigned ComputeUltimateVN(VNInfo *VNI,
1774                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1775                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1776                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1777                                   SmallVector<int, 16> &ThisValNoAssignments,
1778                                   SmallVector<int, 16> &OtherValNoAssignments) {
1779   unsigned VN = VNI->id;
1780
1781   // If the VN has already been computed, just return it.
1782   if (ThisValNoAssignments[VN] >= 0)
1783     return ThisValNoAssignments[VN];
1784 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1785
1786   // If this val is not a copy from the other val, then it must be a new value
1787   // number in the destination.
1788   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1789   if (I == ThisFromOther.end()) {
1790     NewVNInfo.push_back(VNI);
1791     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1792   }
1793   VNInfo *OtherValNo = I->second;
1794
1795   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1796   // been computed, return it.
1797   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1798     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1799   
1800   // Mark this value number as currently being computed, then ask what the
1801   // ultimate value # of the other value is.
1802   ThisValNoAssignments[VN] = -2;
1803   unsigned UltimateVN =
1804     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1805                       OtherValNoAssignments, ThisValNoAssignments);
1806   return ThisValNoAssignments[VN] = UltimateVN;
1807 }
1808
1809 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1810   return std::find(V.begin(), V.end(), Val) != V.end();
1811 }
1812
1813 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1814 /// the specified live interval is defined by a copy from the specified
1815 /// register.
1816 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1817                                                            LiveRange *LR,
1818                                                            unsigned Reg) {
1819   unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1820   if (SrcReg == Reg)
1821     return true;
1822   // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1823   if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1824       TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1825       *tri_->getSuperRegisters(li.reg)) {
1826     // It's a sub-register live interval, we may not have precise information.
1827     // Re-compute it.
1828     MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1829     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1830     if (DefMI &&
1831         tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1832         DstReg == li.reg && SrcReg == Reg) {
1833       // Cache computed info.
1834       LR->valno->def  = LR->start;
1835       LR->valno->copy = DefMI;
1836       return true;
1837     }
1838   }
1839   return false;
1840 }
1841
1842 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1843 /// caller of this method must guarantee that the RHS only contains a single
1844 /// value number and that the RHS is not defined by a copy from this
1845 /// interval.  This returns false if the intervals are not joinable, or it
1846 /// joins them and returns true.
1847 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1848   assert(RHS.containsOneValue());
1849   
1850   // Some number (potentially more than one) value numbers in the current
1851   // interval may be defined as copies from the RHS.  Scan the overlapping
1852   // portions of the LHS and RHS, keeping track of this and looking for
1853   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1854   // cannot coalesce.
1855   
1856   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1857   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1858   
1859   if (LHSIt->start < RHSIt->start) {
1860     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1861     if (LHSIt != LHS.begin()) --LHSIt;
1862   } else if (RHSIt->start < LHSIt->start) {
1863     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1864     if (RHSIt != RHS.begin()) --RHSIt;
1865   }
1866   
1867   SmallVector<VNInfo*, 8> EliminatedLHSVals;
1868   
1869   while (1) {
1870     // Determine if these live intervals overlap.
1871     bool Overlaps = false;
1872     if (LHSIt->start <= RHSIt->start)
1873       Overlaps = LHSIt->end > RHSIt->start;
1874     else
1875       Overlaps = RHSIt->end > LHSIt->start;
1876     
1877     // If the live intervals overlap, there are two interesting cases: if the
1878     // LHS interval is defined by a copy from the RHS, it's ok and we record
1879     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1880     // coalesce these live ranges and we bail out.
1881     if (Overlaps) {
1882       // If we haven't already recorded that this value # is safe, check it.
1883       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1884         // Copy from the RHS?
1885         if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1886           return false;    // Nope, bail out.
1887
1888         if (LHSIt->contains(RHSIt->valno->def))
1889           // Here is an interesting situation:
1890           // BB1:
1891           //   vr1025 = copy vr1024
1892           //   ..
1893           // BB2:
1894           //   vr1024 = op 
1895           //          = vr1025
1896           // Even though vr1025 is copied from vr1024, it's not safe to
1897           // coalesce them since the live range of vr1025 intersects the
1898           // def of vr1024. This happens because vr1025 is assigned the
1899           // value of the previous iteration of vr1024.
1900           return false;
1901         EliminatedLHSVals.push_back(LHSIt->valno);
1902       }
1903       
1904       // We know this entire LHS live range is okay, so skip it now.
1905       if (++LHSIt == LHSEnd) break;
1906       continue;
1907     }
1908     
1909     if (LHSIt->end < RHSIt->end) {
1910       if (++LHSIt == LHSEnd) break;
1911     } else {
1912       // One interesting case to check here.  It's possible that we have
1913       // something like "X3 = Y" which defines a new value number in the LHS,
1914       // and is the last use of this liverange of the RHS.  In this case, we
1915       // want to notice this copy (so that it gets coalesced away) even though
1916       // the live ranges don't actually overlap.
1917       if (LHSIt->start == RHSIt->end) {
1918         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1919           // We already know that this value number is going to be merged in
1920           // if coalescing succeeds.  Just skip the liverange.
1921           if (++LHSIt == LHSEnd) break;
1922         } else {
1923           // Otherwise, if this is a copy from the RHS, mark it as being merged
1924           // in.
1925           if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1926             if (LHSIt->contains(RHSIt->valno->def))
1927               // Here is an interesting situation:
1928               // BB1:
1929               //   vr1025 = copy vr1024
1930               //   ..
1931               // BB2:
1932               //   vr1024 = op 
1933               //          = vr1025
1934               // Even though vr1025 is copied from vr1024, it's not safe to
1935               // coalesced them since live range of vr1025 intersects the
1936               // def of vr1024. This happens because vr1025 is assigned the
1937               // value of the previous iteration of vr1024.
1938               return false;
1939             EliminatedLHSVals.push_back(LHSIt->valno);
1940
1941             // We know this entire LHS live range is okay, so skip it now.
1942             if (++LHSIt == LHSEnd) break;
1943           }
1944         }
1945       }
1946       
1947       if (++RHSIt == RHSEnd) break;
1948     }
1949   }
1950   
1951   // If we got here, we know that the coalescing will be successful and that
1952   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1953   // the most common case is that EliminatedLHSVals has a single number, we
1954   // optimize for it: if there is more than one value, we merge them all into
1955   // the lowest numbered one, then handle the interval as if we were merging
1956   // with one value number.
1957   VNInfo *LHSValNo = NULL;
1958   if (EliminatedLHSVals.size() > 1) {
1959     // Loop through all the equal value numbers merging them into the smallest
1960     // one.
1961     VNInfo *Smallest = EliminatedLHSVals[0];
1962     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1963       if (EliminatedLHSVals[i]->id < Smallest->id) {
1964         // Merge the current notion of the smallest into the smaller one.
1965         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1966         Smallest = EliminatedLHSVals[i];
1967       } else {
1968         // Merge into the smallest.
1969         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1970       }
1971     }
1972     LHSValNo = Smallest;
1973   } else if (EliminatedLHSVals.empty()) {
1974     if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1975         *tri_->getSuperRegisters(LHS.reg))
1976       // Imprecise sub-register information. Can't handle it.
1977       return false;
1978     llvm_unreachable("No copies from the RHS?");
1979   } else {
1980     LHSValNo = EliminatedLHSVals[0];
1981   }
1982   
1983   // Okay, now that there is a single LHS value number that we're merging the
1984   // RHS into, update the value number info for the LHS to indicate that the
1985   // value number is defined where the RHS value number was.
1986   const VNInfo *VNI = RHS.getValNumInfo(0);
1987   LHSValNo->def  = VNI->def;
1988   LHSValNo->copy = VNI->copy;
1989   
1990   // Okay, the final step is to loop over the RHS live intervals, adding them to
1991   // the LHS.
1992   if (VNI->hasPHIKill())
1993     LHSValNo->setHasPHIKill(true);
1994   LHS.addKills(LHSValNo, VNI->kills);
1995   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1996
1997   LHS.ComputeJoinedWeight(RHS);
1998
1999   // Update regalloc hint if both are virtual registers.
2000   if (TargetRegisterInfo::isVirtualRegister(LHS.reg) && 
2001       TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2002     std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2003     std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2004     if (RHSPref != LHSPref)
2005       mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2006   }
2007
2008   // Update the liveintervals of sub-registers.
2009   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2010     for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2011       li_->getOrCreateInterval(*AS).MergeInClobberRanges(LHS,
2012                                                     li_->getVNInfoAllocator());
2013
2014   return true;
2015 }
2016
2017 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
2018 /// returns false.  Otherwise, if one of the intervals being joined is a
2019 /// physreg, this method always canonicalizes LHS to be it.  The output
2020 /// "RHS" will not have been modified, so we can use this information
2021 /// below to update aliases.
2022 bool
2023 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2024                                         bool &Swapped) {
2025   // Compute the final value assignment, assuming that the live ranges can be
2026   // coalesced.
2027   SmallVector<int, 16> LHSValNoAssignments;
2028   SmallVector<int, 16> RHSValNoAssignments;
2029   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2030   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2031   SmallVector<VNInfo*, 16> NewVNInfo;
2032
2033   // If a live interval is a physical register, conservatively check if any
2034   // of its sub-registers is overlapping the live interval of the virtual
2035   // register. If so, do not coalesce.
2036   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2037       *tri_->getSubRegisters(LHS.reg)) {
2038     // If it's coalescing a virtual register to a physical register, estimate
2039     // its live interval length. This is the *cost* of scanning an entire live
2040     // interval. If the cost is low, we'll do an exhaustive check instead.
2041
2042     // If this is something like this:
2043     // BB1:
2044     // v1024 = op
2045     // ...
2046     // BB2:
2047     // ...
2048     // RAX   = v1024
2049     //
2050     // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2051     // less conservative check. It's possible a sub-register is defined before
2052     // v1024 (or live in) and live out of BB1.
2053     if (RHS.containsOneValue() &&
2054         li_->intervalIsInOneMBB(RHS) &&
2055         li_->getApproximateInstructionCount(RHS) <= 10) {
2056       // Perform a more exhaustive check for some common cases.
2057       if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2058         return false;
2059     } else {
2060       for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2061         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2062           DOUT << "Interfere with sub-register ";
2063           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
2064           return false;
2065         }
2066     }
2067   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2068              *tri_->getSubRegisters(RHS.reg)) {
2069     if (LHS.containsOneValue() &&
2070         li_->getApproximateInstructionCount(LHS) <= 10) {
2071       // Perform a more exhaustive check for some common cases.
2072       if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2073         return false;
2074     } else {
2075       for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2076         if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2077           DOUT << "Interfere with sub-register ";
2078           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
2079           return false;
2080         }
2081     }
2082   }
2083                           
2084   // Compute ultimate value numbers for the LHS and RHS values.
2085   if (RHS.containsOneValue()) {
2086     // Copies from a liveinterval with a single value are simple to handle and
2087     // very common, handle the special case here.  This is important, because
2088     // often RHS is small and LHS is large (e.g. a physreg).
2089     
2090     // Find out if the RHS is defined as a copy from some value in the LHS.
2091     int RHSVal0DefinedFromLHS = -1;
2092     int RHSValID = -1;
2093     VNInfo *RHSValNoInfo = NULL;
2094     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2095     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2096     if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2097       // If RHS is not defined as a copy from the LHS, we can use simpler and
2098       // faster checks to see if the live ranges are coalescable.  This joiner
2099       // can't swap the LHS/RHS intervals though.
2100       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2101         return SimpleJoin(LHS, RHS);
2102       } else {
2103         RHSValNoInfo = RHSValNoInfo0;
2104       }
2105     } else {
2106       // It was defined as a copy from the LHS, find out what value # it is.
2107       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
2108       RHSValID = RHSValNoInfo->id;
2109       RHSVal0DefinedFromLHS = RHSValID;
2110     }
2111     
2112     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2113     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2114     NewVNInfo.resize(LHS.getNumValNums(), NULL);
2115     
2116     // Okay, *all* of the values in LHS that are defined as a copy from RHS
2117     // should now get updated.
2118     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2119          i != e; ++i) {
2120       VNInfo *VNI = *i;
2121       unsigned VN = VNI->id;
2122       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2123         if (LHSSrcReg != RHS.reg) {
2124           // If this is not a copy from the RHS, its value number will be
2125           // unmodified by the coalescing.
2126           NewVNInfo[VN] = VNI;
2127           LHSValNoAssignments[VN] = VN;
2128         } else if (RHSValID == -1) {
2129           // Otherwise, it is a copy from the RHS, and we don't already have a
2130           // value# for it.  Keep the current value number, but remember it.
2131           LHSValNoAssignments[VN] = RHSValID = VN;
2132           NewVNInfo[VN] = RHSValNoInfo;
2133           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2134         } else {
2135           // Otherwise, use the specified value #.
2136           LHSValNoAssignments[VN] = RHSValID;
2137           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
2138             NewVNInfo[VN] = RHSValNoInfo;
2139             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2140           }
2141         }
2142       } else {
2143         NewVNInfo[VN] = VNI;
2144         LHSValNoAssignments[VN] = VN;
2145       }
2146     }
2147     
2148     assert(RHSValID != -1 && "Didn't find value #?");
2149     RHSValNoAssignments[0] = RHSValID;
2150     if (RHSVal0DefinedFromLHS != -1) {
2151       // This path doesn't go through ComputeUltimateVN so just set
2152       // it to anything.
2153       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2154     }
2155   } else {
2156     // Loop over the value numbers of the LHS, seeing if any are defined from
2157     // the RHS.
2158     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2159          i != e; ++i) {
2160       VNInfo *VNI = *i;
2161       if (VNI->isUnused() || VNI->copy == 0)  // Src not defined by a copy?
2162         continue;
2163       
2164       // DstReg is known to be a register in the LHS interval.  If the src is
2165       // from the RHS interval, we can use its value #.
2166       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2167         continue;
2168       
2169       // Figure out the value # from the RHS.
2170       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
2171     }
2172     
2173     // Loop over the value numbers of the RHS, seeing if any are defined from
2174     // the LHS.
2175     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2176          i != e; ++i) {
2177       VNInfo *VNI = *i;
2178       if (VNI->isUnused() || VNI->copy == 0)  // Src not defined by a copy?
2179         continue;
2180       
2181       // DstReg is known to be a register in the RHS interval.  If the src is
2182       // from the LHS interval, we can use its value #.
2183       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2184         continue;
2185       
2186       // Figure out the value # from the LHS.
2187       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
2188     }
2189     
2190     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2191     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2192     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2193     
2194     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2195          i != e; ++i) {
2196       VNInfo *VNI = *i;
2197       unsigned VN = VNI->id;
2198       if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused()) 
2199         continue;
2200       ComputeUltimateVN(VNI, NewVNInfo,
2201                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2202                         LHSValNoAssignments, RHSValNoAssignments);
2203     }
2204     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2205          i != e; ++i) {
2206       VNInfo *VNI = *i;
2207       unsigned VN = VNI->id;
2208       if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2209         continue;
2210       // If this value number isn't a copy from the LHS, it's a new number.
2211       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2212         NewVNInfo.push_back(VNI);
2213         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2214         continue;
2215       }
2216       
2217       ComputeUltimateVN(VNI, NewVNInfo,
2218                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2219                         RHSValNoAssignments, LHSValNoAssignments);
2220     }
2221   }
2222   
2223   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2224   // interval lists to see if these intervals are coalescable.
2225   LiveInterval::const_iterator I = LHS.begin();
2226   LiveInterval::const_iterator IE = LHS.end();
2227   LiveInterval::const_iterator J = RHS.begin();
2228   LiveInterval::const_iterator JE = RHS.end();
2229   
2230   // Skip ahead until the first place of potential sharing.
2231   if (I->start < J->start) {
2232     I = std::upper_bound(I, IE, J->start);
2233     if (I != LHS.begin()) --I;
2234   } else if (J->start < I->start) {
2235     J = std::upper_bound(J, JE, I->start);
2236     if (J != RHS.begin()) --J;
2237   }
2238   
2239   while (1) {
2240     // Determine if these two live ranges overlap.
2241     bool Overlaps;
2242     if (I->start < J->start) {
2243       Overlaps = I->end > J->start;
2244     } else {
2245       Overlaps = J->end > I->start;
2246     }
2247
2248     // If so, check value # info to determine if they are really different.
2249     if (Overlaps) {
2250       // If the live range overlap will map to the same value number in the
2251       // result liverange, we can still coalesce them.  If not, we can't.
2252       if (LHSValNoAssignments[I->valno->id] !=
2253           RHSValNoAssignments[J->valno->id])
2254         return false;
2255     }
2256     
2257     if (I->end < J->end) {
2258       ++I;
2259       if (I == IE) break;
2260     } else {
2261       ++J;
2262       if (J == JE) break;
2263     }
2264   }
2265
2266   // Update kill info. Some live ranges are extended due to copy coalescing.
2267   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2268          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2269     VNInfo *VNI = I->first;
2270     unsigned LHSValID = LHSValNoAssignments[VNI->id];
2271     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
2272     if (VNI->hasPHIKill())
2273       NewVNInfo[LHSValID]->setHasPHIKill(true);
2274     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2275   }
2276
2277   // Update kill info. Some live ranges are extended due to copy coalescing.
2278   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2279          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2280     VNInfo *VNI = I->first;
2281     unsigned RHSValID = RHSValNoAssignments[VNI->id];
2282     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
2283     if (VNI->hasPHIKill())
2284       NewVNInfo[RHSValID]->setHasPHIKill(true);
2285     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2286   }
2287
2288   // If we get here, we know that we can coalesce the live ranges.  Ask the
2289   // intervals to coalesce themselves now.
2290   if ((RHS.ranges.size() > LHS.ranges.size() &&
2291       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2292       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2293     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2294              mri_);
2295     Swapped = true;
2296   } else {
2297     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2298              mri_);
2299     Swapped = false;
2300   }
2301   return true;
2302 }
2303
2304 namespace {
2305   // DepthMBBCompare - Comparison predicate that sort first based on the loop
2306   // depth of the basic block (the unsigned), and then on the MBB number.
2307   struct DepthMBBCompare {
2308     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2309     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2310       if (LHS.first > RHS.first) return true;   // Deeper loops first
2311       return LHS.first == RHS.first &&
2312         LHS.second->getNumber() < RHS.second->getNumber();
2313     }
2314   };
2315 }
2316
2317 /// getRepIntervalSize - Returns the size of the interval that represents the
2318 /// specified register.
2319 template<class SF>
2320 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2321   return Rc->getRepIntervalSize(Reg);
2322 }
2323
2324 /// CopyRecSort::operator - Join priority queue sorting function.
2325 ///
2326 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2327   // Inner loops first.
2328   if (left.LoopDepth > right.LoopDepth)
2329     return false;
2330   else if (left.LoopDepth == right.LoopDepth)
2331     if (left.isBackEdge && !right.isBackEdge)
2332       return false;
2333   return true;
2334 }
2335
2336 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2337                                                std::vector<CopyRec> &TryAgain) {
2338   DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
2339
2340   std::vector<CopyRec> VirtCopies;
2341   std::vector<CopyRec> PhysCopies;
2342   std::vector<CopyRec> ImpDefCopies;
2343   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
2344   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2345        MII != E;) {
2346     MachineInstr *Inst = MII++;
2347     
2348     // If this isn't a copy nor a extract_subreg, we can't join intervals.
2349     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2350     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2351       DstReg = Inst->getOperand(0).getReg();
2352       SrcReg = Inst->getOperand(1).getReg();
2353     } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2354                Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
2355       DstReg = Inst->getOperand(0).getReg();
2356       SrcReg = Inst->getOperand(2).getReg();
2357     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2358       continue;
2359
2360     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2361     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2362     if (NewHeuristic) {
2363       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
2364     } else {
2365       if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2366         ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2367       else if (SrcIsPhys || DstIsPhys)
2368         PhysCopies.push_back(CopyRec(Inst, 0, false));
2369       else
2370         VirtCopies.push_back(CopyRec(Inst, 0, false));
2371     }
2372   }
2373
2374   if (NewHeuristic)
2375     return;
2376
2377   // Try coalescing implicit copies first, followed by copies to / from
2378   // physical registers, then finally copies from virtual registers to
2379   // virtual registers.
2380   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2381     CopyRec &TheCopy = ImpDefCopies[i];
2382     bool Again = false;
2383     if (!JoinCopy(TheCopy, Again))
2384       if (Again)
2385         TryAgain.push_back(TheCopy);
2386   }
2387   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2388     CopyRec &TheCopy = PhysCopies[i];
2389     bool Again = false;
2390     if (!JoinCopy(TheCopy, Again))
2391       if (Again)
2392         TryAgain.push_back(TheCopy);
2393   }
2394   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2395     CopyRec &TheCopy = VirtCopies[i];
2396     bool Again = false;
2397     if (!JoinCopy(TheCopy, Again))
2398       if (Again)
2399         TryAgain.push_back(TheCopy);
2400   }
2401 }
2402
2403 void SimpleRegisterCoalescing::joinIntervals() {
2404   DOUT << "********** JOINING INTERVALS ***********\n";
2405
2406   if (NewHeuristic)
2407     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2408
2409   std::vector<CopyRec> TryAgainList;
2410   if (loopInfo->empty()) {
2411     // If there are no loops in the function, join intervals in function order.
2412     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2413          I != E; ++I)
2414       CopyCoalesceInMBB(I, TryAgainList);
2415   } else {
2416     // Otherwise, join intervals in inner loops before other intervals.
2417     // Unfortunately we can't just iterate over loop hierarchy here because
2418     // there may be more MBB's than BB's.  Collect MBB's for sorting.
2419
2420     // Join intervals in the function prolog first. We want to join physical
2421     // registers with virtual registers before the intervals got too long.
2422     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2423     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2424       MachineBasicBlock *MBB = I;
2425       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2426     }
2427
2428     // Sort by loop depth.
2429     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2430
2431     // Finally, join intervals in loop nest order.
2432     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2433       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2434   }
2435   
2436   // Joining intervals can allow other intervals to be joined.  Iteratively join
2437   // until we make no progress.
2438   if (NewHeuristic) {
2439     SmallVector<CopyRec, 16> TryAgain;
2440     bool ProgressMade = true;
2441     while (ProgressMade) {
2442       ProgressMade = false;
2443       while (!JoinQueue->empty()) {
2444         CopyRec R = JoinQueue->pop();
2445         bool Again = false;
2446         bool Success = JoinCopy(R, Again);
2447         if (Success)
2448           ProgressMade = true;
2449         else if (Again)
2450           TryAgain.push_back(R);
2451       }
2452
2453       if (ProgressMade) {
2454         while (!TryAgain.empty()) {
2455           JoinQueue->push(TryAgain.back());
2456           TryAgain.pop_back();
2457         }
2458       }
2459     }
2460   } else {
2461     bool ProgressMade = true;
2462     while (ProgressMade) {
2463       ProgressMade = false;
2464
2465       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2466         CopyRec &TheCopy = TryAgainList[i];
2467         if (TheCopy.MI) {
2468           bool Again = false;
2469           bool Success = JoinCopy(TheCopy, Again);
2470           if (Success || !Again) {
2471             TheCopy.MI = 0;   // Mark this one as done.
2472             ProgressMade = true;
2473           }
2474         }
2475       }
2476     }
2477   }
2478
2479   if (NewHeuristic)
2480     delete JoinQueue;  
2481 }
2482
2483 /// Return true if the two specified registers belong to different register
2484 /// classes.  The registers may be either phys or virt regs.
2485 bool
2486 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2487                                                    unsigned RegB) const {
2488   // Get the register classes for the first reg.
2489   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2490     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2491            "Shouldn't consider two physregs!");
2492     return !mri_->getRegClass(RegB)->contains(RegA);
2493   }
2494
2495   // Compare against the regclass for the second reg.
2496   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2497   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2498     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2499     return RegClassA != RegClassB;
2500   }
2501   return !RegClassA->contains(RegB);
2502 }
2503
2504 /// lastRegisterUse - Returns the last use of the specific register between
2505 /// cycles Start and End or NULL if there are no uses.
2506 MachineOperand *
2507 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
2508                                           unsigned Reg, unsigned &UseIdx) const{
2509   UseIdx = 0;
2510   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2511     MachineOperand *LastUse = NULL;
2512     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2513            E = mri_->use_end(); I != E; ++I) {
2514       MachineOperand &Use = I.getOperand();
2515       MachineInstr *UseMI = Use.getParent();
2516       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2517       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2518           SrcReg == DstReg)
2519         // Ignore identity copies.
2520         continue;
2521       unsigned Idx = li_->getInstructionIndex(UseMI);
2522       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2523         LastUse = &Use;
2524         UseIdx = li_->getUseIndex(Idx);
2525       }
2526     }
2527     return LastUse;
2528   }
2529
2530   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2531   int s = Start;
2532   while (e >= s) {
2533     // Skip deleted instructions
2534     MachineInstr *MI = li_->getInstructionFromIndex(e);
2535     while ((e - InstrSlots::NUM) >= s && !MI) {
2536       e -= InstrSlots::NUM;
2537       MI = li_->getInstructionFromIndex(e);
2538     }
2539     if (e < s || MI == NULL)
2540       return NULL;
2541
2542     // Ignore identity copies.
2543     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2544     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2545           SrcReg == DstReg))
2546       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2547         MachineOperand &Use = MI->getOperand(i);
2548         if (Use.isReg() && Use.isUse() && Use.getReg() &&
2549             tri_->regsOverlap(Use.getReg(), Reg)) {
2550           UseIdx = li_->getUseIndex(e);
2551           return &Use;
2552         }
2553       }
2554
2555     e -= InstrSlots::NUM;
2556   }
2557
2558   return NULL;
2559 }
2560
2561
2562 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2563   if (TargetRegisterInfo::isPhysicalRegister(reg))
2564     cerr << tri_->getName(reg);
2565   else
2566     cerr << "%reg" << reg;
2567 }
2568
2569 void SimpleRegisterCoalescing::releaseMemory() {
2570   JoinedCopies.clear();
2571   ReMatCopies.clear();
2572   ReMatDefs.clear();
2573 }
2574
2575 static bool isZeroLengthInterval(LiveInterval *li) {
2576   for (LiveInterval::Ranges::const_iterator
2577          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2578     if (i->end - i->start > LiveInterval::InstrSlots::NUM)
2579       return false;
2580   return true;
2581 }
2582
2583
2584 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2585   mf_ = &fn;
2586   mri_ = &fn.getRegInfo();
2587   tm_ = &fn.getTarget();
2588   tri_ = tm_->getRegisterInfo();
2589   tii_ = tm_->getInstrInfo();
2590   li_ = &getAnalysis<LiveIntervals>();
2591   loopInfo = &getAnalysis<MachineLoopInfo>();
2592
2593   DEBUG(errs() << "********** SIMPLE REGISTER COALESCING **********\n"
2594         << "********** Function: "
2595         << ((Value*)mf_->getFunction())->getName() << '\n');
2596
2597   allocatableRegs_ = tri_->getAllocatableSet(fn);
2598   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2599          E = tri_->regclass_end(); I != E; ++I)
2600     allocatableRCRegs_.insert(std::make_pair(*I,
2601                                              tri_->getAllocatableSet(fn, *I)));
2602
2603   // Join (coalesce) intervals if requested.
2604   if (EnableJoining) {
2605     joinIntervals();
2606     DEBUG({
2607         DOUT << "********** INTERVALS POST JOINING **********\n";
2608         for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2609           I->second->print(DOUT, tri_);
2610           DOUT << "\n";
2611         }
2612       });
2613   }
2614
2615   // Perform a final pass over the instructions and compute spill weights
2616   // and remove identity moves.
2617   SmallVector<unsigned, 4> DeadDefs;
2618   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2619        mbbi != mbbe; ++mbbi) {
2620     MachineBasicBlock* mbb = mbbi;
2621     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2622
2623     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2624          mii != mie; ) {
2625       MachineInstr *MI = mii;
2626       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2627       if (JoinedCopies.count(MI)) {
2628         // Delete all coalesced copies.
2629         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2630           assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2631                   MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2632                   MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
2633                  "Unrecognized copy instruction");
2634           DstReg = MI->getOperand(0).getReg();
2635         }
2636         if (MI->registerDefIsDead(DstReg)) {
2637           LiveInterval &li = li_->getInterval(DstReg);
2638           if (!ShortenDeadCopySrcLiveRange(li, MI))
2639             ShortenDeadCopyLiveRange(li, MI);
2640         }
2641         li_->RemoveMachineInstrFromMaps(MI);
2642         mii = mbbi->erase(mii);
2643         ++numPeep;
2644         continue;
2645       }
2646
2647       // Now check if this is a remat'ed def instruction which is now dead.
2648       if (ReMatDefs.count(MI)) {
2649         bool isDead = true;
2650         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2651           const MachineOperand &MO = MI->getOperand(i);
2652           if (!MO.isReg())
2653             continue;
2654           unsigned Reg = MO.getReg();
2655           if (!Reg)
2656             continue;
2657           if (TargetRegisterInfo::isVirtualRegister(Reg))
2658             DeadDefs.push_back(Reg);
2659           if (MO.isDead())
2660             continue;
2661           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2662               !mri_->use_empty(Reg)) {
2663             isDead = false;
2664             break;
2665           }
2666         }
2667         if (isDead) {
2668           while (!DeadDefs.empty()) {
2669             unsigned DeadDef = DeadDefs.back();
2670             DeadDefs.pop_back();
2671             RemoveDeadDef(li_->getInterval(DeadDef), MI);
2672           }
2673           li_->RemoveMachineInstrFromMaps(mii);
2674           mii = mbbi->erase(mii);
2675           continue;
2676         } else
2677           DeadDefs.clear();
2678       }
2679
2680       // If the move will be an identity move delete it
2681       bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2682       if (isMove && SrcReg == DstReg) {
2683         if (li_->hasInterval(SrcReg)) {
2684           LiveInterval &RegInt = li_->getInterval(SrcReg);
2685           // If def of this move instruction is dead, remove its live range
2686           // from the dstination register's live interval.
2687           if (MI->registerDefIsDead(DstReg)) {
2688             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2689               ShortenDeadCopyLiveRange(RegInt, MI);
2690           }
2691         }
2692         li_->RemoveMachineInstrFromMaps(MI);
2693         mii = mbbi->erase(mii);
2694         ++numPeep;
2695       } else {
2696         SmallSet<unsigned, 4> UniqueUses;
2697         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2698           const MachineOperand &mop = MI->getOperand(i);
2699           if (mop.isReg() && mop.getReg() &&
2700               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2701             unsigned reg = mop.getReg();
2702             // Multiple uses of reg by the same instruction. It should not
2703             // contribute to spill weight again.
2704             if (UniqueUses.count(reg) != 0)
2705               continue;
2706             LiveInterval &RegInt = li_->getInterval(reg);
2707             RegInt.weight +=
2708               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2709             UniqueUses.insert(reg);
2710           }
2711         }
2712         ++mii;
2713       }
2714     }
2715   }
2716
2717   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2718     LiveInterval &LI = *I->second;
2719     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2720       // If the live interval length is essentially zero, i.e. in every live
2721       // range the use follows def immediately, it doesn't make sense to spill
2722       // it and hope it will be easier to allocate for this li.
2723       if (isZeroLengthInterval(&LI))
2724         LI.weight = HUGE_VALF;
2725       else {
2726         bool isLoad = false;
2727         SmallVector<LiveInterval*, 4> SpillIs;
2728         if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2729           // If all of the definitions of the interval are re-materializable,
2730           // it is a preferred candidate for spilling. If non of the defs are
2731           // loads, then it's potentially very cheap to re-materialize.
2732           // FIXME: this gets much more complicated once we support non-trivial
2733           // re-materialization.
2734           if (isLoad)
2735             LI.weight *= 0.9F;
2736           else
2737             LI.weight *= 0.5F;
2738         }
2739       }
2740
2741       // Slightly prefer live interval that has been assigned a preferred reg.
2742       std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(LI.reg);
2743       if (Hint.first || Hint.second)
2744         LI.weight *= 1.01F;
2745
2746       // Divide the weight of the interval by its size.  This encourages 
2747       // spilling of intervals that are large and have few uses, and
2748       // discourages spilling of small intervals with many uses.
2749       LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2750     }
2751   }
2752
2753   DEBUG(dump());
2754   return true;
2755 }
2756
2757 /// print - Implement the dump method.
2758 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2759    li_->print(O, m);
2760 }
2761
2762 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2763   return new SimpleRegisterCoalescing();
2764 }
2765
2766 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2767 DEFINING_FILE_FOR(SimpleRegisterCoalescing)