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