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