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