eliminate the CheckMultiOpcodeMatcher code and have each
[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/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include <algorithm>
38 #include <cmath>
39 using namespace llvm;
40
41 STATISTIC(numJoins    , "Number of interval joins performed");
42 STATISTIC(numCrossRCs , "Number of cross class joins performed");
43 STATISTIC(numCommutes , "Number of instruction commuting performed");
44 STATISTIC(numExtends  , "Number of copies extended");
45 STATISTIC(NumReMats   , "Number of instructions re-materialized");
46 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
47 STATISTIC(numAborts   , "Number of times interval joining aborted");
48 STATISTIC(numDeadValNo, "Number of valno def marked dead");
49
50 char SimpleRegisterCoalescing::ID = 0;
51 static cl::opt<bool>
52 EnableJoining("join-liveintervals",
53               cl::desc("Coalesce copies (default=true)"),
54               cl::init(true));
55
56 static cl::opt<bool>
57 DisableCrossClassJoin("disable-cross-class-join",
58                cl::desc("Avoid coalescing cross register class copies"),
59                cl::init(false), cl::Hidden);
60
61 static cl::opt<bool>
62 PhysJoinTweak("tweak-phys-join-heuristics",
63                cl::desc("Tweak heuristics for joining phys reg with vr"),
64                cl::init(false), cl::Hidden);
65
66 static RegisterPass<SimpleRegisterCoalescing>
67 X("simple-register-coalescing", "Simple Register Coalescing");
68
69 // Declare that we implement the RegisterCoalescer interface
70 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
71
72 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
73
74 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
75   AU.setPreservesCFG();
76   AU.addRequired<AliasAnalysis>();
77   AU.addRequired<LiveIntervals>();
78   AU.addPreserved<LiveIntervals>();
79   AU.addPreserved<SlotIndexes>();
80   AU.addRequired<MachineLoopInfo>();
81   AU.addPreserved<MachineLoopInfo>();
82   AU.addPreservedID(MachineDominatorsID);
83   if (StrongPHIElim)
84     AU.addPreservedID(StrongPHIEliminationID);
85   else
86     AU.addPreservedID(PHIEliminationID);
87   AU.addPreservedID(TwoAddressInstructionPassID);
88   MachineFunctionPass::getAnalysisUsage(AU);
89 }
90
91 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
92 /// being the source and IntB being the dest, thus this defines a value number
93 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
94 /// see if we can merge these two pieces of B into a single value number,
95 /// eliminating a copy.  For example:
96 ///
97 ///  A3 = B0
98 ///    ...
99 ///  B1 = A3      <- this copy
100 ///
101 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
102 /// value number to be replaced with B0 (which simplifies the B liveinterval).
103 ///
104 /// This returns true if an interval was modified.
105 ///
106 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
107                                                     LiveInterval &IntB,
108                                                     MachineInstr *CopyMI) {
109   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
110
111   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
112   // the example above.
113   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
114   assert(BLR != IntB.end() && "Live range not found!");
115   VNInfo *BValNo = BLR->valno;
116
117   // Get the location that B is defined at.  Two options: either this value has
118   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
119   // can't process it.
120   if (!BValNo->getCopy()) return false;
121   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
122
123   // AValNo is the value number in A that defines the copy, A3 in the example.
124   SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
125   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
126   assert(ALR != IntA.end() && "Live range not found!");
127   VNInfo *AValNo = ALR->valno;
128   // If it's re-defined by an early clobber somewhere in the live range, then
129   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
130   // See PR3149:
131   // 172     %ECX<def> = MOV32rr %reg1039<kill>
132   // 180     INLINEASM <es:subl $5,$1
133   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
134   //         %EAX<kill>,
135   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
136   // 188     %EAX<def> = MOV32rr %EAX<kill>
137   // 196     %ECX<def> = MOV32rr %ECX<kill>
138   // 204     %ECX<def> = MOV32rr %ECX<kill>
139   // 212     %EAX<def> = MOV32rr %EAX<kill>
140   // 220     %EAX<def> = MOV32rr %EAX
141   // 228     %reg1039<def> = MOV32rr %ECX<kill>
142   // The early clobber operand ties ECX input to the ECX def.
143   //
144   // The live interval of ECX is represented as this:
145   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
146   // The coalescer has no idea there was a def in the middle of [174,230].
147   if (AValNo->hasRedefByEC())
148     return false;
149
150   // If AValNo is defined as a copy from IntB, we can potentially process this.
151   // Get the instruction that defines this value number.
152   unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
153   if (!SrcReg) return false;  // Not defined by a copy.
154
155   // If the value number is not defined by a copy instruction, ignore it.
156
157   // If the source register comes from an interval other than IntB, we can't
158   // handle this.
159   if (SrcReg != IntB.reg) return false;
160
161   // Get the LiveRange in IntB that this value number starts with.
162   LiveInterval::iterator ValLR =
163     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
164   assert(ValLR != IntB.end() && "Live range not found!");
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 ||
171       ValLREndInst->getParent() != CopyMI->getParent()) 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() << "Interfere with sub-register ";
187             li_->getInterval(*SR).print(dbgs(), tri_);
188           });
189         return false;
190       }
191   }
192
193   DEBUG({
194       dbgs() << "\nExtending: ";
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       LiveInterval &SRLI = li_->getInterval(*SR);
215       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
216                               SRLI.getNextValue(FillerStart, 0, true,
217                                                 li_->getVNInfoAllocator())));
218     }
219   }
220
221   // Okay, merge "B1" into the same value number as "B0".
222   if (BValNo != ValLR->valno) {
223     IntB.addKills(ValLR->valno, BValNo->kills);
224     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
225   }
226   DEBUG({
227       dbgs() << "   result = ";
228       IntB.print(dbgs(), tri_);
229       dbgs() << "\n";
230     });
231
232   // If the source instruction was killing the source register before the
233   // merge, unset the isKill marker given the live range has been extended.
234   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
235   if (UIdx != -1) {
236     ValLREndInst->getOperand(UIdx).setIsKill(false);
237     ValLR->valno->removeKill(FillerStart);
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 (CopyMI->killsRegister(IntA.reg))
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       if (BI->start <= AI->start && BI->end > AI->start)
267         return true;
268       if (BI->start > AI->start && BI->start < AI->end)
269         return true;
270     }
271   }
272   return false;
273 }
274
275 static void
276 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
277   for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
278        i != e; ++i) {
279     MachineOperand &MO = MI->getOperand(i);
280     if (MO.isReg() && MO.isImplicit())
281       NewMI->addOperand(MO);
282   }
283 }
284
285 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
286 /// IntA being the source and IntB being the dest, thus this defines a value
287 /// number in IntB.  If the source value number (in IntA) is defined by a
288 /// commutable instruction and its other operand is coalesced to the copy dest
289 /// register, see if we can transform the copy into a noop by commuting the
290 /// definition. For example,
291 ///
292 ///  A3 = op A2 B0<kill>
293 ///    ...
294 ///  B1 = A3      <- this copy
295 ///    ...
296 ///     = op A3   <- more uses
297 ///
298 /// ==>
299 ///
300 ///  B2 = op B0 A2<kill>
301 ///    ...
302 ///  B1 = B2      <- now an identify copy
303 ///    ...
304 ///     = op B2   <- more uses
305 ///
306 /// This returns true if an interval was modified.
307 ///
308 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
309                                                         LiveInterval &IntB,
310                                                         MachineInstr *CopyMI) {
311   SlotIndex CopyIdx =
312     li_->getInstructionIndex(CopyMI).getDefIndex();
313
314   // FIXME: For now, only eliminate the copy by commuting its def when the
315   // source register is a virtual register. We want to guard against cases
316   // where the copy is a back edge copy and commuting the def lengthen the
317   // live interval of the source register to the entire loop.
318   if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
319     return false;
320
321   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
322   // the example above.
323   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
324   assert(BLR != IntB.end() && "Live range not found!");
325   VNInfo *BValNo = BLR->valno;
326
327   // Get the location that B is defined at.  Two options: either this value has
328   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
329   // can't process it.
330   if (!BValNo->getCopy()) return false;
331   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
332
333   // AValNo is the value number in A that defines the copy, A3 in the example.
334   LiveInterval::iterator ALR =
335     IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); // 
336
337   assert(ALR != IntA.end() && "Live range not found!");
338   VNInfo *AValNo = ALR->valno;
339   // If other defs can reach uses of this def, then it's not safe to perform
340   // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
341   // tested?
342   if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
343       AValNo->isUnused() || AValNo->hasPHIKill())
344     return false;
345   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
346   const TargetInstrDesc &TID = DefMI->getDesc();
347   if (!TID.isCommutable())
348     return false;
349   // If DefMI is a two-address instruction then commuting it will change the
350   // destination register.
351   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
352   assert(DefIdx != -1);
353   unsigned UseOpIdx;
354   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
355     return false;
356   unsigned Op1, Op2, NewDstIdx;
357   if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
358     return false;
359   if (Op1 == UseOpIdx)
360     NewDstIdx = Op2;
361   else if (Op2 == UseOpIdx)
362     NewDstIdx = Op1;
363   else
364     return false;
365
366   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
367   unsigned NewReg = NewDstMO.getReg();
368   if (NewReg != IntB.reg || !NewDstMO.isKill())
369     return false;
370
371   // Make sure there are no other definitions of IntB that would reach the
372   // uses which the new definition can reach.
373   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
374     return false;
375
376   // If some of the uses of IntA.reg is already coalesced away, return false.
377   // It's not possible to determine whether it's safe to perform the coalescing.
378   for (MachineRegisterInfo::use_nodbg_iterator UI = 
379          mri_->use_nodbg_begin(IntA.reg), 
380        UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
381     MachineInstr *UseMI = &*UI;
382     SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
383     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
384     if (ULR == IntA.end())
385       continue;
386     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
387       return false;
388   }
389
390   // At this point we have decided that it is legal to do this
391   // transformation.  Start by commuting the instruction.
392   MachineBasicBlock *MBB = DefMI->getParent();
393   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
394   if (!NewMI)
395     return false;
396   if (NewMI != DefMI) {
397     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
398     MBB->insert(DefMI, NewMI);
399     MBB->erase(DefMI);
400   }
401   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
402   NewMI->getOperand(OpIdx).setIsKill();
403
404   bool BHasPHIKill = BValNo->hasPHIKill();
405   SmallVector<VNInfo*, 4> BDeadValNos;
406   VNInfo::KillSet BKills;
407   std::map<SlotIndex, SlotIndex> BExtend;
408
409   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
410   // A = or A, B
411   // ...
412   // B = A
413   // ...
414   // C = A<kill>
415   // ...
416   //   = B
417   //
418   // then do not add kills of A to the newly created B interval.
419   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
420   if (Extended)
421     BExtend[ALR->end] = BLR->end;
422
423   // Update uses of IntA of the specific Val# with IntB.
424   bool BHasSubRegs = false;
425   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
426     BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
427   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
428          UE = mri_->use_end(); UI != UE;) {
429     MachineOperand &UseMO = UI.getOperand();
430     MachineInstr *UseMI = &*UI;
431     ++UI;
432     if (JoinedCopies.count(UseMI))
433       continue;
434     if (UseMI->isDebugValue()) {
435       // FIXME These don't have an instruction index.  Not clear we have enough
436       // info to decide whether to do this replacement or not.  For now do it.
437       UseMO.setReg(NewReg);
438       continue;
439     }
440     SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
441     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
442     if (ULR == IntA.end() || ULR->valno != AValNo)
443       continue;
444     UseMO.setReg(NewReg);
445     if (UseMI == CopyMI)
446       continue;
447     if (UseMO.isKill()) {
448       if (Extended)
449         UseMO.setIsKill(false);
450       else
451         BKills.push_back(UseIdx.getDefIndex());
452     }
453     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
454     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
455       continue;
456     if (DstReg == IntB.reg) {
457       // This copy will become a noop. If it's defining a new val#,
458       // remove that val# as well. However this live range is being
459       // extended to the end of the existing live range defined by the copy.
460       SlotIndex DefIdx = UseIdx.getDefIndex();
461       const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
462       BHasPHIKill |= DLR->valno->hasPHIKill();
463       assert(DLR->valno->def == DefIdx);
464       BDeadValNos.push_back(DLR->valno);
465       BExtend[DLR->start] = DLR->end;
466       JoinedCopies.insert(UseMI);
467       // If this is a kill but it's going to be removed, the last use
468       // of the same val# is the new kill.
469       if (UseMO.isKill())
470         BKills.pop_back();
471     }
472   }
473
474   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
475   // simply extend BLR if CopyMI doesn't end the range.
476   DEBUG({
477       dbgs() << "\nExtending: ";
478       IntB.print(dbgs(), tri_);
479     });
480
481   // Remove val#'s defined by copies that will be coalesced away.
482   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
483     VNInfo *DeadVNI = BDeadValNos[i];
484     if (BHasSubRegs) {
485       for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
486         LiveInterval &SRLI = li_->getInterval(*SR);
487         const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
488         SRLI.removeValNo(SRLR->valno);
489       }
490     }
491     IntB.removeValNo(BDeadValNos[i]);
492   }
493
494   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
495   // is updated. Kills are also updated.
496   VNInfo *ValNo = BValNo;
497   ValNo->def = AValNo->def;
498   ValNo->setCopy(0);
499   for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
500     if (ValNo->kills[j] != BLR->end)
501       BKills.push_back(ValNo->kills[j]);
502   }
503   ValNo->kills.clear();
504   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
505        AI != AE; ++AI) {
506     if (AI->valno != AValNo) continue;
507     SlotIndex End = AI->end;
508     std::map<SlotIndex, SlotIndex>::iterator
509       EI = BExtend.find(End);
510     if (EI != BExtend.end())
511       End = EI->second;
512     IntB.addRange(LiveRange(AI->start, End, ValNo));
513
514     // If the IntB live range is assigned to a physical register, and if that
515     // physreg has sub-registers, update their live intervals as well.
516     if (BHasSubRegs) {
517       for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
518         LiveInterval &SRLI = li_->getInterval(*SR);
519         SRLI.MergeInClobberRange(*li_, AI->start, End,
520                                  li_->getVNInfoAllocator());
521       }
522     }
523   }
524   IntB.addKills(ValNo, BKills);
525   ValNo->setHasPHIKill(BHasPHIKill);
526
527   DEBUG({
528       dbgs() << "   result = ";
529       IntB.print(dbgs(), tri_);
530       dbgs() << '\n';
531       dbgs() << "\nShortening: ";
532       IntA.print(dbgs(), tri_);
533     });
534
535   IntA.removeValNo(AValNo);
536
537   DEBUG({
538       dbgs() << "   result = ";
539       IntA.print(dbgs(), tri_);
540       dbgs() << '\n';
541     });
542
543   ++numCommutes;
544   return true;
545 }
546
547 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
548 /// fallthoughs to SuccMBB.
549 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
550                                   MachineBasicBlock *SuccMBB,
551                                   const TargetInstrInfo *tii_) {
552   if (MBB == SuccMBB)
553     return true;
554   MachineBasicBlock *TBB = 0, *FBB = 0;
555   SmallVector<MachineOperand, 4> Cond;
556   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
557     MBB->isSuccessor(SuccMBB);
558 }
559
560 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
561 /// from a physical register live interval as well as from the live intervals
562 /// of its sub-registers.
563 static void removeRange(LiveInterval &li,
564                         SlotIndex Start, SlotIndex End,
565                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
566   li.removeRange(Start, End, true);
567   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
568     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
569       if (!li_->hasInterval(*SR))
570         continue;
571       LiveInterval &sli = li_->getInterval(*SR);
572       SlotIndex RemoveStart = Start;
573       SlotIndex RemoveEnd = Start;
574
575       while (RemoveEnd != End) {
576         LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
577         if (LR == sli.end())
578           break;
579         RemoveEnd = (LR->end < End) ? LR->end : End;
580         sli.removeRange(RemoveStart, RemoveEnd, true);
581         RemoveStart = RemoveEnd;
582       }
583     }
584   }
585 }
586
587 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
588 /// as the copy instruction, trim the live interval to the last use and return
589 /// true.
590 bool
591 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
592                                                     MachineBasicBlock *CopyMBB,
593                                                     LiveInterval &li,
594                                                     const LiveRange *LR) {
595   SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
596   SlotIndex LastUseIdx;
597   MachineOperand *LastUse =
598     lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
599   if (LastUse) {
600     MachineInstr *LastUseMI = LastUse->getParent();
601     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
602       // r1024 = op
603       // ...
604       // BB1:
605       //       = r1024
606       //
607       // BB2:
608       // r1025<dead> = r1024<kill>
609       if (MBBStart < LR->end)
610         removeRange(li, MBBStart, LR->end, li_, tri_);
611       return true;
612     }
613
614     // There are uses before the copy, just shorten the live range to the end
615     // of last use.
616     LastUse->setIsKill();
617     removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
618     LR->valno->addKill(LastUseIdx.getDefIndex());
619     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
620     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
621         DstReg == li.reg) {
622       // Last use is itself an identity code.
623       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
624       LastUseMI->getOperand(DeadIdx).setIsDead();
625     }
626     return true;
627   }
628
629   // Is it livein?
630   if (LR->start <= MBBStart && LR->end > MBBStart) {
631     if (LR->start == li_->getZeroIndex()) {
632       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
633       // Live-in to the function but dead. Remove it from entry live-in set.
634       mf_->begin()->removeLiveIn(li.reg);
635     }
636     // FIXME: Shorten intervals in BBs that reaches this BB.
637   }
638
639   return false;
640 }
641
642 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
643 /// computation, replace the copy by rematerialize the definition.
644 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
645                                                        unsigned DstReg,
646                                                        unsigned DstSubIdx,
647                                                        MachineInstr *CopyMI) {
648   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
649   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
650   assert(SrcLR != SrcInt.end() && "Live range not found!");
651   VNInfo *ValNo = SrcLR->valno;
652   // If other defs can reach uses of this def, then it's not safe to perform
653   // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
654   // tested?
655   if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
656       ValNo->isUnused() || ValNo->hasPHIKill())
657     return false;
658   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
659   const TargetInstrDesc &TID = DefMI->getDesc();
660   if (!TID.isAsCheapAsAMove())
661     return false;
662   if (!tii_->isTriviallyReMaterializable(DefMI, AA))
663     return false;
664   bool SawStore = false;
665   if (!DefMI->isSafeToMove(tii_, SawStore, AA))
666     return false;
667   if (TID.getNumDefs() != 1)
668     return false;
669   if (!DefMI->isImplicitDef()) {
670     // Make sure the copy destination register class fits the instruction
671     // definition register class. The mismatch can happen as a result of earlier
672     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
673     const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
674     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
675       if (mri_->getRegClass(DstReg) != RC)
676         return false;
677     } else if (!RC->contains(DstReg))
678       return false;
679   }
680
681   // If destination register has a sub-register index on it, make sure it mtches
682   // the instruction register class.
683   if (DstSubIdx) {
684     const TargetInstrDesc &TID = DefMI->getDesc();
685     if (TID.getNumDefs() != 1)
686       return false;
687     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
688     const TargetRegisterClass *DstSubRC =
689       DstRC->getSubRegisterRegClass(DstSubIdx);
690     const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
691     if (DefRC == DstRC)
692       DstSubIdx = 0;
693     else if (DefRC != DstSubRC)
694       return false;
695   }
696
697   SlotIndex DefIdx = CopyIdx.getDefIndex();
698   const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
699   DLR->valno->setCopy(0);
700   // Don't forget to update sub-register intervals.
701   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
702     for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
703       if (!li_->hasInterval(*SR))
704         continue;
705       const LiveRange *DLR =
706           li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
707       if (DLR && DLR->valno->getCopy() == CopyMI)
708         DLR->valno->setCopy(0);
709     }
710   }
711
712   // If copy kills the source register, find the last use and propagate
713   // kill.
714   bool checkForDeadDef = false;
715   MachineBasicBlock *MBB = CopyMI->getParent();
716   if (CopyMI->killsRegister(SrcInt.reg))
717     if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
718       checkForDeadDef = true;
719     }
720
721   MachineBasicBlock::iterator MII =
722     llvm::next(MachineBasicBlock::iterator(CopyMI));
723   tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, tri_);
724   MachineInstr *NewMI = prior(MII);
725
726   if (checkForDeadDef) {
727     // PR4090 fix: Trim interval failed because there was no use of the
728     // source interval in this MBB. If the def is in this MBB too then we
729     // should mark it dead:
730     if (DefMI->getParent() == MBB) {
731       DefMI->addRegisterDead(SrcInt.reg, tri_);
732       SrcLR->end = SrcLR->start.getNextSlot();
733     }
734   }
735
736   // CopyMI may have implicit operands, transfer them over to the newly
737   // rematerialized instruction. And update implicit def interval valnos.
738   for (unsigned i = CopyMI->getDesc().getNumOperands(),
739          e = CopyMI->getNumOperands(); i != e; ++i) {
740     MachineOperand &MO = CopyMI->getOperand(i);
741     if (MO.isReg() && MO.isImplicit())
742       NewMI->addOperand(MO);
743     if (MO.isDef() && li_->hasInterval(MO.getReg())) {
744       unsigned Reg = MO.getReg();
745       const LiveRange *DLR =
746           li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
747       if (DLR && DLR->valno->getCopy() == CopyMI)
748         DLR->valno->setCopy(0);
749       // Handle subregs as well
750       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
751         for (const unsigned* SR = tri_->getSubRegisters(Reg); *SR; ++SR) {
752           if (!li_->hasInterval(*SR))
753             continue;
754           const LiveRange *DLR =
755               li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
756           if (DLR && DLR->valno->getCopy() == CopyMI)
757             DLR->valno->setCopy(0);
758         }
759       }
760     }
761   }
762
763   TransferImplicitOps(CopyMI, NewMI);
764   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
765   CopyMI->eraseFromParent();
766   ReMatCopies.insert(CopyMI);
767   ReMatDefs.insert(DefMI);
768   DEBUG(dbgs() << "Remat: " << *NewMI);
769   ++NumReMats;
770   return true;
771 }
772
773 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
774 /// update the subregister number if it is not zero. If DstReg is a
775 /// physical register and the existing subregister number of the def / use
776 /// being updated is not zero, make sure to set it to the correct physical
777 /// subregister.
778 void
779 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
780                                             unsigned SubIdx) {
781   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
782   if (DstIsPhys && SubIdx) {
783     // Figure out the real physical register we are updating with.
784     DstReg = tri_->getSubReg(DstReg, SubIdx);
785     SubIdx = 0;
786   }
787
788   // Copy the register use-list before traversing it. We may be adding operands
789   // and invalidating pointers.
790   SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
791   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
792          E = mri_->reg_end(); I != E; ++I)
793     reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
794
795   for (unsigned N=0; N != reglist.size(); ++N) {
796     MachineInstr *UseMI = reglist[N].first;
797     MachineOperand &O = UseMI->getOperand(reglist[N].second);
798     unsigned OldSubIdx = O.getSubReg();
799     if (DstIsPhys) {
800       unsigned UseDstReg = DstReg;
801       if (OldSubIdx)
802           UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
803
804       unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
805       if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
806                             CopySrcSubIdx, CopyDstSubIdx) &&
807           CopySrcReg != CopyDstReg &&
808           CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
809         // If the use is a copy and it won't be coalesced away, and its source
810         // is defined by a trivial computation, try to rematerialize it instead.
811         if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
812                                     CopyDstSubIdx, UseMI))
813           continue;
814       }
815
816       O.setReg(UseDstReg);
817       O.setSubReg(0);
818       if (OldSubIdx) {
819         // Def and kill of subregister of a virtual register actually defs and
820         // kills the whole register. Add imp-defs and imp-kills as needed.
821         if (O.isDef()) {
822           if(O.isDead())
823             UseMI->addRegisterDead(DstReg, tri_, true);
824           else
825             UseMI->addRegisterDefined(DstReg, tri_);
826         } else if (!O.isUndef() &&
827                    (O.isKill() ||
828                     UseMI->isRegTiedToDefOperand(&O-&UseMI->getOperand(0))))
829           UseMI->addRegisterKilled(DstReg, tri_, true);
830       }
831       continue;
832     }
833
834     // Sub-register indexes goes from small to large. e.g.
835     // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
836     // EAX: 1 -> AL, 2 -> AX
837     // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
838     // sub-register 2 is also AX.
839     if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
840       assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
841     else if (SubIdx)
842       O.setSubReg(SubIdx);
843     // Remove would-be duplicated kill marker.
844     if (O.isKill() && UseMI->killsRegister(DstReg))
845       O.setIsKill(false);
846     O.setReg(DstReg);
847
848     // After updating the operand, check if the machine instruction has
849     // become a copy. If so, update its val# information.
850     if (JoinedCopies.count(UseMI))
851       continue;
852
853     const TargetInstrDesc &TID = UseMI->getDesc();
854     unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
855     if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
856         tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
857                           CopySrcSubIdx, CopyDstSubIdx) &&
858         CopySrcReg != CopyDstReg &&
859         (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
860          allocatableRegs_[CopyDstReg])) {
861       LiveInterval &LI = li_->getInterval(CopyDstReg);
862       SlotIndex DefIdx =
863         li_->getInstructionIndex(UseMI).getDefIndex();
864       if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
865         if (DLR->valno->def == DefIdx)
866           DLR->valno->setCopy(UseMI);
867       }
868     }
869   }
870 }
871
872 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
873 /// due to live range lengthening as the result of coalescing.
874 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
875                                                       LiveInterval &LI) {
876   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
877          UE = mri_->use_end(); UI != UE; ++UI) {
878     MachineOperand &UseMO = UI.getOperand();
879     if (!UseMO.isKill())
880       continue;
881     MachineInstr *UseMI = UseMO.getParent();
882     SlotIndex UseIdx =
883       li_->getInstructionIndex(UseMI).getUseIndex();
884     const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
885     if (!LR ||
886         (!LR->valno->isKill(UseIdx.getDefIndex()) &&
887          LR->valno->def != UseIdx.getDefIndex())) {
888       // Interesting problem. After coalescing reg1027's def and kill are both
889       // at the same point:  %reg1027,0.000000e+00 = [56,814:0)  0@70-(814)
890       //
891       // bb5:
892       // 60   %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
893       // 68   %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
894       // 76   t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
895       // 84   %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
896       // 96   t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
897       //
898       // Do not remove the kill marker on t2LDRi12.
899       UseMO.setIsKill(false);
900     }
901   }
902 }
903
904 /// removeIntervalIfEmpty - Check if the live interval of a physical register
905 /// is empty, if so remove it and also remove the empty intervals of its
906 /// sub-registers. Return true if live interval is removed.
907 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
908                                   const TargetRegisterInfo *tri_) {
909   if (li.empty()) {
910     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
911       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
912         if (!li_->hasInterval(*SR))
913           continue;
914         LiveInterval &sli = li_->getInterval(*SR);
915         if (sli.empty())
916           li_->removeInterval(*SR);
917       }
918     li_->removeInterval(li.reg);
919     return true;
920   }
921   return false;
922 }
923
924 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
925 /// Return true if live interval is removed.
926 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
927                                                         MachineInstr *CopyMI) {
928   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
929   LiveInterval::iterator MLR =
930     li.FindLiveRangeContaining(CopyIdx.getDefIndex());
931   if (MLR == li.end())
932     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
933   SlotIndex RemoveStart = MLR->start;
934   SlotIndex RemoveEnd = MLR->end;
935   SlotIndex DefIdx = CopyIdx.getDefIndex();
936   // Remove the liverange that's defined by this.
937   if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
938     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
939     return removeIntervalIfEmpty(li, li_, tri_);
940   }
941   return false;
942 }
943
944 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
945 /// the val# it defines. If the live interval becomes empty, remove it as well.
946 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
947                                              MachineInstr *DefMI) {
948   SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
949   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
950   if (DefIdx != MLR->valno->def)
951     return false;
952   li.removeValNo(MLR->valno);
953   return removeIntervalIfEmpty(li, li_, tri_);
954 }
955
956 /// PropagateDeadness - Propagate the dead marker to the instruction which
957 /// defines the val#.
958 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
959                               SlotIndex &LRStart, LiveIntervals *li_,
960                               const TargetRegisterInfo* tri_) {
961   MachineInstr *DefMI =
962     li_->getInstructionFromIndex(LRStart.getDefIndex());
963   if (DefMI && DefMI != CopyMI) {
964     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
965     if (DeadIdx != -1)
966       DefMI->getOperand(DeadIdx).setIsDead();
967     else
968       DefMI->addOperand(MachineOperand::CreateReg(li.reg,
969                    /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
970     LRStart = LRStart.getNextSlot();
971   }
972 }
973
974 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
975 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
976 /// ends the live range there. If there isn't another use, then this live range
977 /// is dead. Return true if live interval is removed.
978 bool
979 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
980                                                       MachineInstr *CopyMI) {
981   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
982   if (CopyIdx == SlotIndex()) {
983     // FIXME: special case: function live in. It can be a general case if the
984     // first instruction index starts at > 0 value.
985     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
986     // Live-in to the function but dead. Remove it from entry live-in set.
987     if (mf_->begin()->isLiveIn(li.reg))
988       mf_->begin()->removeLiveIn(li.reg);
989     const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
990     removeRange(li, LR->start, LR->end, li_, tri_);
991     return removeIntervalIfEmpty(li, li_, tri_);
992   }
993
994   LiveInterval::iterator LR =
995     li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
996   if (LR == li.end())
997     // Livein but defined by a phi.
998     return false;
999
1000   SlotIndex RemoveStart = LR->start;
1001   SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
1002   if (LR->end > RemoveEnd)
1003     // More uses past this copy? Nothing to do.
1004     return false;
1005
1006   // If there is a last use in the same bb, we can't remove the live range.
1007   // Shorten the live interval and return.
1008   MachineBasicBlock *CopyMBB = CopyMI->getParent();
1009   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
1010     return false;
1011
1012   // There are other kills of the val#. Nothing to do.
1013   if (!li.isOnlyLROfValNo(LR))
1014     return false;
1015
1016   MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
1017   if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
1018     // If the live range starts in another mbb and the copy mbb is not a fall
1019     // through mbb, then we can only cut the range from the beginning of the
1020     // copy mbb.
1021     RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
1022
1023   if (LR->valno->def == RemoveStart) {
1024     // If the def MI defines the val# and this copy is the only kill of the
1025     // val#, then propagate the dead marker.
1026     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
1027     ++numDeadValNo;
1028
1029     if (LR->valno->isKill(RemoveEnd))
1030       LR->valno->removeKill(RemoveEnd);
1031   }
1032
1033   removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
1034   return removeIntervalIfEmpty(li, li_, tri_);
1035 }
1036
1037 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
1038 /// from an implicit def to another register can be coalesced away.
1039 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
1040                                                      LiveInterval &li,
1041                                                      LiveInterval &ImpLi) const{
1042   if (!CopyMI->killsRegister(ImpLi.reg))
1043     return false;
1044   // Make sure this is the only use.
1045   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1046          UE = mri_->use_end(); UI != UE;) {
1047     MachineInstr *UseMI = &*UI;
1048     ++UI;
1049     if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1050       continue;
1051     return false;
1052   }
1053   return true;
1054 }
1055
1056
1057 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1058 /// a virtual destination register with physical source register.
1059 bool
1060 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1061                                                      MachineBasicBlock *CopyMBB,
1062                                                      LiveInterval &DstInt,
1063                                                      LiveInterval &SrcInt) {
1064   // If the virtual register live interval is long but it has low use desity,
1065   // do not join them, instead mark the physical register as its allocation
1066   // preference.
1067   const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1068   unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1069   unsigned Length = li_->getApproximateInstructionCount(DstInt);
1070   if (Length > Threshold &&
1071       (((float)std::distance(mri_->use_nodbg_begin(DstInt.reg),
1072                              mri_->use_nodbg_end()) / Length) < 
1073         (1.0 / Threshold)))
1074     return false;
1075
1076   // If the virtual register live interval extends into a loop, turn down
1077   // aggressiveness.
1078   SlotIndex CopyIdx =
1079     li_->getInstructionIndex(CopyMI).getDefIndex();
1080   const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1081   if (!L) {
1082     // Let's see if the virtual register live interval extends into the loop.
1083     LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1084     assert(DLR != DstInt.end() && "Live range not found!");
1085     DLR = DstInt.FindLiveRangeContaining(DLR->end.getNextSlot());
1086     if (DLR != DstInt.end()) {
1087       CopyMBB = li_->getMBBFromIndex(DLR->start);
1088       L = loopInfo->getLoopFor(CopyMBB);
1089     }
1090   }
1091
1092   if (!L || Length <= Threshold)
1093     return true;
1094
1095   SlotIndex UseIdx = CopyIdx.getUseIndex();
1096   LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1097   MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1098   if (loopInfo->getLoopFor(SMBB) != L) {
1099     if (!loopInfo->isLoopHeader(CopyMBB))
1100       return false;
1101     // If vr's live interval extends pass the loop header, do not join.
1102     for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1103            SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1104       MachineBasicBlock *SuccMBB = *SI;
1105       if (SuccMBB == CopyMBB)
1106         continue;
1107       if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1108                           li_->getMBBEndIdx(SuccMBB)))
1109         return false;
1110     }
1111   }
1112   return true;
1113 }
1114
1115 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1116 /// copy from a virtual source register to a physical destination register.
1117 bool
1118 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1119                                                      MachineBasicBlock *CopyMBB,
1120                                                      LiveInterval &DstInt,
1121                                                      LiveInterval &SrcInt) {
1122   // If the virtual register live interval is long but it has low use density,
1123   // do not join them, instead mark the physical register as its allocation
1124   // preference.
1125   const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1126   unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1127   unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1128   if (Length > Threshold &&
1129       (((float)std::distance(mri_->use_nodbg_begin(SrcInt.reg),
1130                              mri_->use_nodbg_end()) / Length) < 
1131           (1.0 / Threshold)))
1132     return false;
1133
1134   if (SrcInt.empty())
1135     // Must be implicit_def.
1136     return false;
1137
1138   // If the virtual register live interval is defined or cross a loop, turn
1139   // down aggressiveness.
1140   SlotIndex CopyIdx =
1141     li_->getInstructionIndex(CopyMI).getDefIndex();
1142   SlotIndex UseIdx = CopyIdx.getUseIndex();
1143   LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1144   assert(SLR != SrcInt.end() && "Live range not found!");
1145   SLR = SrcInt.FindLiveRangeContaining(SLR->start.getPrevSlot());
1146   if (SLR == SrcInt.end())
1147     return true;
1148   MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1149   const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1150
1151   if (!L || Length <= Threshold)
1152     return true;
1153
1154   if (loopInfo->getLoopFor(CopyMBB) != L) {
1155     if (SMBB != L->getLoopLatch())
1156       return false;
1157     // If vr's live interval is extended from before the loop latch, do not
1158     // join.
1159     for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1160            PE = SMBB->pred_end(); PI != PE; ++PI) {
1161       MachineBasicBlock *PredMBB = *PI;
1162       if (PredMBB == SMBB)
1163         continue;
1164       if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1165                           li_->getMBBEndIdx(PredMBB)))
1166         return false;
1167     }
1168   }
1169   return true;
1170 }
1171
1172 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1173 /// two virtual registers from different register classes.
1174 bool
1175 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1176                                                 unsigned SmallReg,
1177                                                 unsigned Threshold) {
1178   // Then make sure the intervals are *short*.
1179   LiveInterval &LargeInt = li_->getInterval(LargeReg);
1180   LiveInterval &SmallInt = li_->getInterval(SmallReg);
1181   unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1182   unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1183   if (LargeSize > Threshold) {
1184     unsigned SmallUses = std::distance(mri_->use_nodbg_begin(SmallReg),
1185                                        mri_->use_nodbg_end());
1186     unsigned LargeUses = std::distance(mri_->use_nodbg_begin(LargeReg),
1187                                        mri_->use_nodbg_end());
1188     if (SmallUses*LargeSize < LargeUses*SmallSize)
1189       return false;
1190   }
1191   return true;
1192 }
1193
1194 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1195 /// register with a physical register, check if any of the virtual register
1196 /// operand is a sub-register use or def. If so, make sure it won't result
1197 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1198 /// vr1024 = extract_subreg vr1025, 1
1199 /// ...
1200 /// vr1024 = mov8rr AH
1201 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1202 /// AH does not have a super-reg whose sub-register 1 is AH.
1203 bool
1204 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1205                                                       unsigned VirtReg,
1206                                                       unsigned PhysReg) {
1207   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1208          E = mri_->reg_end(); I != E; ++I) {
1209     MachineOperand &O = I.getOperand();
1210     if (O.isDebug())
1211       continue;
1212     MachineInstr *MI = &*I;
1213     if (MI == CopyMI || JoinedCopies.count(MI))
1214       continue;
1215     unsigned SubIdx = O.getSubReg();
1216     if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1217       return true;
1218     if (MI->isExtractSubreg()) {
1219       SubIdx = MI->getOperand(2).getImm();
1220       if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1221         return true;
1222       if (O.isDef()) {
1223         unsigned SrcReg = MI->getOperand(1).getReg();
1224         const TargetRegisterClass *RC =
1225           TargetRegisterInfo::isPhysicalRegister(SrcReg)
1226           ? tri_->getPhysicalRegisterRegClass(SrcReg)
1227           : mri_->getRegClass(SrcReg);
1228         if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1229           return true;
1230       }
1231     }
1232     if (MI->isInsertSubreg() || MI->isSubregToReg()) {
1233       SubIdx = MI->getOperand(3).getImm();
1234       if (VirtReg == MI->getOperand(0).getReg()) {
1235         if (!tri_->getSubReg(PhysReg, SubIdx))
1236           return true;
1237       } else {
1238         unsigned DstReg = MI->getOperand(0).getReg();
1239         const TargetRegisterClass *RC =
1240           TargetRegisterInfo::isPhysicalRegister(DstReg)
1241           ? tri_->getPhysicalRegisterRegClass(DstReg)
1242           : mri_->getRegClass(DstReg);
1243         if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1244           return true;
1245       }
1246     }
1247   }
1248   return false;
1249 }
1250
1251
1252 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1253 /// an extract_subreg where dst is a physical register, e.g.
1254 /// cl = EXTRACT_SUBREG reg1024, 1
1255 bool
1256 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1257                                                unsigned SrcReg, unsigned SubIdx,
1258                                                unsigned &RealDstReg) {
1259   const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1260   RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1261   assert(RealDstReg && "Invalid extract_subreg instruction!");
1262
1263   // For this type of EXTRACT_SUBREG, conservatively
1264   // check if the live interval of the source register interfere with the
1265   // actual super physical register we are trying to coalesce with.
1266   LiveInterval &RHS = li_->getInterval(SrcReg);
1267   if (li_->hasInterval(RealDstReg) &&
1268       RHS.overlaps(li_->getInterval(RealDstReg))) {
1269     DEBUG({
1270         dbgs() << "Interfere with register ";
1271         li_->getInterval(RealDstReg).print(dbgs(), tri_);
1272       });
1273     return false; // Not coalescable
1274   }
1275   for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1276     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1277       DEBUG({
1278           dbgs() << "Interfere with sub-register ";
1279           li_->getInterval(*SR).print(dbgs(), tri_);
1280         });
1281       return false; // Not coalescable
1282     }
1283   return true;
1284 }
1285
1286 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1287 /// an insert_subreg where src is a physical register, e.g.
1288 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1289 bool
1290 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1291                                                unsigned SrcReg, unsigned SubIdx,
1292                                                unsigned &RealSrcReg) {
1293   const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1294   RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1295   assert(RealSrcReg && "Invalid extract_subreg instruction!");
1296
1297   LiveInterval &RHS = li_->getInterval(DstReg);
1298   if (li_->hasInterval(RealSrcReg) &&
1299       RHS.overlaps(li_->getInterval(RealSrcReg))) {
1300     DEBUG({
1301         dbgs() << "Interfere with register ";
1302         li_->getInterval(RealSrcReg).print(dbgs(), tri_);
1303       });
1304     return false; // Not coalescable
1305   }
1306   for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1307     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1308       DEBUG({
1309           dbgs() << "Interfere with sub-register ";
1310           li_->getInterval(*SR).print(dbgs(), tri_);
1311         });
1312       return false; // Not coalescable
1313     }
1314   return true;
1315 }
1316
1317 /// getRegAllocPreference - Return register allocation preference register.
1318 ///
1319 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1320                                       MachineRegisterInfo *MRI,
1321                                       const TargetRegisterInfo *TRI) {
1322   if (TargetRegisterInfo::isPhysicalRegister(Reg))
1323     return 0;
1324   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1325   return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1326 }
1327
1328 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1329 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1330 /// if the copy was successfully coalesced away. If it is not currently
1331 /// possible to coalesce this interval, but it may be possible if other
1332 /// things get coalesced, then it returns true by reference in 'Again'.
1333 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1334   MachineInstr *CopyMI = TheCopy.MI;
1335
1336   Again = false;
1337   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1338     return false; // Already done.
1339
1340   DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1341
1342   unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1343   bool isExtSubReg = CopyMI->isExtractSubreg();
1344   bool isInsSubReg = CopyMI->isInsertSubreg();
1345   bool isSubRegToReg = CopyMI->isSubregToReg();
1346   unsigned SubIdx = 0;
1347   if (isExtSubReg) {
1348     DstReg    = CopyMI->getOperand(0).getReg();
1349     DstSubIdx = CopyMI->getOperand(0).getSubReg();
1350     SrcReg    = CopyMI->getOperand(1).getReg();
1351     SrcSubIdx = CopyMI->getOperand(2).getImm();
1352   } else if (isInsSubReg || isSubRegToReg) {
1353     DstReg    = CopyMI->getOperand(0).getReg();
1354     DstSubIdx = CopyMI->getOperand(3).getImm();
1355     SrcReg    = CopyMI->getOperand(2).getReg();
1356     SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1357     if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1358       // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1359       // coalesced to a larger register so the subreg indices cancel out.
1360       DEBUG(dbgs() << "\tSource of insert_subreg or subreg_to_reg is already "
1361                       "coalesced to another register.\n");
1362       return false;  // Not coalescable.
1363     }
1364   } else if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
1365     if (SrcSubIdx && DstSubIdx && SrcSubIdx != DstSubIdx) {
1366       // e.g. %reg16404:1<def> = MOV8rr %reg16412:2<kill>
1367       Again = true;
1368       return false;  // Not coalescable.
1369     }
1370   } else {
1371     llvm_unreachable("Unrecognized copy instruction!");
1372   }
1373
1374   // If they are already joined we continue.
1375   if (SrcReg == DstReg) {
1376     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1377     return false;  // Not coalescable.
1378   }
1379
1380   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1381   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1382
1383   // If they are both physical registers, we cannot join them.
1384   if (SrcIsPhys && DstIsPhys) {
1385     DEBUG(dbgs() << "\tCan not coalesce physregs.\n");
1386     return false;  // Not coalescable.
1387   }
1388
1389   // We only join virtual registers with allocatable physical registers.
1390   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1391     DEBUG(dbgs() << "\tSrc reg is unallocatable physreg.\n");
1392     return false;  // Not coalescable.
1393   }
1394   if (DstIsPhys && !allocatableRegs_[DstReg]) {
1395     DEBUG(dbgs() << "\tDst reg is unallocatable physreg.\n");
1396     return false;  // Not coalescable.
1397   }
1398
1399   // Check that a physical source register is compatible with dst regclass
1400   if (SrcIsPhys) {
1401     unsigned SrcSubReg = SrcSubIdx ?
1402       tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1403     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1404     const TargetRegisterClass *DstSubRC = DstRC;
1405     if (DstSubIdx)
1406       DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1407     assert(DstSubRC && "Illegal subregister index");
1408     if (!DstSubRC->contains(SrcSubReg)) {
1409       DEBUG(dbgs() << "\tIncompatible destination regclass: "
1410                    << tri_->getName(SrcSubReg) << " not in "
1411                    << DstSubRC->getName() << ".\n");
1412       return false;             // Not coalescable.
1413     }
1414   }
1415
1416   // Check that a physical dst register is compatible with source regclass
1417   if (DstIsPhys) {
1418     unsigned DstSubReg = DstSubIdx ?
1419       tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1420     const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1421     const TargetRegisterClass *SrcSubRC = SrcRC;
1422     if (SrcSubIdx)
1423       SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1424     assert(SrcSubRC && "Illegal subregister index");
1425     if (!SrcSubRC->contains(DstSubReg)) {
1426       DEBUG(dbgs() << "\tIncompatible source regclass: "
1427                    << tri_->getName(DstSubReg) << " not in "
1428                    << SrcSubRC->getName() << ".\n");
1429       (void)DstSubReg;
1430       return false;             // Not coalescable.
1431     }
1432   }
1433
1434   // Should be non-null only when coalescing to a sub-register class.
1435   bool CrossRC = false;
1436   const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1437   const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1438   const TargetRegisterClass *NewRC = NULL;
1439   MachineBasicBlock *CopyMBB = CopyMI->getParent();
1440   unsigned RealDstReg = 0;
1441   unsigned RealSrcReg = 0;
1442   if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1443     SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1444     if (SrcIsPhys && isExtSubReg) {
1445       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1446       // coalesced with AX.
1447       unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1448       if (DstSubIdx) {
1449         // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1450         // coalesced to a larger register so the subreg indices cancel out.
1451         if (DstSubIdx != SubIdx) {
1452           DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1453           return false; // Not coalescable.
1454         }
1455       } else
1456         SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1457       SubIdx = 0;
1458     } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1459       // EAX = INSERT_SUBREG EAX, r1024, 0
1460       unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1461       if (SrcSubIdx) {
1462         // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1463         // coalesced to a larger register so the subreg indices cancel out.
1464         if (SrcSubIdx != SubIdx) {
1465           DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1466           return false; // Not coalescable.
1467         }
1468       } else
1469         DstReg = tri_->getSubReg(DstReg, SubIdx);
1470       SubIdx = 0;
1471     } else if ((DstIsPhys && isExtSubReg) ||
1472                (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1473       if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1474         DEBUG(dbgs() << "\tSrc of extract_subreg already coalesced with reg"
1475                      << " of a super-class.\n");
1476         return false; // Not coalescable.
1477       }
1478
1479       if (isExtSubReg) {
1480         if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1481           return false; // Not coalescable
1482       } else {
1483         if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1484           return false; // Not coalescable
1485       }
1486       SubIdx = 0;
1487     } else {
1488       unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1489         : CopyMI->getOperand(2).getSubReg();
1490       if (OldSubIdx) {
1491         if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1492           // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1493           // coalesced to a larger register so the subreg indices cancel out.
1494           // Also check if the other larger register is of the same register
1495           // class as the would be resulting register.
1496           SubIdx = 0;
1497         else {
1498           DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1499           return false; // Not coalescable.
1500         }
1501       }
1502       if (SubIdx) {
1503         if (!DstIsPhys && !SrcIsPhys) {
1504           if (isInsSubReg || isSubRegToReg) {
1505             NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1506           } else // extract_subreg {
1507             NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1508           }
1509         if (!NewRC) {
1510           DEBUG(dbgs() << "\t Conflicting sub-register indices.\n");
1511           return false;  // Not coalescable
1512         }
1513
1514         unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1515         unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1516         unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1517         if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1518           Again = true;  // May be possible to coalesce later.
1519           return false;
1520         }
1521       }
1522     }
1523   } else if (differingRegisterClasses(SrcReg, DstReg)) {
1524     if (DisableCrossClassJoin)
1525       return false;
1526     CrossRC = true;
1527
1528     // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1529     // with another? If it's the resulting destination register, then
1530     // the subidx must be propagated to uses (but only those defined
1531     // by the EXTRACT_SUBREG). If it's being coalesced into another
1532     // register, it should be safe because register is assumed to have
1533     // the register class of the super-register.
1534
1535     // Process moves where one of the registers have a sub-register index.
1536     MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1537     MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1538     SubIdx = DstMO->getSubReg();
1539     if (SubIdx) {
1540       if (SrcMO->getSubReg())
1541         // FIXME: can we handle this?
1542         return false;
1543       // This is not an insert_subreg but it looks like one.
1544       // e.g. %reg1024:4 = MOV32rr %EAX
1545       isInsSubReg = true;
1546       if (SrcIsPhys) {
1547         if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1548           return false; // Not coalescable
1549         SubIdx = 0;
1550       }
1551     } else {
1552       SubIdx = SrcMO->getSubReg();
1553       if (SubIdx) {
1554         // This is not a extract_subreg but it looks like one.
1555         // e.g. %cl = MOV16rr %reg1024:1
1556         isExtSubReg = true;
1557         if (DstIsPhys) {
1558           if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1559             return false; // Not coalescable
1560           SubIdx = 0;
1561         }
1562       }
1563     }
1564
1565     unsigned LargeReg = SrcReg;
1566     unsigned SmallReg = DstReg;
1567
1568     // Now determine the register class of the joined register.
1569     if (isExtSubReg) {
1570       if (SubIdx && DstRC && DstRC->isASubClass()) {
1571         // This is a move to a sub-register class. However, the source is a
1572         // sub-register of a larger register class. We don't know what should
1573         // the register class be. FIXME.
1574         Again = true;
1575         return false;
1576       }
1577       if (!DstIsPhys && !SrcIsPhys)
1578         NewRC = SrcRC;
1579     } else if (!SrcIsPhys && !DstIsPhys) {
1580       NewRC = getCommonSubClass(SrcRC, DstRC);
1581       if (!NewRC) {
1582         DEBUG(dbgs() << "\tDisjoint regclasses: "
1583                      << SrcRC->getName() << ", "
1584                      << DstRC->getName() << ".\n");
1585         return false;           // Not coalescable.
1586       }
1587       if (DstRC->getSize() > SrcRC->getSize())
1588         std::swap(LargeReg, SmallReg);
1589     }
1590
1591     // If we are joining two virtual registers and the resulting register
1592     // class is more restrictive (fewer register, smaller size). Check if it's
1593     // worth doing the merge.
1594     if (!SrcIsPhys && !DstIsPhys &&
1595         (isExtSubReg || DstRC->isASubClass()) &&
1596         !isWinToJoinCrossClass(LargeReg, SmallReg,
1597                                allocatableRCRegs_[NewRC].count())) {
1598       DEBUG(dbgs() << "\tSrc/Dest are different register classes: "
1599                    << SrcRC->getName() << "/"
1600                    << DstRC->getName() << " -> "
1601                    << NewRC->getName() << ".\n");
1602       // Allow the coalescer to try again in case either side gets coalesced to
1603       // a physical register that's compatible with the other side. e.g.
1604       // r1024 = MOV32to32_ r1025
1605       // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1606       Again = true;  // May be possible to coalesce later.
1607       return false;
1608     }
1609   }
1610
1611   // Will it create illegal extract_subreg / insert_subreg?
1612   if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1613     return false;
1614   if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1615     return false;
1616
1617   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1618   LiveInterval &DstInt = li_->getInterval(DstReg);
1619   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1620          "Register mapping is horribly broken!");
1621
1622   DEBUG({
1623       dbgs() << "\t\tInspecting "; SrcInt.print(dbgs(), tri_);
1624       dbgs() << " and "; DstInt.print(dbgs(), tri_);
1625       dbgs() << ": ";
1626     });
1627
1628   // Save a copy of the virtual register live interval. We'll manually
1629   // merge this into the "real" physical register live interval this is
1630   // coalesced with.
1631   LiveInterval *SavedLI = 0;
1632   if (RealDstReg)
1633     SavedLI = li_->dupInterval(&SrcInt);
1634   else if (RealSrcReg)
1635     SavedLI = li_->dupInterval(&DstInt);
1636
1637   // Check if it is necessary to propagate "isDead" property.
1638   if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1639     MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1640     bool isDead = mopd->isDead();
1641
1642     // We need to be careful about coalescing a source physical register with a
1643     // virtual register. Once the coalescing is done, it cannot be broken and
1644     // these are not spillable! If the destination interval uses are far away,
1645     // think twice about coalescing them!
1646     if (!isDead && (SrcIsPhys || DstIsPhys)) {
1647       // If the copy is in a loop, take care not to coalesce aggressively if the
1648       // src is coming in from outside the loop (or the dst is out of the loop).
1649       // If it's not in a loop, then determine whether to join them base purely
1650       // by the length of the interval.
1651       if (PhysJoinTweak) {
1652         if (SrcIsPhys) {
1653           if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1654             mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1655             ++numAborts;
1656             DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1657             Again = true;  // May be possible to coalesce later.
1658             return false;
1659           }
1660         } else {
1661           if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1662             mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1663             ++numAborts;
1664             DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1665             Again = true;  // May be possible to coalesce later.
1666             return false;
1667           }
1668         }
1669       } else {
1670         // If the virtual register live interval is long but it has low use
1671         // density, do not join them, instead mark the physical register as its
1672         // allocation preference.
1673         LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1674         unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1675         unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1676         const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1677         unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1678         unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1679         float Ratio = 1.0 / Threshold;
1680         if (Length > Threshold &&
1681             (((float)std::distance(mri_->use_nodbg_begin(JoinVReg),
1682                                    mri_->use_nodbg_end()) / Length) < Ratio)) {
1683           mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1684           ++numAborts;
1685           DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1686           Again = true;  // May be possible to coalesce later.
1687           return false;
1688         }
1689       }
1690     }
1691   }
1692
1693   // Okay, attempt to join these two intervals.  On failure, this returns false.
1694   // Otherwise, if one of the intervals being joined is a physreg, this method
1695   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1696   // been modified, so we can use this information below to update aliases.
1697   bool Swapped = false;
1698   // If SrcInt is implicitly defined, it's safe to coalesce.
1699   bool isEmpty = SrcInt.empty();
1700   if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1701     // Only coalesce an empty interval (defined by implicit_def) with
1702     // another interval which has a valno defined by the CopyMI and the CopyMI
1703     // is a kill of the implicit def.
1704     DEBUG(dbgs() << "Not profitable!\n");
1705     return false;
1706   }
1707
1708   if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1709     // Coalescing failed.
1710
1711     // If definition of source is defined by trivial computation, try
1712     // rematerializing it.
1713     if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1714         ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1715       return true;
1716
1717     // If we can eliminate the copy without merging the live ranges, do so now.
1718     if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1719         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1720          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1721       JoinedCopies.insert(CopyMI);
1722       DEBUG(dbgs() << "Trivial!\n");
1723       return true;
1724     }
1725
1726     // Otherwise, we are unable to join the intervals.
1727     DEBUG(dbgs() << "Interference!\n");
1728     Again = true;  // May be possible to coalesce later.
1729     return false;
1730   }
1731
1732   LiveInterval *ResSrcInt = &SrcInt;
1733   LiveInterval *ResDstInt = &DstInt;
1734   if (Swapped) {
1735     std::swap(SrcReg, DstReg);
1736     std::swap(ResSrcInt, ResDstInt);
1737   }
1738   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1739          "LiveInterval::join didn't work right!");
1740
1741   // If we're about to merge live ranges into a physical register live interval,
1742   // we have to update any aliased register's live ranges to indicate that they
1743   // have clobbered values for this range.
1744   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1745     // If this is a extract_subreg where dst is a physical register, e.g.
1746     // cl = EXTRACT_SUBREG reg1024, 1
1747     // then create and update the actual physical register allocated to RHS.
1748     if (RealDstReg || RealSrcReg) {
1749       LiveInterval &RealInt =
1750         li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1751       for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1752              E = SavedLI->vni_end(); I != E; ++I) {
1753         const VNInfo *ValNo = *I;
1754         VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1755                                                 false, // updated at *
1756                                                 li_->getVNInfoAllocator());
1757         NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1758         RealInt.addKills(NewValNo, ValNo->kills);
1759         RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1760       }
1761       RealInt.weight += SavedLI->weight;
1762       DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1763     }
1764
1765     // Update the liveintervals of sub-registers.
1766     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1767       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, *ResSrcInt,
1768                                                  li_->getVNInfoAllocator());
1769   }
1770
1771   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1772   // larger super-register.
1773   if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1774       !SrcIsPhys && !DstIsPhys) {
1775     if ((isExtSubReg && !Swapped) ||
1776         ((isInsSubReg || isSubRegToReg) && Swapped)) {
1777       ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1778       std::swap(SrcReg, DstReg);
1779       std::swap(ResSrcInt, ResDstInt);
1780     }
1781   }
1782
1783   // Coalescing to a virtual register that is of a sub-register class of the
1784   // other. Make sure the resulting register is set to the right register class.
1785   if (CrossRC)
1786     ++numCrossRCs;
1787
1788   // This may happen even if it's cross-rc coalescing. e.g.
1789   // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1790   // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1791   // be allocate a register from GR64_ABCD.
1792   if (NewRC)
1793     mri_->setRegClass(DstReg, NewRC);
1794
1795   // Remember to delete the copy instruction.
1796   JoinedCopies.insert(CopyMI);
1797
1798   // Some live range has been lengthened due to colaescing, eliminate the
1799   // unnecessary kills.
1800   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1801   if (TargetRegisterInfo::isVirtualRegister(DstReg))
1802     RemoveUnnecessaryKills(DstReg, *ResDstInt);
1803
1804   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1805
1806   // If we have extended the live range of a physical register, make sure we
1807   // update live-in lists as well.
1808   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1809     const LiveInterval &VRegInterval = li_->getInterval(SrcReg);
1810     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1811     for (LiveInterval::const_iterator I = VRegInterval.begin(),
1812            E = VRegInterval.end(); I != E; ++I ) {
1813       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1814       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1815         MachineBasicBlock &block = *BlockSeq[idx];
1816         if (!block.isLiveIn(DstReg))
1817           block.addLiveIn(DstReg);
1818       }
1819       BlockSeq.clear();
1820     }
1821   }
1822
1823   // SrcReg is guarateed to be the register whose live interval that is
1824   // being merged.
1825   li_->removeInterval(SrcReg);
1826
1827   // Update regalloc hint.
1828   tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1829
1830   // Manually deleted the live interval copy.
1831   if (SavedLI) {
1832     SavedLI->clear();
1833     delete SavedLI;
1834   }
1835
1836   // If resulting interval has a preference that no longer fits because of subreg
1837   // coalescing, just clear the preference.
1838   unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1839   if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1840       TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1841     const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1842     if (!RC->contains(Preference))
1843       mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1844   }
1845
1846   DEBUG({
1847       dbgs() << "\n\t\tJoined.  Result = ";
1848       ResDstInt->print(dbgs(), tri_);
1849       dbgs() << "\n";
1850     });
1851
1852   ++numJoins;
1853   return true;
1854 }
1855
1856 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1857 /// compute what the resultant value numbers for each value in the input two
1858 /// ranges will be.  This is complicated by copies between the two which can
1859 /// and will commonly cause multiple value numbers to be merged into one.
1860 ///
1861 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1862 /// keeps track of the new InstDefiningValue assignment for the result
1863 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1864 /// whether a value in this or other is a copy from the opposite set.
1865 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1866 /// already been assigned.
1867 ///
1868 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1869 /// contains the value number the copy is from.
1870 ///
1871 static unsigned ComputeUltimateVN(VNInfo *VNI,
1872                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1873                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1874                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1875                                   SmallVector<int, 16> &ThisValNoAssignments,
1876                                   SmallVector<int, 16> &OtherValNoAssignments) {
1877   unsigned VN = VNI->id;
1878
1879   // If the VN has already been computed, just return it.
1880   if (ThisValNoAssignments[VN] >= 0)
1881     return ThisValNoAssignments[VN];
1882   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1883
1884   // If this val is not a copy from the other val, then it must be a new value
1885   // number in the destination.
1886   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1887   if (I == ThisFromOther.end()) {
1888     NewVNInfo.push_back(VNI);
1889     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1890   }
1891   VNInfo *OtherValNo = I->second;
1892
1893   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1894   // been computed, return it.
1895   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1896     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1897
1898   // Mark this value number as currently being computed, then ask what the
1899   // ultimate value # of the other value is.
1900   ThisValNoAssignments[VN] = -2;
1901   unsigned UltimateVN =
1902     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1903                       OtherValNoAssignments, ThisValNoAssignments);
1904   return ThisValNoAssignments[VN] = UltimateVN;
1905 }
1906
1907 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1908   return std::find(V.begin(), V.end(), Val) != V.end();
1909 }
1910
1911 static bool isValNoDefMove(const MachineInstr *MI, unsigned DR, unsigned SR,
1912                            const TargetInstrInfo *TII,
1913                            const TargetRegisterInfo *TRI) {
1914   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1915   if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1916     ;
1917   else if (MI->isExtractSubreg()) {
1918     DstReg = MI->getOperand(0).getReg();
1919     SrcReg = MI->getOperand(1).getReg();
1920   } else if (MI->isSubregToReg() ||
1921              MI->isInsertSubreg()) {
1922     DstReg = MI->getOperand(0).getReg();
1923     SrcReg = MI->getOperand(2).getReg();
1924   } else
1925     return false;
1926   return (SrcReg == SR || TRI->isSuperRegister(SR, SrcReg)) &&
1927          (DstReg == DR || TRI->isSuperRegister(DR, DstReg));
1928 }
1929
1930 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1931 /// the specified live interval is defined by a copy from the specified
1932 /// register.
1933 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1934                                                            LiveRange *LR,
1935                                                            unsigned Reg) {
1936   unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1937   if (SrcReg == Reg)
1938     return true;
1939   // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1940   if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1941       TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1942       *tri_->getSuperRegisters(li.reg)) {
1943     // It's a sub-register live interval, we may not have precise information.
1944     // Re-compute it.
1945     MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1946     if (DefMI && isValNoDefMove(DefMI, li.reg, Reg, tii_, tri_)) {
1947       // Cache computed info.
1948       LR->valno->def = LR->start;
1949       LR->valno->setCopy(DefMI);
1950       return true;
1951     }
1952   }
1953   return false;
1954 }
1955
1956
1957 /// ValueLiveAt - Return true if the LiveRange pointed to by the given
1958 /// iterator, or any subsequent range with the same value number,
1959 /// is live at the given point.
1960 bool SimpleRegisterCoalescing::ValueLiveAt(LiveInterval::iterator LRItr,
1961                                            LiveInterval::iterator LREnd,
1962                                            SlotIndex defPoint) const {
1963   for (const VNInfo *valno = LRItr->valno;
1964        (LRItr != LREnd) && (LRItr->valno == valno); ++LRItr) {
1965     if (LRItr->contains(defPoint))
1966       return true;
1967   }
1968
1969   return false;
1970 }
1971
1972
1973 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1974 /// caller of this method must guarantee that the RHS only contains a single
1975 /// value number and that the RHS is not defined by a copy from this
1976 /// interval.  This returns false if the intervals are not joinable, or it
1977 /// joins them and returns true.
1978 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1979   assert(RHS.containsOneValue());
1980
1981   // Some number (potentially more than one) value numbers in the current
1982   // interval may be defined as copies from the RHS.  Scan the overlapping
1983   // portions of the LHS and RHS, keeping track of this and looking for
1984   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1985   // cannot coalesce.
1986
1987   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1988   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1989
1990   if (LHSIt->start < RHSIt->start) {
1991     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1992     if (LHSIt != LHS.begin()) --LHSIt;
1993   } else if (RHSIt->start < LHSIt->start) {
1994     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1995     if (RHSIt != RHS.begin()) --RHSIt;
1996   }
1997
1998   SmallVector<VNInfo*, 8> EliminatedLHSVals;
1999
2000   while (1) {
2001     // Determine if these live intervals overlap.
2002     bool Overlaps = false;
2003     if (LHSIt->start <= RHSIt->start)
2004       Overlaps = LHSIt->end > RHSIt->start;
2005     else
2006       Overlaps = RHSIt->end > LHSIt->start;
2007
2008     // If the live intervals overlap, there are two interesting cases: if the
2009     // LHS interval is defined by a copy from the RHS, it's ok and we record
2010     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
2011     // coalesce these live ranges and we bail out.
2012     if (Overlaps) {
2013       // If we haven't already recorded that this value # is safe, check it.
2014       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
2015         // If it's re-defined by an early clobber somewhere in the live range,
2016         // then conservatively abort coalescing.
2017         if (LHSIt->valno->hasRedefByEC())
2018           return false;
2019         // Copy from the RHS?
2020         if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
2021           return false;    // Nope, bail out.
2022
2023         if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
2024           // Here is an interesting situation:
2025           // BB1:
2026           //   vr1025 = copy vr1024
2027           //   ..
2028           // BB2:
2029           //   vr1024 = op
2030           //          = vr1025
2031           // Even though vr1025 is copied from vr1024, it's not safe to
2032           // coalesce them since the live range of vr1025 intersects the
2033           // def of vr1024. This happens because vr1025 is assigned the
2034           // value of the previous iteration of vr1024.
2035           return false;
2036         EliminatedLHSVals.push_back(LHSIt->valno);
2037       }
2038
2039       // We know this entire LHS live range is okay, so skip it now.
2040       if (++LHSIt == LHSEnd) break;
2041       continue;
2042     }
2043
2044     if (LHSIt->end < RHSIt->end) {
2045       if (++LHSIt == LHSEnd) break;
2046     } else {
2047       // One interesting case to check here.  It's possible that we have
2048       // something like "X3 = Y" which defines a new value number in the LHS,
2049       // and is the last use of this liverange of the RHS.  In this case, we
2050       // want to notice this copy (so that it gets coalesced away) even though
2051       // the live ranges don't actually overlap.
2052       if (LHSIt->start == RHSIt->end) {
2053         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
2054           // We already know that this value number is going to be merged in
2055           // if coalescing succeeds.  Just skip the liverange.
2056           if (++LHSIt == LHSEnd) break;
2057         } else {
2058           // If it's re-defined by an early clobber somewhere in the live range,
2059           // then conservatively abort coalescing.
2060           if (LHSIt->valno->hasRedefByEC())
2061             return false;
2062           // Otherwise, if this is a copy from the RHS, mark it as being merged
2063           // in.
2064           if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
2065             if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
2066               // Here is an interesting situation:
2067               // BB1:
2068               //   vr1025 = copy vr1024
2069               //   ..
2070               // BB2:
2071               //   vr1024 = op
2072               //          = vr1025
2073               // Even though vr1025 is copied from vr1024, it's not safe to
2074               // coalesced them since live range of vr1025 intersects the
2075               // def of vr1024. This happens because vr1025 is assigned the
2076               // value of the previous iteration of vr1024.
2077               return false;
2078             EliminatedLHSVals.push_back(LHSIt->valno);
2079
2080             // We know this entire LHS live range is okay, so skip it now.
2081             if (++LHSIt == LHSEnd) break;
2082           }
2083         }
2084       }
2085
2086       if (++RHSIt == RHSEnd) break;
2087     }
2088   }
2089
2090   // If we got here, we know that the coalescing will be successful and that
2091   // the value numbers in EliminatedLHSVals will all be merged together.  Since
2092   // the most common case is that EliminatedLHSVals has a single number, we
2093   // optimize for it: if there is more than one value, we merge them all into
2094   // the lowest numbered one, then handle the interval as if we were merging
2095   // with one value number.
2096   VNInfo *LHSValNo = NULL;
2097   if (EliminatedLHSVals.size() > 1) {
2098     // Loop through all the equal value numbers merging them into the smallest
2099     // one.
2100     VNInfo *Smallest = EliminatedLHSVals[0];
2101     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
2102       if (EliminatedLHSVals[i]->id < Smallest->id) {
2103         // Merge the current notion of the smallest into the smaller one.
2104         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
2105         Smallest = EliminatedLHSVals[i];
2106       } else {
2107         // Merge into the smallest.
2108         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
2109       }
2110     }
2111     LHSValNo = Smallest;
2112   } else if (EliminatedLHSVals.empty()) {
2113     if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2114         *tri_->getSuperRegisters(LHS.reg))
2115       // Imprecise sub-register information. Can't handle it.
2116       return false;
2117     llvm_unreachable("No copies from the RHS?");
2118   } else {
2119     LHSValNo = EliminatedLHSVals[0];
2120   }
2121
2122   // Okay, now that there is a single LHS value number that we're merging the
2123   // RHS into, update the value number info for the LHS to indicate that the
2124   // value number is defined where the RHS value number was.
2125   const VNInfo *VNI = RHS.getValNumInfo(0);
2126   LHSValNo->def  = VNI->def;
2127   LHSValNo->setCopy(VNI->getCopy());
2128
2129   // Okay, the final step is to loop over the RHS live intervals, adding them to
2130   // the LHS.
2131   if (VNI->hasPHIKill())
2132     LHSValNo->setHasPHIKill(true);
2133   LHS.addKills(LHSValNo, VNI->kills);
2134   LHS.MergeRangesInAsValue(RHS, LHSValNo);
2135
2136   LHS.ComputeJoinedWeight(RHS);
2137
2138   // Update regalloc hint if both are virtual registers.
2139   if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2140       TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2141     std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2142     std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2143     if (RHSPref != LHSPref)
2144       mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2145   }
2146
2147   // Update the liveintervals of sub-registers.
2148   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2149     for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2150       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, LHS,
2151                                                     li_->getVNInfoAllocator());
2152
2153   return true;
2154 }
2155
2156 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
2157 /// returns false.  Otherwise, if one of the intervals being joined is a
2158 /// physreg, this method always canonicalizes LHS to be it.  The output
2159 /// "RHS" will not have been modified, so we can use this information
2160 /// below to update aliases.
2161 bool
2162 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2163                                         bool &Swapped) {
2164   // Compute the final value assignment, assuming that the live ranges can be
2165   // coalesced.
2166   SmallVector<int, 16> LHSValNoAssignments;
2167   SmallVector<int, 16> RHSValNoAssignments;
2168   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2169   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2170   SmallVector<VNInfo*, 16> NewVNInfo;
2171
2172   // If a live interval is a physical register, conservatively check if any
2173   // of its sub-registers is overlapping the live interval of the virtual
2174   // register. If so, do not coalesce.
2175   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2176       *tri_->getSubRegisters(LHS.reg)) {
2177     // If it's coalescing a virtual register to a physical register, estimate
2178     // its live interval length. This is the *cost* of scanning an entire live
2179     // interval. If the cost is low, we'll do an exhaustive check instead.
2180
2181     // If this is something like this:
2182     // BB1:
2183     // v1024 = op
2184     // ...
2185     // BB2:
2186     // ...
2187     // RAX   = v1024
2188     //
2189     // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2190     // less conservative check. It's possible a sub-register is defined before
2191     // v1024 (or live in) and live out of BB1.
2192     if (RHS.containsOneValue() &&
2193         li_->intervalIsInOneMBB(RHS) &&
2194         li_->getApproximateInstructionCount(RHS) <= 10) {
2195       // Perform a more exhaustive check for some common cases.
2196       if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2197         return false;
2198     } else {
2199       for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2200         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2201           DEBUG({
2202               dbgs() << "Interfere with sub-register ";
2203               li_->getInterval(*SR).print(dbgs(), tri_);
2204             });
2205           return false;
2206         }
2207     }
2208   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2209              *tri_->getSubRegisters(RHS.reg)) {
2210     if (LHS.containsOneValue() &&
2211         li_->getApproximateInstructionCount(LHS) <= 10) {
2212       // Perform a more exhaustive check for some common cases.
2213       if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2214         return false;
2215     } else {
2216       for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2217         if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2218           DEBUG({
2219               dbgs() << "Interfere with sub-register ";
2220               li_->getInterval(*SR).print(dbgs(), tri_);
2221             });
2222           return false;
2223         }
2224     }
2225   }
2226
2227   // Compute ultimate value numbers for the LHS and RHS values.
2228   if (RHS.containsOneValue()) {
2229     // Copies from a liveinterval with a single value are simple to handle and
2230     // very common, handle the special case here.  This is important, because
2231     // often RHS is small and LHS is large (e.g. a physreg).
2232
2233     // Find out if the RHS is defined as a copy from some value in the LHS.
2234     int RHSVal0DefinedFromLHS = -1;
2235     int RHSValID = -1;
2236     VNInfo *RHSValNoInfo = NULL;
2237     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2238     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2239     if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2240       // If RHS is not defined as a copy from the LHS, we can use simpler and
2241       // faster checks to see if the live ranges are coalescable.  This joiner
2242       // can't swap the LHS/RHS intervals though.
2243       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2244         return SimpleJoin(LHS, RHS);
2245       } else {
2246         RHSValNoInfo = RHSValNoInfo0;
2247       }
2248     } else {
2249       // It was defined as a copy from the LHS, find out what value # it is.
2250       RHSValNoInfo =
2251         LHS.getLiveRangeContaining(RHSValNoInfo0->def.getPrevSlot())->valno;
2252       RHSValID = RHSValNoInfo->id;
2253       RHSVal0DefinedFromLHS = RHSValID;
2254     }
2255
2256     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2257     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2258     NewVNInfo.resize(LHS.getNumValNums(), NULL);
2259
2260     // Okay, *all* of the values in LHS that are defined as a copy from RHS
2261     // should now get updated.
2262     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2263          i != e; ++i) {
2264       VNInfo *VNI = *i;
2265       unsigned VN = VNI->id;
2266       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2267         if (LHSSrcReg != RHS.reg) {
2268           // If this is not a copy from the RHS, its value number will be
2269           // unmodified by the coalescing.
2270           NewVNInfo[VN] = VNI;
2271           LHSValNoAssignments[VN] = VN;
2272         } else if (RHSValID == -1) {
2273           // Otherwise, it is a copy from the RHS, and we don't already have a
2274           // value# for it.  Keep the current value number, but remember it.
2275           LHSValNoAssignments[VN] = RHSValID = VN;
2276           NewVNInfo[VN] = RHSValNoInfo;
2277           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2278         } else {
2279           // Otherwise, use the specified value #.
2280           LHSValNoAssignments[VN] = RHSValID;
2281           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
2282             NewVNInfo[VN] = RHSValNoInfo;
2283             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2284           }
2285         }
2286       } else {
2287         NewVNInfo[VN] = VNI;
2288         LHSValNoAssignments[VN] = VN;
2289       }
2290     }
2291
2292     assert(RHSValID != -1 && "Didn't find value #?");
2293     RHSValNoAssignments[0] = RHSValID;
2294     if (RHSVal0DefinedFromLHS != -1) {
2295       // This path doesn't go through ComputeUltimateVN so just set
2296       // it to anything.
2297       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2298     }
2299   } else {
2300     // Loop over the value numbers of the LHS, seeing if any are defined from
2301     // the RHS.
2302     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2303          i != e; ++i) {
2304       VNInfo *VNI = *i;
2305       if (VNI->isUnused() || VNI->getCopy() == 0)  // Src not defined by a copy?
2306         continue;
2307
2308       // DstReg is known to be a register in the LHS interval.  If the src is
2309       // from the RHS interval, we can use its value #.
2310       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2311         continue;
2312
2313       // Figure out the value # from the RHS.
2314       LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
2315       assert(lr && "Cannot find live range");
2316       LHSValsDefinedFromRHS[VNI] = lr->valno;
2317     }
2318
2319     // Loop over the value numbers of the RHS, seeing if any are defined from
2320     // the LHS.
2321     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2322          i != e; ++i) {
2323       VNInfo *VNI = *i;
2324       if (VNI->isUnused() || VNI->getCopy() == 0)  // Src not defined by a copy?
2325         continue;
2326
2327       // DstReg is known to be a register in the RHS interval.  If the src is
2328       // from the LHS interval, we can use its value #.
2329       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2330         continue;
2331
2332       // Figure out the value # from the LHS.
2333       LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
2334       assert(lr && "Cannot find live range");
2335       RHSValsDefinedFromLHS[VNI] = lr->valno;
2336     }
2337
2338     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2339     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2340     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2341
2342     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2343          i != e; ++i) {
2344       VNInfo *VNI = *i;
2345       unsigned VN = VNI->id;
2346       if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2347         continue;
2348       ComputeUltimateVN(VNI, NewVNInfo,
2349                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2350                         LHSValNoAssignments, RHSValNoAssignments);
2351     }
2352     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2353          i != e; ++i) {
2354       VNInfo *VNI = *i;
2355       unsigned VN = VNI->id;
2356       if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2357         continue;
2358       // If this value number isn't a copy from the LHS, it's a new number.
2359       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2360         NewVNInfo.push_back(VNI);
2361         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2362         continue;
2363       }
2364
2365       ComputeUltimateVN(VNI, NewVNInfo,
2366                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2367                         RHSValNoAssignments, LHSValNoAssignments);
2368     }
2369   }
2370
2371   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2372   // interval lists to see if these intervals are coalescable.
2373   LiveInterval::const_iterator I = LHS.begin();
2374   LiveInterval::const_iterator IE = LHS.end();
2375   LiveInterval::const_iterator J = RHS.begin();
2376   LiveInterval::const_iterator JE = RHS.end();
2377
2378   // Skip ahead until the first place of potential sharing.
2379   if (I->start < J->start) {
2380     I = std::upper_bound(I, IE, J->start);
2381     if (I != LHS.begin()) --I;
2382   } else if (J->start < I->start) {
2383     J = std::upper_bound(J, JE, I->start);
2384     if (J != RHS.begin()) --J;
2385   }
2386
2387   while (1) {
2388     // Determine if these two live ranges overlap.
2389     bool Overlaps;
2390     if (I->start < J->start) {
2391       Overlaps = I->end > J->start;
2392     } else {
2393       Overlaps = J->end > I->start;
2394     }
2395
2396     // If so, check value # info to determine if they are really different.
2397     if (Overlaps) {
2398       // If the live range overlap will map to the same value number in the
2399       // result liverange, we can still coalesce them.  If not, we can't.
2400       if (LHSValNoAssignments[I->valno->id] !=
2401           RHSValNoAssignments[J->valno->id])
2402         return false;
2403       // If it's re-defined by an early clobber somewhere in the live range,
2404       // then conservatively abort coalescing.
2405       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
2406         return false;
2407     }
2408
2409     if (I->end < J->end) {
2410       ++I;
2411       if (I == IE) break;
2412     } else {
2413       ++J;
2414       if (J == JE) break;
2415     }
2416   }
2417
2418   // Update kill info. Some live ranges are extended due to copy coalescing.
2419   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2420          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2421     VNInfo *VNI = I->first;
2422     unsigned LHSValID = LHSValNoAssignments[VNI->id];
2423     NewVNInfo[LHSValID]->removeKill(VNI->def);
2424     if (VNI->hasPHIKill())
2425       NewVNInfo[LHSValID]->setHasPHIKill(true);
2426     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2427   }
2428
2429   // Update kill info. Some live ranges are extended due to copy coalescing.
2430   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2431          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2432     VNInfo *VNI = I->first;
2433     unsigned RHSValID = RHSValNoAssignments[VNI->id];
2434     NewVNInfo[RHSValID]->removeKill(VNI->def);
2435     if (VNI->hasPHIKill())
2436       NewVNInfo[RHSValID]->setHasPHIKill(true);
2437     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2438   }
2439
2440   // If we get here, we know that we can coalesce the live ranges.  Ask the
2441   // intervals to coalesce themselves now.
2442   if ((RHS.ranges.size() > LHS.ranges.size() &&
2443       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2444       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2445     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2446              mri_);
2447     Swapped = true;
2448   } else {
2449     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2450              mri_);
2451     Swapped = false;
2452   }
2453   return true;
2454 }
2455
2456 namespace {
2457   // DepthMBBCompare - Comparison predicate that sort first based on the loop
2458   // depth of the basic block (the unsigned), and then on the MBB number.
2459   struct DepthMBBCompare {
2460     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2461     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2462       // Deeper loops first
2463       if (LHS.first != RHS.first)
2464         return LHS.first > RHS.first;
2465
2466       // Prefer blocks that are more connected in the CFG. This takes care of
2467       // the most difficult copies first while intervals are short.
2468       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
2469       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
2470       if (cl != cr)
2471         return cl > cr;
2472
2473       // As a last resort, sort by block number.
2474       return LHS.second->getNumber() < RHS.second->getNumber();
2475     }
2476   };
2477 }
2478
2479 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2480                                                std::vector<CopyRec> &TryAgain) {
2481   DEBUG(dbgs() << MBB->getName() << ":\n");
2482
2483   std::vector<CopyRec> VirtCopies;
2484   std::vector<CopyRec> PhysCopies;
2485   std::vector<CopyRec> ImpDefCopies;
2486   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2487        MII != E;) {
2488     MachineInstr *Inst = MII++;
2489
2490     // If this isn't a copy nor a extract_subreg, we can't join intervals.
2491     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2492     bool isInsUndef = false;
2493     if (Inst->isExtractSubreg()) {
2494       DstReg = Inst->getOperand(0).getReg();
2495       SrcReg = Inst->getOperand(1).getReg();
2496     } else if (Inst->isInsertSubreg()) {
2497       DstReg = Inst->getOperand(0).getReg();
2498       SrcReg = Inst->getOperand(2).getReg();
2499       if (Inst->getOperand(1).isUndef())
2500         isInsUndef = true;
2501     } else if (Inst->isInsertSubreg() || Inst->isSubregToReg()) {
2502       DstReg = Inst->getOperand(0).getReg();
2503       SrcReg = Inst->getOperand(2).getReg();
2504     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2505       continue;
2506
2507     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2508     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2509     if (isInsUndef ||
2510         (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()))
2511       ImpDefCopies.push_back(CopyRec(Inst, 0));
2512     else if (SrcIsPhys || DstIsPhys)
2513       PhysCopies.push_back(CopyRec(Inst, 0));
2514     else
2515       VirtCopies.push_back(CopyRec(Inst, 0));
2516   }
2517
2518   // Try coalescing implicit copies and insert_subreg <undef> first,
2519   // followed by copies to / from physical registers, then finally copies
2520   // from virtual registers to virtual registers.
2521   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2522     CopyRec &TheCopy = ImpDefCopies[i];
2523     bool Again = false;
2524     if (!JoinCopy(TheCopy, Again))
2525       if (Again)
2526         TryAgain.push_back(TheCopy);
2527   }
2528   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2529     CopyRec &TheCopy = PhysCopies[i];
2530     bool Again = false;
2531     if (!JoinCopy(TheCopy, Again))
2532       if (Again)
2533         TryAgain.push_back(TheCopy);
2534   }
2535   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2536     CopyRec &TheCopy = VirtCopies[i];
2537     bool Again = false;
2538     if (!JoinCopy(TheCopy, Again))
2539       if (Again)
2540         TryAgain.push_back(TheCopy);
2541   }
2542 }
2543
2544 void SimpleRegisterCoalescing::joinIntervals() {
2545   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2546
2547   std::vector<CopyRec> TryAgainList;
2548   if (loopInfo->empty()) {
2549     // If there are no loops in the function, join intervals in function order.
2550     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2551          I != E; ++I)
2552       CopyCoalesceInMBB(I, TryAgainList);
2553   } else {
2554     // Otherwise, join intervals in inner loops before other intervals.
2555     // Unfortunately we can't just iterate over loop hierarchy here because
2556     // there may be more MBB's than BB's.  Collect MBB's for sorting.
2557
2558     // Join intervals in the function prolog first. We want to join physical
2559     // registers with virtual registers before the intervals got too long.
2560     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2561     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2562       MachineBasicBlock *MBB = I;
2563       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2564     }
2565
2566     // Sort by loop depth.
2567     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2568
2569     // Finally, join intervals in loop nest order.
2570     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2571       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2572   }
2573
2574   // Joining intervals can allow other intervals to be joined.  Iteratively join
2575   // until we make no progress.
2576   bool ProgressMade = true;
2577   while (ProgressMade) {
2578     ProgressMade = false;
2579
2580     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2581       CopyRec &TheCopy = TryAgainList[i];
2582       if (!TheCopy.MI)
2583         continue;
2584
2585       bool Again = false;
2586       bool Success = JoinCopy(TheCopy, Again);
2587       if (Success || !Again) {
2588         TheCopy.MI = 0;   // Mark this one as done.
2589         ProgressMade = true;
2590       }
2591     }
2592   }
2593 }
2594
2595 /// Return true if the two specified registers belong to different register
2596 /// classes.  The registers may be either phys or virt regs.
2597 bool
2598 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2599                                                    unsigned RegB) const {
2600   // Get the register classes for the first reg.
2601   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2602     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2603            "Shouldn't consider two physregs!");
2604     return !mri_->getRegClass(RegB)->contains(RegA);
2605   }
2606
2607   // Compare against the regclass for the second reg.
2608   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2609   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2610     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2611     return RegClassA != RegClassB;
2612   }
2613   return !RegClassA->contains(RegB);
2614 }
2615
2616 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
2617 /// between cycles Start and End or NULL if there are no uses.
2618 MachineOperand *
2619 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
2620                                           SlotIndex End,
2621                                           unsigned Reg,
2622                                           SlotIndex &UseIdx) const{
2623   UseIdx = SlotIndex();
2624   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2625     MachineOperand *LastUse = NULL;
2626     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
2627            E = mri_->use_nodbg_end(); I != E; ++I) {
2628       MachineOperand &Use = I.getOperand();
2629       MachineInstr *UseMI = Use.getParent();
2630       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2631       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2632           SrcReg == DstReg)
2633         // Ignore identity copies.
2634         continue;
2635       SlotIndex Idx = li_->getInstructionIndex(UseMI);
2636       // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
2637       // that compares higher than any other interval.
2638       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2639         LastUse = &Use;
2640         UseIdx = Idx.getUseIndex();
2641       }
2642     }
2643     return LastUse;
2644   }
2645
2646   SlotIndex s = Start;
2647   SlotIndex e = End.getPrevSlot().getBaseIndex();
2648   while (e >= s) {
2649     // Skip deleted instructions
2650     MachineInstr *MI = li_->getInstructionFromIndex(e);
2651     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
2652       e = e.getPrevIndex();
2653       MI = li_->getInstructionFromIndex(e);
2654     }
2655     if (e < s || MI == NULL)
2656       return NULL;
2657
2658     // Ignore identity copies.
2659     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2660     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2661           SrcReg == DstReg))
2662       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2663         MachineOperand &Use = MI->getOperand(i);
2664         if (Use.isReg() && Use.isUse() && Use.getReg() &&
2665             tri_->regsOverlap(Use.getReg(), Reg)) {
2666           UseIdx = e.getUseIndex();
2667           return &Use;
2668         }
2669       }
2670
2671     e = e.getPrevIndex();
2672   }
2673
2674   return NULL;
2675 }
2676
2677 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2678   if (TargetRegisterInfo::isPhysicalRegister(reg))
2679     dbgs() << tri_->getName(reg);
2680   else
2681     dbgs() << "%reg" << reg;
2682 }
2683
2684 void SimpleRegisterCoalescing::releaseMemory() {
2685   JoinedCopies.clear();
2686   ReMatCopies.clear();
2687   ReMatDefs.clear();
2688 }
2689
2690 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2691   mf_ = &fn;
2692   mri_ = &fn.getRegInfo();
2693   tm_ = &fn.getTarget();
2694   tri_ = tm_->getRegisterInfo();
2695   tii_ = tm_->getInstrInfo();
2696   li_ = &getAnalysis<LiveIntervals>();
2697   AA = &getAnalysis<AliasAnalysis>();
2698   loopInfo = &getAnalysis<MachineLoopInfo>();
2699
2700   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2701                << "********** Function: "
2702                << ((Value*)mf_->getFunction())->getName() << '\n');
2703
2704   allocatableRegs_ = tri_->getAllocatableSet(fn);
2705   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2706          E = tri_->regclass_end(); I != E; ++I)
2707     allocatableRCRegs_.insert(std::make_pair(*I,
2708                                              tri_->getAllocatableSet(fn, *I)));
2709
2710   // Join (coalesce) intervals if requested.
2711   if (EnableJoining) {
2712     joinIntervals();
2713     DEBUG({
2714         dbgs() << "********** INTERVALS POST JOINING **********\n";
2715         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
2716              I != E; ++I){
2717           I->second->print(dbgs(), tri_);
2718           dbgs() << "\n";
2719         }
2720       });
2721   }
2722
2723   // Perform a final pass over the instructions and compute spill weights
2724   // and remove identity moves.
2725   SmallVector<unsigned, 4> DeadDefs;
2726   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2727        mbbi != mbbe; ++mbbi) {
2728     MachineBasicBlock* mbb = mbbi;
2729     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2730          mii != mie; ) {
2731       MachineInstr *MI = mii;
2732       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2733       if (JoinedCopies.count(MI)) {
2734         // Delete all coalesced copies.
2735         bool DoDelete = true;
2736         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2737           assert((MI->isExtractSubreg() || MI->isInsertSubreg() ||
2738                   MI->isSubregToReg()) && "Unrecognized copy instruction");
2739           DstReg = MI->getOperand(0).getReg();
2740           if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2741             // Do not delete extract_subreg, insert_subreg of physical
2742             // registers unless the definition is dead. e.g.
2743             // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
2744             // or else the scavenger may complain. LowerSubregs will
2745             // delete them later.
2746             DoDelete = false;
2747         }
2748         if (MI->registerDefIsDead(DstReg)) {
2749           LiveInterval &li = li_->getInterval(DstReg);
2750           if (!ShortenDeadCopySrcLiveRange(li, MI))
2751             ShortenDeadCopyLiveRange(li, MI);
2752           DoDelete = true;
2753         }
2754         if (!DoDelete)
2755           mii = llvm::next(mii);
2756         else {
2757           li_->RemoveMachineInstrFromMaps(MI);
2758           mii = mbbi->erase(mii);
2759           ++numPeep;
2760         }
2761         continue;
2762       }
2763
2764       // Now check if this is a remat'ed def instruction which is now dead.
2765       if (ReMatDefs.count(MI)) {
2766         bool isDead = true;
2767         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2768           const MachineOperand &MO = MI->getOperand(i);
2769           if (!MO.isReg())
2770             continue;
2771           unsigned Reg = MO.getReg();
2772           if (!Reg)
2773             continue;
2774           if (TargetRegisterInfo::isVirtualRegister(Reg))
2775             DeadDefs.push_back(Reg);
2776           if (MO.isDead())
2777             continue;
2778           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2779               !mri_->use_empty(Reg)) {
2780             isDead = false;
2781             break;
2782           }
2783         }
2784         if (isDead) {
2785           while (!DeadDefs.empty()) {
2786             unsigned DeadDef = DeadDefs.back();
2787             DeadDefs.pop_back();
2788             RemoveDeadDef(li_->getInterval(DeadDef), MI);
2789           }
2790           li_->RemoveMachineInstrFromMaps(mii);
2791           mii = mbbi->erase(mii);
2792           continue;
2793         } else
2794           DeadDefs.clear();
2795       }
2796
2797       // If the move will be an identity move delete it
2798       bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2799       if (isMove && SrcReg == DstReg) {
2800         if (li_->hasInterval(SrcReg)) {
2801           LiveInterval &RegInt = li_->getInterval(SrcReg);
2802           // If def of this move instruction is dead, remove its live range
2803           // from the dstination register's live interval.
2804           if (MI->registerDefIsDead(DstReg)) {
2805             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2806               ShortenDeadCopyLiveRange(RegInt, MI);
2807           }
2808         }
2809         li_->RemoveMachineInstrFromMaps(MI);
2810         mii = mbbi->erase(mii);
2811         ++numPeep;
2812       } else {
2813         ++mii;
2814       }
2815     }
2816   }
2817
2818   DEBUG(dump());
2819   return true;
2820 }
2821
2822 /// print - Implement the dump method.
2823 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2824    li_->print(O, m);
2825 }
2826
2827 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2828   return new SimpleRegisterCoalescing();
2829 }
2830
2831 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2832 DEFINING_FILE_FOR(SimpleRegisterCoalescing)