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