1faa5a094a4e4679d2a2b9f95a5f818dda630174
[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 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       DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
706       if (DLR && DLR->valno->getCopy() == CopyMI)
707         DLR->valno->setCopy(0);
708     }
709   }
710
711   // If copy kills the source register, find the last use and propagate
712   // kill.
713   bool checkForDeadDef = false;
714   MachineBasicBlock *MBB = CopyMI->getParent();
715   if (CopyMI->killsRegister(SrcInt.reg))
716     if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
717       checkForDeadDef = true;
718     }
719
720   MachineBasicBlock::iterator MII =
721     llvm::next(MachineBasicBlock::iterator(CopyMI));
722   tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, tri_);
723   MachineInstr *NewMI = prior(MII);
724
725   if (checkForDeadDef) {
726     // PR4090 fix: Trim interval failed because there was no use of the
727     // source interval in this MBB. If the def is in this MBB too then we
728     // should mark it dead:
729     if (DefMI->getParent() == MBB) {
730       DefMI->addRegisterDead(SrcInt.reg, tri_);
731       SrcLR->end = SrcLR->start.getNextSlot();
732     }
733   }
734
735   // CopyMI may have implicit operands, transfer them over to the newly
736   // rematerialized instruction. And update implicit def interval valnos.
737   for (unsigned i = CopyMI->getDesc().getNumOperands(),
738          e = CopyMI->getNumOperands(); i != e; ++i) {
739     MachineOperand &MO = CopyMI->getOperand(i);
740     if (MO.isReg() && MO.isImplicit())
741       NewMI->addOperand(MO);
742     if (MO.isDef() && li_->hasInterval(MO.getReg())) {
743       unsigned Reg = MO.getReg();
744       DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
745       if (DLR && DLR->valno->getCopy() == CopyMI)
746         DLR->valno->setCopy(0);
747     }
748   }
749
750   TransferImplicitOps(CopyMI, NewMI);
751   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
752   CopyMI->eraseFromParent();
753   ReMatCopies.insert(CopyMI);
754   ReMatDefs.insert(DefMI);
755   ++NumReMats;
756   return true;
757 }
758
759 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
760 /// update the subregister number if it is not zero. If DstReg is a
761 /// physical register and the existing subregister number of the def / use
762 /// being updated is not zero, make sure to set it to the correct physical
763 /// subregister.
764 void
765 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
766                                             unsigned SubIdx) {
767   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
768   if (DstIsPhys && SubIdx) {
769     // Figure out the real physical register we are updating with.
770     DstReg = tri_->getSubReg(DstReg, SubIdx);
771     SubIdx = 0;
772   }
773
774   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
775          E = mri_->reg_end(); I != E; ) {
776     MachineOperand &O = I.getOperand();
777     MachineInstr *UseMI = &*I;
778     ++I;
779     unsigned OldSubIdx = O.getSubReg();
780     if (DstIsPhys) {
781       unsigned UseDstReg = DstReg;
782       if (OldSubIdx)
783           UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
784
785       unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
786       if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
787                             CopySrcSubIdx, CopyDstSubIdx) &&
788           CopySrcReg != CopyDstReg &&
789           CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
790         // If the use is a copy and it won't be coalesced away, and its source
791         // is defined by a trivial computation, try to rematerialize it instead.
792         if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
793                                     CopyDstSubIdx, UseMI))
794           continue;
795       }
796
797       O.setReg(UseDstReg);
798       O.setSubReg(0);
799       continue;
800     }
801
802     // Sub-register indexes goes from small to large. e.g.
803     // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
804     // EAX: 1 -> AL, 2 -> AX
805     // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
806     // sub-register 2 is also AX.
807     if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
808       assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
809     else if (SubIdx)
810       O.setSubReg(SubIdx);
811     // Remove would-be duplicated kill marker.
812     if (O.isKill() && UseMI->killsRegister(DstReg))
813       O.setIsKill(false);
814     O.setReg(DstReg);
815
816     // After updating the operand, check if the machine instruction has
817     // become a copy. If so, update its val# information.
818     if (JoinedCopies.count(UseMI))
819       continue;
820
821     const TargetInstrDesc &TID = UseMI->getDesc();
822     unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
823     if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
824         tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
825                           CopySrcSubIdx, CopyDstSubIdx) &&
826         CopySrcReg != CopyDstReg &&
827         (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
828          allocatableRegs_[CopyDstReg])) {
829       LiveInterval &LI = li_->getInterval(CopyDstReg);
830       SlotIndex DefIdx =
831         li_->getInstructionIndex(UseMI).getDefIndex();
832       if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
833         if (DLR->valno->def == DefIdx)
834           DLR->valno->setCopy(UseMI);
835       }
836     }
837   }
838 }
839
840 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
841 /// due to live range lengthening as the result of coalescing.
842 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
843                                                       LiveInterval &LI) {
844   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
845          UE = mri_->use_end(); UI != UE; ++UI) {
846     MachineOperand &UseMO = UI.getOperand();
847     if (!UseMO.isKill())
848       continue;
849     MachineInstr *UseMI = UseMO.getParent();
850     SlotIndex UseIdx =
851       li_->getInstructionIndex(UseMI).getUseIndex();
852     const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
853     if (!LR ||
854         (!LR->valno->isKill(UseIdx.getDefIndex()) &&
855          LR->valno->def != UseIdx.getDefIndex())) {
856       // Interesting problem. After coalescing reg1027's def and kill are both
857       // at the same point:  %reg1027,0.000000e+00 = [56,814:0)  0@70-(814)
858       //
859       // bb5:
860       // 60   %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
861       // 68   %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
862       // 76   t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
863       // 84   %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
864       // 96   t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
865       //
866       // Do not remove the kill marker on t2LDRi12.
867       UseMO.setIsKill(false);
868     }
869   }
870 }
871
872 /// removeIntervalIfEmpty - Check if the live interval of a physical register
873 /// is empty, if so remove it and also remove the empty intervals of its
874 /// sub-registers. Return true if live interval is removed.
875 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
876                                   const TargetRegisterInfo *tri_) {
877   if (li.empty()) {
878     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
879       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
880         if (!li_->hasInterval(*SR))
881           continue;
882         LiveInterval &sli = li_->getInterval(*SR);
883         if (sli.empty())
884           li_->removeInterval(*SR);
885       }
886     li_->removeInterval(li.reg);
887     return true;
888   }
889   return false;
890 }
891
892 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
893 /// Return true if live interval is removed.
894 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
895                                                         MachineInstr *CopyMI) {
896   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
897   LiveInterval::iterator MLR =
898     li.FindLiveRangeContaining(CopyIdx.getDefIndex());
899   if (MLR == li.end())
900     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
901   SlotIndex RemoveStart = MLR->start;
902   SlotIndex RemoveEnd = MLR->end;
903   SlotIndex DefIdx = CopyIdx.getDefIndex();
904   // Remove the liverange that's defined by this.
905   if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
906     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
907     return removeIntervalIfEmpty(li, li_, tri_);
908   }
909   return false;
910 }
911
912 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
913 /// the val# it defines. If the live interval becomes empty, remove it as well.
914 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
915                                              MachineInstr *DefMI) {
916   SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
917   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
918   if (DefIdx != MLR->valno->def)
919     return false;
920   li.removeValNo(MLR->valno);
921   return removeIntervalIfEmpty(li, li_, tri_);
922 }
923
924 /// PropagateDeadness - Propagate the dead marker to the instruction which
925 /// defines the val#.
926 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
927                               SlotIndex &LRStart, LiveIntervals *li_,
928                               const TargetRegisterInfo* tri_) {
929   MachineInstr *DefMI =
930     li_->getInstructionFromIndex(LRStart.getDefIndex());
931   if (DefMI && DefMI != CopyMI) {
932     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
933     if (DeadIdx != -1)
934       DefMI->getOperand(DeadIdx).setIsDead();
935     else
936       DefMI->addOperand(MachineOperand::CreateReg(li.reg,
937                    /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
938     LRStart = LRStart.getNextSlot();
939   }
940 }
941
942 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
943 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
944 /// ends the live range there. If there isn't another use, then this live range
945 /// is dead. Return true if live interval is removed.
946 bool
947 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
948                                                       MachineInstr *CopyMI) {
949   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
950   if (CopyIdx == SlotIndex()) {
951     // FIXME: special case: function live in. It can be a general case if the
952     // first instruction index starts at > 0 value.
953     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
954     // Live-in to the function but dead. Remove it from entry live-in set.
955     if (mf_->begin()->isLiveIn(li.reg))
956       mf_->begin()->removeLiveIn(li.reg);
957     const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
958     removeRange(li, LR->start, LR->end, li_, tri_);
959     return removeIntervalIfEmpty(li, li_, tri_);
960   }
961
962   LiveInterval::iterator LR =
963     li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
964   if (LR == li.end())
965     // Livein but defined by a phi.
966     return false;
967
968   SlotIndex RemoveStart = LR->start;
969   SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
970   if (LR->end > RemoveEnd)
971     // More uses past this copy? Nothing to do.
972     return false;
973
974   // If there is a last use in the same bb, we can't remove the live range.
975   // Shorten the live interval and return.
976   MachineBasicBlock *CopyMBB = CopyMI->getParent();
977   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
978     return false;
979
980   // There are other kills of the val#. Nothing to do.
981   if (!li.isOnlyLROfValNo(LR))
982     return false;
983
984   MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
985   if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
986     // If the live range starts in another mbb and the copy mbb is not a fall
987     // through mbb, then we can only cut the range from the beginning of the
988     // copy mbb.
989     RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
990
991   if (LR->valno->def == RemoveStart) {
992     // If the def MI defines the val# and this copy is the only kill of the
993     // val#, then propagate the dead marker.
994     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
995     ++numDeadValNo;
996
997     if (LR->valno->isKill(RemoveEnd))
998       LR->valno->removeKill(RemoveEnd);
999   }
1000
1001   removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
1002   return removeIntervalIfEmpty(li, li_, tri_);
1003 }
1004
1005 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
1006 /// from an implicit def to another register can be coalesced away.
1007 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
1008                                                      LiveInterval &li,
1009                                                      LiveInterval &ImpLi) const{
1010   if (!CopyMI->killsRegister(ImpLi.reg))
1011     return false;
1012   // Make sure this is the only use.
1013   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1014          UE = mri_->use_end(); UI != UE;) {
1015     MachineInstr *UseMI = &*UI;
1016     ++UI;
1017     if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1018       continue;
1019     return false;
1020   }
1021   return true;
1022 }
1023
1024
1025 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1026 /// a virtual destination register with physical source register.
1027 bool
1028 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1029                                                      MachineBasicBlock *CopyMBB,
1030                                                      LiveInterval &DstInt,
1031                                                      LiveInterval &SrcInt) {
1032   // If the virtual register live interval is long but it has low use desity,
1033   // do not join them, instead mark the physical register as its allocation
1034   // preference.
1035   const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1036   unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1037   unsigned Length = li_->getApproximateInstructionCount(DstInt);
1038   if (Length > Threshold &&
1039       (((float)std::distance(mri_->use_nodbg_begin(DstInt.reg),
1040                              mri_->use_nodbg_end()) / Length) < 
1041         (1.0 / Threshold)))
1042     return false;
1043
1044   // If the virtual register live interval extends into a loop, turn down
1045   // aggressiveness.
1046   SlotIndex CopyIdx =
1047     li_->getInstructionIndex(CopyMI).getDefIndex();
1048   const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1049   if (!L) {
1050     // Let's see if the virtual register live interval extends into the loop.
1051     LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1052     assert(DLR != DstInt.end() && "Live range not found!");
1053     DLR = DstInt.FindLiveRangeContaining(DLR->end.getNextSlot());
1054     if (DLR != DstInt.end()) {
1055       CopyMBB = li_->getMBBFromIndex(DLR->start);
1056       L = loopInfo->getLoopFor(CopyMBB);
1057     }
1058   }
1059
1060   if (!L || Length <= Threshold)
1061     return true;
1062
1063   SlotIndex UseIdx = CopyIdx.getUseIndex();
1064   LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1065   MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1066   if (loopInfo->getLoopFor(SMBB) != L) {
1067     if (!loopInfo->isLoopHeader(CopyMBB))
1068       return false;
1069     // If vr's live interval extends pass the loop header, do not join.
1070     for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1071            SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1072       MachineBasicBlock *SuccMBB = *SI;
1073       if (SuccMBB == CopyMBB)
1074         continue;
1075       if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1076                           li_->getMBBEndIdx(SuccMBB)))
1077         return false;
1078     }
1079   }
1080   return true;
1081 }
1082
1083 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1084 /// copy from a virtual source register to a physical destination register.
1085 bool
1086 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1087                                                      MachineBasicBlock *CopyMBB,
1088                                                      LiveInterval &DstInt,
1089                                                      LiveInterval &SrcInt) {
1090   // If the virtual register live interval is long but it has low use density,
1091   // do not join them, instead mark the physical register as its allocation
1092   // preference.
1093   const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1094   unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1095   unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1096   if (Length > Threshold &&
1097       (((float)std::distance(mri_->use_nodbg_begin(SrcInt.reg),
1098                              mri_->use_nodbg_end()) / Length) < 
1099           (1.0 / Threshold)))
1100     return false;
1101
1102   if (SrcInt.empty())
1103     // Must be implicit_def.
1104     return false;
1105
1106   // If the virtual register live interval is defined or cross a loop, turn
1107   // down aggressiveness.
1108   SlotIndex CopyIdx =
1109     li_->getInstructionIndex(CopyMI).getDefIndex();
1110   SlotIndex UseIdx = CopyIdx.getUseIndex();
1111   LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1112   assert(SLR != SrcInt.end() && "Live range not found!");
1113   SLR = SrcInt.FindLiveRangeContaining(SLR->start.getPrevSlot());
1114   if (SLR == SrcInt.end())
1115     return true;
1116   MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1117   const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1118
1119   if (!L || Length <= Threshold)
1120     return true;
1121
1122   if (loopInfo->getLoopFor(CopyMBB) != L) {
1123     if (SMBB != L->getLoopLatch())
1124       return false;
1125     // If vr's live interval is extended from before the loop latch, do not
1126     // join.
1127     for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1128            PE = SMBB->pred_end(); PI != PE; ++PI) {
1129       MachineBasicBlock *PredMBB = *PI;
1130       if (PredMBB == SMBB)
1131         continue;
1132       if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1133                           li_->getMBBEndIdx(PredMBB)))
1134         return false;
1135     }
1136   }
1137   return true;
1138 }
1139
1140 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1141 /// two virtual registers from different register classes.
1142 bool
1143 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1144                                                 unsigned SmallReg,
1145                                                 unsigned Threshold) {
1146   // Then make sure the intervals are *short*.
1147   LiveInterval &LargeInt = li_->getInterval(LargeReg);
1148   LiveInterval &SmallInt = li_->getInterval(SmallReg);
1149   unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1150   unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1151   if (SmallSize > Threshold || LargeSize > Threshold)
1152     if ((float)std::distance(mri_->use_nodbg_begin(SmallReg),
1153                              mri_->use_nodbg_end()) / SmallSize <
1154         (float)std::distance(mri_->use_nodbg_begin(LargeReg),
1155                              mri_->use_nodbg_end()) / LargeSize)
1156       return false;
1157   return true;
1158 }
1159
1160 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1161 /// register with a physical register, check if any of the virtual register
1162 /// operand is a sub-register use or def. If so, make sure it won't result
1163 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1164 /// vr1024 = extract_subreg vr1025, 1
1165 /// ...
1166 /// vr1024 = mov8rr AH
1167 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1168 /// AH does not have a super-reg whose sub-register 1 is AH.
1169 bool
1170 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1171                                                       unsigned VirtReg,
1172                                                       unsigned PhysReg) {
1173   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1174          E = mri_->reg_end(); I != E; ++I) {
1175     MachineOperand &O = I.getOperand();
1176     MachineInstr *MI = &*I;
1177     if (MI == CopyMI || JoinedCopies.count(MI))
1178       continue;
1179     unsigned SubIdx = O.getSubReg();
1180     if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1181       return true;
1182     if (MI->isExtractSubreg()) {
1183       SubIdx = MI->getOperand(2).getImm();
1184       if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1185         return true;
1186       if (O.isDef()) {
1187         unsigned SrcReg = MI->getOperand(1).getReg();
1188         const TargetRegisterClass *RC =
1189           TargetRegisterInfo::isPhysicalRegister(SrcReg)
1190           ? tri_->getPhysicalRegisterRegClass(SrcReg)
1191           : mri_->getRegClass(SrcReg);
1192         if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1193           return true;
1194       }
1195     }
1196     if (MI->isInsertSubreg() || MI->isSubregToReg()) {
1197       SubIdx = MI->getOperand(3).getImm();
1198       if (VirtReg == MI->getOperand(0).getReg()) {
1199         if (!tri_->getSubReg(PhysReg, SubIdx))
1200           return true;
1201       } else {
1202         unsigned DstReg = MI->getOperand(0).getReg();
1203         const TargetRegisterClass *RC =
1204           TargetRegisterInfo::isPhysicalRegister(DstReg)
1205           ? tri_->getPhysicalRegisterRegClass(DstReg)
1206           : mri_->getRegClass(DstReg);
1207         if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1208           return true;
1209       }
1210     }
1211   }
1212   return false;
1213 }
1214
1215
1216 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1217 /// an extract_subreg where dst is a physical register, e.g.
1218 /// cl = EXTRACT_SUBREG reg1024, 1
1219 bool
1220 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1221                                                unsigned SrcReg, unsigned SubIdx,
1222                                                unsigned &RealDstReg) {
1223   const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1224   RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1225   assert(RealDstReg && "Invalid extract_subreg instruction!");
1226
1227   // For this type of EXTRACT_SUBREG, conservatively
1228   // check if the live interval of the source register interfere with the
1229   // actual super physical register we are trying to coalesce with.
1230   LiveInterval &RHS = li_->getInterval(SrcReg);
1231   if (li_->hasInterval(RealDstReg) &&
1232       RHS.overlaps(li_->getInterval(RealDstReg))) {
1233     DEBUG({
1234         dbgs() << "Interfere with register ";
1235         li_->getInterval(RealDstReg).print(dbgs(), tri_);
1236       });
1237     return false; // Not coalescable
1238   }
1239   for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1240     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1241       DEBUG({
1242           dbgs() << "Interfere with sub-register ";
1243           li_->getInterval(*SR).print(dbgs(), tri_);
1244         });
1245       return false; // Not coalescable
1246     }
1247   return true;
1248 }
1249
1250 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1251 /// an insert_subreg where src is a physical register, e.g.
1252 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1253 bool
1254 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1255                                                unsigned SrcReg, unsigned SubIdx,
1256                                                unsigned &RealSrcReg) {
1257   const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1258   RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1259   assert(RealSrcReg && "Invalid extract_subreg instruction!");
1260
1261   LiveInterval &RHS = li_->getInterval(DstReg);
1262   if (li_->hasInterval(RealSrcReg) &&
1263       RHS.overlaps(li_->getInterval(RealSrcReg))) {
1264     DEBUG({
1265         dbgs() << "Interfere with register ";
1266         li_->getInterval(RealSrcReg).print(dbgs(), tri_);
1267       });
1268     return false; // Not coalescable
1269   }
1270   for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1271     if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1272       DEBUG({
1273           dbgs() << "Interfere with sub-register ";
1274           li_->getInterval(*SR).print(dbgs(), tri_);
1275         });
1276       return false; // Not coalescable
1277     }
1278   return true;
1279 }
1280
1281 /// getRegAllocPreference - Return register allocation preference register.
1282 ///
1283 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1284                                       MachineRegisterInfo *MRI,
1285                                       const TargetRegisterInfo *TRI) {
1286   if (TargetRegisterInfo::isPhysicalRegister(Reg))
1287     return 0;
1288   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1289   return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1290 }
1291
1292 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1293 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1294 /// if the copy was successfully coalesced away. If it is not currently
1295 /// possible to coalesce this interval, but it may be possible if other
1296 /// things get coalesced, then it returns true by reference in 'Again'.
1297 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1298   MachineInstr *CopyMI = TheCopy.MI;
1299
1300   Again = false;
1301   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1302     return false; // Already done.
1303
1304   DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1305
1306   unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1307   bool isExtSubReg = CopyMI->isExtractSubreg();
1308   bool isInsSubReg = CopyMI->isInsertSubreg();
1309   bool isSubRegToReg = CopyMI->isSubregToReg();
1310   unsigned SubIdx = 0;
1311   if (isExtSubReg) {
1312     DstReg    = CopyMI->getOperand(0).getReg();
1313     DstSubIdx = CopyMI->getOperand(0).getSubReg();
1314     SrcReg    = CopyMI->getOperand(1).getReg();
1315     SrcSubIdx = CopyMI->getOperand(2).getImm();
1316   } else if (isInsSubReg || isSubRegToReg) {
1317     DstReg    = CopyMI->getOperand(0).getReg();
1318     DstSubIdx = CopyMI->getOperand(3).getImm();
1319     SrcReg    = CopyMI->getOperand(2).getReg();
1320     SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1321     if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1322       // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1323       // coalesced to a larger register so the subreg indices cancel out.
1324       DEBUG(dbgs() << "\tSource of insert_subreg or subreg_to_reg is already "
1325                       "coalesced to another register.\n");
1326       return false;  // Not coalescable.
1327     }
1328   } else if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
1329     if (SrcSubIdx && DstSubIdx && SrcSubIdx != DstSubIdx) {
1330       // e.g. %reg16404:1<def> = MOV8rr %reg16412:2<kill>
1331       Again = true;
1332       return false;  // Not coalescable.
1333     }
1334   } else {
1335     llvm_unreachable("Unrecognized copy instruction!");
1336   }
1337
1338   // If they are already joined we continue.
1339   if (SrcReg == DstReg) {
1340     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1341     return false;  // Not coalescable.
1342   }
1343
1344   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1345   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1346
1347   // If they are both physical registers, we cannot join them.
1348   if (SrcIsPhys && DstIsPhys) {
1349     DEBUG(dbgs() << "\tCan not coalesce physregs.\n");
1350     return false;  // Not coalescable.
1351   }
1352
1353   // We only join virtual registers with allocatable physical registers.
1354   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1355     DEBUG(dbgs() << "\tSrc reg is unallocatable physreg.\n");
1356     return false;  // Not coalescable.
1357   }
1358   if (DstIsPhys && !allocatableRegs_[DstReg]) {
1359     DEBUG(dbgs() << "\tDst reg is unallocatable physreg.\n");
1360     return false;  // Not coalescable.
1361   }
1362
1363   // Check that a physical source register is compatible with dst regclass
1364   if (SrcIsPhys) {
1365     unsigned SrcSubReg = SrcSubIdx ?
1366       tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1367     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1368     const TargetRegisterClass *DstSubRC = DstRC;
1369     if (DstSubIdx)
1370       DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1371     assert(DstSubRC && "Illegal subregister index");
1372     if (!DstSubRC->contains(SrcSubReg)) {
1373       DEBUG(dbgs() << "\tIncompatible destination regclass: "
1374                    << tri_->getName(SrcSubReg) << " not in "
1375                    << DstSubRC->getName() << ".\n");
1376       return false;             // Not coalescable.
1377     }
1378   }
1379
1380   // Check that a physical dst register is compatible with source regclass
1381   if (DstIsPhys) {
1382     unsigned DstSubReg = DstSubIdx ?
1383       tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1384     const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1385     const TargetRegisterClass *SrcSubRC = SrcRC;
1386     if (SrcSubIdx)
1387       SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1388     assert(SrcSubRC && "Illegal subregister index");
1389     if (!SrcSubRC->contains(DstSubReg)) {
1390       DEBUG(dbgs() << "\tIncompatible source regclass: "
1391                    << tri_->getName(DstSubReg) << " not in "
1392                    << SrcSubRC->getName() << ".\n");
1393       (void)DstSubReg;
1394       return false;             // Not coalescable.
1395     }
1396   }
1397
1398   // Should be non-null only when coalescing to a sub-register class.
1399   bool CrossRC = false;
1400   const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1401   const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1402   const TargetRegisterClass *NewRC = NULL;
1403   MachineBasicBlock *CopyMBB = CopyMI->getParent();
1404   unsigned RealDstReg = 0;
1405   unsigned RealSrcReg = 0;
1406   if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1407     SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1408     if (SrcIsPhys && isExtSubReg) {
1409       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1410       // coalesced with AX.
1411       unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1412       if (DstSubIdx) {
1413         // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1414         // coalesced to a larger register so the subreg indices cancel out.
1415         if (DstSubIdx != SubIdx) {
1416           DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1417           return false; // Not coalescable.
1418         }
1419       } else
1420         SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1421       SubIdx = 0;
1422     } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1423       // EAX = INSERT_SUBREG EAX, r1024, 0
1424       unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1425       if (SrcSubIdx) {
1426         // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1427         // coalesced to a larger register so the subreg indices cancel out.
1428         if (SrcSubIdx != SubIdx) {
1429           DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1430           return false; // Not coalescable.
1431         }
1432       } else
1433         DstReg = tri_->getSubReg(DstReg, SubIdx);
1434       SubIdx = 0;
1435     } else if ((DstIsPhys && isExtSubReg) ||
1436                (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1437       if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1438         DEBUG(dbgs() << "\tSrc of extract_subreg already coalesced with reg"
1439                      << " of a super-class.\n");
1440         return false; // Not coalescable.
1441       }
1442
1443       if (isExtSubReg) {
1444         if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1445           return false; // Not coalescable
1446       } else {
1447         if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1448           return false; // Not coalescable
1449       }
1450       SubIdx = 0;
1451     } else {
1452       unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1453         : CopyMI->getOperand(2).getSubReg();
1454       if (OldSubIdx) {
1455         if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1456           // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1457           // coalesced to a larger register so the subreg indices cancel out.
1458           // Also check if the other larger register is of the same register
1459           // class as the would be resulting register.
1460           SubIdx = 0;
1461         else {
1462           DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1463           return false; // Not coalescable.
1464         }
1465       }
1466       if (SubIdx) {
1467         if (!DstIsPhys && !SrcIsPhys) {
1468           if (isInsSubReg || isSubRegToReg) {
1469             NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1470           } else // extract_subreg {
1471             NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1472           }
1473         if (!NewRC) {
1474           DEBUG(dbgs() << "\t Conflicting sub-register indices.\n");
1475           return false;  // Not coalescable
1476         }
1477
1478         unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1479         unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1480         unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1481         if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1482           Again = true;  // May be possible to coalesce later.
1483           return false;
1484         }
1485       }
1486     }
1487   } else if (differingRegisterClasses(SrcReg, DstReg)) {
1488     if (DisableCrossClassJoin)
1489       return false;
1490     CrossRC = true;
1491
1492     // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1493     // with another? If it's the resulting destination register, then
1494     // the subidx must be propagated to uses (but only those defined
1495     // by the EXTRACT_SUBREG). If it's being coalesced into another
1496     // register, it should be safe because register is assumed to have
1497     // the register class of the super-register.
1498
1499     // Process moves where one of the registers have a sub-register index.
1500     MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1501     MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1502     SubIdx = DstMO->getSubReg();
1503     if (SubIdx) {
1504       if (SrcMO->getSubReg())
1505         // FIXME: can we handle this?
1506         return false;
1507       // This is not an insert_subreg but it looks like one.
1508       // e.g. %reg1024:4 = MOV32rr %EAX
1509       isInsSubReg = true;
1510       if (SrcIsPhys) {
1511         if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1512           return false; // Not coalescable
1513         SubIdx = 0;
1514       }
1515     } else {
1516       SubIdx = SrcMO->getSubReg();
1517       if (SubIdx) {
1518         // This is not a extract_subreg but it looks like one.
1519         // e.g. %cl = MOV16rr %reg1024:1
1520         isExtSubReg = true;
1521         if (DstIsPhys) {
1522           if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1523             return false; // Not coalescable
1524           SubIdx = 0;
1525         }
1526       }
1527     }
1528
1529     unsigned LargeReg = SrcReg;
1530     unsigned SmallReg = DstReg;
1531
1532     // Now determine the register class of the joined register.
1533     if (isExtSubReg) {
1534       if (SubIdx && DstRC && DstRC->isASubClass()) {
1535         // This is a move to a sub-register class. However, the source is a
1536         // sub-register of a larger register class. We don't know what should
1537         // the register class be. FIXME.
1538         Again = true;
1539         return false;
1540       }
1541       if (!DstIsPhys && !SrcIsPhys)
1542         NewRC = SrcRC;
1543     } else if (!SrcIsPhys && !DstIsPhys) {
1544       NewRC = getCommonSubClass(SrcRC, DstRC);
1545       if (!NewRC) {
1546         DEBUG(dbgs() << "\tDisjoint regclasses: "
1547                      << SrcRC->getName() << ", "
1548                      << DstRC->getName() << ".\n");
1549         return false;           // Not coalescable.
1550       }
1551       if (DstRC->getSize() > SrcRC->getSize())
1552         std::swap(LargeReg, SmallReg);
1553     }
1554
1555     // If we are joining two virtual registers and the resulting register
1556     // class is more restrictive (fewer register, smaller size). Check if it's
1557     // worth doing the merge.
1558     if (!SrcIsPhys && !DstIsPhys &&
1559         (isExtSubReg || DstRC->isASubClass()) &&
1560         !isWinToJoinCrossClass(LargeReg, SmallReg,
1561                                allocatableRCRegs_[NewRC].count())) {
1562       DEBUG(dbgs() << "\tSrc/Dest are different register classes.\n");
1563       // Allow the coalescer to try again in case either side gets coalesced to
1564       // a physical register that's compatible with the other side. e.g.
1565       // r1024 = MOV32to32_ r1025
1566       // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1567       Again = true;  // May be possible to coalesce later.
1568       return false;
1569     }
1570   }
1571
1572   // Will it create illegal extract_subreg / insert_subreg?
1573   if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1574     return false;
1575   if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1576     return false;
1577
1578   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1579   LiveInterval &DstInt = li_->getInterval(DstReg);
1580   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1581          "Register mapping is horribly broken!");
1582
1583   DEBUG({
1584       dbgs() << "\t\tInspecting "; SrcInt.print(dbgs(), tri_);
1585       dbgs() << " and "; DstInt.print(dbgs(), tri_);
1586       dbgs() << ": ";
1587     });
1588
1589   // Save a copy of the virtual register live interval. We'll manually
1590   // merge this into the "real" physical register live interval this is
1591   // coalesced with.
1592   LiveInterval *SavedLI = 0;
1593   if (RealDstReg)
1594     SavedLI = li_->dupInterval(&SrcInt);
1595   else if (RealSrcReg)
1596     SavedLI = li_->dupInterval(&DstInt);
1597
1598   // Check if it is necessary to propagate "isDead" property.
1599   if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1600     MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1601     bool isDead = mopd->isDead();
1602
1603     // We need to be careful about coalescing a source physical register with a
1604     // virtual register. Once the coalescing is done, it cannot be broken and
1605     // these are not spillable! If the destination interval uses are far away,
1606     // think twice about coalescing them!
1607     if (!isDead && (SrcIsPhys || DstIsPhys)) {
1608       // If the copy is in a loop, take care not to coalesce aggressively if the
1609       // src is coming in from outside the loop (or the dst is out of the loop).
1610       // If it's not in a loop, then determine whether to join them base purely
1611       // by the length of the interval.
1612       if (PhysJoinTweak) {
1613         if (SrcIsPhys) {
1614           if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1615             mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1616             ++numAborts;
1617             DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1618             Again = true;  // May be possible to coalesce later.
1619             return false;
1620           }
1621         } else {
1622           if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1623             mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1624             ++numAborts;
1625             DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1626             Again = true;  // May be possible to coalesce later.
1627             return false;
1628           }
1629         }
1630       } else {
1631         // If the virtual register live interval is long but it has low use
1632         // density, do not join them, instead mark the physical register as its
1633         // allocation preference.
1634         LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1635         unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1636         unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1637         const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1638         unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1639         unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1640         float Ratio = 1.0 / Threshold;
1641         if (Length > Threshold &&
1642             (((float)std::distance(mri_->use_nodbg_begin(JoinVReg),
1643                                    mri_->use_nodbg_end()) / Length) < Ratio)) {
1644           mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1645           ++numAborts;
1646           DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1647           Again = true;  // May be possible to coalesce later.
1648           return false;
1649         }
1650       }
1651     }
1652   }
1653
1654   // Okay, attempt to join these two intervals.  On failure, this returns false.
1655   // Otherwise, if one of the intervals being joined is a physreg, this method
1656   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1657   // been modified, so we can use this information below to update aliases.
1658   bool Swapped = false;
1659   // If SrcInt is implicitly defined, it's safe to coalesce.
1660   bool isEmpty = SrcInt.empty();
1661   if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1662     // Only coalesce an empty interval (defined by implicit_def) with
1663     // another interval which has a valno defined by the CopyMI and the CopyMI
1664     // is a kill of the implicit def.
1665     DEBUG(dbgs() << "Not profitable!\n");
1666     return false;
1667   }
1668
1669   if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1670     // Coalescing failed.
1671
1672     // If definition of source is defined by trivial computation, try
1673     // rematerializing it.
1674     if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1675         ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1676       return true;
1677
1678     // If we can eliminate the copy without merging the live ranges, do so now.
1679     if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1680         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1681          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1682       JoinedCopies.insert(CopyMI);
1683       return true;
1684     }
1685
1686     // Otherwise, we are unable to join the intervals.
1687     DEBUG(dbgs() << "Interference!\n");
1688     Again = true;  // May be possible to coalesce later.
1689     return false;
1690   }
1691
1692   LiveInterval *ResSrcInt = &SrcInt;
1693   LiveInterval *ResDstInt = &DstInt;
1694   if (Swapped) {
1695     std::swap(SrcReg, DstReg);
1696     std::swap(ResSrcInt, ResDstInt);
1697   }
1698   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1699          "LiveInterval::join didn't work right!");
1700
1701   // If we're about to merge live ranges into a physical register live interval,
1702   // we have to update any aliased register's live ranges to indicate that they
1703   // have clobbered values for this range.
1704   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1705     // If this is a extract_subreg where dst is a physical register, e.g.
1706     // cl = EXTRACT_SUBREG reg1024, 1
1707     // then create and update the actual physical register allocated to RHS.
1708     if (RealDstReg || RealSrcReg) {
1709       LiveInterval &RealInt =
1710         li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1711       for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1712              E = SavedLI->vni_end(); I != E; ++I) {
1713         const VNInfo *ValNo = *I;
1714         VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1715                                                 false, // updated at *
1716                                                 li_->getVNInfoAllocator());
1717         NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1718         RealInt.addKills(NewValNo, ValNo->kills);
1719         RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1720       }
1721       RealInt.weight += SavedLI->weight;
1722       DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1723     }
1724
1725     // Update the liveintervals of sub-registers.
1726     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1727       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, *ResSrcInt,
1728                                                  li_->getVNInfoAllocator());
1729   }
1730
1731   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1732   // larger super-register.
1733   if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1734       !SrcIsPhys && !DstIsPhys) {
1735     if ((isExtSubReg && !Swapped) ||
1736         ((isInsSubReg || isSubRegToReg) && Swapped)) {
1737       ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1738       std::swap(SrcReg, DstReg);
1739       std::swap(ResSrcInt, ResDstInt);
1740     }
1741   }
1742
1743   // Coalescing to a virtual register that is of a sub-register class of the
1744   // other. Make sure the resulting register is set to the right register class.
1745   if (CrossRC)
1746     ++numCrossRCs;
1747
1748   // This may happen even if it's cross-rc coalescing. e.g.
1749   // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1750   // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1751   // be allocate a register from GR64_ABCD.
1752   if (NewRC)
1753     mri_->setRegClass(DstReg, NewRC);
1754
1755   // Remember to delete the copy instruction.
1756   JoinedCopies.insert(CopyMI);
1757
1758   // Some live range has been lengthened due to colaescing, eliminate the
1759   // unnecessary kills.
1760   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1761   if (TargetRegisterInfo::isVirtualRegister(DstReg))
1762     RemoveUnnecessaryKills(DstReg, *ResDstInt);
1763
1764   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1765
1766   // If we have extended the live range of a physical register, make sure we
1767   // update live-in lists as well.
1768   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1769     const LiveInterval &VRegInterval = li_->getInterval(SrcReg);
1770     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1771     for (LiveInterval::const_iterator I = VRegInterval.begin(),
1772            E = VRegInterval.end(); I != E; ++I ) {
1773       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1774       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1775         MachineBasicBlock &block = *BlockSeq[idx];
1776         if (!block.isLiveIn(DstReg))
1777           block.addLiveIn(DstReg);
1778       }
1779       BlockSeq.clear();
1780     }
1781   }
1782
1783   // SrcReg is guarateed to be the register whose live interval that is
1784   // being merged.
1785   li_->removeInterval(SrcReg);
1786
1787   // Update regalloc hint.
1788   tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1789
1790   // Manually deleted the live interval copy.
1791   if (SavedLI) {
1792     SavedLI->clear();
1793     delete SavedLI;
1794   }
1795
1796   // If resulting interval has a preference that no longer fits because of subreg
1797   // coalescing, just clear the preference.
1798   unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1799   if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1800       TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1801     const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1802     if (!RC->contains(Preference))
1803       mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1804   }
1805
1806   DEBUG({
1807       dbgs() << "\n\t\tJoined.  Result = ";
1808       ResDstInt->print(dbgs(), tri_);
1809       dbgs() << "\n";
1810     });
1811
1812   ++numJoins;
1813   return true;
1814 }
1815
1816 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1817 /// compute what the resultant value numbers for each value in the input two
1818 /// ranges will be.  This is complicated by copies between the two which can
1819 /// and will commonly cause multiple value numbers to be merged into one.
1820 ///
1821 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1822 /// keeps track of the new InstDefiningValue assignment for the result
1823 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1824 /// whether a value in this or other is a copy from the opposite set.
1825 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1826 /// already been assigned.
1827 ///
1828 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1829 /// contains the value number the copy is from.
1830 ///
1831 static unsigned ComputeUltimateVN(VNInfo *VNI,
1832                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1833                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1834                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1835                                   SmallVector<int, 16> &ThisValNoAssignments,
1836                                   SmallVector<int, 16> &OtherValNoAssignments) {
1837   unsigned VN = VNI->id;
1838
1839   // If the VN has already been computed, just return it.
1840   if (ThisValNoAssignments[VN] >= 0)
1841     return ThisValNoAssignments[VN];
1842 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1843
1844   // If this val is not a copy from the other val, then it must be a new value
1845   // number in the destination.
1846   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1847   if (I == ThisFromOther.end()) {
1848     NewVNInfo.push_back(VNI);
1849     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1850   }
1851   VNInfo *OtherValNo = I->second;
1852
1853   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1854   // been computed, return it.
1855   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1856     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1857
1858   // Mark this value number as currently being computed, then ask what the
1859   // ultimate value # of the other value is.
1860   ThisValNoAssignments[VN] = -2;
1861   unsigned UltimateVN =
1862     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1863                       OtherValNoAssignments, ThisValNoAssignments);
1864   return ThisValNoAssignments[VN] = UltimateVN;
1865 }
1866
1867 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1868   return std::find(V.begin(), V.end(), Val) != V.end();
1869 }
1870
1871 static bool isValNoDefMove(const MachineInstr *MI, unsigned DR, unsigned SR,
1872                            const TargetInstrInfo *TII,
1873                            const TargetRegisterInfo *TRI) {
1874   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1875   if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1876     ;
1877   else if (MI->isExtractSubreg()) {
1878     DstReg = MI->getOperand(0).getReg();
1879     SrcReg = MI->getOperand(1).getReg();
1880   } else if (MI->isSubregToReg() ||
1881              MI->isInsertSubreg()) {
1882     DstReg = MI->getOperand(0).getReg();
1883     SrcReg = MI->getOperand(2).getReg();
1884   } else
1885     return false;
1886   return (SrcReg == SR || TRI->isSuperRegister(SR, SrcReg)) &&
1887          (DstReg == DR || TRI->isSuperRegister(DR, DstReg));
1888 }
1889
1890 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1891 /// the specified live interval is defined by a copy from the specified
1892 /// register.
1893 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1894                                                            LiveRange *LR,
1895                                                            unsigned Reg) {
1896   unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1897   if (SrcReg == Reg)
1898     return true;
1899   // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1900   if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1901       TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1902       *tri_->getSuperRegisters(li.reg)) {
1903     // It's a sub-register live interval, we may not have precise information.
1904     // Re-compute it.
1905     MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1906     if (DefMI && isValNoDefMove(DefMI, li.reg, Reg, tii_, tri_)) {
1907       // Cache computed info.
1908       LR->valno->def = LR->start;
1909       LR->valno->setCopy(DefMI);
1910       return true;
1911     }
1912   }
1913   return false;
1914 }
1915
1916
1917 /// ValueLiveAt - Return true if the LiveRange pointed to by the given
1918 /// iterator, or any subsequent range with the same value number,
1919 /// is live at the given point.
1920 bool SimpleRegisterCoalescing::ValueLiveAt(LiveInterval::iterator LRItr,
1921                                            LiveInterval::iterator LREnd,
1922                                            SlotIndex defPoint) const {
1923   for (const VNInfo *valno = LRItr->valno;
1924        (LRItr != LREnd) && (LRItr->valno == valno); ++LRItr) {
1925     if (LRItr->contains(defPoint))
1926       return true;
1927   }
1928
1929   return false;
1930 }
1931
1932
1933 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1934 /// caller of this method must guarantee that the RHS only contains a single
1935 /// value number and that the RHS is not defined by a copy from this
1936 /// interval.  This returns false if the intervals are not joinable, or it
1937 /// joins them and returns true.
1938 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1939   assert(RHS.containsOneValue());
1940
1941   // Some number (potentially more than one) value numbers in the current
1942   // interval may be defined as copies from the RHS.  Scan the overlapping
1943   // portions of the LHS and RHS, keeping track of this and looking for
1944   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1945   // cannot coalesce.
1946
1947   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1948   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1949
1950   if (LHSIt->start < RHSIt->start) {
1951     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1952     if (LHSIt != LHS.begin()) --LHSIt;
1953   } else if (RHSIt->start < LHSIt->start) {
1954     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1955     if (RHSIt != RHS.begin()) --RHSIt;
1956   }
1957
1958   SmallVector<VNInfo*, 8> EliminatedLHSVals;
1959
1960   while (1) {
1961     // Determine if these live intervals overlap.
1962     bool Overlaps = false;
1963     if (LHSIt->start <= RHSIt->start)
1964       Overlaps = LHSIt->end > RHSIt->start;
1965     else
1966       Overlaps = RHSIt->end > LHSIt->start;
1967
1968     // If the live intervals overlap, there are two interesting cases: if the
1969     // LHS interval is defined by a copy from the RHS, it's ok and we record
1970     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1971     // coalesce these live ranges and we bail out.
1972     if (Overlaps) {
1973       // If we haven't already recorded that this value # is safe, check it.
1974       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1975         // If it's re-defined by an early clobber somewhere in the live range,
1976         // then conservatively abort coalescing.
1977         if (LHSIt->valno->hasRedefByEC())
1978           return false;
1979         // Copy from the RHS?
1980         if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1981           return false;    // Nope, bail out.
1982
1983         if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
1984           // Here is an interesting situation:
1985           // BB1:
1986           //   vr1025 = copy vr1024
1987           //   ..
1988           // BB2:
1989           //   vr1024 = op
1990           //          = vr1025
1991           // Even though vr1025 is copied from vr1024, it's not safe to
1992           // coalesce them since the live range of vr1025 intersects the
1993           // def of vr1024. This happens because vr1025 is assigned the
1994           // value of the previous iteration of vr1024.
1995           return false;
1996         EliminatedLHSVals.push_back(LHSIt->valno);
1997       }
1998
1999       // We know this entire LHS live range is okay, so skip it now.
2000       if (++LHSIt == LHSEnd) break;
2001       continue;
2002     }
2003
2004     if (LHSIt->end < RHSIt->end) {
2005       if (++LHSIt == LHSEnd) break;
2006     } else {
2007       // One interesting case to check here.  It's possible that we have
2008       // something like "X3 = Y" which defines a new value number in the LHS,
2009       // and is the last use of this liverange of the RHS.  In this case, we
2010       // want to notice this copy (so that it gets coalesced away) even though
2011       // the live ranges don't actually overlap.
2012       if (LHSIt->start == RHSIt->end) {
2013         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
2014           // We already know that this value number is going to be merged in
2015           // if coalescing succeeds.  Just skip the liverange.
2016           if (++LHSIt == LHSEnd) break;
2017         } else {
2018           // If it's re-defined by an early clobber somewhere in the live range,
2019           // then conservatively abort coalescing.
2020           if (LHSIt->valno->hasRedefByEC())
2021             return false;
2022           // Otherwise, if this is a copy from the RHS, mark it as being merged
2023           // in.
2024           if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
2025             if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
2026               // Here is an interesting situation:
2027               // BB1:
2028               //   vr1025 = copy vr1024
2029               //   ..
2030               // BB2:
2031               //   vr1024 = op
2032               //          = vr1025
2033               // Even though vr1025 is copied from vr1024, it's not safe to
2034               // coalesced them since live range of vr1025 intersects the
2035               // def of vr1024. This happens because vr1025 is assigned the
2036               // value of the previous iteration of vr1024.
2037               return false;
2038             EliminatedLHSVals.push_back(LHSIt->valno);
2039
2040             // We know this entire LHS live range is okay, so skip it now.
2041             if (++LHSIt == LHSEnd) break;
2042           }
2043         }
2044       }
2045
2046       if (++RHSIt == RHSEnd) break;
2047     }
2048   }
2049
2050   // If we got here, we know that the coalescing will be successful and that
2051   // the value numbers in EliminatedLHSVals will all be merged together.  Since
2052   // the most common case is that EliminatedLHSVals has a single number, we
2053   // optimize for it: if there is more than one value, we merge them all into
2054   // the lowest numbered one, then handle the interval as if we were merging
2055   // with one value number.
2056   VNInfo *LHSValNo = NULL;
2057   if (EliminatedLHSVals.size() > 1) {
2058     // Loop through all the equal value numbers merging them into the smallest
2059     // one.
2060     VNInfo *Smallest = EliminatedLHSVals[0];
2061     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
2062       if (EliminatedLHSVals[i]->id < Smallest->id) {
2063         // Merge the current notion of the smallest into the smaller one.
2064         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
2065         Smallest = EliminatedLHSVals[i];
2066       } else {
2067         // Merge into the smallest.
2068         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
2069       }
2070     }
2071     LHSValNo = Smallest;
2072   } else if (EliminatedLHSVals.empty()) {
2073     if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2074         *tri_->getSuperRegisters(LHS.reg))
2075       // Imprecise sub-register information. Can't handle it.
2076       return false;
2077     llvm_unreachable("No copies from the RHS?");
2078   } else {
2079     LHSValNo = EliminatedLHSVals[0];
2080   }
2081
2082   // Okay, now that there is a single LHS value number that we're merging the
2083   // RHS into, update the value number info for the LHS to indicate that the
2084   // value number is defined where the RHS value number was.
2085   const VNInfo *VNI = RHS.getValNumInfo(0);
2086   LHSValNo->def  = VNI->def;
2087   LHSValNo->setCopy(VNI->getCopy());
2088
2089   // Okay, the final step is to loop over the RHS live intervals, adding them to
2090   // the LHS.
2091   if (VNI->hasPHIKill())
2092     LHSValNo->setHasPHIKill(true);
2093   LHS.addKills(LHSValNo, VNI->kills);
2094   LHS.MergeRangesInAsValue(RHS, LHSValNo);
2095
2096   LHS.ComputeJoinedWeight(RHS);
2097
2098   // Update regalloc hint if both are virtual registers.
2099   if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2100       TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2101     std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2102     std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2103     if (RHSPref != LHSPref)
2104       mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2105   }
2106
2107   // Update the liveintervals of sub-registers.
2108   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2109     for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2110       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, LHS,
2111                                                     li_->getVNInfoAllocator());
2112
2113   return true;
2114 }
2115
2116 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
2117 /// returns false.  Otherwise, if one of the intervals being joined is a
2118 /// physreg, this method always canonicalizes LHS to be it.  The output
2119 /// "RHS" will not have been modified, so we can use this information
2120 /// below to update aliases.
2121 bool
2122 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2123                                         bool &Swapped) {
2124   // Compute the final value assignment, assuming that the live ranges can be
2125   // coalesced.
2126   SmallVector<int, 16> LHSValNoAssignments;
2127   SmallVector<int, 16> RHSValNoAssignments;
2128   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2129   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2130   SmallVector<VNInfo*, 16> NewVNInfo;
2131
2132   // If a live interval is a physical register, conservatively check if any
2133   // of its sub-registers is overlapping the live interval of the virtual
2134   // register. If so, do not coalesce.
2135   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2136       *tri_->getSubRegisters(LHS.reg)) {
2137     // If it's coalescing a virtual register to a physical register, estimate
2138     // its live interval length. This is the *cost* of scanning an entire live
2139     // interval. If the cost is low, we'll do an exhaustive check instead.
2140
2141     // If this is something like this:
2142     // BB1:
2143     // v1024 = op
2144     // ...
2145     // BB2:
2146     // ...
2147     // RAX   = v1024
2148     //
2149     // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2150     // less conservative check. It's possible a sub-register is defined before
2151     // v1024 (or live in) and live out of BB1.
2152     if (RHS.containsOneValue() &&
2153         li_->intervalIsInOneMBB(RHS) &&
2154         li_->getApproximateInstructionCount(RHS) <= 10) {
2155       // Perform a more exhaustive check for some common cases.
2156       if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2157         return false;
2158     } else {
2159       for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2160         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2161           DEBUG({
2162               dbgs() << "Interfere with sub-register ";
2163               li_->getInterval(*SR).print(dbgs(), tri_);
2164             });
2165           return false;
2166         }
2167     }
2168   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2169              *tri_->getSubRegisters(RHS.reg)) {
2170     if (LHS.containsOneValue() &&
2171         li_->getApproximateInstructionCount(LHS) <= 10) {
2172       // Perform a more exhaustive check for some common cases.
2173       if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2174         return false;
2175     } else {
2176       for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2177         if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2178           DEBUG({
2179               dbgs() << "Interfere with sub-register ";
2180               li_->getInterval(*SR).print(dbgs(), tri_);
2181             });
2182           return false;
2183         }
2184     }
2185   }
2186
2187   // Compute ultimate value numbers for the LHS and RHS values.
2188   if (RHS.containsOneValue()) {
2189     // Copies from a liveinterval with a single value are simple to handle and
2190     // very common, handle the special case here.  This is important, because
2191     // often RHS is small and LHS is large (e.g. a physreg).
2192
2193     // Find out if the RHS is defined as a copy from some value in the LHS.
2194     int RHSVal0DefinedFromLHS = -1;
2195     int RHSValID = -1;
2196     VNInfo *RHSValNoInfo = NULL;
2197     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2198     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2199     if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2200       // If RHS is not defined as a copy from the LHS, we can use simpler and
2201       // faster checks to see if the live ranges are coalescable.  This joiner
2202       // can't swap the LHS/RHS intervals though.
2203       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2204         return SimpleJoin(LHS, RHS);
2205       } else {
2206         RHSValNoInfo = RHSValNoInfo0;
2207       }
2208     } else {
2209       // It was defined as a copy from the LHS, find out what value # it is.
2210       RHSValNoInfo =
2211         LHS.getLiveRangeContaining(RHSValNoInfo0->def.getPrevSlot())->valno;
2212       RHSValID = RHSValNoInfo->id;
2213       RHSVal0DefinedFromLHS = RHSValID;
2214     }
2215
2216     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2217     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2218     NewVNInfo.resize(LHS.getNumValNums(), NULL);
2219
2220     // Okay, *all* of the values in LHS that are defined as a copy from RHS
2221     // should now get updated.
2222     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2223          i != e; ++i) {
2224       VNInfo *VNI = *i;
2225       unsigned VN = VNI->id;
2226       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2227         if (LHSSrcReg != RHS.reg) {
2228           // If this is not a copy from the RHS, its value number will be
2229           // unmodified by the coalescing.
2230           NewVNInfo[VN] = VNI;
2231           LHSValNoAssignments[VN] = VN;
2232         } else if (RHSValID == -1) {
2233           // Otherwise, it is a copy from the RHS, and we don't already have a
2234           // value# for it.  Keep the current value number, but remember it.
2235           LHSValNoAssignments[VN] = RHSValID = VN;
2236           NewVNInfo[VN] = RHSValNoInfo;
2237           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2238         } else {
2239           // Otherwise, use the specified value #.
2240           LHSValNoAssignments[VN] = RHSValID;
2241           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
2242             NewVNInfo[VN] = RHSValNoInfo;
2243             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2244           }
2245         }
2246       } else {
2247         NewVNInfo[VN] = VNI;
2248         LHSValNoAssignments[VN] = VN;
2249       }
2250     }
2251
2252     assert(RHSValID != -1 && "Didn't find value #?");
2253     RHSValNoAssignments[0] = RHSValID;
2254     if (RHSVal0DefinedFromLHS != -1) {
2255       // This path doesn't go through ComputeUltimateVN so just set
2256       // it to anything.
2257       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2258     }
2259   } else {
2260     // Loop over the value numbers of the LHS, seeing if any are defined from
2261     // the RHS.
2262     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2263          i != e; ++i) {
2264       VNInfo *VNI = *i;
2265       if (VNI->isUnused() || VNI->getCopy() == 0)  // Src not defined by a copy?
2266         continue;
2267
2268       // DstReg is known to be a register in the LHS interval.  If the src is
2269       // from the RHS interval, we can use its value #.
2270       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2271         continue;
2272
2273       // Figure out the value # from the RHS.
2274       LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
2275       assert(lr && "Cannot find live range");
2276       LHSValsDefinedFromRHS[VNI] = lr->valno;
2277     }
2278
2279     // Loop over the value numbers of the RHS, seeing if any are defined from
2280     // the LHS.
2281     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2282          i != e; ++i) {
2283       VNInfo *VNI = *i;
2284       if (VNI->isUnused() || VNI->getCopy() == 0)  // Src not defined by a copy?
2285         continue;
2286
2287       // DstReg is known to be a register in the RHS interval.  If the src is
2288       // from the LHS interval, we can use its value #.
2289       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2290         continue;
2291
2292       // Figure out the value # from the LHS.
2293       LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
2294       assert(lr && "Cannot find live range");
2295       RHSValsDefinedFromLHS[VNI] = lr->valno;
2296     }
2297
2298     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2299     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2300     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2301
2302     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2303          i != e; ++i) {
2304       VNInfo *VNI = *i;
2305       unsigned VN = VNI->id;
2306       if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2307         continue;
2308       ComputeUltimateVN(VNI, NewVNInfo,
2309                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2310                         LHSValNoAssignments, RHSValNoAssignments);
2311     }
2312     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2313          i != e; ++i) {
2314       VNInfo *VNI = *i;
2315       unsigned VN = VNI->id;
2316       if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2317         continue;
2318       // If this value number isn't a copy from the LHS, it's a new number.
2319       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2320         NewVNInfo.push_back(VNI);
2321         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2322         continue;
2323       }
2324
2325       ComputeUltimateVN(VNI, NewVNInfo,
2326                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2327                         RHSValNoAssignments, LHSValNoAssignments);
2328     }
2329   }
2330
2331   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2332   // interval lists to see if these intervals are coalescable.
2333   LiveInterval::const_iterator I = LHS.begin();
2334   LiveInterval::const_iterator IE = LHS.end();
2335   LiveInterval::const_iterator J = RHS.begin();
2336   LiveInterval::const_iterator JE = RHS.end();
2337
2338   // Skip ahead until the first place of potential sharing.
2339   if (I->start < J->start) {
2340     I = std::upper_bound(I, IE, J->start);
2341     if (I != LHS.begin()) --I;
2342   } else if (J->start < I->start) {
2343     J = std::upper_bound(J, JE, I->start);
2344     if (J != RHS.begin()) --J;
2345   }
2346
2347   while (1) {
2348     // Determine if these two live ranges overlap.
2349     bool Overlaps;
2350     if (I->start < J->start) {
2351       Overlaps = I->end > J->start;
2352     } else {
2353       Overlaps = J->end > I->start;
2354     }
2355
2356     // If so, check value # info to determine if they are really different.
2357     if (Overlaps) {
2358       // If the live range overlap will map to the same value number in the
2359       // result liverange, we can still coalesce them.  If not, we can't.
2360       if (LHSValNoAssignments[I->valno->id] !=
2361           RHSValNoAssignments[J->valno->id])
2362         return false;
2363       // If it's re-defined by an early clobber somewhere in the live range,
2364       // then conservatively abort coalescing.
2365       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
2366         return false;
2367     }
2368
2369     if (I->end < J->end) {
2370       ++I;
2371       if (I == IE) break;
2372     } else {
2373       ++J;
2374       if (J == JE) break;
2375     }
2376   }
2377
2378   // Update kill info. Some live ranges are extended due to copy coalescing.
2379   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2380          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2381     VNInfo *VNI = I->first;
2382     unsigned LHSValID = LHSValNoAssignments[VNI->id];
2383     NewVNInfo[LHSValID]->removeKill(VNI->def);
2384     if (VNI->hasPHIKill())
2385       NewVNInfo[LHSValID]->setHasPHIKill(true);
2386     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2387   }
2388
2389   // Update kill info. Some live ranges are extended due to copy coalescing.
2390   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2391          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2392     VNInfo *VNI = I->first;
2393     unsigned RHSValID = RHSValNoAssignments[VNI->id];
2394     NewVNInfo[RHSValID]->removeKill(VNI->def);
2395     if (VNI->hasPHIKill())
2396       NewVNInfo[RHSValID]->setHasPHIKill(true);
2397     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2398   }
2399
2400   // If we get here, we know that we can coalesce the live ranges.  Ask the
2401   // intervals to coalesce themselves now.
2402   if ((RHS.ranges.size() > LHS.ranges.size() &&
2403       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2404       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2405     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2406              mri_);
2407     Swapped = true;
2408   } else {
2409     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2410              mri_);
2411     Swapped = false;
2412   }
2413   return true;
2414 }
2415
2416 namespace {
2417   // DepthMBBCompare - Comparison predicate that sort first based on the loop
2418   // depth of the basic block (the unsigned), and then on the MBB number.
2419   struct DepthMBBCompare {
2420     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2421     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2422       // Deeper loops first
2423       if (LHS.first != RHS.first)
2424         return LHS.first > RHS.first;
2425
2426       // Prefer blocks that are more connected in the CFG. This takes care of
2427       // the most difficult copies first while intervals are short.
2428       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
2429       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
2430       if (cl != cr)
2431         return cl > cr;
2432
2433       // As a last resort, sort by block number.
2434       return LHS.second->getNumber() < RHS.second->getNumber();
2435     }
2436   };
2437 }
2438
2439 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2440                                                std::vector<CopyRec> &TryAgain) {
2441   DEBUG(dbgs() << MBB->getName() << ":\n");
2442
2443   std::vector<CopyRec> VirtCopies;
2444   std::vector<CopyRec> PhysCopies;
2445   std::vector<CopyRec> ImpDefCopies;
2446   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2447        MII != E;) {
2448     MachineInstr *Inst = MII++;
2449
2450     // If this isn't a copy nor a extract_subreg, we can't join intervals.
2451     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2452     bool isInsUndef = false;
2453     if (Inst->isExtractSubreg()) {
2454       DstReg = Inst->getOperand(0).getReg();
2455       SrcReg = Inst->getOperand(1).getReg();
2456     } else if (Inst->isInsertSubreg()) {
2457       DstReg = Inst->getOperand(0).getReg();
2458       SrcReg = Inst->getOperand(2).getReg();
2459       if (Inst->getOperand(1).isUndef())
2460         isInsUndef = true;
2461     } else if (Inst->isInsertSubreg() || Inst->isSubregToReg()) {
2462       DstReg = Inst->getOperand(0).getReg();
2463       SrcReg = Inst->getOperand(2).getReg();
2464     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2465       continue;
2466
2467     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2468     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2469     if (isInsUndef ||
2470         (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()))
2471       ImpDefCopies.push_back(CopyRec(Inst, 0));
2472     else if (SrcIsPhys || DstIsPhys)
2473       PhysCopies.push_back(CopyRec(Inst, 0));
2474     else
2475       VirtCopies.push_back(CopyRec(Inst, 0));
2476   }
2477
2478   // Try coalescing implicit copies and insert_subreg <undef> first,
2479   // followed by copies to / from physical registers, then finally copies
2480   // from virtual registers to virtual registers.
2481   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2482     CopyRec &TheCopy = ImpDefCopies[i];
2483     bool Again = false;
2484     if (!JoinCopy(TheCopy, Again))
2485       if (Again)
2486         TryAgain.push_back(TheCopy);
2487   }
2488   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2489     CopyRec &TheCopy = PhysCopies[i];
2490     bool Again = false;
2491     if (!JoinCopy(TheCopy, Again))
2492       if (Again)
2493         TryAgain.push_back(TheCopy);
2494   }
2495   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2496     CopyRec &TheCopy = VirtCopies[i];
2497     bool Again = false;
2498     if (!JoinCopy(TheCopy, Again))
2499       if (Again)
2500         TryAgain.push_back(TheCopy);
2501   }
2502 }
2503
2504 void SimpleRegisterCoalescing::joinIntervals() {
2505   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2506
2507   std::vector<CopyRec> TryAgainList;
2508   if (loopInfo->empty()) {
2509     // If there are no loops in the function, join intervals in function order.
2510     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2511          I != E; ++I)
2512       CopyCoalesceInMBB(I, TryAgainList);
2513   } else {
2514     // Otherwise, join intervals in inner loops before other intervals.
2515     // Unfortunately we can't just iterate over loop hierarchy here because
2516     // there may be more MBB's than BB's.  Collect MBB's for sorting.
2517
2518     // Join intervals in the function prolog first. We want to join physical
2519     // registers with virtual registers before the intervals got too long.
2520     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2521     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2522       MachineBasicBlock *MBB = I;
2523       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2524     }
2525
2526     // Sort by loop depth.
2527     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2528
2529     // Finally, join intervals in loop nest order.
2530     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2531       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2532   }
2533
2534   // Joining intervals can allow other intervals to be joined.  Iteratively join
2535   // until we make no progress.
2536   bool ProgressMade = true;
2537   while (ProgressMade) {
2538     ProgressMade = false;
2539
2540     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2541       CopyRec &TheCopy = TryAgainList[i];
2542       if (!TheCopy.MI)
2543         continue;
2544
2545       bool Again = false;
2546       bool Success = JoinCopy(TheCopy, Again);
2547       if (Success || !Again) {
2548         TheCopy.MI = 0;   // Mark this one as done.
2549         ProgressMade = true;
2550       }
2551     }
2552   }
2553 }
2554
2555 /// Return true if the two specified registers belong to different register
2556 /// classes.  The registers may be either phys or virt regs.
2557 bool
2558 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2559                                                    unsigned RegB) const {
2560   // Get the register classes for the first reg.
2561   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2562     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2563            "Shouldn't consider two physregs!");
2564     return !mri_->getRegClass(RegB)->contains(RegA);
2565   }
2566
2567   // Compare against the regclass for the second reg.
2568   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2569   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2570     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2571     return RegClassA != RegClassB;
2572   }
2573   return !RegClassA->contains(RegB);
2574 }
2575
2576 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
2577 /// between cycles Start and End or NULL if there are no uses.
2578 MachineOperand *
2579 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
2580                                           SlotIndex End,
2581                                           unsigned Reg,
2582                                           SlotIndex &UseIdx) const{
2583   UseIdx = SlotIndex();
2584   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2585     MachineOperand *LastUse = NULL;
2586     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
2587            E = mri_->use_nodbg_end(); I != E; ++I) {
2588       MachineOperand &Use = I.getOperand();
2589       MachineInstr *UseMI = Use.getParent();
2590       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2591       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2592           SrcReg == DstReg)
2593         // Ignore identity copies.
2594         continue;
2595       SlotIndex Idx = li_->getInstructionIndex(UseMI);
2596       // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
2597       // that compares higher than any other interval.
2598       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2599         LastUse = &Use;
2600         UseIdx = Idx.getUseIndex();
2601       }
2602     }
2603     return LastUse;
2604   }
2605
2606   SlotIndex s = Start;
2607   SlotIndex e = End.getPrevSlot().getBaseIndex();
2608   while (e >= s) {
2609     // Skip deleted instructions
2610     MachineInstr *MI = li_->getInstructionFromIndex(e);
2611     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
2612       e = e.getPrevIndex();
2613       MI = li_->getInstructionFromIndex(e);
2614     }
2615     if (e < s || MI == NULL)
2616       return NULL;
2617
2618     // Ignore identity copies.
2619     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2620     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2621           SrcReg == DstReg))
2622       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2623         MachineOperand &Use = MI->getOperand(i);
2624         if (Use.isReg() && Use.isUse() && Use.getReg() &&
2625             tri_->regsOverlap(Use.getReg(), Reg)) {
2626           UseIdx = e.getUseIndex();
2627           return &Use;
2628         }
2629       }
2630
2631     e = e.getPrevIndex();
2632   }
2633
2634   return NULL;
2635 }
2636
2637 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2638   if (TargetRegisterInfo::isPhysicalRegister(reg))
2639     dbgs() << tri_->getName(reg);
2640   else
2641     dbgs() << "%reg" << reg;
2642 }
2643
2644 void SimpleRegisterCoalescing::releaseMemory() {
2645   JoinedCopies.clear();
2646   ReMatCopies.clear();
2647   ReMatDefs.clear();
2648 }
2649
2650 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2651   mf_ = &fn;
2652   mri_ = &fn.getRegInfo();
2653   tm_ = &fn.getTarget();
2654   tri_ = tm_->getRegisterInfo();
2655   tii_ = tm_->getInstrInfo();
2656   li_ = &getAnalysis<LiveIntervals>();
2657   AA = &getAnalysis<AliasAnalysis>();
2658   loopInfo = &getAnalysis<MachineLoopInfo>();
2659
2660   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2661                << "********** Function: "
2662                << ((Value*)mf_->getFunction())->getName() << '\n');
2663
2664   allocatableRegs_ = tri_->getAllocatableSet(fn);
2665   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2666          E = tri_->regclass_end(); I != E; ++I)
2667     allocatableRCRegs_.insert(std::make_pair(*I,
2668                                              tri_->getAllocatableSet(fn, *I)));
2669
2670   // Join (coalesce) intervals if requested.
2671   if (EnableJoining) {
2672     joinIntervals();
2673     DEBUG({
2674         dbgs() << "********** INTERVALS POST JOINING **********\n";
2675         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
2676              I != E; ++I){
2677           I->second->print(dbgs(), tri_);
2678           dbgs() << "\n";
2679         }
2680       });
2681   }
2682
2683   // Perform a final pass over the instructions and compute spill weights
2684   // and remove identity moves.
2685   SmallVector<unsigned, 4> DeadDefs;
2686   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2687        mbbi != mbbe; ++mbbi) {
2688     MachineBasicBlock* mbb = mbbi;
2689     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2690          mii != mie; ) {
2691       MachineInstr *MI = mii;
2692       unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2693       if (JoinedCopies.count(MI)) {
2694         // Delete all coalesced copies.
2695         bool DoDelete = true;
2696         if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2697           assert((MI->isExtractSubreg() || MI->isInsertSubreg() ||
2698                   MI->isSubregToReg()) && "Unrecognized copy instruction");
2699           DstReg = MI->getOperand(0).getReg();
2700           if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2701             // Do not delete extract_subreg, insert_subreg of physical
2702             // registers unless the definition is dead. e.g.
2703             // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
2704             // or else the scavenger may complain. LowerSubregs will
2705             // delete them later.
2706             DoDelete = false;
2707         }
2708         if (MI->registerDefIsDead(DstReg)) {
2709           LiveInterval &li = li_->getInterval(DstReg);
2710           if (!ShortenDeadCopySrcLiveRange(li, MI))
2711             ShortenDeadCopyLiveRange(li, MI);
2712           DoDelete = true;
2713         }
2714         if (!DoDelete)
2715           mii = llvm::next(mii);
2716         else {
2717           li_->RemoveMachineInstrFromMaps(MI);
2718           mii = mbbi->erase(mii);
2719           ++numPeep;
2720         }
2721         continue;
2722       }
2723
2724       // Now check if this is a remat'ed def instruction which is now dead.
2725       if (ReMatDefs.count(MI)) {
2726         bool isDead = true;
2727         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2728           const MachineOperand &MO = MI->getOperand(i);
2729           if (!MO.isReg())
2730             continue;
2731           unsigned Reg = MO.getReg();
2732           if (!Reg)
2733             continue;
2734           if (TargetRegisterInfo::isVirtualRegister(Reg))
2735             DeadDefs.push_back(Reg);
2736           if (MO.isDead())
2737             continue;
2738           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2739               !mri_->use_empty(Reg)) {
2740             isDead = false;
2741             break;
2742           }
2743         }
2744         if (isDead) {
2745           while (!DeadDefs.empty()) {
2746             unsigned DeadDef = DeadDefs.back();
2747             DeadDefs.pop_back();
2748             RemoveDeadDef(li_->getInterval(DeadDef), MI);
2749           }
2750           li_->RemoveMachineInstrFromMaps(mii);
2751           mii = mbbi->erase(mii);
2752           continue;
2753         } else
2754           DeadDefs.clear();
2755       }
2756
2757       // If the move will be an identity move delete it
2758       bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2759       if (isMove && SrcReg == DstReg) {
2760         if (li_->hasInterval(SrcReg)) {
2761           LiveInterval &RegInt = li_->getInterval(SrcReg);
2762           // If def of this move instruction is dead, remove its live range
2763           // from the dstination register's live interval.
2764           if (MI->registerDefIsDead(DstReg)) {
2765             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2766               ShortenDeadCopyLiveRange(RegInt, MI);
2767           }
2768         }
2769         li_->RemoveMachineInstrFromMaps(MI);
2770         mii = mbbi->erase(mii);
2771         ++numPeep;
2772       } else {
2773         ++mii;
2774       }
2775     }
2776   }
2777
2778   DEBUG(dump());
2779   return true;
2780 }
2781
2782 /// print - Implement the dump method.
2783 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2784    li_->print(O, m);
2785 }
2786
2787 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2788   return new SimpleRegisterCoalescing();
2789 }
2790
2791 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2792 DEFINING_FILE_FOR(SimpleRegisterCoalescing)