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