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