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