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