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