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