Be conservative if getresult operand is neither call nor invoke.
[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) {
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 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
475 /// due to live range lengthening as the result of coalescing.
476 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
477                                                       LiveInterval &LI) {
478   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
479          UE = mri_->use_end(); UI != UE; ++UI) {
480     MachineOperand &UseMO = UI.getOperand();
481     if (UseMO.isKill()) {
482       MachineInstr *UseMI = UseMO.getParent();
483       unsigned SReg, DReg;
484       if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
485         continue;
486       unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
487       if (JoinedCopies.count(UseMI))
488         continue;
489       LiveInterval::const_iterator UI = LI.FindLiveRangeContaining(UseIdx);
490       assert(UI != LI.end());
491       if (!LI.isKill(UI->valno, UseIdx+1))
492         UseMO.setIsKill(false);
493     }
494   }
495 }
496
497 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
498 /// from a physical register live interval as well as from the live intervals
499 /// of its sub-registers.
500 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
501                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
502   li.removeRange(Start, End, true);
503   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
504     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
505       if (!li_->hasInterval(*SR))
506         continue;
507       LiveInterval &sli = li_->getInterval(*SR);
508       unsigned RemoveEnd = Start;
509       while (RemoveEnd != End) {
510         LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
511         if (LR == sli.end())
512           break;
513         RemoveEnd = (LR->end < End) ? LR->end : End;
514         sli.removeRange(Start, RemoveEnd, true);
515         Start = RemoveEnd;
516       }
517     }
518   }
519 }
520
521 /// removeIntervalIfEmpty - Check if the live interval of a physical register
522 /// is empty, if so remove it and also remove the empty intervals of its
523 /// sub-registers.
524 static void removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
525                                   const TargetRegisterInfo *tri_) {
526   if (li.empty()) {
527     li_->removeInterval(li.reg);
528     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
529       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
530         if (!li_->hasInterval(*SR))
531           continue;
532         LiveInterval &sli = li_->getInterval(*SR);
533         if (sli.empty())
534           li_->removeInterval(*SR);
535       }
536   }
537 }
538
539 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
540 ///
541 void SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
542                                                         MachineInstr *CopyMI) {
543   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
544   LiveInterval::iterator MLR =
545     li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
546   if (MLR == li.end())
547     return;  // Already removed by ShortenDeadCopySrcLiveRange.
548   unsigned RemoveStart = MLR->start;
549   unsigned RemoveEnd = MLR->end;
550   // Remove the liverange that's defined by this.
551   if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
552     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
553     removeIntervalIfEmpty(li, li_, tri_);
554   }
555 }
556
557 /// PropagateDeadness - Propagate the dead marker to the instruction which
558 /// defines the val#.
559 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
560                               unsigned &LRStart, LiveIntervals *li_,
561                               const TargetRegisterInfo* tri_) {
562   MachineInstr *DefMI =
563     li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
564   if (DefMI && DefMI != CopyMI) {
565     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
566     if (DeadIdx != -1) {
567       DefMI->getOperand(DeadIdx).setIsDead();
568       // A dead def should have a single cycle interval.
569       ++LRStart;
570     }
571   }
572 }
573
574 /// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially
575 /// extended by a dead copy. Mark the last use (if any) of the val# as kill
576 /// as ends the live range there. If there isn't another use, then this
577 /// live range is dead.
578 void
579 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
580                                                       MachineInstr *CopyMI) {
581   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
582   if (CopyIdx == 0) {
583     // FIXME: special case: function live in. It can be a general case if the
584     // first instruction index starts at > 0 value.
585     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
586     // Live-in to the function but dead. Remove it from entry live-in set.
587     mf_->begin()->removeLiveIn(li.reg);
588     LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
589     removeRange(li, LR->start, LR->end, li_, tri_);
590     removeIntervalIfEmpty(li, li_, tri_);
591     return;
592   }
593
594   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
595   if (LR == li.end())
596     // Livein but defined by a phi.
597     return;
598
599   unsigned RemoveStart = LR->start;
600   unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
601   if (LR->end > RemoveEnd)
602     // More uses past this copy? Nothing to do.
603     return;
604
605   unsigned LastUseIdx;
606   MachineOperand *LastUse =
607     lastRegisterUse(LR->start, CopyIdx-1, li.reg, LastUseIdx);
608   if (LastUse) {
609     // There are uses before the copy, just shorten the live range to the end
610     // of last use.
611     LastUse->setIsKill();
612     MachineInstr *LastUseMI = LastUse->getParent();
613     removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
614     unsigned SrcReg, DstReg;
615     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
616         DstReg == li.reg) {
617       // Last use is itself an identity code.
618       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
619       LastUseMI->getOperand(DeadIdx).setIsDead();
620     }
621     return;
622   }
623
624   // Is it livein?
625   MachineBasicBlock *CopyMBB = CopyMI->getParent();
626   unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
627   if (LR->start <= MBBStart && LR->end > MBBStart) {
628     if (LR->start == 0) {
629       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
630       // Live-in to the function but dead. Remove it from entry live-in set.
631       mf_->begin()->removeLiveIn(li.reg);
632     }
633     // FIXME: Shorten intervals in BBs that reaches this BB.
634   }
635
636   if (LR->valno->def == RemoveStart)
637     // If the def MI defines the val#, propagate the dead marker.
638     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
639
640   removeRange(li, RemoveStart, LR->end, li_, tri_);
641   removeIntervalIfEmpty(li, li_, tri_);
642 }
643
644 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
645 /// which are the src/dst of the copy instruction CopyMI.  This returns true
646 /// if the copy was successfully coalesced away. If it is not currently
647 /// possible to coalesce this interval, but it may be possible if other
648 /// things get coalesced, then it returns true by reference in 'Again'.
649 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
650   MachineInstr *CopyMI = TheCopy.MI;
651
652   Again = false;
653   if (JoinedCopies.count(CopyMI))
654     return false; // Already done.
655
656   DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
657
658   unsigned SrcReg;
659   unsigned DstReg;
660   bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
661   unsigned SubIdx = 0;
662   if (isExtSubReg) {
663     DstReg = CopyMI->getOperand(0).getReg();
664     SrcReg = CopyMI->getOperand(1).getReg();
665   } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
666     assert(0 && "Unrecognized copy instruction!");
667     return false;
668   }
669
670   // If they are already joined we continue.
671   if (SrcReg == DstReg) {
672     DOUT << "\tCopy already coalesced.\n";
673     return false;  // Not coalescable.
674   }
675   
676   bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
677   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
678
679   // If they are both physical registers, we cannot join them.
680   if (SrcIsPhys && DstIsPhys) {
681     DOUT << "\tCan not coalesce physregs.\n";
682     return false;  // Not coalescable.
683   }
684   
685   // We only join virtual registers with allocatable physical registers.
686   if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
687     DOUT << "\tSrc reg is unallocatable physreg.\n";
688     return false;  // Not coalescable.
689   }
690   if (DstIsPhys && !allocatableRegs_[DstReg]) {
691     DOUT << "\tDst reg is unallocatable physreg.\n";
692     return false;  // Not coalescable.
693   }
694
695   unsigned RealDstReg = 0;
696   if (isExtSubReg) {
697     SubIdx = CopyMI->getOperand(2).getImm();
698     if (SrcIsPhys) {
699       // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
700       // coalesced with AX.
701       SrcReg = tri_->getSubReg(SrcReg, SubIdx);
702       SubIdx = 0;
703     } else if (DstIsPhys) {
704       // If this is a extract_subreg where dst is a physical register, e.g.
705       // cl = EXTRACT_SUBREG reg1024, 1
706       // then create and update the actual physical register allocated to RHS.
707       const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
708       for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
709            unsigned SR = *SRs; ++SRs) {
710         if (DstReg == tri_->getSubReg(SR, SubIdx) &&
711             RC->contains(SR)) {
712           RealDstReg = SR;
713           break;
714         }
715       }
716       assert(RealDstReg && "Invalid extra_subreg instruction!");
717
718       // For this type of EXTRACT_SUBREG, conservatively
719       // check if the live interval of the source register interfere with the
720       // actual super physical register we are trying to coalesce with.
721       LiveInterval &RHS = li_->getInterval(SrcReg);
722       if (li_->hasInterval(RealDstReg) &&
723           RHS.overlaps(li_->getInterval(RealDstReg))) {
724         DOUT << "Interfere with register ";
725         DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
726         return false; // Not coalescable
727       }
728       for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
729         if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
730           DOUT << "Interfere with sub-register ";
731           DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
732           return false; // Not coalescable
733         }
734       SubIdx = 0;
735     } else {
736       unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
737       unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
738       const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
739       unsigned Threshold = allocatableRCRegs_[RC].count();
740       // Be conservative. If both sides are virtual registers, do not coalesce
741       // if this will cause a high use density interval to target a smaller set
742       // of registers.
743       if (DstSize > Threshold || SrcSize > Threshold) {
744         LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
745         LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
746         if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
747           Again = true;  // May be possible to coalesce later.
748           return false;
749         }
750       }
751     }
752   } else if (differingRegisterClasses(SrcReg, DstReg)) {
753     // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
754     // with another? If it's the resulting destination register, then
755     // the subidx must be propagated to uses (but only those defined
756     // by the EXTRACT_SUBREG). If it's being coalesced into another
757     // register, it should be safe because register is assumed to have
758     // the register class of the super-register.
759
760     // If they are not of the same register class, we cannot join them.
761     DOUT << "\tSrc/Dest are different register classes.\n";
762     // Allow the coalescer to try again in case either side gets coalesced to
763     // a physical register that's compatible with the other side. e.g.
764     // r1024 = MOV32to32_ r1025
765     // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
766     Again = true;  // May be possible to coalesce later.
767     return false;
768   }
769   
770   LiveInterval &SrcInt = li_->getInterval(SrcReg);
771   LiveInterval &DstInt = li_->getInterval(DstReg);
772   assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
773          "Register mapping is horribly broken!");
774
775   DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
776   DOUT << " and "; DstInt.print(DOUT, tri_);
777   DOUT << ": ";
778
779   // Check if it is necessary to propagate "isDead" property.
780   MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
781   bool isDead = mopd->isDead();
782
783   // We need to be careful about coalescing a source physical register with a
784   // virtual register. Once the coalescing is done, it cannot be broken and
785   // these are not spillable! If the destination interval uses are far away,
786   // think twice about coalescing them!
787   if (!isDead && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
788     LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
789     unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
790     unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
791     const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
792     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
793     if (TheCopy.isBackEdge)
794       Threshold *= 2; // Favors back edge copies.
795
796     // If the virtual register live interval is long but it has low use desity,
797     // do not join them, instead mark the physical register as its allocation
798     // preference.
799     unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
800     LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
801     if (Length > Threshold &&
802         (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
803       JoinVInt.preference = JoinPReg;
804       ++numAborts;
805       DOUT << "\tMay tie down a physical register, abort!\n";
806       Again = true;  // May be possible to coalesce later.
807       return false;
808     }
809   }
810
811   // Okay, attempt to join these two intervals.  On failure, this returns false.
812   // Otherwise, if one of the intervals being joined is a physreg, this method
813   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
814   // been modified, so we can use this information below to update aliases.
815   bool Swapped = false;
816   // If SrcInt is implicitly defined, it's safe to coalesce.
817   bool isEmpty = SrcInt.empty();
818   if (isEmpty && DstInt.getNumValNums() != 1) {
819     // Only coalesce an empty interval (defined by implicit_def) with
820     // another interval that's defined by a single copy.
821     DOUT << "Not profitable!\n";
822     return false;
823   }
824
825   if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
826     // Coalescing failed.
827     
828     // If we can eliminate the copy without merging the live ranges, do so now.
829     if (!isExtSubReg &&
830         (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
831          RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
832       JoinedCopies.insert(CopyMI);
833       return true;
834     }
835     
836     // Otherwise, we are unable to join the intervals.
837     DOUT << "Interference!\n";
838     Again = true;  // May be possible to coalesce later.
839     return false;
840   }
841
842   LiveInterval *ResSrcInt = &SrcInt;
843   LiveInterval *ResDstInt = &DstInt;
844   if (Swapped) {
845     std::swap(SrcReg, DstReg);
846     std::swap(ResSrcInt, ResDstInt);
847   }
848   assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
849          "LiveInterval::join didn't work right!");
850                                
851   // If we're about to merge live ranges into a physical register live range,
852   // we have to update any aliased register's live ranges to indicate that they
853   // have clobbered values for this range.
854   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
855     // If this is a extract_subreg where dst is a physical register, e.g.
856     // cl = EXTRACT_SUBREG reg1024, 1
857     // then create and update the actual physical register allocated to RHS.
858     if (RealDstReg) {
859       LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
860       SmallSet<const VNInfo*, 4> CopiedValNos;
861       for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
862              E = ResSrcInt->ranges.end(); I != E; ++I) {
863         LiveInterval::const_iterator DstLR =
864           ResDstInt->FindLiveRangeContaining(I->start);
865         assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
866         const VNInfo *DstValNo = DstLR->valno;
867         if (CopiedValNos.insert(DstValNo)) {
868           VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
869                                                   li_->getVNInfoAllocator());
870           ValNo->hasPHIKill = DstValNo->hasPHIKill;
871           RealDstInt.addKills(ValNo, DstValNo->kills);
872           RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
873         }
874       }
875       DstReg = RealDstReg;
876     }
877
878     // Update the liveintervals of sub-registers.
879     for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
880       li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
881                                                  li_->getVNInfoAllocator());
882   } else {
883     // Merge use info if the destination is a virtual register.
884     LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
885     LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
886     dVI.NumUses += sVI.NumUses;
887   }
888
889   // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
890   // larger super-register.
891   if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
892     if (!Swapped) {
893       ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
894       std::swap(SrcReg, DstReg);
895       std::swap(ResSrcInt, ResDstInt);
896     }
897   }
898
899   if (NewHeuristic) {
900     // Add all copies that define val# in the source interval into the queue.
901     for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
902            e = ResSrcInt->vni_end(); i != e; ++i) {
903       const VNInfo *vni = *i;
904       if (!vni->def || vni->def == ~1U || vni->def == ~0U)
905         continue;
906       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
907       unsigned NewSrcReg, NewDstReg;
908       if (CopyMI &&
909           JoinedCopies.count(CopyMI) == 0 &&
910           tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
911         unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
912         JoinQueue->push(CopyRec(CopyMI, LoopDepth,
913                                 isBackEdgeCopy(CopyMI, DstReg)));
914       }
915     }
916   }
917
918   // Remember to delete the copy instruction.
919   JoinedCopies.insert(CopyMI);
920
921   // Some live range has been lengthened due to colaescing, eliminate the
922   // unnecessary kills.
923   RemoveUnnecessaryKills(SrcReg, *ResDstInt);
924   if (TargetRegisterInfo::isVirtualRegister(DstReg))
925     RemoveUnnecessaryKills(DstReg, *ResDstInt);
926
927   // SrcReg is guarateed to be the register whose live interval that is
928   // being merged.
929   li_->removeInterval(SrcReg);
930   UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
931
932   if (isEmpty) {
933     // Now the copy is being coalesced away, the val# previously defined
934     // by the copy is being defined by an IMPLICIT_DEF which defines a zero
935     // length interval. Remove the val#.
936     unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
937     LiveInterval::iterator LR = ResDstInt->FindLiveRangeContaining(CopyIdx);
938     VNInfo *ImpVal = LR->valno;
939     assert(ImpVal->def == CopyIdx);
940     ResDstInt->removeValNo(ImpVal);
941   }
942
943   DOUT << "\n\t\tJoined.  Result = "; ResDstInt->print(DOUT, tri_);
944   DOUT << "\n";
945
946   ++numJoins;
947   return true;
948 }
949
950 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
951 /// compute what the resultant value numbers for each value in the input two
952 /// ranges will be.  This is complicated by copies between the two which can
953 /// and will commonly cause multiple value numbers to be merged into one.
954 ///
955 /// VN is the value number that we're trying to resolve.  InstDefiningValue
956 /// keeps track of the new InstDefiningValue assignment for the result
957 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
958 /// whether a value in this or other is a copy from the opposite set.
959 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
960 /// already been assigned.
961 ///
962 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
963 /// contains the value number the copy is from.
964 ///
965 static unsigned ComputeUltimateVN(VNInfo *VNI,
966                                   SmallVector<VNInfo*, 16> &NewVNInfo,
967                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
968                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
969                                   SmallVector<int, 16> &ThisValNoAssignments,
970                                   SmallVector<int, 16> &OtherValNoAssignments) {
971   unsigned VN = VNI->id;
972
973   // If the VN has already been computed, just return it.
974   if (ThisValNoAssignments[VN] >= 0)
975     return ThisValNoAssignments[VN];
976 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
977
978   // If this val is not a copy from the other val, then it must be a new value
979   // number in the destination.
980   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
981   if (I == ThisFromOther.end()) {
982     NewVNInfo.push_back(VNI);
983     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
984   }
985   VNInfo *OtherValNo = I->second;
986
987   // Otherwise, this *is* a copy from the RHS.  If the other side has already
988   // been computed, return it.
989   if (OtherValNoAssignments[OtherValNo->id] >= 0)
990     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
991   
992   // Mark this value number as currently being computed, then ask what the
993   // ultimate value # of the other value is.
994   ThisValNoAssignments[VN] = -2;
995   unsigned UltimateVN =
996     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
997                       OtherValNoAssignments, ThisValNoAssignments);
998   return ThisValNoAssignments[VN] = UltimateVN;
999 }
1000
1001 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1002   return std::find(V.begin(), V.end(), Val) != V.end();
1003 }
1004
1005 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1006 /// caller of this method must guarantee that the RHS only contains a single
1007 /// value number and that the RHS is not defined by a copy from this
1008 /// interval.  This returns false if the intervals are not joinable, or it
1009 /// joins them and returns true.
1010 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1011   assert(RHS.containsOneValue());
1012   
1013   // Some number (potentially more than one) value numbers in the current
1014   // interval may be defined as copies from the RHS.  Scan the overlapping
1015   // portions of the LHS and RHS, keeping track of this and looking for
1016   // overlapping live ranges that are NOT defined as copies.  If these exist, we
1017   // cannot coalesce.
1018   
1019   LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1020   LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1021   
1022   if (LHSIt->start < RHSIt->start) {
1023     LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1024     if (LHSIt != LHS.begin()) --LHSIt;
1025   } else if (RHSIt->start < LHSIt->start) {
1026     RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1027     if (RHSIt != RHS.begin()) --RHSIt;
1028   }
1029   
1030   SmallVector<VNInfo*, 8> EliminatedLHSVals;
1031   
1032   while (1) {
1033     // Determine if these live intervals overlap.
1034     bool Overlaps = false;
1035     if (LHSIt->start <= RHSIt->start)
1036       Overlaps = LHSIt->end > RHSIt->start;
1037     else
1038       Overlaps = RHSIt->end > LHSIt->start;
1039     
1040     // If the live intervals overlap, there are two interesting cases: if the
1041     // LHS interval is defined by a copy from the RHS, it's ok and we record
1042     // that the LHS value # is the same as the RHS.  If it's not, then we cannot
1043     // coalesce these live ranges and we bail out.
1044     if (Overlaps) {
1045       // If we haven't already recorded that this value # is safe, check it.
1046       if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1047         // Copy from the RHS?
1048         unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
1049         if (SrcReg != RHS.reg)
1050           return false;    // Nope, bail out.
1051         
1052         EliminatedLHSVals.push_back(LHSIt->valno);
1053       }
1054       
1055       // We know this entire LHS live range is okay, so skip it now.
1056       if (++LHSIt == LHSEnd) break;
1057       continue;
1058     }
1059     
1060     if (LHSIt->end < RHSIt->end) {
1061       if (++LHSIt == LHSEnd) break;
1062     } else {
1063       // One interesting case to check here.  It's possible that we have
1064       // something like "X3 = Y" which defines a new value number in the LHS,
1065       // and is the last use of this liverange of the RHS.  In this case, we
1066       // want to notice this copy (so that it gets coalesced away) even though
1067       // the live ranges don't actually overlap.
1068       if (LHSIt->start == RHSIt->end) {
1069         if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1070           // We already know that this value number is going to be merged in
1071           // if coalescing succeeds.  Just skip the liverange.
1072           if (++LHSIt == LHSEnd) break;
1073         } else {
1074           // Otherwise, if this is a copy from the RHS, mark it as being merged
1075           // in.
1076           if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
1077             EliminatedLHSVals.push_back(LHSIt->valno);
1078
1079             // We know this entire LHS live range is okay, so skip it now.
1080             if (++LHSIt == LHSEnd) break;
1081           }
1082         }
1083       }
1084       
1085       if (++RHSIt == RHSEnd) break;
1086     }
1087   }
1088   
1089   // If we got here, we know that the coalescing will be successful and that
1090   // the value numbers in EliminatedLHSVals will all be merged together.  Since
1091   // the most common case is that EliminatedLHSVals has a single number, we
1092   // optimize for it: if there is more than one value, we merge them all into
1093   // the lowest numbered one, then handle the interval as if we were merging
1094   // with one value number.
1095   VNInfo *LHSValNo;
1096   if (EliminatedLHSVals.size() > 1) {
1097     // Loop through all the equal value numbers merging them into the smallest
1098     // one.
1099     VNInfo *Smallest = EliminatedLHSVals[0];
1100     for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1101       if (EliminatedLHSVals[i]->id < Smallest->id) {
1102         // Merge the current notion of the smallest into the smaller one.
1103         LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1104         Smallest = EliminatedLHSVals[i];
1105       } else {
1106         // Merge into the smallest.
1107         LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1108       }
1109     }
1110     LHSValNo = Smallest;
1111   } else {
1112     assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1113     LHSValNo = EliminatedLHSVals[0];
1114   }
1115   
1116   // Okay, now that there is a single LHS value number that we're merging the
1117   // RHS into, update the value number info for the LHS to indicate that the
1118   // value number is defined where the RHS value number was.
1119   const VNInfo *VNI = RHS.getValNumInfo(0);
1120   LHSValNo->def  = VNI->def;
1121   LHSValNo->copy = VNI->copy;
1122   
1123   // Okay, the final step is to loop over the RHS live intervals, adding them to
1124   // the LHS.
1125   LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1126   LHS.addKills(LHSValNo, VNI->kills);
1127   LHS.MergeRangesInAsValue(RHS, LHSValNo);
1128   LHS.weight += RHS.weight;
1129   if (RHS.preference && !LHS.preference)
1130     LHS.preference = RHS.preference;
1131   
1132   return true;
1133 }
1134
1135 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1136 /// returns false.  Otherwise, if one of the intervals being joined is a
1137 /// physreg, this method always canonicalizes LHS to be it.  The output
1138 /// "RHS" will not have been modified, so we can use this information
1139 /// below to update aliases.
1140 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1141                                              LiveInterval &RHS, bool &Swapped) {
1142   // Compute the final value assignment, assuming that the live ranges can be
1143   // coalesced.
1144   SmallVector<int, 16> LHSValNoAssignments;
1145   SmallVector<int, 16> RHSValNoAssignments;
1146   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1147   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1148   SmallVector<VNInfo*, 16> NewVNInfo;
1149                           
1150   // If a live interval is a physical register, conservatively check if any
1151   // of its sub-registers is overlapping the live interval of the virtual
1152   // register. If so, do not coalesce.
1153   if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1154       *tri_->getSubRegisters(LHS.reg)) {
1155     for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1156       if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1157         DOUT << "Interfere with sub-register ";
1158         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1159         return false;
1160       }
1161   } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1162              *tri_->getSubRegisters(RHS.reg)) {
1163     for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1164       if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1165         DOUT << "Interfere with sub-register ";
1166         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1167         return false;
1168       }
1169   }
1170                           
1171   // Compute ultimate value numbers for the LHS and RHS values.
1172   if (RHS.containsOneValue()) {
1173     // Copies from a liveinterval with a single value are simple to handle and
1174     // very common, handle the special case here.  This is important, because
1175     // often RHS is small and LHS is large (e.g. a physreg).
1176     
1177     // Find out if the RHS is defined as a copy from some value in the LHS.
1178     int RHSVal0DefinedFromLHS = -1;
1179     int RHSValID = -1;
1180     VNInfo *RHSValNoInfo = NULL;
1181     VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1182     unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1183     if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1184       // If RHS is not defined as a copy from the LHS, we can use simpler and
1185       // faster checks to see if the live ranges are coalescable.  This joiner
1186       // can't swap the LHS/RHS intervals though.
1187       if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1188         return SimpleJoin(LHS, RHS);
1189       } else {
1190         RHSValNoInfo = RHSValNoInfo0;
1191       }
1192     } else {
1193       // It was defined as a copy from the LHS, find out what value # it is.
1194       RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1195       RHSValID = RHSValNoInfo->id;
1196       RHSVal0DefinedFromLHS = RHSValID;
1197     }
1198     
1199     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1200     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1201     NewVNInfo.resize(LHS.getNumValNums(), NULL);
1202     
1203     // Okay, *all* of the values in LHS that are defined as a copy from RHS
1204     // should now get updated.
1205     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1206          i != e; ++i) {
1207       VNInfo *VNI = *i;
1208       unsigned VN = VNI->id;
1209       if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1210         if (LHSSrcReg != RHS.reg) {
1211           // If this is not a copy from the RHS, its value number will be
1212           // unmodified by the coalescing.
1213           NewVNInfo[VN] = VNI;
1214           LHSValNoAssignments[VN] = VN;
1215         } else if (RHSValID == -1) {
1216           // Otherwise, it is a copy from the RHS, and we don't already have a
1217           // value# for it.  Keep the current value number, but remember it.
1218           LHSValNoAssignments[VN] = RHSValID = VN;
1219           NewVNInfo[VN] = RHSValNoInfo;
1220           LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1221         } else {
1222           // Otherwise, use the specified value #.
1223           LHSValNoAssignments[VN] = RHSValID;
1224           if (VN == (unsigned)RHSValID) {  // Else this val# is dead.
1225             NewVNInfo[VN] = RHSValNoInfo;
1226             LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1227           }
1228         }
1229       } else {
1230         NewVNInfo[VN] = VNI;
1231         LHSValNoAssignments[VN] = VN;
1232       }
1233     }
1234     
1235     assert(RHSValID != -1 && "Didn't find value #?");
1236     RHSValNoAssignments[0] = RHSValID;
1237     if (RHSVal0DefinedFromLHS != -1) {
1238       // This path doesn't go through ComputeUltimateVN so just set
1239       // it to anything.
1240       RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1241     }
1242   } else {
1243     // Loop over the value numbers of the LHS, seeing if any are defined from
1244     // the RHS.
1245     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1246          i != e; ++i) {
1247       VNInfo *VNI = *i;
1248       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1249         continue;
1250       
1251       // DstReg is known to be a register in the LHS interval.  If the src is
1252       // from the RHS interval, we can use its value #.
1253       if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1254         continue;
1255       
1256       // Figure out the value # from the RHS.
1257       LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1258     }
1259     
1260     // Loop over the value numbers of the RHS, seeing if any are defined from
1261     // the LHS.
1262     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1263          i != e; ++i) {
1264       VNInfo *VNI = *i;
1265       if (VNI->def == ~1U || VNI->copy == 0)  // Src not defined by a copy?
1266         continue;
1267       
1268       // DstReg is known to be a register in the RHS interval.  If the src is
1269       // from the LHS interval, we can use its value #.
1270       if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1271         continue;
1272       
1273       // Figure out the value # from the LHS.
1274       RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1275     }
1276     
1277     LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1278     RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1279     NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1280     
1281     for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1282          i != e; ++i) {
1283       VNInfo *VNI = *i;
1284       unsigned VN = VNI->id;
1285       if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
1286         continue;
1287       ComputeUltimateVN(VNI, NewVNInfo,
1288                         LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1289                         LHSValNoAssignments, RHSValNoAssignments);
1290     }
1291     for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1292          i != e; ++i) {
1293       VNInfo *VNI = *i;
1294       unsigned VN = VNI->id;
1295       if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1296         continue;
1297       // If this value number isn't a copy from the LHS, it's a new number.
1298       if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1299         NewVNInfo.push_back(VNI);
1300         RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1301         continue;
1302       }
1303       
1304       ComputeUltimateVN(VNI, NewVNInfo,
1305                         RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1306                         RHSValNoAssignments, LHSValNoAssignments);
1307     }
1308   }
1309   
1310   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1311   // interval lists to see if these intervals are coalescable.
1312   LiveInterval::const_iterator I = LHS.begin();
1313   LiveInterval::const_iterator IE = LHS.end();
1314   LiveInterval::const_iterator J = RHS.begin();
1315   LiveInterval::const_iterator JE = RHS.end();
1316   
1317   // Skip ahead until the first place of potential sharing.
1318   if (I->start < J->start) {
1319     I = std::upper_bound(I, IE, J->start);
1320     if (I != LHS.begin()) --I;
1321   } else if (J->start < I->start) {
1322     J = std::upper_bound(J, JE, I->start);
1323     if (J != RHS.begin()) --J;
1324   }
1325   
1326   while (1) {
1327     // Determine if these two live ranges overlap.
1328     bool Overlaps;
1329     if (I->start < J->start) {
1330       Overlaps = I->end > J->start;
1331     } else {
1332       Overlaps = J->end > I->start;
1333     }
1334
1335     // If so, check value # info to determine if they are really different.
1336     if (Overlaps) {
1337       // If the live range overlap will map to the same value number in the
1338       // result liverange, we can still coalesce them.  If not, we can't.
1339       if (LHSValNoAssignments[I->valno->id] !=
1340           RHSValNoAssignments[J->valno->id])
1341         return false;
1342     }
1343     
1344     if (I->end < J->end) {
1345       ++I;
1346       if (I == IE) break;
1347     } else {
1348       ++J;
1349       if (J == JE) break;
1350     }
1351   }
1352
1353   // Update kill info. Some live ranges are extended due to copy coalescing.
1354   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1355          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1356     VNInfo *VNI = I->first;
1357     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1358     LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1359     NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1360     RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1361   }
1362
1363   // Update kill info. Some live ranges are extended due to copy coalescing.
1364   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1365          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1366     VNInfo *VNI = I->first;
1367     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1368     LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1369     NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1370     LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1371   }
1372
1373   // If we get here, we know that we can coalesce the live ranges.  Ask the
1374   // intervals to coalesce themselves now.
1375   if ((RHS.ranges.size() > LHS.ranges.size() &&
1376       TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1377       TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1378     RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1379     Swapped = true;
1380   } else {
1381     LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1382     Swapped = false;
1383   }
1384   return true;
1385 }
1386
1387 namespace {
1388   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1389   // depth of the basic block (the unsigned), and then on the MBB number.
1390   struct DepthMBBCompare {
1391     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1392     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1393       if (LHS.first > RHS.first) return true;   // Deeper loops first
1394       return LHS.first == RHS.first &&
1395         LHS.second->getNumber() < RHS.second->getNumber();
1396     }
1397   };
1398 }
1399
1400 /// getRepIntervalSize - Returns the size of the interval that represents the
1401 /// specified register.
1402 template<class SF>
1403 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1404   return Rc->getRepIntervalSize(Reg);
1405 }
1406
1407 /// CopyRecSort::operator - Join priority queue sorting function.
1408 ///
1409 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1410   // Inner loops first.
1411   if (left.LoopDepth > right.LoopDepth)
1412     return false;
1413   else if (left.LoopDepth == right.LoopDepth)
1414     if (left.isBackEdge && !right.isBackEdge)
1415       return false;
1416   return true;
1417 }
1418
1419 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1420                                                std::vector<CopyRec> &TryAgain) {
1421   DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1422
1423   std::vector<CopyRec> VirtCopies;
1424   std::vector<CopyRec> PhysCopies;
1425   unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1426   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1427        MII != E;) {
1428     MachineInstr *Inst = MII++;
1429     
1430     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1431     unsigned SrcReg, DstReg;
1432     if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1433       DstReg = Inst->getOperand(0).getReg();
1434       SrcReg = Inst->getOperand(1).getReg();
1435     } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1436       continue;
1437
1438     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1439     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1440     if (NewHeuristic) {
1441       JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1442     } else {
1443       if (SrcIsPhys || DstIsPhys)
1444         PhysCopies.push_back(CopyRec(Inst, 0, false));
1445       else
1446         VirtCopies.push_back(CopyRec(Inst, 0, false));
1447     }
1448   }
1449
1450   if (NewHeuristic)
1451     return;
1452
1453   // Try coalescing physical register + virtual register first.
1454   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1455     CopyRec &TheCopy = PhysCopies[i];
1456     bool Again = false;
1457     if (!JoinCopy(TheCopy, Again))
1458       if (Again)
1459         TryAgain.push_back(TheCopy);
1460   }
1461   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1462     CopyRec &TheCopy = VirtCopies[i];
1463     bool Again = false;
1464     if (!JoinCopy(TheCopy, Again))
1465       if (Again)
1466         TryAgain.push_back(TheCopy);
1467   }
1468 }
1469
1470 void SimpleRegisterCoalescing::joinIntervals() {
1471   DOUT << "********** JOINING INTERVALS ***********\n";
1472
1473   if (NewHeuristic)
1474     JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1475
1476   std::vector<CopyRec> TryAgainList;
1477   if (loopInfo->begin() == loopInfo->end()) {
1478     // If there are no loops in the function, join intervals in function order.
1479     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1480          I != E; ++I)
1481       CopyCoalesceInMBB(I, TryAgainList);
1482   } else {
1483     // Otherwise, join intervals in inner loops before other intervals.
1484     // Unfortunately we can't just iterate over loop hierarchy here because
1485     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1486
1487     // Join intervals in the function prolog first. We want to join physical
1488     // registers with virtual registers before the intervals got too long.
1489     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1490     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1491       MachineBasicBlock *MBB = I;
1492       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1493     }
1494
1495     // Sort by loop depth.
1496     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1497
1498     // Finally, join intervals in loop nest order.
1499     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1500       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1501   }
1502   
1503   // Joining intervals can allow other intervals to be joined.  Iteratively join
1504   // until we make no progress.
1505   if (NewHeuristic) {
1506     SmallVector<CopyRec, 16> TryAgain;
1507     bool ProgressMade = true;
1508     while (ProgressMade) {
1509       ProgressMade = false;
1510       while (!JoinQueue->empty()) {
1511         CopyRec R = JoinQueue->pop();
1512         bool Again = false;
1513         bool Success = JoinCopy(R, Again);
1514         if (Success)
1515           ProgressMade = true;
1516         else if (Again)
1517           TryAgain.push_back(R);
1518       }
1519
1520       if (ProgressMade) {
1521         while (!TryAgain.empty()) {
1522           JoinQueue->push(TryAgain.back());
1523           TryAgain.pop_back();
1524         }
1525       }
1526     }
1527   } else {
1528     bool ProgressMade = true;
1529     while (ProgressMade) {
1530       ProgressMade = false;
1531
1532       for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1533         CopyRec &TheCopy = TryAgainList[i];
1534         if (TheCopy.MI) {
1535           bool Again = false;
1536           bool Success = JoinCopy(TheCopy, Again);
1537           if (Success || !Again) {
1538             TheCopy.MI = 0;   // Mark this one as done.
1539             ProgressMade = true;
1540           }
1541         }
1542       }
1543     }
1544   }
1545
1546   if (NewHeuristic)
1547     delete JoinQueue;  
1548 }
1549
1550 /// Return true if the two specified registers belong to different register
1551 /// classes.  The registers may be either phys or virt regs.
1552 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1553                                                         unsigned RegB) const {
1554
1555   // Get the register classes for the first reg.
1556   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1557     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1558            "Shouldn't consider two physregs!");
1559     return !mri_->getRegClass(RegB)->contains(RegA);
1560   }
1561
1562   // Compare against the regclass for the second reg.
1563   const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1564   if (TargetRegisterInfo::isVirtualRegister(RegB))
1565     return RegClass != mri_->getRegClass(RegB);
1566   else
1567     return !RegClass->contains(RegB);
1568 }
1569
1570 /// lastRegisterUse - Returns the last use of the specific register between
1571 /// cycles Start and End or NULL if there are no uses.
1572 MachineOperand *
1573 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1574                                           unsigned Reg, unsigned &UseIdx) const{
1575   UseIdx = 0;
1576   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1577     MachineOperand *LastUse = NULL;
1578     for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1579            E = mri_->use_end(); I != E; ++I) {
1580       MachineOperand &Use = I.getOperand();
1581       MachineInstr *UseMI = Use.getParent();
1582       unsigned SrcReg, DstReg;
1583       if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1584         // Ignore identity copies.
1585         continue;
1586       unsigned Idx = li_->getInstructionIndex(UseMI);
1587       if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1588         LastUse = &Use;
1589         UseIdx = Idx;
1590       }
1591     }
1592     return LastUse;
1593   }
1594
1595   int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1596   int s = Start;
1597   while (e >= s) {
1598     // Skip deleted instructions
1599     MachineInstr *MI = li_->getInstructionFromIndex(e);
1600     while ((e - InstrSlots::NUM) >= s && !MI) {
1601       e -= InstrSlots::NUM;
1602       MI = li_->getInstructionFromIndex(e);
1603     }
1604     if (e < s || MI == NULL)
1605       return NULL;
1606
1607     // Ignore identity copies.
1608     unsigned SrcReg, DstReg;
1609     if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
1610       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1611         MachineOperand &Use = MI->getOperand(i);
1612         if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1613             tri_->regsOverlap(Use.getReg(), Reg)) {
1614           UseIdx = e;
1615           return &Use;
1616         }
1617       }
1618
1619     e -= InstrSlots::NUM;
1620   }
1621
1622   return NULL;
1623 }
1624
1625
1626 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1627   if (TargetRegisterInfo::isPhysicalRegister(reg))
1628     cerr << tri_->getName(reg);
1629   else
1630     cerr << "%reg" << reg;
1631 }
1632
1633 void SimpleRegisterCoalescing::releaseMemory() {
1634   JoinedCopies.clear();
1635 }
1636
1637 static bool isZeroLengthInterval(LiveInterval *li) {
1638   for (LiveInterval::Ranges::const_iterator
1639          i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1640     if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1641       return false;
1642   return true;
1643 }
1644
1645 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
1646 /// turn the copy into an implicit def.
1647 bool
1648 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
1649                                              MachineBasicBlock *MBB,
1650                                              unsigned DstReg, unsigned SrcReg) {
1651   MachineInstr *CopyMI = &*I;
1652   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1653   if (!li_->hasInterval(SrcReg))
1654     return false;
1655   LiveInterval &SrcInt = li_->getInterval(SrcReg);
1656   if (!SrcInt.empty())
1657     return false;
1658   if (!li_->hasInterval(DstReg))
1659     return false;
1660   LiveInterval &DstInt = li_->getInterval(DstReg);
1661   LiveInterval::iterator DstLR = DstInt.FindLiveRangeContaining(CopyIdx);
1662   DstInt.removeValNo(DstLR->valno);
1663   CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
1664   for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
1665     CopyMI->RemoveOperand(i);
1666   bool NoUse = mri_->use_begin(SrcReg) == mri_->use_end();
1667   if (NoUse) {
1668     for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
1669            E = mri_->reg_end(); I != E; ) {
1670       assert(I.getOperand().isDef());
1671       MachineInstr *DefMI = &*I;
1672       ++I;
1673       // The implicit_def source has no other uses, delete it.
1674       assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
1675       li_->RemoveMachineInstrFromMaps(DefMI);
1676       DefMI->eraseFromParent();
1677       ++numPeep;
1678     }
1679   }
1680   ++I;
1681   return true;
1682 }
1683
1684
1685 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1686   mf_ = &fn;
1687   mri_ = &fn.getRegInfo();
1688   tm_ = &fn.getTarget();
1689   tri_ = tm_->getRegisterInfo();
1690   tii_ = tm_->getInstrInfo();
1691   li_ = &getAnalysis<LiveIntervals>();
1692   lv_ = &getAnalysis<LiveVariables>();
1693   loopInfo = &getAnalysis<MachineLoopInfo>();
1694
1695   DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1696        << "********** Function: "
1697        << ((Value*)mf_->getFunction())->getName() << '\n';
1698
1699   allocatableRegs_ = tri_->getAllocatableSet(fn);
1700   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1701          E = tri_->regclass_end(); I != E; ++I)
1702     allocatableRCRegs_.insert(std::make_pair(*I,
1703                                              tri_->getAllocatableSet(fn, *I)));
1704
1705   // Join (coalesce) intervals if requested.
1706   if (EnableJoining) {
1707     joinIntervals();
1708     DOUT << "********** INTERVALS POST JOINING **********\n";
1709     for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1710       I->second.print(DOUT, tri_);
1711       DOUT << "\n";
1712     }
1713
1714     // Delete all coalesced copies.
1715     for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1716            E = JoinedCopies.end(); I != E; ++I) {
1717       MachineInstr *CopyMI = *I;
1718       unsigned SrcReg, DstReg;
1719       tii_->isMoveInstr(*CopyMI, SrcReg, DstReg);
1720       if (CopyMI->registerDefIsDead(DstReg)) {
1721         LiveInterval &li = li_->getInterval(DstReg);
1722         ShortenDeadCopySrcLiveRange(li, CopyMI);
1723         ShortenDeadCopyLiveRange(li, CopyMI);
1724       }
1725       li_->RemoveMachineInstrFromMaps(*I);
1726       (*I)->eraseFromParent();
1727       ++numPeep;
1728     }
1729   }
1730
1731   // Perform a final pass over the instructions and compute spill weights
1732   // and remove identity moves.
1733   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1734        mbbi != mbbe; ++mbbi) {
1735     MachineBasicBlock* mbb = mbbi;
1736     unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1737
1738     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1739          mii != mie; ) {
1740       // if the move will be an identity move delete it
1741       unsigned srcReg, dstReg;
1742       bool isMove = tii_->isMoveInstr(*mii, srcReg, dstReg);
1743       if (isMove && srcReg == dstReg) {
1744         if (li_->hasInterval(srcReg)) {
1745           LiveInterval &RegInt = li_->getInterval(srcReg);
1746           // If def of this move instruction is dead, remove its live range
1747           // from the dstination register's live interval.
1748           if (mii->registerDefIsDead(dstReg)) {
1749             ShortenDeadCopySrcLiveRange(RegInt, mii);
1750             ShortenDeadCopyLiveRange(RegInt, mii);
1751           }
1752         }
1753         li_->RemoveMachineInstrFromMaps(mii);
1754         mii = mbbi->erase(mii);
1755         ++numPeep;
1756       } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, dstReg, srcReg)) {
1757         SmallSet<unsigned, 4> UniqueUses;
1758         for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1759           const MachineOperand &mop = mii->getOperand(i);
1760           if (mop.isRegister() && mop.getReg() &&
1761               TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1762             unsigned reg = mop.getReg();
1763             // Multiple uses of reg by the same instruction. It should not
1764             // contribute to spill weight again.
1765             if (UniqueUses.count(reg) != 0)
1766               continue;
1767             LiveInterval &RegInt = li_->getInterval(reg);
1768             RegInt.weight +=
1769               li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1770             UniqueUses.insert(reg);
1771           }
1772         }
1773         ++mii;
1774       }
1775     }
1776   }
1777
1778   for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1779     LiveInterval &LI = I->second;
1780     if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1781       // If the live interval length is essentially zero, i.e. in every live
1782       // range the use follows def immediately, it doesn't make sense to spill
1783       // it and hope it will be easier to allocate for this li.
1784       if (isZeroLengthInterval(&LI))
1785         LI.weight = HUGE_VALF;
1786       else {
1787         bool isLoad = false;
1788         if (li_->isReMaterializable(LI, isLoad)) {
1789           // If all of the definitions of the interval are re-materializable,
1790           // it is a preferred candidate for spilling. If non of the defs are
1791           // loads, then it's potentially very cheap to re-materialize.
1792           // FIXME: this gets much more complicated once we support non-trivial
1793           // re-materialization.
1794           if (isLoad)
1795             LI.weight *= 0.9F;
1796           else
1797             LI.weight *= 0.5F;
1798         }
1799       }
1800
1801       // Slightly prefer live interval that has been assigned a preferred reg.
1802       if (LI.preference)
1803         LI.weight *= 1.01F;
1804
1805       // Divide the weight of the interval by its size.  This encourages 
1806       // spilling of intervals that are large and have few uses, and
1807       // discourages spilling of small intervals with many uses.
1808       LI.weight /= LI.getSize();
1809     }
1810   }
1811
1812   DEBUG(dump());
1813   return true;
1814 }
1815
1816 /// print - Implement the dump method.
1817 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1818    li_->print(O, m);
1819 }
1820
1821 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1822   return new SimpleRegisterCoalescing();
1823 }
1824
1825 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1826 DEFINING_FILE_FOR(SimpleRegisterCoalescing)