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