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