Also use shrinkToUses after AdjustCopiesBackFrom().
[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 "LiveDebugVariables.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/OwningPtr.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include <algorithm>
40 #include <cmath>
41 using namespace llvm;
42
43 STATISTIC(numJoins    , "Number of interval joins performed");
44 STATISTIC(numCrossRCs , "Number of cross class joins performed");
45 STATISTIC(numCommutes , "Number of instruction commuting performed");
46 STATISTIC(numExtends  , "Number of copies extended");
47 STATISTIC(NumReMats   , "Number of instructions re-materialized");
48 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
49 STATISTIC(numAborts   , "Number of times interval joining aborted");
50 STATISTIC(numDeadValNo, "Number of valno def marked dead");
51
52 char SimpleRegisterCoalescing::ID = 0;
53 static cl::opt<bool>
54 EnableJoining("join-liveintervals",
55               cl::desc("Coalesce copies (default=true)"),
56               cl::init(true));
57
58 static cl::opt<bool>
59 DisableCrossClassJoin("disable-cross-class-join",
60                cl::desc("Avoid coalescing cross register class copies"),
61                cl::init(false), cl::Hidden);
62
63 static cl::opt<bool>
64 EnablePhysicalJoin("join-physregs",
65                    cl::desc("Join physical register copies"),
66                    cl::init(false), cl::Hidden);
67
68 static cl::opt<bool>
69 VerifyCoalescing("verify-coalescing",
70          cl::desc("Verify machine instrs before and after register coalescing"),
71          cl::Hidden);
72
73 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing, RegisterCoalescer,
74                 "simple-register-coalescing", "Simple Register Coalescing", 
75                 false, false, true)
76 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
77 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
78 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
79 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
80 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
81 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
82 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
83 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
84 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing, RegisterCoalescer,
85                 "simple-register-coalescing", "Simple Register Coalescing", 
86                 false, false, true)
87
88 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
89
90 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
91   AU.setPreservesCFG();
92   AU.addRequired<AliasAnalysis>();
93   AU.addRequired<LiveIntervals>();
94   AU.addPreserved<LiveIntervals>();
95   AU.addRequired<LiveDebugVariables>();
96   AU.addPreserved<LiveDebugVariables>();
97   AU.addPreserved<SlotIndexes>();
98   AU.addRequired<MachineLoopInfo>();
99   AU.addPreserved<MachineLoopInfo>();
100   AU.addPreservedID(MachineDominatorsID);
101   AU.addPreservedID(StrongPHIEliminationID);
102   AU.addPreservedID(PHIEliminationID);
103   AU.addPreservedID(TwoAddressInstructionPassID);
104   MachineFunctionPass::getAnalysisUsage(AU);
105 }
106
107 void SimpleRegisterCoalescing::markAsJoined(MachineInstr *CopyMI) {
108   /// Joined copies are not deleted immediately, but kept in JoinedCopies.
109   JoinedCopies.insert(CopyMI);
110
111   /// Mark all register operands of CopyMI as <undef> so they won't affect dead
112   /// code elimination.
113   for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
114        E = CopyMI->operands_end(); I != E; ++I)
115     if (I->isReg())
116       I->setIsUndef(true);
117 }
118
119 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
120 /// being the source and IntB being the dest, thus this defines a value number
121 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
122 /// see if we can merge these two pieces of B into a single value number,
123 /// eliminating a copy.  For example:
124 ///
125 ///  A3 = B0
126 ///    ...
127 ///  B1 = A3      <- this copy
128 ///
129 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
130 /// value number to be replaced with B0 (which simplifies the B liveinterval).
131 ///
132 /// This returns true if an interval was modified.
133 ///
134 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
135                                                     MachineInstr *CopyMI) {
136   // Bail if there is no dst interval - can happen when merging physical subreg
137   // operations.
138   if (!li_->hasInterval(CP.getDstReg()))
139     return false;
140
141   LiveInterval &IntA =
142     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
143   LiveInterval &IntB =
144     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
145   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
146
147   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
148   // the example above.
149   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
150   if (BLR == IntB.end()) return false;
151   VNInfo *BValNo = BLR->valno;
152
153   // Get the location that B is defined at.  Two options: either this value has
154   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
155   // can't process it.
156   if (!BValNo->isDefByCopy()) return false;
157   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
158
159   // AValNo is the value number in A that defines the copy, A3 in the example.
160   SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
161   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
162   // The live range might not exist after fun with physreg coalescing.
163   if (ALR == IntA.end()) return false;
164   VNInfo *AValNo = ALR->valno;
165   // If it's re-defined by an early clobber somewhere in the live range, then
166   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
167   // See PR3149:
168   // 172     %ECX<def> = MOV32rr %reg1039<kill>
169   // 180     INLINEASM <es:subl $5,$1
170   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
171   //         %EAX<kill>,
172   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
173   // 188     %EAX<def> = MOV32rr %EAX<kill>
174   // 196     %ECX<def> = MOV32rr %ECX<kill>
175   // 204     %ECX<def> = MOV32rr %ECX<kill>
176   // 212     %EAX<def> = MOV32rr %EAX<kill>
177   // 220     %EAX<def> = MOV32rr %EAX
178   // 228     %reg1039<def> = MOV32rr %ECX<kill>
179   // The early clobber operand ties ECX input to the ECX def.
180   //
181   // The live interval of ECX is represented as this:
182   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
183   // The coalescer has no idea there was a def in the middle of [174,230].
184   if (AValNo->hasRedefByEC())
185     return false;
186
187   // If AValNo is defined as a copy from IntB, we can potentially process this.
188   // Get the instruction that defines this value number.
189   if (!CP.isCoalescable(AValNo->getCopy()))
190     return false;
191
192   // Get the LiveRange in IntB that this value number starts with.
193   LiveInterval::iterator ValLR =
194     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
195   if (ValLR == IntB.end())
196     return false;
197
198   // Make sure that the end of the live range is inside the same block as
199   // CopyMI.
200   MachineInstr *ValLREndInst =
201     li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
202   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
203     return false;
204
205   // Okay, we now know that ValLR ends in the same block that the CopyMI
206   // live-range starts.  If there are no intervening live ranges between them in
207   // IntB, we can merge them.
208   if (ValLR+1 != BLR) return false;
209
210   // If a live interval is a physical register, conservatively check if any
211   // of its aliases is overlapping the live interval of the virtual register.
212   // If so, do not coalesce.
213   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
214     for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
215       if (li_->hasInterval(*AS) && IntA.overlaps(li_->getInterval(*AS))) {
216         DEBUG({
217             dbgs() << "\t\tInterfere with alias ";
218             li_->getInterval(*AS).print(dbgs(), tri_);
219           });
220         return false;
221       }
222   }
223
224   DEBUG({
225       dbgs() << "Extending: ";
226       IntB.print(dbgs(), tri_);
227     });
228
229   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
230   // We are about to delete CopyMI, so need to remove it as the 'instruction
231   // that defines this value #'. Update the valnum with the new defining
232   // instruction #.
233   BValNo->def  = FillerStart;
234   BValNo->setCopy(0);
235
236   // Okay, we can merge them.  We need to insert a new liverange:
237   // [ValLR.end, BLR.begin) of either value number, then we merge the
238   // two value numbers.
239   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
240
241   // If the IntB live range is assigned to a physical register, and if that
242   // physreg has sub-registers, update their live intervals as well.
243   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
244     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
245       if (!li_->hasInterval(*SR))
246         continue;
247       LiveInterval &SRLI = li_->getInterval(*SR);
248       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
249                               SRLI.getNextValue(FillerStart, 0,
250                                                 li_->getVNInfoAllocator())));
251     }
252   }
253
254   // Okay, merge "B1" into the same value number as "B0".
255   if (BValNo != ValLR->valno) {
256     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
257   }
258   DEBUG({
259       dbgs() << "   result = ";
260       IntB.print(dbgs(), tri_);
261       dbgs() << "\n";
262     });
263
264   // If the source instruction was killing the source register before the
265   // merge, unset the isKill marker given the live range has been extended.
266   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
267   if (UIdx != -1) {
268     ValLREndInst->getOperand(UIdx).setIsKill(false);
269   }
270
271   // If the copy instruction was killing the destination register before the
272   // merge, find the last use and trim the live range. That will also add the
273   // isKill marker.
274   if (ALR->end == CopyIdx)
275     li_->shrinkToUses(&IntA);
276
277   ++numExtends;
278   return true;
279 }
280
281 /// HasOtherReachingDefs - Return true if there are definitions of IntB
282 /// other than BValNo val# that can reach uses of AValno val# of IntA.
283 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
284                                                     LiveInterval &IntB,
285                                                     VNInfo *AValNo,
286                                                     VNInfo *BValNo) {
287   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
288        AI != AE; ++AI) {
289     if (AI->valno != AValNo) continue;
290     LiveInterval::Ranges::iterator BI =
291       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
292     if (BI != IntB.ranges.begin())
293       --BI;
294     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
295       if (BI->valno == BValNo)
296         continue;
297       if (BI->start <= AI->start && BI->end > AI->start)
298         return true;
299       if (BI->start > AI->start && BI->start < AI->end)
300         return true;
301     }
302   }
303   return false;
304 }
305
306 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
307 /// IntA being the source and IntB being the dest, thus this defines a value
308 /// number in IntB.  If the source value number (in IntA) is defined by a
309 /// commutable instruction and its other operand is coalesced to the copy dest
310 /// register, see if we can transform the copy into a noop by commuting the
311 /// definition. For example,
312 ///
313 ///  A3 = op A2 B0<kill>
314 ///    ...
315 ///  B1 = A3      <- this copy
316 ///    ...
317 ///     = op A3   <- more uses
318 ///
319 /// ==>
320 ///
321 ///  B2 = op B0 A2<kill>
322 ///    ...
323 ///  B1 = B2      <- now an identify copy
324 ///    ...
325 ///     = op B2   <- more uses
326 ///
327 /// This returns true if an interval was modified.
328 ///
329 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
330                                                         MachineInstr *CopyMI) {
331   // FIXME: For now, only eliminate the copy by commuting its def when the
332   // source register is a virtual register. We want to guard against cases
333   // where the copy is a back edge copy and commuting the def lengthen the
334   // live interval of the source register to the entire loop.
335   if (CP.isPhys() && CP.isFlipped())
336     return false;
337
338   // Bail if there is no dst interval.
339   if (!li_->hasInterval(CP.getDstReg()))
340     return false;
341
342   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
343
344   LiveInterval &IntA =
345     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
346   LiveInterval &IntB =
347     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
348
349   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
350   // the example above.
351   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
352   if (!BValNo || !BValNo->isDefByCopy())
353     return false;
354
355   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
356
357   // AValNo is the value number in A that defines the copy, A3 in the example.
358   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
359   assert(AValNo && "COPY source not live");
360
361   // If other defs can reach uses of this def, then it's not safe to perform
362   // the optimization.
363   if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
364     return false;
365   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
366   if (!DefMI)
367     return false;
368   const TargetInstrDesc &TID = DefMI->getDesc();
369   if (!TID.isCommutable())
370     return false;
371   // If DefMI is a two-address instruction then commuting it will change the
372   // destination register.
373   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
374   assert(DefIdx != -1);
375   unsigned UseOpIdx;
376   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
377     return false;
378   unsigned Op1, Op2, NewDstIdx;
379   if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
380     return false;
381   if (Op1 == UseOpIdx)
382     NewDstIdx = Op2;
383   else if (Op2 == UseOpIdx)
384     NewDstIdx = Op1;
385   else
386     return false;
387
388   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
389   unsigned NewReg = NewDstMO.getReg();
390   if (NewReg != IntB.reg || !NewDstMO.isKill())
391     return false;
392
393   // Make sure there are no other definitions of IntB that would reach the
394   // uses which the new definition can reach.
395   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
396     return false;
397
398   // Abort if the aliases of IntB.reg have values that are not simply the
399   // clobbers from the superreg.
400   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
401     for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
402       if (li_->hasInterval(*AS) &&
403           HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
404         return false;
405
406   // If some of the uses of IntA.reg is already coalesced away, return false.
407   // It's not possible to determine whether it's safe to perform the coalescing.
408   for (MachineRegisterInfo::use_nodbg_iterator UI = 
409          mri_->use_nodbg_begin(IntA.reg), 
410        UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
411     MachineInstr *UseMI = &*UI;
412     SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
413     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
414     if (ULR == IntA.end())
415       continue;
416     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
417       return false;
418   }
419
420   DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
421                << *DefMI);
422
423   // At this point we have decided that it is legal to do this
424   // transformation.  Start by commuting the instruction.
425   MachineBasicBlock *MBB = DefMI->getParent();
426   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
427   if (!NewMI)
428     return false;
429   if (NewMI != DefMI) {
430     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
431     MBB->insert(DefMI, NewMI);
432     MBB->erase(DefMI);
433   }
434   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
435   NewMI->getOperand(OpIdx).setIsKill();
436
437   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
438   // A = or A, B
439   // ...
440   // B = A
441   // ...
442   // C = A<kill>
443   // ...
444   //   = B
445
446   // Update uses of IntA of the specific Val# with IntB.
447   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
448          UE = mri_->use_end(); UI != UE;) {
449     MachineOperand &UseMO = UI.getOperand();
450     MachineInstr *UseMI = &*UI;
451     ++UI;
452     if (JoinedCopies.count(UseMI))
453       continue;
454     if (UseMI->isDebugValue()) {
455       // FIXME These don't have an instruction index.  Not clear we have enough
456       // info to decide whether to do this replacement or not.  For now do it.
457       UseMO.setReg(NewReg);
458       continue;
459     }
460     SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
461     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
462     if (ULR == IntA.end() || ULR->valno != AValNo)
463       continue;
464     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
465       UseMO.substPhysReg(NewReg, *tri_);
466     else
467       UseMO.setReg(NewReg);
468     if (UseMI == CopyMI)
469       continue;
470     if (!UseMI->isCopy())
471       continue;
472     if (UseMI->getOperand(0).getReg() != IntB.reg ||
473         UseMI->getOperand(0).getSubReg())
474       continue;
475
476     // This copy will become a noop. If it's defining a new val#, merge it into
477     // BValNo.
478     SlotIndex DefIdx = UseIdx.getDefIndex();
479     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
480     if (!DVNI)
481       continue;
482     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
483     assert(DVNI->def == DefIdx);
484     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
485     markAsJoined(UseMI);
486   }
487
488   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
489   // is updated.
490   VNInfo *ValNo = BValNo;
491   ValNo->def = AValNo->def;
492   ValNo->setCopy(0);
493   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
494        AI != AE; ++AI) {
495     if (AI->valno != AValNo) continue;
496     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
497   }
498   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
499
500   IntA.removeValNo(AValNo);
501   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
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,
523                         SlotIndex Start, SlotIndex End,
524                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
525   li.removeRange(Start, End, true);
526   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
527     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
528       if (!li_->hasInterval(*SR))
529         continue;
530       LiveInterval &sli = li_->getInterval(*SR);
531       SlotIndex RemoveStart = Start;
532       SlotIndex RemoveEnd = Start;
533
534       while (RemoveEnd != End) {
535         LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
536         if (LR == sli.end())
537           break;
538         RemoveEnd = (LR->end < End) ? LR->end : End;
539         sli.removeRange(RemoveStart, RemoveEnd, true);
540         RemoveStart = RemoveEnd;
541       }
542     }
543   }
544 }
545
546 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
547 /// as the copy instruction, trim the live interval to the last use and return
548 /// true.
549 bool
550 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
551                                                     MachineBasicBlock *CopyMBB,
552                                                     LiveInterval &li,
553                                                     const LiveRange *LR) {
554   SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
555   SlotIndex LastUseIdx;
556   MachineOperand *LastUse =
557     lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
558   if (LastUse) {
559     MachineInstr *LastUseMI = LastUse->getParent();
560     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
561       // r1024 = op
562       // ...
563       // BB1:
564       //       = r1024
565       //
566       // BB2:
567       // r1025<dead> = r1024<kill>
568       if (MBBStart < LR->end)
569         removeRange(li, MBBStart, LR->end, li_, tri_);
570       return true;
571     }
572
573     // There are uses before the copy, just shorten the live range to the end
574     // of last use.
575     LastUse->setIsKill();
576     removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
577     if (LastUseMI->isCopy()) {
578       MachineOperand &DefMO = LastUseMI->getOperand(0);
579       if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
580         DefMO.setIsDead();
581     }
582     return true;
583   }
584
585   // Is it livein?
586   if (LR->start <= MBBStart && LR->end > MBBStart) {
587     if (LR->start == li_->getZeroIndex()) {
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                                                        bool preserveSrcInt,
602                                                        unsigned DstReg,
603                                                        unsigned DstSubIdx,
604                                                        MachineInstr *CopyMI) {
605   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
606   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
607   assert(SrcLR != SrcInt.end() && "Live range not found!");
608   VNInfo *ValNo = SrcLR->valno;
609   // If other defs can reach uses of this def, then it's not safe to perform
610   // the optimization.
611   if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
612     return false;
613   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
614   if (!DefMI)
615     return false;
616   assert(DefMI && "Defining instruction disappeared");
617   const TargetInstrDesc &TID = DefMI->getDesc();
618   if (!TID.isAsCheapAsAMove())
619     return false;
620   if (!tii_->isTriviallyReMaterializable(DefMI, AA))
621     return false;
622   bool SawStore = false;
623   if (!DefMI->isSafeToMove(tii_, AA, SawStore))
624     return false;
625   if (TID.getNumDefs() != 1)
626     return false;
627   if (!DefMI->isImplicitDef()) {
628     // Make sure the copy destination register class fits the instruction
629     // definition register class. The mismatch can happen as a result of earlier
630     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
631     const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
632     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
633       if (mri_->getRegClass(DstReg) != RC)
634         return false;
635     } else if (!RC->contains(DstReg))
636       return false;
637   }
638
639   // If destination register has a sub-register index on it, make sure it
640   // matches the instruction register class.
641   if (DstSubIdx) {
642     const TargetInstrDesc &TID = DefMI->getDesc();
643     if (TID.getNumDefs() != 1)
644       return false;
645     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
646     const TargetRegisterClass *DstSubRC =
647       DstRC->getSubRegisterRegClass(DstSubIdx);
648     const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
649     if (DefRC == DstRC)
650       DstSubIdx = 0;
651     else if (DefRC != DstSubRC)
652       return false;
653   }
654
655   RemoveCopyFlag(DstReg, CopyMI);
656
657   MachineBasicBlock *MBB = CopyMI->getParent();
658   MachineBasicBlock::iterator MII =
659     llvm::next(MachineBasicBlock::iterator(CopyMI));
660   tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
661   MachineInstr *NewMI = prior(MII);
662
663   // CopyMI may have implicit operands, transfer them over to the newly
664   // rematerialized instruction. And update implicit def interval valnos.
665   for (unsigned i = CopyMI->getDesc().getNumOperands(),
666          e = CopyMI->getNumOperands(); i != e; ++i) {
667     MachineOperand &MO = CopyMI->getOperand(i);
668     if (MO.isReg() && MO.isImplicit())
669       NewMI->addOperand(MO);
670     if (MO.isDef())
671       RemoveCopyFlag(MO.getReg(), CopyMI);
672   }
673
674   NewMI->copyImplicitOps(CopyMI);
675   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
676   CopyMI->eraseFromParent();
677   ReMatCopies.insert(CopyMI);
678   ReMatDefs.insert(DefMI);
679   DEBUG(dbgs() << "Remat: " << *NewMI);
680   ++NumReMats;
681
682   // The source interval can become smaller because we removed a use.
683   if (preserveSrcInt)
684     li_->shrinkToUses(&SrcInt);
685
686   return true;
687 }
688
689 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
690 /// update the subregister number if it is not zero. If DstReg is a
691 /// physical register and the existing subregister number of the def / use
692 /// being updated is not zero, make sure to set it to the correct physical
693 /// subregister.
694 void
695 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
696   bool DstIsPhys = CP.isPhys();
697   unsigned SrcReg = CP.getSrcReg();
698   unsigned DstReg = CP.getDstReg();
699   unsigned SubIdx = CP.getSubIdx();
700
701   // Update LiveDebugVariables.
702   ldv_->renameRegister(SrcReg, DstReg, SubIdx);
703
704   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
705        MachineInstr *UseMI = I.skipInstruction();) {
706     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
707     // instead.
708     if (DstIsPhys) {
709       if (UseMI->isCopy() &&
710           !UseMI->getOperand(1).getSubReg() &&
711           !UseMI->getOperand(0).getSubReg() &&
712           UseMI->getOperand(1).getReg() == SrcReg &&
713           UseMI->getOperand(0).getReg() != SrcReg &&
714           UseMI->getOperand(0).getReg() != DstReg &&
715           !JoinedCopies.count(UseMI) &&
716           ReMaterializeTrivialDef(li_->getInterval(SrcReg), false,
717                                   UseMI->getOperand(0).getReg(), 0, UseMI))
718         continue;
719     }
720
721     SmallVector<unsigned,8> Ops;
722     bool Reads, Writes;
723     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
724     bool Kills = false, Deads = false;
725
726     // Replace SrcReg with DstReg in all UseMI operands.
727     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
728       MachineOperand &MO = UseMI->getOperand(Ops[i]);
729       Kills |= MO.isKill();
730       Deads |= MO.isDead();
731
732       if (DstIsPhys)
733         MO.substPhysReg(DstReg, *tri_);
734       else
735         MO.substVirtReg(DstReg, SubIdx, *tri_);
736     }
737
738     // This instruction is a copy that will be removed.
739     if (JoinedCopies.count(UseMI))
740       continue;
741
742     if (SubIdx) {
743       // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
744       // read-modify-write of DstReg.
745       if (Deads)
746         UseMI->addRegisterDead(DstReg, tri_);
747       else if (!Reads && Writes)
748         UseMI->addRegisterDefined(DstReg, tri_);
749
750       // Kill flags apply to the whole physical register.
751       if (DstIsPhys && Kills)
752         UseMI->addRegisterKilled(DstReg, tri_);
753     }
754
755     DEBUG({
756         dbgs() << "\t\tupdated: ";
757         if (!UseMI->isDebugValue())
758           dbgs() << li_->getInstructionIndex(UseMI) << "\t";
759         dbgs() << *UseMI;
760       });
761   }
762 }
763
764 /// removeIntervalIfEmpty - Check if the live interval of a physical register
765 /// is empty, if so remove it and also remove the empty intervals of its
766 /// sub-registers. Return true if live interval is removed.
767 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
768                                   const TargetRegisterInfo *tri_) {
769   if (li.empty()) {
770     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
771       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
772         if (!li_->hasInterval(*SR))
773           continue;
774         LiveInterval &sli = li_->getInterval(*SR);
775         if (sli.empty())
776           li_->removeInterval(*SR);
777       }
778     li_->removeInterval(li.reg);
779     return true;
780   }
781   return false;
782 }
783
784 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
785 /// Return true if live interval is removed.
786 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
787                                                         MachineInstr *CopyMI) {
788   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
789   LiveInterval::iterator MLR =
790     li.FindLiveRangeContaining(CopyIdx.getDefIndex());
791   if (MLR == li.end())
792     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
793   SlotIndex RemoveStart = MLR->start;
794   SlotIndex RemoveEnd = MLR->end;
795   SlotIndex DefIdx = CopyIdx.getDefIndex();
796   // Remove the liverange that's defined by this.
797   if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
798     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
799     return removeIntervalIfEmpty(li, li_, tri_);
800   }
801   return false;
802 }
803
804 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
805 /// the val# it defines. If the live interval becomes empty, remove it as well.
806 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
807                                              MachineInstr *DefMI) {
808   SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
809   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
810   if (DefIdx != MLR->valno->def)
811     return false;
812   li.removeValNo(MLR->valno);
813   return removeIntervalIfEmpty(li, li_, tri_);
814 }
815
816 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
817                                               const MachineInstr *CopyMI) {
818   SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
819   if (li_->hasInterval(DstReg)) {
820     LiveInterval &LI = li_->getInterval(DstReg);
821     if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
822       if (LR->valno->def == DefIdx)
823         LR->valno->setCopy(0);
824   }
825   if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
826     return;
827   for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
828     if (!li_->hasInterval(*AS))
829       continue;
830     LiveInterval &LI = li_->getInterval(*AS);
831     if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
832       if (LR->valno->def == DefIdx)
833         LR->valno->setCopy(0);
834   }
835 }
836
837 /// PropagateDeadness - Propagate the dead marker to the instruction which
838 /// defines the val#.
839 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
840                               SlotIndex &LRStart, LiveIntervals *li_,
841                               const TargetRegisterInfo* tri_) {
842   MachineInstr *DefMI =
843     li_->getInstructionFromIndex(LRStart.getDefIndex());
844   if (DefMI && DefMI != CopyMI) {
845     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
846     if (DeadIdx != -1)
847       DefMI->getOperand(DeadIdx).setIsDead();
848     else
849       DefMI->addOperand(MachineOperand::CreateReg(li.reg,
850                    /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
851     LRStart = LRStart.getNextSlot();
852   }
853 }
854
855 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
856 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
857 /// ends the live range there. If there isn't another use, then this live range
858 /// is dead. Return true if live interval is removed.
859 bool
860 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
861                                                       MachineInstr *CopyMI) {
862   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
863   if (CopyIdx == SlotIndex()) {
864     // FIXME: special case: function live in. It can be a general case if the
865     // first instruction index starts at > 0 value.
866     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
867     // Live-in to the function but dead. Remove it from entry live-in set.
868     if (mf_->begin()->isLiveIn(li.reg))
869       mf_->begin()->removeLiveIn(li.reg);
870     if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
871       removeRange(li, LR->start, LR->end, li_, tri_);
872     return removeIntervalIfEmpty(li, li_, tri_);
873   }
874
875   LiveInterval::iterator LR =
876     li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
877   if (LR == li.end())
878     // Livein but defined by a phi.
879     return false;
880
881   SlotIndex RemoveStart = LR->start;
882   SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
883   if (LR->end > RemoveEnd)
884     // More uses past this copy? Nothing to do.
885     return false;
886
887   // If there is a last use in the same bb, we can't remove the live range.
888   // Shorten the live interval and return.
889   MachineBasicBlock *CopyMBB = CopyMI->getParent();
890   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
891     return false;
892
893   // There are other kills of the val#. Nothing to do.
894   if (!li.isOnlyLROfValNo(LR))
895     return false;
896
897   MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
898   if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
899     // If the live range starts in another mbb and the copy mbb is not a fall
900     // through mbb, then we can only cut the range from the beginning of the
901     // copy mbb.
902     RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
903
904   if (LR->valno->def == RemoveStart) {
905     // If the def MI defines the val# and this copy is the only kill of the
906     // val#, then propagate the dead marker.
907     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
908     ++numDeadValNo;
909   }
910
911   removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
912   return removeIntervalIfEmpty(li, li_, tri_);
913 }
914
915 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
916 /// We need to be careful about coalescing a source physical register with a
917 /// virtual register. Once the coalescing is done, it cannot be broken and these
918 /// are not spillable! If the destination interval uses are far away, think
919 /// twice about coalescing them!
920 bool SimpleRegisterCoalescing::shouldJoinPhys(CoalescerPair &CP) {
921   bool Allocatable = li_->isAllocatable(CP.getDstReg());
922   LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
923
924   /// Always join simple intervals that are defined by a single copy from a
925   /// reserved register. This doesn't increase register pressure, so it is
926   /// always beneficial.
927   if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
928     return true;
929
930   if (!EnablePhysicalJoin) {
931     DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
932     return false;
933   }
934
935   // Only coalesce to allocatable physreg, we don't want to risk modifying
936   // reserved registers.
937   if (!Allocatable) {
938     DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
939     return false;  // Not coalescable.
940   }
941
942   // Don't join with physregs that have a ridiculous number of live
943   // ranges. The data structure performance is really bad when that
944   // happens.
945   if (li_->hasInterval(CP.getDstReg()) &&
946       li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
947     ++numAborts;
948     DEBUG(dbgs()
949           << "\tPhysical register live interval too complicated, abort!\n");
950     return false;
951   }
952
953   // FIXME: Why are we skipping this test for partial copies?
954   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
955   if (!CP.isPartial()) {
956     const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
957     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
958     unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
959     if (Length > Threshold) {
960       ++numAborts;
961       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
962       return false;
963     }
964   }
965   return true;
966 }
967
968 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
969 /// two virtual registers from different register classes.
970 bool
971 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
972                                                 unsigned DstReg,
973                                              const TargetRegisterClass *SrcRC,
974                                              const TargetRegisterClass *DstRC,
975                                              const TargetRegisterClass *NewRC) {
976   unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
977   // This heuristics is good enough in practice, but it's obviously not *right*.
978   // 4 is a magic number that works well enough for x86, ARM, etc. It filter
979   // out all but the most restrictive register classes.
980   if (NewRCCount > 4 ||
981       // Early exit if the function is fairly small, coalesce aggressively if
982       // that's the case. For really special register classes with 3 or
983       // fewer registers, be a bit more careful.
984       (li_->getFuncInstructionCount() / NewRCCount) < 8)
985     return true;
986   LiveInterval &SrcInt = li_->getInterval(SrcReg);
987   LiveInterval &DstInt = li_->getInterval(DstReg);
988   unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
989   unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
990
991   // Coalesce aggressively if the intervals are small compared to the number of
992   // registers in the new class. The number 4 is fairly arbitrary, chosen to be
993   // less aggressive than the 8 used for the whole function size.
994   const unsigned ThresSize = 4 * NewRCCount;
995   if (SrcSize <= ThresSize && DstSize <= ThresSize)
996     return true;
997
998   // Estimate *register use density*. If it doubles or more, abort.
999   unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
1000                                    mri_->use_nodbg_end());
1001   unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
1002                                    mri_->use_nodbg_end());
1003   unsigned NewUses = SrcUses + DstUses;
1004   unsigned NewSize = SrcSize + DstSize;
1005   if (SrcRC != NewRC && SrcSize > ThresSize) {
1006     unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1007     if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1008       return false;
1009   }
1010   if (DstRC != NewRC && DstSize > ThresSize) {
1011     unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1012     if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1013       return false;
1014   }
1015   return true;
1016 }
1017
1018
1019 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1020 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1021 /// if the copy was successfully coalesced away. If it is not currently
1022 /// possible to coalesce this interval, but it may be possible if other
1023 /// things get coalesced, then it returns true by reference in 'Again'.
1024 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1025   MachineInstr *CopyMI = TheCopy.MI;
1026
1027   Again = false;
1028   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1029     return false; // Already done.
1030
1031   DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1032
1033   CoalescerPair CP(*tii_, *tri_);
1034   if (!CP.setRegisters(CopyMI)) {
1035     DEBUG(dbgs() << "\tNot coalescable.\n");
1036     return false;
1037   }
1038
1039   // If they are already joined we continue.
1040   if (CP.getSrcReg() == CP.getDstReg()) {
1041     markAsJoined(CopyMI);
1042     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1043     return false;  // Not coalescable.
1044   }
1045
1046   DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_)
1047                << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
1048                << "\n");
1049
1050   // Enforce policies.
1051   if (CP.isPhys()) {
1052     if (!shouldJoinPhys(CP)) {
1053       // Before giving up coalescing, if definition of source is defined by
1054       // trivial computation, try rematerializing it.
1055       if (!CP.isFlipped() &&
1056           ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1057                                   CP.getDstReg(), 0, CopyMI))
1058         return true;
1059       return false;
1060     }
1061   } else {
1062     // Avoid constraining virtual register regclass too much.
1063     if (CP.isCrossClass()) {
1064       DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1065       if (DisableCrossClassJoin) {
1066         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1067         return false;
1068       }
1069       if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1070                                  mri_->getRegClass(CP.getSrcReg()),
1071                                  mri_->getRegClass(CP.getDstReg()),
1072                                  CP.getNewRC())) {
1073         DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
1074         Again = true;  // May be possible to coalesce later.
1075         return false;
1076       }
1077     }
1078
1079     // When possible, let DstReg be the larger interval.
1080     if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1081                            li_->getInterval(CP.getDstReg()).ranges.size())
1082       CP.flip();
1083   }
1084
1085   // Okay, attempt to join these two intervals.  On failure, this returns false.
1086   // Otherwise, if one of the intervals being joined is a physreg, this method
1087   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1088   // been modified, so we can use this information below to update aliases.
1089   if (!JoinIntervals(CP)) {
1090     // Coalescing failed.
1091
1092     // If definition of source is defined by trivial computation, try
1093     // rematerializing it.
1094     if (!CP.isFlipped() &&
1095         ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1096                                 CP.getDstReg(), 0, CopyMI))
1097       return true;
1098
1099     // If we can eliminate the copy without merging the live ranges, do so now.
1100     if (!CP.isPartial()) {
1101       if (AdjustCopiesBackFrom(CP, CopyMI) ||
1102           RemoveCopyByCommutingDef(CP, CopyMI)) {
1103         markAsJoined(CopyMI);
1104         DEBUG(dbgs() << "\tTrivial!\n");
1105         return true;
1106       }
1107     }
1108
1109     // Otherwise, we are unable to join the intervals.
1110     DEBUG(dbgs() << "\tInterference!\n");
1111     Again = true;  // May be possible to coalesce later.
1112     return false;
1113   }
1114
1115   // Coalescing to a virtual register that is of a sub-register class of the
1116   // other. Make sure the resulting register is set to the right register class.
1117   if (CP.isCrossClass()) {
1118     ++numCrossRCs;
1119     mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1120   }
1121
1122   // Remember to delete the copy instruction.
1123   markAsJoined(CopyMI);
1124
1125   UpdateRegDefsUses(CP);
1126
1127   // If we have extended the live range of a physical register, make sure we
1128   // update live-in lists as well.
1129   if (CP.isPhys()) {
1130     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1131     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1132     // ranges for this, and they are preserved.
1133     LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1134     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1135          I != E; ++I ) {
1136       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1137       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1138         MachineBasicBlock &block = *BlockSeq[idx];
1139         if (!block.isLiveIn(CP.getDstReg()))
1140           block.addLiveIn(CP.getDstReg());
1141       }
1142       BlockSeq.clear();
1143     }
1144   }
1145
1146   // SrcReg is guarateed to be the register whose live interval that is
1147   // being merged.
1148   li_->removeInterval(CP.getSrcReg());
1149
1150   // Update regalloc hint.
1151   tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1152
1153   DEBUG({
1154     LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1155     dbgs() << "\tJoined. Result = ";
1156     DstInt.print(dbgs(), tri_);
1157     dbgs() << "\n";
1158   });
1159
1160   ++numJoins;
1161   return true;
1162 }
1163
1164 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1165 /// compute what the resultant value numbers for each value in the input two
1166 /// ranges will be.  This is complicated by copies between the two which can
1167 /// and will commonly cause multiple value numbers to be merged into one.
1168 ///
1169 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1170 /// keeps track of the new InstDefiningValue assignment for the result
1171 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1172 /// whether a value in this or other is a copy from the opposite set.
1173 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1174 /// already been assigned.
1175 ///
1176 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1177 /// contains the value number the copy is from.
1178 ///
1179 static unsigned ComputeUltimateVN(VNInfo *VNI,
1180                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1181                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1182                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1183                                   SmallVector<int, 16> &ThisValNoAssignments,
1184                                   SmallVector<int, 16> &OtherValNoAssignments) {
1185   unsigned VN = VNI->id;
1186
1187   // If the VN has already been computed, just return it.
1188   if (ThisValNoAssignments[VN] >= 0)
1189     return ThisValNoAssignments[VN];
1190   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1191
1192   // If this val is not a copy from the other val, then it must be a new value
1193   // number in the destination.
1194   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1195   if (I == ThisFromOther.end()) {
1196     NewVNInfo.push_back(VNI);
1197     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1198   }
1199   VNInfo *OtherValNo = I->second;
1200
1201   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1202   // been computed, return it.
1203   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1204     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1205
1206   // Mark this value number as currently being computed, then ask what the
1207   // ultimate value # of the other value is.
1208   ThisValNoAssignments[VN] = -2;
1209   unsigned UltimateVN =
1210     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1211                       OtherValNoAssignments, ThisValNoAssignments);
1212   return ThisValNoAssignments[VN] = UltimateVN;
1213 }
1214
1215 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1216 /// returns false.
1217 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1218   LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1219   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1220
1221   // If a live interval is a physical register, check for interference with any
1222   // aliases. The interference check implemented here is a bit more conservative
1223   // than the full interfeence check below. We allow overlapping live ranges
1224   // only when one is a copy of the other.
1225   if (CP.isPhys()) {
1226     for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1227       if (!li_->hasInterval(*AS))
1228         continue;
1229       const LiveInterval &LHS = li_->getInterval(*AS);
1230       LiveInterval::const_iterator LI = LHS.begin();
1231       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1232            RI != RE; ++RI) {
1233         LI = std::lower_bound(LI, LHS.end(), RI->start);
1234         // Does LHS have an overlapping live range starting before RI?
1235         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1236             (RI->start != RI->valno->def ||
1237              !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1238           DEBUG({
1239             dbgs() << "\t\tInterference from alias: ";
1240             LHS.print(dbgs(), tri_);
1241             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1242           });
1243           return false;
1244         }
1245
1246         // Check that LHS ranges beginning in this range are copies.
1247         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1248           if (LI->start != LI->valno->def ||
1249               !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1250             DEBUG({
1251               dbgs() << "\t\tInterference from alias: ";
1252               LHS.print(dbgs(), tri_);
1253               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1254             });
1255             return false;
1256           }
1257         }
1258       }
1259     }
1260   }
1261
1262   // Compute the final value assignment, assuming that the live ranges can be
1263   // coalesced.
1264   SmallVector<int, 16> LHSValNoAssignments;
1265   SmallVector<int, 16> RHSValNoAssignments;
1266   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1267   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1268   SmallVector<VNInfo*, 16> NewVNInfo;
1269
1270   LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1271   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1272
1273   // Loop over the value numbers of the LHS, seeing if any are defined from
1274   // the RHS.
1275   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1276        i != e; ++i) {
1277     VNInfo *VNI = *i;
1278     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1279       continue;
1280
1281     // Never join with a register that has EarlyClobber redefs.
1282     if (VNI->hasRedefByEC())
1283       return false;
1284
1285     // DstReg is known to be a register in the LHS interval.  If the src is
1286     // from the RHS interval, we can use its value #.
1287     if (!CP.isCoalescable(VNI->getCopy()))
1288       continue;
1289
1290     // Figure out the value # from the RHS.
1291     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1292     // The copy could be to an aliased physreg.
1293     if (!lr) continue;
1294     LHSValsDefinedFromRHS[VNI] = lr->valno;
1295   }
1296
1297   // Loop over the value numbers of the RHS, seeing if any are defined from
1298   // the LHS.
1299   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1300        i != e; ++i) {
1301     VNInfo *VNI = *i;
1302     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1303       continue;
1304
1305     // Never join with a register that has EarlyClobber redefs.
1306     if (VNI->hasRedefByEC())
1307       return false;
1308
1309     // DstReg is known to be a register in the RHS interval.  If the src is
1310     // from the LHS interval, we can use its value #.
1311     if (!CP.isCoalescable(VNI->getCopy()))
1312       continue;
1313
1314     // Figure out the value # from the LHS.
1315     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1316     // The copy could be to an aliased physreg.
1317     if (!lr) continue;
1318     RHSValsDefinedFromLHS[VNI] = lr->valno;
1319   }
1320
1321   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1322   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1323   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1324
1325   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1326        i != e; ++i) {
1327     VNInfo *VNI = *i;
1328     unsigned VN = VNI->id;
1329     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1330       continue;
1331     ComputeUltimateVN(VNI, NewVNInfo,
1332                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1333                       LHSValNoAssignments, RHSValNoAssignments);
1334   }
1335   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1336        i != e; ++i) {
1337     VNInfo *VNI = *i;
1338     unsigned VN = VNI->id;
1339     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1340       continue;
1341     // If this value number isn't a copy from the LHS, it's a new number.
1342     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1343       NewVNInfo.push_back(VNI);
1344       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1345       continue;
1346     }
1347
1348     ComputeUltimateVN(VNI, NewVNInfo,
1349                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1350                       RHSValNoAssignments, LHSValNoAssignments);
1351   }
1352
1353   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1354   // interval lists to see if these intervals are coalescable.
1355   LiveInterval::const_iterator I = LHS.begin();
1356   LiveInterval::const_iterator IE = LHS.end();
1357   LiveInterval::const_iterator J = RHS.begin();
1358   LiveInterval::const_iterator JE = RHS.end();
1359
1360   // Skip ahead until the first place of potential sharing.
1361   if (I != IE && J != JE) {
1362     if (I->start < J->start) {
1363       I = std::upper_bound(I, IE, J->start);
1364       if (I != LHS.begin()) --I;
1365     } else if (J->start < I->start) {
1366       J = std::upper_bound(J, JE, I->start);
1367       if (J != RHS.begin()) --J;
1368     }
1369   }
1370
1371   while (I != IE && J != JE) {
1372     // Determine if these two live ranges overlap.
1373     bool Overlaps;
1374     if (I->start < J->start) {
1375       Overlaps = I->end > J->start;
1376     } else {
1377       Overlaps = J->end > I->start;
1378     }
1379
1380     // If so, check value # info to determine if they are really different.
1381     if (Overlaps) {
1382       // If the live range overlap will map to the same value number in the
1383       // result liverange, we can still coalesce them.  If not, we can't.
1384       if (LHSValNoAssignments[I->valno->id] !=
1385           RHSValNoAssignments[J->valno->id])
1386         return false;
1387       // If it's re-defined by an early clobber somewhere in the live range,
1388       // then conservatively abort coalescing.
1389       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1390         return false;
1391     }
1392
1393     if (I->end < J->end)
1394       ++I;
1395     else
1396       ++J;
1397   }
1398
1399   // Update kill info. Some live ranges are extended due to copy coalescing.
1400   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1401          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1402     VNInfo *VNI = I->first;
1403     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1404     if (VNI->hasPHIKill())
1405       NewVNInfo[LHSValID]->setHasPHIKill(true);
1406   }
1407
1408   // Update kill info. Some live ranges are extended due to copy coalescing.
1409   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1410          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1411     VNInfo *VNI = I->first;
1412     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1413     if (VNI->hasPHIKill())
1414       NewVNInfo[RHSValID]->setHasPHIKill(true);
1415   }
1416
1417   if (LHSValNoAssignments.empty())
1418     LHSValNoAssignments.push_back(-1);
1419   if (RHSValNoAssignments.empty())
1420     RHSValNoAssignments.push_back(-1);
1421
1422   // If we get here, we know that we can coalesce the live ranges.  Ask the
1423   // intervals to coalesce themselves now.
1424   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1425            mri_);
1426   return true;
1427 }
1428
1429 namespace {
1430   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1431   // depth of the basic block (the unsigned), and then on the MBB number.
1432   struct DepthMBBCompare {
1433     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1434     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1435       // Deeper loops first
1436       if (LHS.first != RHS.first)
1437         return LHS.first > RHS.first;
1438
1439       // Prefer blocks that are more connected in the CFG. This takes care of
1440       // the most difficult copies first while intervals are short.
1441       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1442       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1443       if (cl != cr)
1444         return cl > cr;
1445
1446       // As a last resort, sort by block number.
1447       return LHS.second->getNumber() < RHS.second->getNumber();
1448     }
1449   };
1450 }
1451
1452 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1453                                                std::vector<CopyRec> &TryAgain) {
1454   DEBUG(dbgs() << MBB->getName() << ":\n");
1455
1456   SmallVector<CopyRec, 8> VirtCopies;
1457   SmallVector<CopyRec, 8> PhysCopies;
1458   SmallVector<CopyRec, 8> ImpDefCopies;
1459   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1460        MII != E;) {
1461     MachineInstr *Inst = MII++;
1462
1463     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1464     unsigned SrcReg, DstReg;
1465     if (Inst->isCopy()) {
1466       DstReg = Inst->getOperand(0).getReg();
1467       SrcReg = Inst->getOperand(1).getReg();
1468     } else if (Inst->isSubregToReg()) {
1469       DstReg = Inst->getOperand(0).getReg();
1470       SrcReg = Inst->getOperand(2).getReg();
1471     } else
1472       continue;
1473
1474     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1475     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1476     if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1477       ImpDefCopies.push_back(CopyRec(Inst, 0));
1478     else if (SrcIsPhys || DstIsPhys)
1479       PhysCopies.push_back(CopyRec(Inst, 0));
1480     else
1481       VirtCopies.push_back(CopyRec(Inst, 0));
1482   }
1483
1484   // Try coalescing implicit copies and insert_subreg <undef> first,
1485   // followed by copies to / from physical registers, then finally copies
1486   // from virtual registers to virtual registers.
1487   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1488     CopyRec &TheCopy = ImpDefCopies[i];
1489     bool Again = false;
1490     if (!JoinCopy(TheCopy, Again))
1491       if (Again)
1492         TryAgain.push_back(TheCopy);
1493   }
1494   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1495     CopyRec &TheCopy = PhysCopies[i];
1496     bool Again = false;
1497     if (!JoinCopy(TheCopy, Again))
1498       if (Again)
1499         TryAgain.push_back(TheCopy);
1500   }
1501   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1502     CopyRec &TheCopy = VirtCopies[i];
1503     bool Again = false;
1504     if (!JoinCopy(TheCopy, Again))
1505       if (Again)
1506         TryAgain.push_back(TheCopy);
1507   }
1508 }
1509
1510 void SimpleRegisterCoalescing::joinIntervals() {
1511   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1512
1513   std::vector<CopyRec> TryAgainList;
1514   if (loopInfo->empty()) {
1515     // If there are no loops in the function, join intervals in function order.
1516     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1517          I != E; ++I)
1518       CopyCoalesceInMBB(I, TryAgainList);
1519   } else {
1520     // Otherwise, join intervals in inner loops before other intervals.
1521     // Unfortunately we can't just iterate over loop hierarchy here because
1522     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1523
1524     // Join intervals in the function prolog first. We want to join physical
1525     // registers with virtual registers before the intervals got too long.
1526     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1527     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1528       MachineBasicBlock *MBB = I;
1529       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1530     }
1531
1532     // Sort by loop depth.
1533     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1534
1535     // Finally, join intervals in loop nest order.
1536     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1537       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1538   }
1539
1540   // Joining intervals can allow other intervals to be joined.  Iteratively join
1541   // until we make no progress.
1542   bool ProgressMade = true;
1543   while (ProgressMade) {
1544     ProgressMade = false;
1545
1546     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1547       CopyRec &TheCopy = TryAgainList[i];
1548       if (!TheCopy.MI)
1549         continue;
1550
1551       bool Again = false;
1552       bool Success = JoinCopy(TheCopy, Again);
1553       if (Success || !Again) {
1554         TheCopy.MI = 0;   // Mark this one as done.
1555         ProgressMade = true;
1556       }
1557     }
1558   }
1559 }
1560
1561 /// Return true if the two specified registers belong to different register
1562 /// classes.  The registers may be either phys or virt regs.
1563 bool
1564 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1565                                                    unsigned RegB) const {
1566   // Get the register classes for the first reg.
1567   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1568     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1569            "Shouldn't consider two physregs!");
1570     return !mri_->getRegClass(RegB)->contains(RegA);
1571   }
1572
1573   // Compare against the regclass for the second reg.
1574   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1575   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1576     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1577     return RegClassA != RegClassB;
1578   }
1579   return !RegClassA->contains(RegB);
1580 }
1581
1582 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1583 /// between cycles Start and End or NULL if there are no uses.
1584 MachineOperand *
1585 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1586                                           SlotIndex End,
1587                                           unsigned Reg,
1588                                           SlotIndex &UseIdx) const{
1589   UseIdx = SlotIndex();
1590   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1591     MachineOperand *LastUse = NULL;
1592     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1593            E = mri_->use_nodbg_end(); I != E; ++I) {
1594       MachineOperand &Use = I.getOperand();
1595       MachineInstr *UseMI = Use.getParent();
1596       if (UseMI->isIdentityCopy())
1597         continue;
1598       SlotIndex Idx = li_->getInstructionIndex(UseMI);
1599       if (Idx >= Start && Idx < End && (!UseIdx.isValid() || Idx >= UseIdx)) {
1600         LastUse = &Use;
1601         UseIdx = Idx.getUseIndex();
1602       }
1603     }
1604     return LastUse;
1605   }
1606
1607   SlotIndex s = Start;
1608   SlotIndex e = End.getPrevSlot().getBaseIndex();
1609   while (e >= s) {
1610     // Skip deleted instructions
1611     MachineInstr *MI = li_->getInstructionFromIndex(e);
1612     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1613       e = e.getPrevIndex();
1614       MI = li_->getInstructionFromIndex(e);
1615     }
1616     if (e < s || MI == NULL)
1617       return NULL;
1618
1619     // Ignore identity copies.
1620     if (!MI->isIdentityCopy())
1621       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1622         MachineOperand &Use = MI->getOperand(i);
1623         if (Use.isReg() && Use.isUse() && Use.getReg() &&
1624             tri_->regsOverlap(Use.getReg(), Reg)) {
1625           UseIdx = e.getUseIndex();
1626           return &Use;
1627         }
1628       }
1629
1630     e = e.getPrevIndex();
1631   }
1632
1633   return NULL;
1634 }
1635
1636 void SimpleRegisterCoalescing::releaseMemory() {
1637   JoinedCopies.clear();
1638   ReMatCopies.clear();
1639   ReMatDefs.clear();
1640 }
1641
1642 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1643   mf_ = &fn;
1644   mri_ = &fn.getRegInfo();
1645   tm_ = &fn.getTarget();
1646   tri_ = tm_->getRegisterInfo();
1647   tii_ = tm_->getInstrInfo();
1648   li_ = &getAnalysis<LiveIntervals>();
1649   ldv_ = &getAnalysis<LiveDebugVariables>();
1650   AA = &getAnalysis<AliasAnalysis>();
1651   loopInfo = &getAnalysis<MachineLoopInfo>();
1652
1653   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1654                << "********** Function: "
1655                << ((Value*)mf_->getFunction())->getName() << '\n');
1656
1657   if (VerifyCoalescing)
1658     mf_->verify(this, "Before register coalescing");
1659
1660   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1661          E = tri_->regclass_end(); I != E; ++I)
1662     allocatableRCRegs_.insert(std::make_pair(*I,
1663                                              tri_->getAllocatableSet(fn, *I)));
1664
1665   // Join (coalesce) intervals if requested.
1666   if (EnableJoining) {
1667     joinIntervals();
1668     DEBUG({
1669         dbgs() << "********** INTERVALS POST JOINING **********\n";
1670         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1671              I != E; ++I){
1672           I->second->print(dbgs(), tri_);
1673           dbgs() << "\n";
1674         }
1675       });
1676   }
1677
1678   // Perform a final pass over the instructions and compute spill weights
1679   // and remove identity moves.
1680   SmallVector<unsigned, 4> DeadDefs;
1681   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1682        mbbi != mbbe; ++mbbi) {
1683     MachineBasicBlock* mbb = mbbi;
1684     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1685          mii != mie; ) {
1686       MachineInstr *MI = mii;
1687       if (JoinedCopies.count(MI)) {
1688         // Delete all coalesced copies.
1689         bool DoDelete = true;
1690         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1691         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1692         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1693             MI->getNumOperands() > 2)
1694           // Do not delete extract_subreg, insert_subreg of physical
1695           // registers unless the definition is dead. e.g.
1696           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1697           // or else the scavenger may complain. LowerSubregs will
1698           // delete them later.
1699           DoDelete = false;
1700
1701         if (MI->allDefsAreDead()) {
1702           if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1703               li_->hasInterval(SrcReg))
1704             li_->shrinkToUses(&li_->getInterval(SrcReg));
1705           DoDelete = true;
1706         }
1707         if (!DoDelete) {
1708           // We need the instruction to adjust liveness, so make it a KILL.
1709           if (MI->isSubregToReg()) {
1710             MI->RemoveOperand(3);
1711             MI->RemoveOperand(1);
1712           }
1713           MI->setDesc(tii_->get(TargetOpcode::KILL));
1714           mii = llvm::next(mii);
1715         } else {
1716           li_->RemoveMachineInstrFromMaps(MI);
1717           mii = mbbi->erase(mii);
1718           ++numPeep;
1719         }
1720         continue;
1721       }
1722
1723       // Now check if this is a remat'ed def instruction which is now dead.
1724       if (ReMatDefs.count(MI)) {
1725         bool isDead = true;
1726         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1727           const MachineOperand &MO = MI->getOperand(i);
1728           if (!MO.isReg())
1729             continue;
1730           unsigned Reg = MO.getReg();
1731           if (!Reg)
1732             continue;
1733           if (TargetRegisterInfo::isVirtualRegister(Reg))
1734             DeadDefs.push_back(Reg);
1735           if (MO.isDead())
1736             continue;
1737           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1738               !mri_->use_nodbg_empty(Reg)) {
1739             isDead = false;
1740             break;
1741           }
1742         }
1743         if (isDead) {
1744           while (!DeadDefs.empty()) {
1745             unsigned DeadDef = DeadDefs.back();
1746             DeadDefs.pop_back();
1747             RemoveDeadDef(li_->getInterval(DeadDef), MI);
1748           }
1749           li_->RemoveMachineInstrFromMaps(mii);
1750           mii = mbbi->erase(mii);
1751           continue;
1752         } else
1753           DeadDefs.clear();
1754       }
1755
1756       ++mii;
1757
1758       // Check for now unnecessary kill flags.
1759       if (li_->isNotInMIMap(MI)) continue;
1760       SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1761       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1762         MachineOperand &MO = MI->getOperand(i);
1763         if (!MO.isReg() || !MO.isKill()) continue;
1764         unsigned reg = MO.getReg();
1765         if (!reg || !li_->hasInterval(reg)) continue;
1766         if (!li_->getInterval(reg).killedAt(DefIdx)) {
1767           MO.setIsKill(false);
1768           continue;
1769         }
1770         // When leaving a kill flag on a physreg, check if any subregs should
1771         // remain alive.
1772         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1773           continue;
1774         for (const unsigned *SR = tri_->getSubRegisters(reg);
1775              unsigned S = *SR; ++SR)
1776           if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1777             MI->addRegisterDefined(S, tri_);
1778       }
1779     }
1780   }
1781
1782   DEBUG(dump());
1783   DEBUG(ldv_->dump());
1784   if (VerifyCoalescing)
1785     mf_->verify(this, "After register coalescing");
1786   return true;
1787 }
1788
1789 /// print - Implement the dump method.
1790 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1791    li_->print(O, m);
1792 }
1793
1794 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1795   return new SimpleRegisterCoalescing();
1796 }
1797
1798 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1799 DEFINING_FILE_FOR(SimpleRegisterCoalescing)