Remember to set flag.
[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 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     TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
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 (DisablePhysicalJoin) {
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   if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
991     return true;
992   // Estimate *register use density*. If it doubles or more, abort.
993   unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
994                                    mri_->use_nodbg_end());
995   unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
996                                    mri_->use_nodbg_end());
997   unsigned NewUses = SrcUses + DstUses;
998   unsigned NewSize = SrcSize + DstSize;
999   if (SrcRC != NewRC && SrcSize > NewRCCount) {
1000     unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
1001     if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1002       return false;
1003   }
1004   if (DstRC != NewRC && DstSize > NewRCCount) {
1005     unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
1006     if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1007       return false;
1008   }
1009   return true;
1010 }
1011
1012
1013 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1014 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1015 /// if the copy was successfully coalesced away. If it is not currently
1016 /// possible to coalesce this interval, but it may be possible if other
1017 /// things get coalesced, then it returns true by reference in 'Again'.
1018 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1019   MachineInstr *CopyMI = TheCopy.MI;
1020
1021   Again = false;
1022   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1023     return false; // Already done.
1024
1025   DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1026
1027   CoalescerPair CP(*tii_, *tri_);
1028   if (!CP.setRegisters(CopyMI)) {
1029     DEBUG(dbgs() << "\tNot coalescable.\n");
1030     return false;
1031   }
1032
1033   // If they are already joined we continue.
1034   if (CP.getSrcReg() == CP.getDstReg()) {
1035     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1036     return false;  // Not coalescable.
1037   }
1038
1039   DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_)
1040                << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
1041                << "\n");
1042
1043   // Enforce policies.
1044   if (CP.isPhys()) {
1045     if (!shouldJoinPhys(CP)) {
1046       // Before giving up coalescing, if definition of source is defined by
1047       // trivial computation, try rematerializing it.
1048       if (!CP.isFlipped() &&
1049           ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1050                                   CP.getDstReg(), 0, CopyMI))
1051         return true;
1052       return false;
1053     }
1054   } else {
1055     // Avoid constraining virtual register regclass too much.
1056     if (CP.isCrossClass()) {
1057       DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1058       if (DisableCrossClassJoin) {
1059         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1060         return false;
1061       }
1062       if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1063                                  mri_->getRegClass(CP.getSrcReg()),
1064                                  mri_->getRegClass(CP.getDstReg()),
1065                                  CP.getNewRC())) {
1066         DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
1067         Again = true;  // May be possible to coalesce later.
1068         return false;
1069       }
1070     }
1071
1072     // When possible, let DstReg be the larger interval.
1073     if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1074                            li_->getInterval(CP.getDstReg()).ranges.size())
1075       CP.flip();
1076   }
1077
1078   // Okay, attempt to join these two intervals.  On failure, this returns false.
1079   // Otherwise, if one of the intervals being joined is a physreg, this method
1080   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1081   // been modified, so we can use this information below to update aliases.
1082   if (!JoinIntervals(CP)) {
1083     // Coalescing failed.
1084
1085     // If definition of source is defined by trivial computation, try
1086     // rematerializing it.
1087     if (!CP.isFlipped() &&
1088         ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1089                                 CP.getDstReg(), 0, CopyMI))
1090       return true;
1091
1092     // If we can eliminate the copy without merging the live ranges, do so now.
1093     if (!CP.isPartial()) {
1094       if (AdjustCopiesBackFrom(CP, CopyMI) ||
1095           RemoveCopyByCommutingDef(CP, CopyMI)) {
1096         markAsJoined(CopyMI);
1097         DEBUG(dbgs() << "\tTrivial!\n");
1098         return true;
1099       }
1100     }
1101
1102     // Otherwise, we are unable to join the intervals.
1103     DEBUG(dbgs() << "\tInterference!\n");
1104     Again = true;  // May be possible to coalesce later.
1105     return false;
1106   }
1107
1108   // Coalescing to a virtual register that is of a sub-register class of the
1109   // other. Make sure the resulting register is set to the right register class.
1110   if (CP.isCrossClass()) {
1111     ++numCrossRCs;
1112     mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1113   }
1114
1115   // Remember to delete the copy instruction.
1116   markAsJoined(CopyMI);
1117
1118   UpdateRegDefsUses(CP);
1119
1120   // If we have extended the live range of a physical register, make sure we
1121   // update live-in lists as well.
1122   if (CP.isPhys()) {
1123     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1124     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1125     // ranges for this, and they are preserved.
1126     LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1127     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1128          I != E; ++I ) {
1129       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1130       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1131         MachineBasicBlock &block = *BlockSeq[idx];
1132         if (!block.isLiveIn(CP.getDstReg()))
1133           block.addLiveIn(CP.getDstReg());
1134       }
1135       BlockSeq.clear();
1136     }
1137   }
1138
1139   // SrcReg is guarateed to be the register whose live interval that is
1140   // being merged.
1141   li_->removeInterval(CP.getSrcReg());
1142
1143   // Update regalloc hint.
1144   tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1145
1146   DEBUG({
1147     LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1148     dbgs() << "\tJoined. Result = ";
1149     DstInt.print(dbgs(), tri_);
1150     dbgs() << "\n";
1151   });
1152
1153   ++numJoins;
1154   return true;
1155 }
1156
1157 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1158 /// compute what the resultant value numbers for each value in the input two
1159 /// ranges will be.  This is complicated by copies between the two which can
1160 /// and will commonly cause multiple value numbers to be merged into one.
1161 ///
1162 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1163 /// keeps track of the new InstDefiningValue assignment for the result
1164 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1165 /// whether a value in this or other is a copy from the opposite set.
1166 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1167 /// already been assigned.
1168 ///
1169 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1170 /// contains the value number the copy is from.
1171 ///
1172 static unsigned ComputeUltimateVN(VNInfo *VNI,
1173                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1174                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1175                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1176                                   SmallVector<int, 16> &ThisValNoAssignments,
1177                                   SmallVector<int, 16> &OtherValNoAssignments) {
1178   unsigned VN = VNI->id;
1179
1180   // If the VN has already been computed, just return it.
1181   if (ThisValNoAssignments[VN] >= 0)
1182     return ThisValNoAssignments[VN];
1183   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1184
1185   // If this val is not a copy from the other val, then it must be a new value
1186   // number in the destination.
1187   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1188   if (I == ThisFromOther.end()) {
1189     NewVNInfo.push_back(VNI);
1190     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1191   }
1192   VNInfo *OtherValNo = I->second;
1193
1194   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1195   // been computed, return it.
1196   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1197     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1198
1199   // Mark this value number as currently being computed, then ask what the
1200   // ultimate value # of the other value is.
1201   ThisValNoAssignments[VN] = -2;
1202   unsigned UltimateVN =
1203     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1204                       OtherValNoAssignments, ThisValNoAssignments);
1205   return ThisValNoAssignments[VN] = UltimateVN;
1206 }
1207
1208 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1209 /// returns false.
1210 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1211   LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1212   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1213
1214   // If a live interval is a physical register, check for interference with any
1215   // aliases. The interference check implemented here is a bit more conservative
1216   // than the full interfeence check below. We allow overlapping live ranges
1217   // only when one is a copy of the other.
1218   if (CP.isPhys()) {
1219     for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1220       if (!li_->hasInterval(*AS))
1221         continue;
1222       const LiveInterval &LHS = li_->getInterval(*AS);
1223       LiveInterval::const_iterator LI = LHS.begin();
1224       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1225            RI != RE; ++RI) {
1226         LI = std::lower_bound(LI, LHS.end(), RI->start);
1227         // Does LHS have an overlapping live range starting before RI?
1228         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1229             (RI->start != RI->valno->def ||
1230              !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1231           DEBUG({
1232             dbgs() << "\t\tInterference from alias: ";
1233             LHS.print(dbgs(), tri_);
1234             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1235           });
1236           return false;
1237         }
1238
1239         // Check that LHS ranges beginning in this range are copies.
1240         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1241           if (LI->start != LI->valno->def ||
1242               !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1243             DEBUG({
1244               dbgs() << "\t\tInterference from alias: ";
1245               LHS.print(dbgs(), tri_);
1246               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1247             });
1248             return false;
1249           }
1250         }
1251       }
1252     }
1253   }
1254
1255   // Compute the final value assignment, assuming that the live ranges can be
1256   // coalesced.
1257   SmallVector<int, 16> LHSValNoAssignments;
1258   SmallVector<int, 16> RHSValNoAssignments;
1259   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1260   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1261   SmallVector<VNInfo*, 16> NewVNInfo;
1262
1263   LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1264   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1265
1266   // Loop over the value numbers of the LHS, seeing if any are defined from
1267   // the RHS.
1268   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1269        i != e; ++i) {
1270     VNInfo *VNI = *i;
1271     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1272       continue;
1273
1274     // Never join with a register that has EarlyClobber redefs.
1275     if (VNI->hasRedefByEC())
1276       return false;
1277
1278     // DstReg is known to be a register in the LHS interval.  If the src is
1279     // from the RHS interval, we can use its value #.
1280     if (!CP.isCoalescable(VNI->getCopy()))
1281       continue;
1282
1283     // Figure out the value # from the RHS.
1284     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1285     // The copy could be to an aliased physreg.
1286     if (!lr) continue;
1287     LHSValsDefinedFromRHS[VNI] = lr->valno;
1288   }
1289
1290   // Loop over the value numbers of the RHS, seeing if any are defined from
1291   // the LHS.
1292   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1293        i != e; ++i) {
1294     VNInfo *VNI = *i;
1295     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1296       continue;
1297
1298     // Never join with a register that has EarlyClobber redefs.
1299     if (VNI->hasRedefByEC())
1300       return false;
1301
1302     // DstReg is known to be a register in the RHS interval.  If the src is
1303     // from the LHS interval, we can use its value #.
1304     if (!CP.isCoalescable(VNI->getCopy()))
1305       continue;
1306
1307     // Figure out the value # from the LHS.
1308     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1309     // The copy could be to an aliased physreg.
1310     if (!lr) continue;
1311     RHSValsDefinedFromLHS[VNI] = lr->valno;
1312   }
1313
1314   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1315   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1316   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1317
1318   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1319        i != e; ++i) {
1320     VNInfo *VNI = *i;
1321     unsigned VN = VNI->id;
1322     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1323       continue;
1324     ComputeUltimateVN(VNI, NewVNInfo,
1325                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1326                       LHSValNoAssignments, RHSValNoAssignments);
1327   }
1328   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1329        i != e; ++i) {
1330     VNInfo *VNI = *i;
1331     unsigned VN = VNI->id;
1332     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1333       continue;
1334     // If this value number isn't a copy from the LHS, it's a new number.
1335     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1336       NewVNInfo.push_back(VNI);
1337       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1338       continue;
1339     }
1340
1341     ComputeUltimateVN(VNI, NewVNInfo,
1342                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1343                       RHSValNoAssignments, LHSValNoAssignments);
1344   }
1345
1346   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1347   // interval lists to see if these intervals are coalescable.
1348   LiveInterval::const_iterator I = LHS.begin();
1349   LiveInterval::const_iterator IE = LHS.end();
1350   LiveInterval::const_iterator J = RHS.begin();
1351   LiveInterval::const_iterator JE = RHS.end();
1352
1353   // Skip ahead until the first place of potential sharing.
1354   if (I != IE && J != JE) {
1355     if (I->start < J->start) {
1356       I = std::upper_bound(I, IE, J->start);
1357       if (I != LHS.begin()) --I;
1358     } else if (J->start < I->start) {
1359       J = std::upper_bound(J, JE, I->start);
1360       if (J != RHS.begin()) --J;
1361     }
1362   }
1363
1364   while (I != IE && J != JE) {
1365     // Determine if these two live ranges overlap.
1366     bool Overlaps;
1367     if (I->start < J->start) {
1368       Overlaps = I->end > J->start;
1369     } else {
1370       Overlaps = J->end > I->start;
1371     }
1372
1373     // If so, check value # info to determine if they are really different.
1374     if (Overlaps) {
1375       // If the live range overlap will map to the same value number in the
1376       // result liverange, we can still coalesce them.  If not, we can't.
1377       if (LHSValNoAssignments[I->valno->id] !=
1378           RHSValNoAssignments[J->valno->id])
1379         return false;
1380       // If it's re-defined by an early clobber somewhere in the live range,
1381       // then conservatively abort coalescing.
1382       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1383         return false;
1384     }
1385
1386     if (I->end < J->end)
1387       ++I;
1388     else
1389       ++J;
1390   }
1391
1392   // Update kill info. Some live ranges are extended due to copy coalescing.
1393   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1394          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1395     VNInfo *VNI = I->first;
1396     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1397     if (VNI->hasPHIKill())
1398       NewVNInfo[LHSValID]->setHasPHIKill(true);
1399   }
1400
1401   // Update kill info. Some live ranges are extended due to copy coalescing.
1402   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1403          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1404     VNInfo *VNI = I->first;
1405     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1406     if (VNI->hasPHIKill())
1407       NewVNInfo[RHSValID]->setHasPHIKill(true);
1408   }
1409
1410   if (LHSValNoAssignments.empty())
1411     LHSValNoAssignments.push_back(-1);
1412   if (RHSValNoAssignments.empty())
1413     RHSValNoAssignments.push_back(-1);
1414
1415   // If we get here, we know that we can coalesce the live ranges.  Ask the
1416   // intervals to coalesce themselves now.
1417   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1418            mri_);
1419   return true;
1420 }
1421
1422 namespace {
1423   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1424   // depth of the basic block (the unsigned), and then on the MBB number.
1425   struct DepthMBBCompare {
1426     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1427     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1428       // Deeper loops first
1429       if (LHS.first != RHS.first)
1430         return LHS.first > RHS.first;
1431
1432       // Prefer blocks that are more connected in the CFG. This takes care of
1433       // the most difficult copies first while intervals are short.
1434       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1435       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1436       if (cl != cr)
1437         return cl > cr;
1438
1439       // As a last resort, sort by block number.
1440       return LHS.second->getNumber() < RHS.second->getNumber();
1441     }
1442   };
1443 }
1444
1445 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1446                                                std::vector<CopyRec> &TryAgain) {
1447   DEBUG(dbgs() << MBB->getName() << ":\n");
1448
1449   SmallVector<CopyRec, 8> VirtCopies;
1450   SmallVector<CopyRec, 8> PhysCopies;
1451   SmallVector<CopyRec, 8> ImpDefCopies;
1452   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1453        MII != E;) {
1454     MachineInstr *Inst = MII++;
1455
1456     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1457     unsigned SrcReg, DstReg;
1458     if (Inst->isCopy()) {
1459       DstReg = Inst->getOperand(0).getReg();
1460       SrcReg = Inst->getOperand(1).getReg();
1461     } else if (Inst->isSubregToReg()) {
1462       DstReg = Inst->getOperand(0).getReg();
1463       SrcReg = Inst->getOperand(2).getReg();
1464     } else
1465       continue;
1466
1467     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1468     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1469     if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1470       ImpDefCopies.push_back(CopyRec(Inst, 0));
1471     else if (SrcIsPhys || DstIsPhys)
1472       PhysCopies.push_back(CopyRec(Inst, 0));
1473     else
1474       VirtCopies.push_back(CopyRec(Inst, 0));
1475   }
1476
1477   // Try coalescing implicit copies and insert_subreg <undef> first,
1478   // followed by copies to / from physical registers, then finally copies
1479   // from virtual registers to virtual registers.
1480   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1481     CopyRec &TheCopy = ImpDefCopies[i];
1482     bool Again = false;
1483     if (!JoinCopy(TheCopy, Again))
1484       if (Again)
1485         TryAgain.push_back(TheCopy);
1486   }
1487   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1488     CopyRec &TheCopy = PhysCopies[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 = VirtCopies.size(); i != e; ++i) {
1495     CopyRec &TheCopy = VirtCopies[i];
1496     bool Again = false;
1497     if (!JoinCopy(TheCopy, Again))
1498       if (Again)
1499         TryAgain.push_back(TheCopy);
1500   }
1501 }
1502
1503 void SimpleRegisterCoalescing::joinIntervals() {
1504   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1505
1506   std::vector<CopyRec> TryAgainList;
1507   if (loopInfo->empty()) {
1508     // If there are no loops in the function, join intervals in function order.
1509     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1510          I != E; ++I)
1511       CopyCoalesceInMBB(I, TryAgainList);
1512   } else {
1513     // Otherwise, join intervals in inner loops before other intervals.
1514     // Unfortunately we can't just iterate over loop hierarchy here because
1515     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1516
1517     // Join intervals in the function prolog first. We want to join physical
1518     // registers with virtual registers before the intervals got too long.
1519     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1520     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1521       MachineBasicBlock *MBB = I;
1522       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1523     }
1524
1525     // Sort by loop depth.
1526     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1527
1528     // Finally, join intervals in loop nest order.
1529     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1530       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1531   }
1532
1533   // Joining intervals can allow other intervals to be joined.  Iteratively join
1534   // until we make no progress.
1535   bool ProgressMade = true;
1536   while (ProgressMade) {
1537     ProgressMade = false;
1538
1539     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1540       CopyRec &TheCopy = TryAgainList[i];
1541       if (!TheCopy.MI)
1542         continue;
1543
1544       bool Again = false;
1545       bool Success = JoinCopy(TheCopy, Again);
1546       if (Success || !Again) {
1547         TheCopy.MI = 0;   // Mark this one as done.
1548         ProgressMade = true;
1549       }
1550     }
1551   }
1552 }
1553
1554 /// Return true if the two specified registers belong to different register
1555 /// classes.  The registers may be either phys or virt regs.
1556 bool
1557 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1558                                                    unsigned RegB) const {
1559   // Get the register classes for the first reg.
1560   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1561     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1562            "Shouldn't consider two physregs!");
1563     return !mri_->getRegClass(RegB)->contains(RegA);
1564   }
1565
1566   // Compare against the regclass for the second reg.
1567   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1568   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1569     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1570     return RegClassA != RegClassB;
1571   }
1572   return !RegClassA->contains(RegB);
1573 }
1574
1575 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1576 /// between cycles Start and End or NULL if there are no uses.
1577 MachineOperand *
1578 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1579                                           SlotIndex End,
1580                                           unsigned Reg,
1581                                           SlotIndex &UseIdx) const{
1582   UseIdx = SlotIndex();
1583   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1584     MachineOperand *LastUse = NULL;
1585     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1586            E = mri_->use_nodbg_end(); I != E; ++I) {
1587       MachineOperand &Use = I.getOperand();
1588       MachineInstr *UseMI = Use.getParent();
1589       if (UseMI->isIdentityCopy())
1590         continue;
1591       SlotIndex Idx = li_->getInstructionIndex(UseMI);
1592       if (Idx >= Start && Idx < End && (!UseIdx.isValid() || Idx >= UseIdx)) {
1593         LastUse = &Use;
1594         UseIdx = Idx.getUseIndex();
1595       }
1596     }
1597     return LastUse;
1598   }
1599
1600   SlotIndex s = Start;
1601   SlotIndex e = End.getPrevSlot().getBaseIndex();
1602   while (e >= s) {
1603     // Skip deleted instructions
1604     MachineInstr *MI = li_->getInstructionFromIndex(e);
1605     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1606       e = e.getPrevIndex();
1607       MI = li_->getInstructionFromIndex(e);
1608     }
1609     if (e < s || MI == NULL)
1610       return NULL;
1611
1612     // Ignore identity copies.
1613     if (!MI->isIdentityCopy())
1614       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1615         MachineOperand &Use = MI->getOperand(i);
1616         if (Use.isReg() && Use.isUse() && Use.getReg() &&
1617             tri_->regsOverlap(Use.getReg(), Reg)) {
1618           UseIdx = e.getUseIndex();
1619           return &Use;
1620         }
1621       }
1622
1623     e = e.getPrevIndex();
1624   }
1625
1626   return NULL;
1627 }
1628
1629 void SimpleRegisterCoalescing::releaseMemory() {
1630   JoinedCopies.clear();
1631   ReMatCopies.clear();
1632   ReMatDefs.clear();
1633 }
1634
1635 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1636   mf_ = &fn;
1637   mri_ = &fn.getRegInfo();
1638   tm_ = &fn.getTarget();
1639   tri_ = tm_->getRegisterInfo();
1640   tii_ = tm_->getInstrInfo();
1641   li_ = &getAnalysis<LiveIntervals>();
1642   ldv_ = &getAnalysis<LiveDebugVariables>();
1643   AA = &getAnalysis<AliasAnalysis>();
1644   loopInfo = &getAnalysis<MachineLoopInfo>();
1645
1646   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1647                << "********** Function: "
1648                << ((Value*)mf_->getFunction())->getName() << '\n');
1649
1650   if (VerifyCoalescing)
1651     mf_->verify(this, "Before register coalescing");
1652
1653   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1654          E = tri_->regclass_end(); I != E; ++I)
1655     allocatableRCRegs_.insert(std::make_pair(*I,
1656                                              tri_->getAllocatableSet(fn, *I)));
1657
1658   // Join (coalesce) intervals if requested.
1659   if (EnableJoining) {
1660     joinIntervals();
1661     DEBUG({
1662         dbgs() << "********** INTERVALS POST JOINING **********\n";
1663         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1664              I != E; ++I){
1665           I->second->print(dbgs(), tri_);
1666           dbgs() << "\n";
1667         }
1668       });
1669   }
1670
1671   // Perform a final pass over the instructions and compute spill weights
1672   // and remove identity moves.
1673   SmallVector<unsigned, 4> DeadDefs;
1674   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1675        mbbi != mbbe; ++mbbi) {
1676     MachineBasicBlock* mbb = mbbi;
1677     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1678          mii != mie; ) {
1679       MachineInstr *MI = mii;
1680       if (JoinedCopies.count(MI)) {
1681         // Delete all coalesced copies.
1682         bool DoDelete = true;
1683         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1684         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1685         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1686             MI->getNumOperands() > 2)
1687           // Do not delete extract_subreg, insert_subreg of physical
1688           // registers unless the definition is dead. e.g.
1689           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1690           // or else the scavenger may complain. LowerSubregs will
1691           // delete them later.
1692           DoDelete = false;
1693         
1694         if (MI->allDefsAreDead()) {
1695           if (li_->hasInterval(SrcReg)) {
1696             LiveInterval &li = li_->getInterval(SrcReg);
1697             if (!ShortenDeadCopySrcLiveRange(li, MI))
1698               ShortenDeadCopyLiveRange(li, MI);
1699           }
1700           DoDelete = true;
1701         }
1702         if (!DoDelete) {
1703           // We need the instruction to adjust liveness, so make it a KILL.
1704           if (MI->isSubregToReg()) {
1705             MI->RemoveOperand(3);
1706             MI->RemoveOperand(1);
1707           }
1708           MI->setDesc(tii_->get(TargetOpcode::KILL));
1709           mii = llvm::next(mii);
1710         } else {
1711           li_->RemoveMachineInstrFromMaps(MI);
1712           mii = mbbi->erase(mii);
1713           ++numPeep;
1714         }
1715         continue;
1716       }
1717
1718       // Now check if this is a remat'ed def instruction which is now dead.
1719       if (ReMatDefs.count(MI)) {
1720         bool isDead = true;
1721         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1722           const MachineOperand &MO = MI->getOperand(i);
1723           if (!MO.isReg())
1724             continue;
1725           unsigned Reg = MO.getReg();
1726           if (!Reg)
1727             continue;
1728           if (TargetRegisterInfo::isVirtualRegister(Reg))
1729             DeadDefs.push_back(Reg);
1730           if (MO.isDead())
1731             continue;
1732           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1733               !mri_->use_nodbg_empty(Reg)) {
1734             isDead = false;
1735             break;
1736           }
1737         }
1738         if (isDead) {
1739           while (!DeadDefs.empty()) {
1740             unsigned DeadDef = DeadDefs.back();
1741             DeadDefs.pop_back();
1742             RemoveDeadDef(li_->getInterval(DeadDef), MI);
1743           }
1744           li_->RemoveMachineInstrFromMaps(mii);
1745           mii = mbbi->erase(mii);
1746           continue;
1747         } else
1748           DeadDefs.clear();
1749       }
1750
1751       // If the move will be an identity move delete it
1752       if (MI->isIdentityCopy()) {
1753         unsigned SrcReg = MI->getOperand(1).getReg();
1754         if (li_->hasInterval(SrcReg)) {
1755           LiveInterval &RegInt = li_->getInterval(SrcReg);
1756           // If def of this move instruction is dead, remove its live range
1757           // from the destination register's live interval.
1758           if (MI->allDefsAreDead()) {
1759             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1760               ShortenDeadCopyLiveRange(RegInt, MI);
1761           }
1762         }
1763         li_->RemoveMachineInstrFromMaps(MI);
1764         mii = mbbi->erase(mii);
1765         ++numPeep;
1766         continue;
1767       }
1768
1769       ++mii;
1770
1771       // Check for now unnecessary kill flags.
1772       if (li_->isNotInMIMap(MI)) continue;
1773       SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1774       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1775         MachineOperand &MO = MI->getOperand(i);
1776         if (!MO.isReg() || !MO.isKill()) continue;
1777         unsigned reg = MO.getReg();
1778         if (!reg || !li_->hasInterval(reg)) continue;
1779         if (!li_->getInterval(reg).killedAt(DefIdx)) {
1780           MO.setIsKill(false);
1781           continue;
1782         }
1783         // When leaving a kill flag on a physreg, check if any subregs should
1784         // remain alive.
1785         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1786           continue;
1787         for (const unsigned *SR = tri_->getSubRegisters(reg);
1788              unsigned S = *SR; ++SR)
1789           if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1790             MI->addRegisterDefined(S, tri_);
1791       }
1792     }
1793   }
1794
1795   DEBUG(dump());
1796   DEBUG(ldv_->dump());
1797   if (VerifyCoalescing)
1798     mf_->verify(this, "After register coalescing");
1799   return true;
1800 }
1801
1802 /// print - Implement the dump method.
1803 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1804    li_->print(O, m);
1805 }
1806
1807 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1808   return new SimpleRegisterCoalescing();
1809 }
1810
1811 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1812 DEFINING_FILE_FOR(SimpleRegisterCoalescing)