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