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