Add hidden -verify-coalescing to run the machine code verifier before and after
[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 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
108 /// being the source and IntB being the dest, thus this defines a value number
109 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
110 /// see if we can merge these two pieces of B into a single value number,
111 /// eliminating a copy.  For example:
112 ///
113 ///  A3 = B0
114 ///    ...
115 ///  B1 = A3      <- this copy
116 ///
117 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
118 /// value number to be replaced with B0 (which simplifies the B liveinterval).
119 ///
120 /// This returns true if an interval was modified.
121 ///
122 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
123                                                     MachineInstr *CopyMI) {
124   // Bail if there is no dst interval - can happen when merging physical subreg
125   // operations.
126   if (!li_->hasInterval(CP.getDstReg()))
127     return false;
128
129   LiveInterval &IntA =
130     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
131   LiveInterval &IntB =
132     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
133   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
134
135   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
136   // the example above.
137   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
138   if (BLR == IntB.end()) return false;
139   VNInfo *BValNo = BLR->valno;
140
141   // Get the location that B is defined at.  Two options: either this value has
142   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
143   // can't process it.
144   if (!BValNo->isDefByCopy()) return false;
145   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
146
147   // AValNo is the value number in A that defines the copy, A3 in the example.
148   SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
149   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
150   // The live range might not exist after fun with physreg coalescing.
151   if (ALR == IntA.end()) return false;
152   VNInfo *AValNo = ALR->valno;
153   // If it's re-defined by an early clobber somewhere in the live range, then
154   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
155   // See PR3149:
156   // 172     %ECX<def> = MOV32rr %reg1039<kill>
157   // 180     INLINEASM <es:subl $5,$1
158   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
159   //         %EAX<kill>,
160   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
161   // 188     %EAX<def> = MOV32rr %EAX<kill>
162   // 196     %ECX<def> = MOV32rr %ECX<kill>
163   // 204     %ECX<def> = MOV32rr %ECX<kill>
164   // 212     %EAX<def> = MOV32rr %EAX<kill>
165   // 220     %EAX<def> = MOV32rr %EAX
166   // 228     %reg1039<def> = MOV32rr %ECX<kill>
167   // The early clobber operand ties ECX input to the ECX def.
168   //
169   // The live interval of ECX is represented as this:
170   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
171   // The coalescer has no idea there was a def in the middle of [174,230].
172   if (AValNo->hasRedefByEC())
173     return false;
174
175   // If AValNo is defined as a copy from IntB, we can potentially process this.
176   // Get the instruction that defines this value number.
177   if (!CP.isCoalescable(AValNo->getCopy()))
178     return false;
179
180   // Get the LiveRange in IntB that this value number starts with.
181   LiveInterval::iterator ValLR =
182     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
183   if (ValLR == IntB.end())
184     return false;
185
186   // Make sure that the end of the live range is inside the same block as
187   // CopyMI.
188   MachineInstr *ValLREndInst =
189     li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
190   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
191     return false;
192
193   // Okay, we now know that ValLR ends in the same block that the CopyMI
194   // live-range starts.  If there are no intervening live ranges between them in
195   // IntB, we can merge them.
196   if (ValLR+1 != BLR) return false;
197
198   // If a live interval is a physical register, conservatively check if any
199   // of its sub-registers is overlapping the live interval of the virtual
200   // register. If so, do not coalesce.
201   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
202       *tri_->getSubRegisters(IntB.reg)) {
203     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
204       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
205         DEBUG({
206             dbgs() << "\t\tInterfere with sub-register ";
207             li_->getInterval(*SR).print(dbgs(), tri_);
208           });
209         return false;
210       }
211   }
212
213   DEBUG({
214       dbgs() << "Extending: ";
215       IntB.print(dbgs(), tri_);
216     });
217
218   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
219   // We are about to delete CopyMI, so need to remove it as the 'instruction
220   // that defines this value #'. Update the valnum with the new defining
221   // instruction #.
222   BValNo->def  = FillerStart;
223   BValNo->setCopy(0);
224
225   // Okay, we can merge them.  We need to insert a new liverange:
226   // [ValLR.end, BLR.begin) of either value number, then we merge the
227   // two value numbers.
228   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
229
230   // If the IntB live range is assigned to a physical register, and if that
231   // physreg has sub-registers, update their live intervals as well.
232   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
233     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
234       if (!li_->hasInterval(*SR))
235         continue;
236       LiveInterval &SRLI = li_->getInterval(*SR);
237       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
238                               SRLI.getNextValue(FillerStart, 0,
239                                                 li_->getVNInfoAllocator())));
240     }
241   }
242
243   // Okay, merge "B1" into the same value number as "B0".
244   if (BValNo != ValLR->valno) {
245     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
246   }
247   DEBUG({
248       dbgs() << "   result = ";
249       IntB.print(dbgs(), tri_);
250       dbgs() << "\n";
251     });
252
253   // If the source instruction was killing the source register before the
254   // merge, unset the isKill marker given the live range has been extended.
255   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
256   if (UIdx != -1) {
257     ValLREndInst->getOperand(UIdx).setIsKill(false);
258   }
259
260   // If the copy instruction was killing the destination register before the
261   // merge, find the last use and trim the live range. That will also add the
262   // isKill marker.
263   if (ALR->end == CopyIdx)
264     TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
265
266   ++numExtends;
267   return true;
268 }
269
270 /// HasOtherReachingDefs - Return true if there are definitions of IntB
271 /// other than BValNo val# that can reach uses of AValno val# of IntA.
272 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
273                                                     LiveInterval &IntB,
274                                                     VNInfo *AValNo,
275                                                     VNInfo *BValNo) {
276   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
277        AI != AE; ++AI) {
278     if (AI->valno != AValNo) continue;
279     LiveInterval::Ranges::iterator BI =
280       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
281     if (BI != IntB.ranges.begin())
282       --BI;
283     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
284       if (BI->valno == BValNo)
285         continue;
286       if (BI->start <= AI->start && BI->end > AI->start)
287         return true;
288       if (BI->start > AI->start && BI->start < AI->end)
289         return true;
290     }
291   }
292   return false;
293 }
294
295 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
296 /// IntA being the source and IntB being the dest, thus this defines a value
297 /// number in IntB.  If the source value number (in IntA) is defined by a
298 /// commutable instruction and its other operand is coalesced to the copy dest
299 /// register, see if we can transform the copy into a noop by commuting the
300 /// definition. For example,
301 ///
302 ///  A3 = op A2 B0<kill>
303 ///    ...
304 ///  B1 = A3      <- this copy
305 ///    ...
306 ///     = op A3   <- more uses
307 ///
308 /// ==>
309 ///
310 ///  B2 = op B0 A2<kill>
311 ///    ...
312 ///  B1 = B2      <- now an identify copy
313 ///    ...
314 ///     = op B2   <- more uses
315 ///
316 /// This returns true if an interval was modified.
317 ///
318 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
319                                                         MachineInstr *CopyMI) {
320   // FIXME: For now, only eliminate the copy by commuting its def when the
321   // source register is a virtual register. We want to guard against cases
322   // where the copy is a back edge copy and commuting the def lengthen the
323   // live interval of the source register to the entire loop.
324   if (CP.isPhys() && CP.isFlipped())
325     return false;
326
327   // Bail if there is no dst interval.
328   if (!li_->hasInterval(CP.getDstReg()))
329     return false;
330
331   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
332
333   LiveInterval &IntA =
334     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
335   LiveInterval &IntB =
336     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
337
338   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
339   // the example above.
340   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
341   if (!BValNo || !BValNo->isDefByCopy())
342     return false;
343
344   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
345
346   // AValNo is the value number in A that defines the copy, A3 in the example.
347   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
348   assert(AValNo && "COPY source not live");
349
350   // If other defs can reach uses of this def, then it's not safe to perform
351   // the optimization.
352   if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
353     return false;
354   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
355   if (!DefMI)
356     return false;
357   const TargetInstrDesc &TID = DefMI->getDesc();
358   if (!TID.isCommutable())
359     return false;
360   // If DefMI is a two-address instruction then commuting it will change the
361   // destination register.
362   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
363   assert(DefIdx != -1);
364   unsigned UseOpIdx;
365   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
366     return false;
367   unsigned Op1, Op2, NewDstIdx;
368   if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
369     return false;
370   if (Op1 == UseOpIdx)
371     NewDstIdx = Op2;
372   else if (Op2 == UseOpIdx)
373     NewDstIdx = Op1;
374   else
375     return false;
376
377   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
378   unsigned NewReg = NewDstMO.getReg();
379   if (NewReg != IntB.reg || !NewDstMO.isKill())
380     return false;
381
382   // Make sure there are no other definitions of IntB that would reach the
383   // uses which the new definition can reach.
384   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
385     return false;
386
387   // Abort if the aliases of IntB.reg have values that are not simply the
388   // clobbers from the superreg.
389   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
390     for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
391       if (li_->hasInterval(*AS) &&
392           HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
393         return false;
394
395   // If some of the uses of IntA.reg is already coalesced away, return false.
396   // It's not possible to determine whether it's safe to perform the coalescing.
397   for (MachineRegisterInfo::use_nodbg_iterator UI = 
398          mri_->use_nodbg_begin(IntA.reg), 
399        UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
400     MachineInstr *UseMI = &*UI;
401     SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
402     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
403     if (ULR == IntA.end())
404       continue;
405     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
406       return false;
407   }
408
409   DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
410                << *DefMI);
411
412   // At this point we have decided that it is legal to do this
413   // transformation.  Start by commuting the instruction.
414   MachineBasicBlock *MBB = DefMI->getParent();
415   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
416   if (!NewMI)
417     return false;
418   if (NewMI != DefMI) {
419     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
420     MBB->insert(DefMI, NewMI);
421     MBB->erase(DefMI);
422   }
423   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
424   NewMI->getOperand(OpIdx).setIsKill();
425
426   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
427   // A = or A, B
428   // ...
429   // B = A
430   // ...
431   // C = A<kill>
432   // ...
433   //   = B
434
435   // Update uses of IntA of the specific Val# with IntB.
436   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
437          UE = mri_->use_end(); UI != UE;) {
438     MachineOperand &UseMO = UI.getOperand();
439     MachineInstr *UseMI = &*UI;
440     ++UI;
441     if (JoinedCopies.count(UseMI))
442       continue;
443     if (UseMI->isDebugValue()) {
444       // FIXME These don't have an instruction index.  Not clear we have enough
445       // info to decide whether to do this replacement or not.  For now do it.
446       UseMO.setReg(NewReg);
447       continue;
448     }
449     SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
450     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
451     if (ULR == IntA.end() || ULR->valno != AValNo)
452       continue;
453     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
454       UseMO.substPhysReg(NewReg, *tri_);
455     else
456       UseMO.setReg(NewReg);
457     if (UseMI == CopyMI)
458       continue;
459     if (!UseMI->isCopy())
460       continue;
461     if (UseMI->getOperand(0).getReg() != IntB.reg ||
462         UseMI->getOperand(0).getSubReg())
463       continue;
464
465     // This copy will become a noop. If it's defining a new val#, merge it into
466     // BValNo.
467     SlotIndex DefIdx = UseIdx.getDefIndex();
468     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
469     if (!DVNI)
470       continue;
471     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
472     assert(DVNI->def == DefIdx);
473     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
474     JoinedCopies.insert(UseMI);
475   }
476
477   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
478   // is updated.
479   VNInfo *ValNo = BValNo;
480   ValNo->def = AValNo->def;
481   ValNo->setCopy(0);
482   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
483        AI != AE; ++AI) {
484     if (AI->valno != AValNo) continue;
485     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
486   }
487   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
488
489   IntA.removeValNo(AValNo);
490   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
491   ++numCommutes;
492   return true;
493 }
494
495 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
496 /// fallthoughs to SuccMBB.
497 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
498                                   MachineBasicBlock *SuccMBB,
499                                   const TargetInstrInfo *tii_) {
500   if (MBB == SuccMBB)
501     return true;
502   MachineBasicBlock *TBB = 0, *FBB = 0;
503   SmallVector<MachineOperand, 4> Cond;
504   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
505     MBB->isSuccessor(SuccMBB);
506 }
507
508 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
509 /// from a physical register live interval as well as from the live intervals
510 /// of its sub-registers.
511 static void removeRange(LiveInterval &li,
512                         SlotIndex Start, SlotIndex End,
513                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
514   li.removeRange(Start, End, true);
515   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
516     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
517       if (!li_->hasInterval(*SR))
518         continue;
519       LiveInterval &sli = li_->getInterval(*SR);
520       SlotIndex RemoveStart = Start;
521       SlotIndex RemoveEnd = Start;
522
523       while (RemoveEnd != End) {
524         LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
525         if (LR == sli.end())
526           break;
527         RemoveEnd = (LR->end < End) ? LR->end : End;
528         sli.removeRange(RemoveStart, RemoveEnd, true);
529         RemoveStart = RemoveEnd;
530       }
531     }
532   }
533 }
534
535 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
536 /// as the copy instruction, trim the live interval to the last use and return
537 /// true.
538 bool
539 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
540                                                     MachineBasicBlock *CopyMBB,
541                                                     LiveInterval &li,
542                                                     const LiveRange *LR) {
543   SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
544   SlotIndex LastUseIdx;
545   MachineOperand *LastUse =
546     lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
547   if (LastUse) {
548     MachineInstr *LastUseMI = LastUse->getParent();
549     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
550       // r1024 = op
551       // ...
552       // BB1:
553       //       = r1024
554       //
555       // BB2:
556       // r1025<dead> = r1024<kill>
557       if (MBBStart < LR->end)
558         removeRange(li, MBBStart, LR->end, li_, tri_);
559       return true;
560     }
561
562     // There are uses before the copy, just shorten the live range to the end
563     // of last use.
564     LastUse->setIsKill();
565     removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
566     if (LastUseMI->isCopy()) {
567       MachineOperand &DefMO = LastUseMI->getOperand(0);
568       if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
569         DefMO.setIsDead();
570     }
571     return true;
572   }
573
574   // Is it livein?
575   if (LR->start <= MBBStart && LR->end > MBBStart) {
576     if (LR->start == li_->getZeroIndex()) {
577       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
578       // Live-in to the function but dead. Remove it from entry live-in set.
579       mf_->begin()->removeLiveIn(li.reg);
580     }
581     // FIXME: Shorten intervals in BBs that reaches this BB.
582   }
583
584   return false;
585 }
586
587 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
588 /// computation, replace the copy by rematerialize the definition.
589 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
590                                                        unsigned DstReg,
591                                                        unsigned DstSubIdx,
592                                                        MachineInstr *CopyMI) {
593   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
594   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
595   assert(SrcLR != SrcInt.end() && "Live range not found!");
596   VNInfo *ValNo = SrcLR->valno;
597   // If other defs can reach uses of this def, then it's not safe to perform
598   // the optimization.
599   if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
600     return false;
601   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
602   if (!DefMI)
603     return false;
604   assert(DefMI && "Defining instruction disappeared");
605   const TargetInstrDesc &TID = DefMI->getDesc();
606   if (!TID.isAsCheapAsAMove())
607     return false;
608   if (!tii_->isTriviallyReMaterializable(DefMI, AA))
609     return false;
610   bool SawStore = false;
611   if (!DefMI->isSafeToMove(tii_, AA, SawStore))
612     return false;
613   if (TID.getNumDefs() != 1)
614     return false;
615   if (!DefMI->isImplicitDef()) {
616     // Make sure the copy destination register class fits the instruction
617     // definition register class. The mismatch can happen as a result of earlier
618     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
619     const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
620     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
621       if (mri_->getRegClass(DstReg) != RC)
622         return false;
623     } else if (!RC->contains(DstReg))
624       return false;
625   }
626
627   // If destination register has a sub-register index on it, make sure it
628   // matches the instruction register class.
629   if (DstSubIdx) {
630     const TargetInstrDesc &TID = DefMI->getDesc();
631     if (TID.getNumDefs() != 1)
632       return false;
633     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
634     const TargetRegisterClass *DstSubRC =
635       DstRC->getSubRegisterRegClass(DstSubIdx);
636     const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
637     if (DefRC == DstRC)
638       DstSubIdx = 0;
639     else if (DefRC != DstSubRC)
640       return false;
641   }
642
643   RemoveCopyFlag(DstReg, CopyMI);
644
645   // If copy kills the source register, find the last use and propagate
646   // kill.
647   bool checkForDeadDef = false;
648   MachineBasicBlock *MBB = CopyMI->getParent();
649   if (SrcLR->end == CopyIdx.getDefIndex())
650     if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
651       checkForDeadDef = true;
652     }
653
654   MachineBasicBlock::iterator MII =
655     llvm::next(MachineBasicBlock::iterator(CopyMI));
656   tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
657   MachineInstr *NewMI = prior(MII);
658
659   if (checkForDeadDef) {
660     // PR4090 fix: Trim interval failed because there was no use of the
661     // source interval in this MBB. If the def is in this MBB too then we
662     // should mark it dead:
663     if (DefMI->getParent() == MBB) {
664       DefMI->addRegisterDead(SrcInt.reg, tri_);
665       SrcLR->end = SrcLR->start.getNextSlot();
666     }
667   }
668
669   // CopyMI may have implicit operands, transfer them over to the newly
670   // rematerialized instruction. And update implicit def interval valnos.
671   for (unsigned i = CopyMI->getDesc().getNumOperands(),
672          e = CopyMI->getNumOperands(); i != e; ++i) {
673     MachineOperand &MO = CopyMI->getOperand(i);
674     if (MO.isReg() && MO.isImplicit())
675       NewMI->addOperand(MO);
676     if (MO.isDef())
677       RemoveCopyFlag(MO.getReg(), CopyMI);
678   }
679
680   NewMI->copyImplicitOps(CopyMI);
681   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
682   CopyMI->eraseFromParent();
683   ReMatCopies.insert(CopyMI);
684   ReMatDefs.insert(DefMI);
685   DEBUG(dbgs() << "Remat: " << *NewMI);
686   ++NumReMats;
687   return true;
688 }
689
690 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
691 /// update the subregister number if it is not zero. If DstReg is a
692 /// physical register and the existing subregister number of the def / use
693 /// being updated is not zero, make sure to set it to the correct physical
694 /// subregister.
695 void
696 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
697   bool DstIsPhys = CP.isPhys();
698   unsigned SrcReg = CP.getSrcReg();
699   unsigned DstReg = CP.getDstReg();
700   unsigned SubIdx = CP.getSubIdx();
701
702   // Update LiveDebugVariables.
703   ldv_->renameRegister(SrcReg, DstReg, SubIdx);
704
705   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
706        MachineInstr *UseMI = I.skipInstruction();) {
707     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
708     // instead.
709     if (DstIsPhys) {
710       if (UseMI->isCopy() &&
711           !UseMI->getOperand(1).getSubReg() &&
712           !UseMI->getOperand(0).getSubReg() &&
713           UseMI->getOperand(1).getReg() == SrcReg &&
714           UseMI->getOperand(0).getReg() != SrcReg &&
715           UseMI->getOperand(0).getReg() != DstReg &&
716           !JoinedCopies.count(UseMI) &&
717           ReMaterializeTrivialDef(li_->getInterval(SrcReg),
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 " << PrintReg(CP.getSrcReg(), tri_));
994
995   // Enforce policies.
996   if (CP.isPhys()) {
997     DEBUG(dbgs() <<" with physreg " << PrintReg(CP.getDstReg(), tri_) << "\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(dbgs() << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
1005                  << " to " << CP.getNewRC()->getName() << "\n");
1006
1007     // Avoid constraining virtual register regclass too much.
1008     if (CP.isCrossClass()) {
1009       if (DisableCrossClassJoin) {
1010         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1011         return false;
1012       }
1013       if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1014                                  mri_->getRegClass(CP.getSrcReg()),
1015                                  mri_->getRegClass(CP.getDstReg()),
1016                                  CP.getNewRC())) {
1017         DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1018                      << CP.getNewRC()->getName() << ".\n");
1019         Again = true;  // May be possible to coalesce later.
1020         return false;
1021       }
1022     }
1023
1024     // When possible, let DstReg be the larger interval.
1025     if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1026                            li_->getInterval(CP.getDstReg()).ranges.size())
1027       CP.flip();
1028   }
1029
1030   // We need to be careful about coalescing a source physical register with a
1031   // virtual register. Once the coalescing is done, it cannot be broken and
1032   // these are not spillable! If the destination interval uses are far away,
1033   // think twice about coalescing them!
1034   // FIXME: Why are we skipping this test for partial copies?
1035   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1036   if (!CP.isPartial() && CP.isPhys()) {
1037     LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1038
1039     // Don't join with physregs that have a ridiculous number of live
1040     // ranges. The data structure performance is really bad when that
1041     // happens.
1042     if (li_->hasInterval(CP.getDstReg()) &&
1043         li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1044       ++numAborts;
1045       DEBUG(dbgs()
1046            << "\tPhysical register live interval too complicated, abort!\n");
1047       return false;
1048     }
1049
1050     const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1051     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1052     unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1053     if (Length > Threshold &&
1054         std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1055                       mri_->use_nodbg_end()) * Threshold < Length) {
1056       // Before giving up coalescing, if definition of source is defined by
1057       // trivial computation, try rematerializing it.
1058       if (!CP.isFlipped() &&
1059           ReMaterializeTrivialDef(JoinVInt, CP.getDstReg(), 0, CopyMI))
1060         return true;
1061
1062       ++numAborts;
1063       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1064       Again = true;  // May be possible to coalesce later.
1065       return false;
1066     }
1067   }
1068
1069   // Okay, attempt to join these two intervals.  On failure, this returns false.
1070   // Otherwise, if one of the intervals being joined is a physreg, this method
1071   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1072   // been modified, so we can use this information below to update aliases.
1073   if (!JoinIntervals(CP)) {
1074     // Coalescing failed.
1075
1076     // If definition of source is defined by trivial computation, try
1077     // rematerializing it.
1078     if (!CP.isFlipped() &&
1079         ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()),
1080                                 CP.getDstReg(), 0, CopyMI))
1081       return true;
1082
1083     // If we can eliminate the copy without merging the live ranges, do so now.
1084     if (!CP.isPartial()) {
1085       if (AdjustCopiesBackFrom(CP, CopyMI) ||
1086           RemoveCopyByCommutingDef(CP, CopyMI)) {
1087         JoinedCopies.insert(CopyMI);
1088         DEBUG(dbgs() << "\tTrivial!\n");
1089         return true;
1090       }
1091     }
1092
1093     // Otherwise, we are unable to join the intervals.
1094     DEBUG(dbgs() << "\tInterference!\n");
1095     Again = true;  // May be possible to coalesce later.
1096     return false;
1097   }
1098
1099   // Coalescing to a virtual register that is of a sub-register class of the
1100   // other. Make sure the resulting register is set to the right register class.
1101   if (CP.isCrossClass()) {
1102     ++numCrossRCs;
1103     mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1104   }
1105
1106   // Remember to delete the copy instruction.
1107   JoinedCopies.insert(CopyMI);
1108
1109   UpdateRegDefsUses(CP);
1110
1111   // If we have extended the live range of a physical register, make sure we
1112   // update live-in lists as well.
1113   if (CP.isPhys()) {
1114     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1115     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1116     // ranges for this, and they are preserved.
1117     LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1118     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1119          I != E; ++I ) {
1120       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1121       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1122         MachineBasicBlock &block = *BlockSeq[idx];
1123         if (!block.isLiveIn(CP.getDstReg()))
1124           block.addLiveIn(CP.getDstReg());
1125       }
1126       BlockSeq.clear();
1127     }
1128   }
1129
1130   // SrcReg is guarateed to be the register whose live interval that is
1131   // being merged.
1132   li_->removeInterval(CP.getSrcReg());
1133
1134   // Update regalloc hint.
1135   tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1136
1137   DEBUG({
1138     LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1139     dbgs() << "\tJoined. Result = ";
1140     DstInt.print(dbgs(), tri_);
1141     dbgs() << "\n";
1142   });
1143
1144   ++numJoins;
1145   return true;
1146 }
1147
1148 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1149 /// compute what the resultant value numbers for each value in the input two
1150 /// ranges will be.  This is complicated by copies between the two which can
1151 /// and will commonly cause multiple value numbers to be merged into one.
1152 ///
1153 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1154 /// keeps track of the new InstDefiningValue assignment for the result
1155 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1156 /// whether a value in this or other is a copy from the opposite set.
1157 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1158 /// already been assigned.
1159 ///
1160 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1161 /// contains the value number the copy is from.
1162 ///
1163 static unsigned ComputeUltimateVN(VNInfo *VNI,
1164                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1165                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1166                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1167                                   SmallVector<int, 16> &ThisValNoAssignments,
1168                                   SmallVector<int, 16> &OtherValNoAssignments) {
1169   unsigned VN = VNI->id;
1170
1171   // If the VN has already been computed, just return it.
1172   if (ThisValNoAssignments[VN] >= 0)
1173     return ThisValNoAssignments[VN];
1174   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1175
1176   // If this val is not a copy from the other val, then it must be a new value
1177   // number in the destination.
1178   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1179   if (I == ThisFromOther.end()) {
1180     NewVNInfo.push_back(VNI);
1181     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1182   }
1183   VNInfo *OtherValNo = I->second;
1184
1185   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1186   // been computed, return it.
1187   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1188     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1189
1190   // Mark this value number as currently being computed, then ask what the
1191   // ultimate value # of the other value is.
1192   ThisValNoAssignments[VN] = -2;
1193   unsigned UltimateVN =
1194     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1195                       OtherValNoAssignments, ThisValNoAssignments);
1196   return ThisValNoAssignments[VN] = UltimateVN;
1197 }
1198
1199 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1200 /// returns false.
1201 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1202   LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1203   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1204
1205   // If a live interval is a physical register, check for interference with any
1206   // aliases. The interference check implemented here is a bit more conservative
1207   // than the full interfeence check below. We allow overlapping live ranges
1208   // only when one is a copy of the other.
1209   if (CP.isPhys()) {
1210     for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1211       if (!li_->hasInterval(*AS))
1212         continue;
1213       const LiveInterval &LHS = li_->getInterval(*AS);
1214       LiveInterval::const_iterator LI = LHS.begin();
1215       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1216            RI != RE; ++RI) {
1217         LI = std::lower_bound(LI, LHS.end(), RI->start);
1218         // Does LHS have an overlapping live range starting before RI?
1219         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1220             (RI->start != RI->valno->def ||
1221              !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1222           DEBUG({
1223             dbgs() << "\t\tInterference from alias: ";
1224             LHS.print(dbgs(), tri_);
1225             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1226           });
1227           return false;
1228         }
1229
1230         // Check that LHS ranges beginning in this range are copies.
1231         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1232           if (LI->start != LI->valno->def ||
1233               !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1234             DEBUG({
1235               dbgs() << "\t\tInterference from alias: ";
1236               LHS.print(dbgs(), tri_);
1237               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1238             });
1239             return false;
1240           }
1241         }
1242       }
1243     }
1244   }
1245
1246   // Compute the final value assignment, assuming that the live ranges can be
1247   // coalesced.
1248   SmallVector<int, 16> LHSValNoAssignments;
1249   SmallVector<int, 16> RHSValNoAssignments;
1250   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1251   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1252   SmallVector<VNInfo*, 16> NewVNInfo;
1253
1254   LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1255   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1256
1257   // Loop over the value numbers of the LHS, seeing if any are defined from
1258   // the RHS.
1259   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1260        i != e; ++i) {
1261     VNInfo *VNI = *i;
1262     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1263       continue;
1264
1265     // Never join with a register that has EarlyClobber redefs.
1266     if (VNI->hasRedefByEC())
1267       return false;
1268
1269     // DstReg is known to be a register in the LHS interval.  If the src is
1270     // from the RHS interval, we can use its value #.
1271     if (!CP.isCoalescable(VNI->getCopy()))
1272       continue;
1273
1274     // Figure out the value # from the RHS.
1275     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1276     // The copy could be to an aliased physreg.
1277     if (!lr) continue;
1278     LHSValsDefinedFromRHS[VNI] = lr->valno;
1279   }
1280
1281   // Loop over the value numbers of the RHS, seeing if any are defined from
1282   // the LHS.
1283   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1284        i != e; ++i) {
1285     VNInfo *VNI = *i;
1286     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1287       continue;
1288
1289     // Never join with a register that has EarlyClobber redefs.
1290     if (VNI->hasRedefByEC())
1291       return false;
1292
1293     // DstReg is known to be a register in the RHS interval.  If the src is
1294     // from the LHS interval, we can use its value #.
1295     if (!CP.isCoalescable(VNI->getCopy()))
1296       continue;
1297
1298     // Figure out the value # from the LHS.
1299     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1300     // The copy could be to an aliased physreg.
1301     if (!lr) continue;
1302     RHSValsDefinedFromLHS[VNI] = lr->valno;
1303   }
1304
1305   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1306   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1307   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1308
1309   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1310        i != e; ++i) {
1311     VNInfo *VNI = *i;
1312     unsigned VN = VNI->id;
1313     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1314       continue;
1315     ComputeUltimateVN(VNI, NewVNInfo,
1316                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1317                       LHSValNoAssignments, RHSValNoAssignments);
1318   }
1319   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1320        i != e; ++i) {
1321     VNInfo *VNI = *i;
1322     unsigned VN = VNI->id;
1323     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1324       continue;
1325     // If this value number isn't a copy from the LHS, it's a new number.
1326     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1327       NewVNInfo.push_back(VNI);
1328       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1329       continue;
1330     }
1331
1332     ComputeUltimateVN(VNI, NewVNInfo,
1333                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1334                       RHSValNoAssignments, LHSValNoAssignments);
1335   }
1336
1337   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1338   // interval lists to see if these intervals are coalescable.
1339   LiveInterval::const_iterator I = LHS.begin();
1340   LiveInterval::const_iterator IE = LHS.end();
1341   LiveInterval::const_iterator J = RHS.begin();
1342   LiveInterval::const_iterator JE = RHS.end();
1343
1344   // Skip ahead until the first place of potential sharing.
1345   if (I != IE && J != JE) {
1346     if (I->start < J->start) {
1347       I = std::upper_bound(I, IE, J->start);
1348       if (I != LHS.begin()) --I;
1349     } else if (J->start < I->start) {
1350       J = std::upper_bound(J, JE, I->start);
1351       if (J != RHS.begin()) --J;
1352     }
1353   }
1354
1355   while (I != IE && J != JE) {
1356     // Determine if these two live ranges overlap.
1357     bool Overlaps;
1358     if (I->start < J->start) {
1359       Overlaps = I->end > J->start;
1360     } else {
1361       Overlaps = J->end > I->start;
1362     }
1363
1364     // If so, check value # info to determine if they are really different.
1365     if (Overlaps) {
1366       // If the live range overlap will map to the same value number in the
1367       // result liverange, we can still coalesce them.  If not, we can't.
1368       if (LHSValNoAssignments[I->valno->id] !=
1369           RHSValNoAssignments[J->valno->id])
1370         return false;
1371       // If it's re-defined by an early clobber somewhere in the live range,
1372       // then conservatively abort coalescing.
1373       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1374         return false;
1375     }
1376
1377     if (I->end < J->end)
1378       ++I;
1379     else
1380       ++J;
1381   }
1382
1383   // Update kill info. Some live ranges are extended due to copy coalescing.
1384   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1385          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1386     VNInfo *VNI = I->first;
1387     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1388     if (VNI->hasPHIKill())
1389       NewVNInfo[LHSValID]->setHasPHIKill(true);
1390   }
1391
1392   // Update kill info. Some live ranges are extended due to copy coalescing.
1393   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1394          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1395     VNInfo *VNI = I->first;
1396     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1397     if (VNI->hasPHIKill())
1398       NewVNInfo[RHSValID]->setHasPHIKill(true);
1399   }
1400
1401   if (LHSValNoAssignments.empty())
1402     LHSValNoAssignments.push_back(-1);
1403   if (RHSValNoAssignments.empty())
1404     RHSValNoAssignments.push_back(-1);
1405
1406   // If we get here, we know that we can coalesce the live ranges.  Ask the
1407   // intervals to coalesce themselves now.
1408   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1409            mri_);
1410   return true;
1411 }
1412
1413 namespace {
1414   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1415   // depth of the basic block (the unsigned), and then on the MBB number.
1416   struct DepthMBBCompare {
1417     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1418     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1419       // Deeper loops first
1420       if (LHS.first != RHS.first)
1421         return LHS.first > RHS.first;
1422
1423       // Prefer blocks that are more connected in the CFG. This takes care of
1424       // the most difficult copies first while intervals are short.
1425       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1426       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1427       if (cl != cr)
1428         return cl > cr;
1429
1430       // As a last resort, sort by block number.
1431       return LHS.second->getNumber() < RHS.second->getNumber();
1432     }
1433   };
1434 }
1435
1436 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1437                                                std::vector<CopyRec> &TryAgain) {
1438   DEBUG(dbgs() << MBB->getName() << ":\n");
1439
1440   std::vector<CopyRec> VirtCopies;
1441   std::vector<CopyRec> PhysCopies;
1442   std::vector<CopyRec> ImpDefCopies;
1443   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1444        MII != E;) {
1445     MachineInstr *Inst = MII++;
1446
1447     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1448     unsigned SrcReg, DstReg;
1449     if (Inst->isCopy()) {
1450       DstReg = Inst->getOperand(0).getReg();
1451       SrcReg = Inst->getOperand(1).getReg();
1452     } else if (Inst->isSubregToReg()) {
1453       DstReg = Inst->getOperand(0).getReg();
1454       SrcReg = Inst->getOperand(2).getReg();
1455     } else
1456       continue;
1457
1458     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1459     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1460     if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1461       ImpDefCopies.push_back(CopyRec(Inst, 0));
1462     else if (SrcIsPhys || DstIsPhys)
1463       PhysCopies.push_back(CopyRec(Inst, 0));
1464     else
1465       VirtCopies.push_back(CopyRec(Inst, 0));
1466   }
1467
1468   // Try coalescing implicit copies and insert_subreg <undef> first,
1469   // followed by copies to / from physical registers, then finally copies
1470   // from virtual registers to virtual registers.
1471   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1472     CopyRec &TheCopy = ImpDefCopies[i];
1473     bool Again = false;
1474     if (!JoinCopy(TheCopy, Again))
1475       if (Again)
1476         TryAgain.push_back(TheCopy);
1477   }
1478   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1479     CopyRec &TheCopy = PhysCopies[i];
1480     bool Again = false;
1481     if (!JoinCopy(TheCopy, Again))
1482       if (Again)
1483         TryAgain.push_back(TheCopy);
1484   }
1485   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1486     CopyRec &TheCopy = VirtCopies[i];
1487     bool Again = false;
1488     if (!JoinCopy(TheCopy, Again))
1489       if (Again)
1490         TryAgain.push_back(TheCopy);
1491   }
1492 }
1493
1494 void SimpleRegisterCoalescing::joinIntervals() {
1495   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1496
1497   std::vector<CopyRec> TryAgainList;
1498   if (loopInfo->empty()) {
1499     // If there are no loops in the function, join intervals in function order.
1500     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1501          I != E; ++I)
1502       CopyCoalesceInMBB(I, TryAgainList);
1503   } else {
1504     // Otherwise, join intervals in inner loops before other intervals.
1505     // Unfortunately we can't just iterate over loop hierarchy here because
1506     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1507
1508     // Join intervals in the function prolog first. We want to join physical
1509     // registers with virtual registers before the intervals got too long.
1510     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1511     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1512       MachineBasicBlock *MBB = I;
1513       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1514     }
1515
1516     // Sort by loop depth.
1517     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1518
1519     // Finally, join intervals in loop nest order.
1520     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1521       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1522   }
1523
1524   // Joining intervals can allow other intervals to be joined.  Iteratively join
1525   // until we make no progress.
1526   bool ProgressMade = true;
1527   while (ProgressMade) {
1528     ProgressMade = false;
1529
1530     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1531       CopyRec &TheCopy = TryAgainList[i];
1532       if (!TheCopy.MI)
1533         continue;
1534
1535       bool Again = false;
1536       bool Success = JoinCopy(TheCopy, Again);
1537       if (Success || !Again) {
1538         TheCopy.MI = 0;   // Mark this one as done.
1539         ProgressMade = true;
1540       }
1541     }
1542   }
1543 }
1544
1545 /// Return true if the two specified registers belong to different register
1546 /// classes.  The registers may be either phys or virt regs.
1547 bool
1548 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1549                                                    unsigned RegB) const {
1550   // Get the register classes for the first reg.
1551   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1552     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1553            "Shouldn't consider two physregs!");
1554     return !mri_->getRegClass(RegB)->contains(RegA);
1555   }
1556
1557   // Compare against the regclass for the second reg.
1558   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1559   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1560     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1561     return RegClassA != RegClassB;
1562   }
1563   return !RegClassA->contains(RegB);
1564 }
1565
1566 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1567 /// between cycles Start and End or NULL if there are no uses.
1568 MachineOperand *
1569 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1570                                           SlotIndex End,
1571                                           unsigned Reg,
1572                                           SlotIndex &UseIdx) const{
1573   UseIdx = SlotIndex();
1574   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1575     MachineOperand *LastUse = NULL;
1576     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1577            E = mri_->use_nodbg_end(); I != E; ++I) {
1578       MachineOperand &Use = I.getOperand();
1579       MachineInstr *UseMI = Use.getParent();
1580       if (UseMI->isIdentityCopy())
1581         continue;
1582       SlotIndex Idx = li_->getInstructionIndex(UseMI);
1583       // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1584       // that compares higher than any other interval.
1585       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1586         LastUse = &Use;
1587         UseIdx = Idx.getUseIndex();
1588       }
1589     }
1590     return LastUse;
1591   }
1592
1593   SlotIndex s = Start;
1594   SlotIndex e = End.getPrevSlot().getBaseIndex();
1595   while (e >= s) {
1596     // Skip deleted instructions
1597     MachineInstr *MI = li_->getInstructionFromIndex(e);
1598     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1599       e = e.getPrevIndex();
1600       MI = li_->getInstructionFromIndex(e);
1601     }
1602     if (e < s || MI == NULL)
1603       return NULL;
1604
1605     // Ignore identity copies.
1606     if (!MI->isIdentityCopy())
1607       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1608         MachineOperand &Use = MI->getOperand(i);
1609         if (Use.isReg() && Use.isUse() && Use.getReg() &&
1610             tri_->regsOverlap(Use.getReg(), Reg)) {
1611           UseIdx = e.getUseIndex();
1612           return &Use;
1613         }
1614       }
1615
1616     e = e.getPrevIndex();
1617   }
1618
1619   return NULL;
1620 }
1621
1622 void SimpleRegisterCoalescing::releaseMemory() {
1623   JoinedCopies.clear();
1624   ReMatCopies.clear();
1625   ReMatDefs.clear();
1626 }
1627
1628 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1629   mf_ = &fn;
1630   mri_ = &fn.getRegInfo();
1631   tm_ = &fn.getTarget();
1632   tri_ = tm_->getRegisterInfo();
1633   tii_ = tm_->getInstrInfo();
1634   li_ = &getAnalysis<LiveIntervals>();
1635   ldv_ = &getAnalysis<LiveDebugVariables>();
1636   AA = &getAnalysis<AliasAnalysis>();
1637   loopInfo = &getAnalysis<MachineLoopInfo>();
1638
1639   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1640                << "********** Function: "
1641                << ((Value*)mf_->getFunction())->getName() << '\n');
1642
1643   if (VerifyCoalescing)
1644     mf_->verify(this, "Before register coalescing");
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   DEBUG(ldv_->dump());
1788   if (VerifyCoalescing)
1789     mf_->verify(this, "After register coalescing");
1790   return true;
1791 }
1792
1793 /// print - Implement the dump method.
1794 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1795    li_->print(O, m);
1796 }
1797
1798 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1799   return new SimpleRegisterCoalescing();
1800 }
1801
1802 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1803 DEFINING_FILE_FOR(SimpleRegisterCoalescing)