Avoid comparing invalid slot indexes, and assert that it doesn't happen.
[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 "LiveDebugVariables.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/OwningPtr.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include <algorithm>
40 #include <cmath>
41 using namespace llvm;
42
43 STATISTIC(numJoins    , "Number of interval joins performed");
44 STATISTIC(numCrossRCs , "Number of cross class joins performed");
45 STATISTIC(numCommutes , "Number of instruction commuting performed");
46 STATISTIC(numExtends  , "Number of copies extended");
47 STATISTIC(NumReMats   , "Number of instructions re-materialized");
48 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
49 STATISTIC(numAborts   , "Number of times interval joining aborted");
50 STATISTIC(numDeadValNo, "Number of valno def marked dead");
51
52 char SimpleRegisterCoalescing::ID = 0;
53 static cl::opt<bool>
54 EnableJoining("join-liveintervals",
55               cl::desc("Coalesce copies (default=true)"),
56               cl::init(true));
57
58 static cl::opt<bool>
59 DisableCrossClassJoin("disable-cross-class-join",
60                cl::desc("Avoid coalescing cross register class copies"),
61                cl::init(false), cl::Hidden);
62
63 static cl::opt<bool>
64 DisablePhysicalJoin("disable-physical-join",
65                cl::desc("Avoid coalescing physical register copies"),
66                cl::init(false), cl::Hidden);
67
68 static cl::opt<bool>
69 VerifyCoalescing("verify-coalescing",
70          cl::desc("Verify machine instrs before and after register coalescing"),
71          cl::Hidden);
72
73 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing, RegisterCoalescer,
74                 "simple-register-coalescing", "Simple Register Coalescing", 
75                 false, false, true)
76 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
77 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
78 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
79 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
80 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
81 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
82 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
83 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
84 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing, RegisterCoalescer,
85                 "simple-register-coalescing", "Simple Register Coalescing", 
86                 false, false, true)
87
88 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
89
90 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
91   AU.setPreservesCFG();
92   AU.addRequired<AliasAnalysis>();
93   AU.addRequired<LiveIntervals>();
94   AU.addPreserved<LiveIntervals>();
95   AU.addRequired<LiveDebugVariables>();
96   AU.addPreserved<LiveDebugVariables>();
97   AU.addPreserved<SlotIndexes>();
98   AU.addRequired<MachineLoopInfo>();
99   AU.addPreserved<MachineLoopInfo>();
100   AU.addPreservedID(MachineDominatorsID);
101   AU.addPreservedID(StrongPHIEliminationID);
102   AU.addPreservedID(PHIEliminationID);
103   AU.addPreservedID(TwoAddressInstructionPassID);
104   MachineFunctionPass::getAnalysisUsage(AU);
105 }
106
107 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
108 /// being the source and IntB being the dest, thus this defines a value number
109 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
110 /// see if we can merge these two pieces of B into a single value number,
111 /// eliminating a copy.  For example:
112 ///
113 ///  A3 = B0
114 ///    ...
115 ///  B1 = A3      <- this copy
116 ///
117 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
118 /// value number to be replaced with B0 (which simplifies the B liveinterval).
119 ///
120 /// This returns true if an interval was modified.
121 ///
122 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
123                                                     MachineInstr *CopyMI) {
124   // Bail if there is no dst interval - can happen when merging physical subreg
125   // operations.
126   if (!li_->hasInterval(CP.getDstReg()))
127     return false;
128
129   LiveInterval &IntA =
130     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
131   LiveInterval &IntB =
132     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
133   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
134
135   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
136   // the example above.
137   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
138   if (BLR == IntB.end()) return false;
139   VNInfo *BValNo = BLR->valno;
140
141   // Get the location that B is defined at.  Two options: either this value has
142   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
143   // can't process it.
144   if (!BValNo->isDefByCopy()) return false;
145   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
146
147   // AValNo is the value number in A that defines the copy, A3 in the example.
148   SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
149   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
150   // The live range might not exist after fun with physreg coalescing.
151   if (ALR == IntA.end()) return false;
152   VNInfo *AValNo = ALR->valno;
153   // If it's re-defined by an early clobber somewhere in the live range, then
154   // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
155   // See PR3149:
156   // 172     %ECX<def> = MOV32rr %reg1039<kill>
157   // 180     INLINEASM <es:subl $5,$1
158   //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
159   //         %EAX<kill>,
160   // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
161   // 188     %EAX<def> = MOV32rr %EAX<kill>
162   // 196     %ECX<def> = MOV32rr %ECX<kill>
163   // 204     %ECX<def> = MOV32rr %ECX<kill>
164   // 212     %EAX<def> = MOV32rr %EAX<kill>
165   // 220     %EAX<def> = MOV32rr %EAX
166   // 228     %reg1039<def> = MOV32rr %ECX<kill>
167   // The early clobber operand ties ECX input to the ECX def.
168   //
169   // The live interval of ECX is represented as this:
170   // %reg20,inf = [46,47:1)[174,230:0)  0@174-(230) 1@46-(47)
171   // The coalescer has no idea there was a def in the middle of [174,230].
172   if (AValNo->hasRedefByEC())
173     return false;
174
175   // If AValNo is defined as a copy from IntB, we can potentially process this.
176   // Get the instruction that defines this value number.
177   if (!CP.isCoalescable(AValNo->getCopy()))
178     return false;
179
180   // Get the LiveRange in IntB that this value number starts with.
181   LiveInterval::iterator ValLR =
182     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
183   if (ValLR == IntB.end())
184     return false;
185
186   // Make sure that the end of the live range is inside the same block as
187   // CopyMI.
188   MachineInstr *ValLREndInst =
189     li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
190   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
191     return false;
192
193   // Okay, we now know that ValLR ends in the same block that the CopyMI
194   // live-range starts.  If there are no intervening live ranges between them in
195   // IntB, we can merge them.
196   if (ValLR+1 != BLR) return false;
197
198   // If a live interval is a physical register, conservatively check if any
199   // of its sub-registers is overlapping the live interval of the virtual
200   // register. If so, do not coalesce.
201   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
202       *tri_->getSubRegisters(IntB.reg)) {
203     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
204       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
205         DEBUG({
206             dbgs() << "\t\tInterfere with sub-register ";
207             li_->getInterval(*SR).print(dbgs(), tri_);
208           });
209         return false;
210       }
211   }
212
213   DEBUG({
214       dbgs() << "Extending: ";
215       IntB.print(dbgs(), tri_);
216     });
217
218   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
219   // We are about to delete CopyMI, so need to remove it as the 'instruction
220   // that defines this value #'. Update the valnum with the new defining
221   // instruction #.
222   BValNo->def  = FillerStart;
223   BValNo->setCopy(0);
224
225   // Okay, we can merge them.  We need to insert a new liverange:
226   // [ValLR.end, BLR.begin) of either value number, then we merge the
227   // two value numbers.
228   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
229
230   // If the IntB live range is assigned to a physical register, and if that
231   // physreg has sub-registers, update their live intervals as well.
232   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
233     for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
234       if (!li_->hasInterval(*SR))
235         continue;
236       LiveInterval &SRLI = li_->getInterval(*SR);
237       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
238                               SRLI.getNextValue(FillerStart, 0,
239                                                 li_->getVNInfoAllocator())));
240     }
241   }
242
243   // Okay, merge "B1" into the same value number as "B0".
244   if (BValNo != ValLR->valno) {
245     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
246   }
247   DEBUG({
248       dbgs() << "   result = ";
249       IntB.print(dbgs(), tri_);
250       dbgs() << "\n";
251     });
252
253   // If the source instruction was killing the source register before the
254   // merge, unset the isKill marker given the live range has been extended.
255   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
256   if (UIdx != -1) {
257     ValLREndInst->getOperand(UIdx).setIsKill(false);
258   }
259
260   // If the copy instruction was killing the destination register before the
261   // merge, find the last use and trim the live range. That will also add the
262   // isKill marker.
263   if (ALR->end == CopyIdx)
264     TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
265
266   ++numExtends;
267   return true;
268 }
269
270 /// HasOtherReachingDefs - Return true if there are definitions of IntB
271 /// other than BValNo val# that can reach uses of AValno val# of IntA.
272 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
273                                                     LiveInterval &IntB,
274                                                     VNInfo *AValNo,
275                                                     VNInfo *BValNo) {
276   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
277        AI != AE; ++AI) {
278     if (AI->valno != AValNo) continue;
279     LiveInterval::Ranges::iterator BI =
280       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
281     if (BI != IntB.ranges.begin())
282       --BI;
283     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
284       if (BI->valno == BValNo)
285         continue;
286       if (BI->start <= AI->start && BI->end > AI->start)
287         return true;
288       if (BI->start > AI->start && BI->start < AI->end)
289         return true;
290     }
291   }
292   return false;
293 }
294
295 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
296 /// IntA being the source and IntB being the dest, thus this defines a value
297 /// number in IntB.  If the source value number (in IntA) is defined by a
298 /// commutable instruction and its other operand is coalesced to the copy dest
299 /// register, see if we can transform the copy into a noop by commuting the
300 /// definition. For example,
301 ///
302 ///  A3 = op A2 B0<kill>
303 ///    ...
304 ///  B1 = A3      <- this copy
305 ///    ...
306 ///     = op A3   <- more uses
307 ///
308 /// ==>
309 ///
310 ///  B2 = op B0 A2<kill>
311 ///    ...
312 ///  B1 = B2      <- now an identify copy
313 ///    ...
314 ///     = op B2   <- more uses
315 ///
316 /// This returns true if an interval was modified.
317 ///
318 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
319                                                         MachineInstr *CopyMI) {
320   // FIXME: For now, only eliminate the copy by commuting its def when the
321   // source register is a virtual register. We want to guard against cases
322   // where the copy is a back edge copy and commuting the def lengthen the
323   // live interval of the source register to the entire loop.
324   if (CP.isPhys() && CP.isFlipped())
325     return false;
326
327   // Bail if there is no dst interval.
328   if (!li_->hasInterval(CP.getDstReg()))
329     return false;
330
331   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
332
333   LiveInterval &IntA =
334     li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
335   LiveInterval &IntB =
336     li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
337
338   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
339   // the example above.
340   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
341   if (!BValNo || !BValNo->isDefByCopy())
342     return false;
343
344   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
345
346   // AValNo is the value number in A that defines the copy, A3 in the example.
347   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
348   assert(AValNo && "COPY source not live");
349
350   // If other defs can reach uses of this def, then it's not safe to perform
351   // the optimization.
352   if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
353     return false;
354   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
355   if (!DefMI)
356     return false;
357   const TargetInstrDesc &TID = DefMI->getDesc();
358   if (!TID.isCommutable())
359     return false;
360   // If DefMI is a two-address instruction then commuting it will change the
361   // destination register.
362   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
363   assert(DefIdx != -1);
364   unsigned UseOpIdx;
365   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
366     return false;
367   unsigned Op1, Op2, NewDstIdx;
368   if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
369     return false;
370   if (Op1 == UseOpIdx)
371     NewDstIdx = Op2;
372   else if (Op2 == UseOpIdx)
373     NewDstIdx = Op1;
374   else
375     return false;
376
377   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
378   unsigned NewReg = NewDstMO.getReg();
379   if (NewReg != IntB.reg || !NewDstMO.isKill())
380     return false;
381
382   // Make sure there are no other definitions of IntB that would reach the
383   // uses which the new definition can reach.
384   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
385     return false;
386
387   // Abort if the aliases of IntB.reg have values that are not simply the
388   // clobbers from the superreg.
389   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
390     for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
391       if (li_->hasInterval(*AS) &&
392           HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
393         return false;
394
395   // If some of the uses of IntA.reg is already coalesced away, return false.
396   // It's not possible to determine whether it's safe to perform the coalescing.
397   for (MachineRegisterInfo::use_nodbg_iterator UI = 
398          mri_->use_nodbg_begin(IntA.reg), 
399        UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
400     MachineInstr *UseMI = &*UI;
401     SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
402     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
403     if (ULR == IntA.end())
404       continue;
405     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
406       return false;
407   }
408
409   DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
410                << *DefMI);
411
412   // At this point we have decided that it is legal to do this
413   // transformation.  Start by commuting the instruction.
414   MachineBasicBlock *MBB = DefMI->getParent();
415   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
416   if (!NewMI)
417     return false;
418   if (NewMI != DefMI) {
419     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
420     MBB->insert(DefMI, NewMI);
421     MBB->erase(DefMI);
422   }
423   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
424   NewMI->getOperand(OpIdx).setIsKill();
425
426   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
427   // A = or A, B
428   // ...
429   // B = A
430   // ...
431   // C = A<kill>
432   // ...
433   //   = B
434
435   // Update uses of IntA of the specific Val# with IntB.
436   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
437          UE = mri_->use_end(); UI != UE;) {
438     MachineOperand &UseMO = UI.getOperand();
439     MachineInstr *UseMI = &*UI;
440     ++UI;
441     if (JoinedCopies.count(UseMI))
442       continue;
443     if (UseMI->isDebugValue()) {
444       // FIXME These don't have an instruction index.  Not clear we have enough
445       // info to decide whether to do this replacement or not.  For now do it.
446       UseMO.setReg(NewReg);
447       continue;
448     }
449     SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
450     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
451     if (ULR == IntA.end() || ULR->valno != AValNo)
452       continue;
453     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
454       UseMO.substPhysReg(NewReg, *tri_);
455     else
456       UseMO.setReg(NewReg);
457     if (UseMI == CopyMI)
458       continue;
459     if (!UseMI->isCopy())
460       continue;
461     if (UseMI->getOperand(0).getReg() != IntB.reg ||
462         UseMI->getOperand(0).getSubReg())
463       continue;
464
465     // This copy will become a noop. If it's defining a new val#, merge it into
466     // BValNo.
467     SlotIndex DefIdx = UseIdx.getDefIndex();
468     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
469     if (!DVNI)
470       continue;
471     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
472     assert(DVNI->def == DefIdx);
473     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
474     JoinedCopies.insert(UseMI);
475   }
476
477   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
478   // is updated.
479   VNInfo *ValNo = BValNo;
480   ValNo->def = AValNo->def;
481   ValNo->setCopy(0);
482   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
483        AI != AE; ++AI) {
484     if (AI->valno != AValNo) continue;
485     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
486   }
487   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
488
489   IntA.removeValNo(AValNo);
490   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
491   ++numCommutes;
492   return true;
493 }
494
495 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
496 /// fallthoughs to SuccMBB.
497 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
498                                   MachineBasicBlock *SuccMBB,
499                                   const TargetInstrInfo *tii_) {
500   if (MBB == SuccMBB)
501     return true;
502   MachineBasicBlock *TBB = 0, *FBB = 0;
503   SmallVector<MachineOperand, 4> Cond;
504   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
505     MBB->isSuccessor(SuccMBB);
506 }
507
508 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
509 /// from a physical register live interval as well as from the live intervals
510 /// of its sub-registers.
511 static void removeRange(LiveInterval &li,
512                         SlotIndex Start, SlotIndex End,
513                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
514   li.removeRange(Start, End, true);
515   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
516     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
517       if (!li_->hasInterval(*SR))
518         continue;
519       LiveInterval &sli = li_->getInterval(*SR);
520       SlotIndex RemoveStart = Start;
521       SlotIndex RemoveEnd = Start;
522
523       while (RemoveEnd != End) {
524         LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
525         if (LR == sli.end())
526           break;
527         RemoveEnd = (LR->end < End) ? LR->end : End;
528         sli.removeRange(RemoveStart, RemoveEnd, true);
529         RemoveStart = RemoveEnd;
530       }
531     }
532   }
533 }
534
535 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
536 /// as the copy instruction, trim the live interval to the last use and return
537 /// true.
538 bool
539 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
540                                                     MachineBasicBlock *CopyMBB,
541                                                     LiveInterval &li,
542                                                     const LiveRange *LR) {
543   SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
544   SlotIndex LastUseIdx;
545   MachineOperand *LastUse =
546     lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
547   if (LastUse) {
548     MachineInstr *LastUseMI = LastUse->getParent();
549     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
550       // r1024 = op
551       // ...
552       // BB1:
553       //       = r1024
554       //
555       // BB2:
556       // r1025<dead> = r1024<kill>
557       if (MBBStart < LR->end)
558         removeRange(li, MBBStart, LR->end, li_, tri_);
559       return true;
560     }
561
562     // There are uses before the copy, just shorten the live range to the end
563     // of last use.
564     LastUse->setIsKill();
565     removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
566     if (LastUseMI->isCopy()) {
567       MachineOperand &DefMO = LastUseMI->getOperand(0);
568       if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
569         DefMO.setIsDead();
570     }
571     return true;
572   }
573
574   // Is it livein?
575   if (LR->start <= MBBStart && LR->end > MBBStart) {
576     if (LR->start == li_->getZeroIndex()) {
577       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
578       // Live-in to the function but dead. Remove it from entry live-in set.
579       mf_->begin()->removeLiveIn(li.reg);
580     }
581     // FIXME: Shorten intervals in BBs that reaches this BB.
582   }
583
584   return false;
585 }
586
587 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
588 /// computation, replace the copy by rematerialize the definition.
589 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
590                                                        bool preserveSrcInt,
591                                                        unsigned DstReg,
592                                                        unsigned DstSubIdx,
593                                                        MachineInstr *CopyMI) {
594   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
595   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
596   assert(SrcLR != SrcInt.end() && "Live range not found!");
597   VNInfo *ValNo = SrcLR->valno;
598   // If other defs can reach uses of this def, then it's not safe to perform
599   // the optimization.
600   if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
601     return false;
602   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
603   if (!DefMI)
604     return false;
605   assert(DefMI && "Defining instruction disappeared");
606   const TargetInstrDesc &TID = DefMI->getDesc();
607   if (!TID.isAsCheapAsAMove())
608     return false;
609   if (!tii_->isTriviallyReMaterializable(DefMI, AA))
610     return false;
611   bool SawStore = false;
612   if (!DefMI->isSafeToMove(tii_, AA, SawStore))
613     return false;
614   if (TID.getNumDefs() != 1)
615     return false;
616   if (!DefMI->isImplicitDef()) {
617     // Make sure the copy destination register class fits the instruction
618     // definition register class. The mismatch can happen as a result of earlier
619     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
620     const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
621     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
622       if (mri_->getRegClass(DstReg) != RC)
623         return false;
624     } else if (!RC->contains(DstReg))
625       return false;
626   }
627
628   // If destination register has a sub-register index on it, make sure it
629   // matches the instruction register class.
630   if (DstSubIdx) {
631     const TargetInstrDesc &TID = DefMI->getDesc();
632     if (TID.getNumDefs() != 1)
633       return false;
634     const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
635     const TargetRegisterClass *DstSubRC =
636       DstRC->getSubRegisterRegClass(DstSubIdx);
637     const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
638     if (DefRC == DstRC)
639       DstSubIdx = 0;
640     else if (DefRC != DstSubRC)
641       return false;
642   }
643
644   RemoveCopyFlag(DstReg, CopyMI);
645
646   MachineBasicBlock *MBB = CopyMI->getParent();
647   MachineBasicBlock::iterator MII =
648     llvm::next(MachineBasicBlock::iterator(CopyMI));
649   tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
650   MachineInstr *NewMI = prior(MII);
651
652   // CopyMI may have implicit operands, transfer them over to the newly
653   // rematerialized instruction. And update implicit def interval valnos.
654   for (unsigned i = CopyMI->getDesc().getNumOperands(),
655          e = CopyMI->getNumOperands(); i != e; ++i) {
656     MachineOperand &MO = CopyMI->getOperand(i);
657     if (MO.isReg() && MO.isImplicit())
658       NewMI->addOperand(MO);
659     if (MO.isDef())
660       RemoveCopyFlag(MO.getReg(), CopyMI);
661   }
662
663   NewMI->copyImplicitOps(CopyMI);
664   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
665   CopyMI->eraseFromParent();
666   ReMatCopies.insert(CopyMI);
667   ReMatDefs.insert(DefMI);
668   DEBUG(dbgs() << "Remat: " << *NewMI);
669   ++NumReMats;
670
671   // The source interval can become smaller because we removed a use.
672   if (preserveSrcInt)
673     li_->shrinkToUses(&SrcInt);
674
675   return true;
676 }
677
678 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
679 /// update the subregister number if it is not zero. If DstReg is a
680 /// physical register and the existing subregister number of the def / use
681 /// being updated is not zero, make sure to set it to the correct physical
682 /// subregister.
683 void
684 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
685   bool DstIsPhys = CP.isPhys();
686   unsigned SrcReg = CP.getSrcReg();
687   unsigned DstReg = CP.getDstReg();
688   unsigned SubIdx = CP.getSubIdx();
689
690   // Update LiveDebugVariables.
691   ldv_->renameRegister(SrcReg, DstReg, SubIdx);
692
693   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
694        MachineInstr *UseMI = I.skipInstruction();) {
695     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
696     // instead.
697     if (DstIsPhys) {
698       if (UseMI->isCopy() &&
699           !UseMI->getOperand(1).getSubReg() &&
700           !UseMI->getOperand(0).getSubReg() &&
701           UseMI->getOperand(1).getReg() == SrcReg &&
702           UseMI->getOperand(0).getReg() != SrcReg &&
703           UseMI->getOperand(0).getReg() != DstReg &&
704           !JoinedCopies.count(UseMI) &&
705           ReMaterializeTrivialDef(li_->getInterval(SrcReg), false,
706                                   UseMI->getOperand(0).getReg(), 0, UseMI))
707         continue;
708     }
709
710     SmallVector<unsigned,8> Ops;
711     bool Reads, Writes;
712     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
713     bool Kills = false, Deads = false;
714
715     // Replace SrcReg with DstReg in all UseMI operands.
716     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
717       MachineOperand &MO = UseMI->getOperand(Ops[i]);
718       Kills |= MO.isKill();
719       Deads |= MO.isDead();
720
721       if (DstIsPhys)
722         MO.substPhysReg(DstReg, *tri_);
723       else
724         MO.substVirtReg(DstReg, SubIdx, *tri_);
725     }
726
727     // This instruction is a copy that will be removed.
728     if (JoinedCopies.count(UseMI))
729       continue;
730
731     if (SubIdx) {
732       // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
733       // read-modify-write of DstReg.
734       if (Deads)
735         UseMI->addRegisterDead(DstReg, tri_);
736       else if (!Reads && Writes)
737         UseMI->addRegisterDefined(DstReg, tri_);
738
739       // Kill flags apply to the whole physical register.
740       if (DstIsPhys && Kills)
741         UseMI->addRegisterKilled(DstReg, tri_);
742     }
743
744     DEBUG({
745         dbgs() << "\t\tupdated: ";
746         if (!UseMI->isDebugValue())
747           dbgs() << li_->getInstructionIndex(UseMI) << "\t";
748         dbgs() << *UseMI;
749       });
750   }
751 }
752
753 /// removeIntervalIfEmpty - Check if the live interval of a physical register
754 /// is empty, if so remove it and also remove the empty intervals of its
755 /// sub-registers. Return true if live interval is removed.
756 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
757                                   const TargetRegisterInfo *tri_) {
758   if (li.empty()) {
759     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
760       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
761         if (!li_->hasInterval(*SR))
762           continue;
763         LiveInterval &sli = li_->getInterval(*SR);
764         if (sli.empty())
765           li_->removeInterval(*SR);
766       }
767     li_->removeInterval(li.reg);
768     return true;
769   }
770   return false;
771 }
772
773 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
774 /// Return true if live interval is removed.
775 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
776                                                         MachineInstr *CopyMI) {
777   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
778   LiveInterval::iterator MLR =
779     li.FindLiveRangeContaining(CopyIdx.getDefIndex());
780   if (MLR == li.end())
781     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
782   SlotIndex RemoveStart = MLR->start;
783   SlotIndex RemoveEnd = MLR->end;
784   SlotIndex DefIdx = CopyIdx.getDefIndex();
785   // Remove the liverange that's defined by this.
786   if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
787     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
788     return removeIntervalIfEmpty(li, li_, tri_);
789   }
790   return false;
791 }
792
793 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
794 /// the val# it defines. If the live interval becomes empty, remove it as well.
795 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
796                                              MachineInstr *DefMI) {
797   SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
798   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
799   if (DefIdx != MLR->valno->def)
800     return false;
801   li.removeValNo(MLR->valno);
802   return removeIntervalIfEmpty(li, li_, tri_);
803 }
804
805 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
806                                               const MachineInstr *CopyMI) {
807   SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
808   if (li_->hasInterval(DstReg)) {
809     LiveInterval &LI = li_->getInterval(DstReg);
810     if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
811       if (LR->valno->def == DefIdx)
812         LR->valno->setCopy(0);
813   }
814   if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
815     return;
816   for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
817     if (!li_->hasInterval(*AS))
818       continue;
819     LiveInterval &LI = li_->getInterval(*AS);
820     if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
821       if (LR->valno->def == DefIdx)
822         LR->valno->setCopy(0);
823   }
824 }
825
826 /// PropagateDeadness - Propagate the dead marker to the instruction which
827 /// defines the val#.
828 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
829                               SlotIndex &LRStart, LiveIntervals *li_,
830                               const TargetRegisterInfo* tri_) {
831   MachineInstr *DefMI =
832     li_->getInstructionFromIndex(LRStart.getDefIndex());
833   if (DefMI && DefMI != CopyMI) {
834     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
835     if (DeadIdx != -1)
836       DefMI->getOperand(DeadIdx).setIsDead();
837     else
838       DefMI->addOperand(MachineOperand::CreateReg(li.reg,
839                    /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
840     LRStart = LRStart.getNextSlot();
841   }
842 }
843
844 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
845 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
846 /// ends the live range there. If there isn't another use, then this live range
847 /// is dead. Return true if live interval is removed.
848 bool
849 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
850                                                       MachineInstr *CopyMI) {
851   SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
852   if (CopyIdx == SlotIndex()) {
853     // FIXME: special case: function live in. It can be a general case if the
854     // first instruction index starts at > 0 value.
855     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
856     // Live-in to the function but dead. Remove it from entry live-in set.
857     if (mf_->begin()->isLiveIn(li.reg))
858       mf_->begin()->removeLiveIn(li.reg);
859     if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
860       removeRange(li, LR->start, LR->end, li_, tri_);
861     return removeIntervalIfEmpty(li, li_, tri_);
862   }
863
864   LiveInterval::iterator LR =
865     li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
866   if (LR == li.end())
867     // Livein but defined by a phi.
868     return false;
869
870   SlotIndex RemoveStart = LR->start;
871   SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
872   if (LR->end > RemoveEnd)
873     // More uses past this copy? Nothing to do.
874     return false;
875
876   // If there is a last use in the same bb, we can't remove the live range.
877   // Shorten the live interval and return.
878   MachineBasicBlock *CopyMBB = CopyMI->getParent();
879   if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
880     return false;
881
882   // There are other kills of the val#. Nothing to do.
883   if (!li.isOnlyLROfValNo(LR))
884     return false;
885
886   MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
887   if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
888     // If the live range starts in another mbb and the copy mbb is not a fall
889     // through mbb, then we can only cut the range from the beginning of the
890     // copy mbb.
891     RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
892
893   if (LR->valno->def == RemoveStart) {
894     // If the def MI defines the val# and this copy is the only kill of the
895     // val#, then propagate the dead marker.
896     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
897     ++numDeadValNo;
898   }
899
900   removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
901   return removeIntervalIfEmpty(li, li_, tri_);
902 }
903
904
905 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
906 /// two virtual registers from different register classes.
907 bool
908 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
909                                                 unsigned DstReg,
910                                              const TargetRegisterClass *SrcRC,
911                                              const TargetRegisterClass *DstRC,
912                                              const TargetRegisterClass *NewRC) {
913   unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
914   // This heuristics is good enough in practice, but it's obviously not *right*.
915   // 4 is a magic number that works well enough for x86, ARM, etc. It filter
916   // out all but the most restrictive register classes.
917   if (NewRCCount > 4 ||
918       // Early exit if the function is fairly small, coalesce aggressively if
919       // that's the case. For really special register classes with 3 or
920       // fewer registers, be a bit more careful.
921       (li_->getFuncInstructionCount() / NewRCCount) < 8)
922     return true;
923   LiveInterval &SrcInt = li_->getInterval(SrcReg);
924   LiveInterval &DstInt = li_->getInterval(DstReg);
925   unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
926   unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
927   if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
928     return true;
929   // Estimate *register use density*. If it doubles or more, abort.
930   unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
931                                    mri_->use_nodbg_end());
932   unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
933                                    mri_->use_nodbg_end());
934   unsigned NewUses = SrcUses + DstUses;
935   unsigned NewSize = SrcSize + DstSize;
936   if (SrcRC != NewRC && SrcSize > NewRCCount) {
937     unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
938     if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
939       return false;
940   }
941   if (DstRC != NewRC && DstSize > NewRCCount) {
942     unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
943     if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
944       return false;
945   }
946   return true;
947 }
948
949
950 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
951 /// which are the src/dst of the copy instruction CopyMI.  This returns true
952 /// if the copy was successfully coalesced away. If it is not currently
953 /// possible to coalesce this interval, but it may be possible if other
954 /// things get coalesced, then it returns true by reference in 'Again'.
955 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
956   MachineInstr *CopyMI = TheCopy.MI;
957
958   Again = false;
959   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
960     return false; // Already done.
961
962   DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
963
964   CoalescerPair CP(*tii_, *tri_);
965   if (!CP.setRegisters(CopyMI)) {
966     DEBUG(dbgs() << "\tNot coalescable.\n");
967     return false;
968   }
969
970   // If they are already joined we continue.
971   if (CP.getSrcReg() == CP.getDstReg()) {
972     DEBUG(dbgs() << "\tCopy already coalesced.\n");
973     return false;  // Not coalescable.
974   }
975
976   if (DisablePhysicalJoin && CP.isPhys()) {
977     DEBUG(dbgs() << "\tPhysical joins disabled.\n");
978     return false;
979   }
980
981   DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_));
982
983   // Enforce policies.
984   if (CP.isPhys()) {
985     DEBUG(dbgs() <<" with physreg " << PrintReg(CP.getDstReg(), tri_) << "\n");
986     // Only coalesce to allocatable physreg.
987     if (!li_->isAllocatable(CP.getDstReg())) {
988       DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
989       return false;  // Not coalescable.
990     }
991   } else {
992     DEBUG(dbgs() << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
993                  << " to " << CP.getNewRC()->getName() << "\n");
994
995     // Avoid constraining virtual register regclass too much.
996     if (CP.isCrossClass()) {
997       if (DisableCrossClassJoin) {
998         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
999         return false;
1000       }
1001       if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1002                                  mri_->getRegClass(CP.getSrcReg()),
1003                                  mri_->getRegClass(CP.getDstReg()),
1004                                  CP.getNewRC())) {
1005         DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1006                      << CP.getNewRC()->getName() << ".\n");
1007         Again = true;  // May be possible to coalesce later.
1008         return false;
1009       }
1010     }
1011
1012     // When possible, let DstReg be the larger interval.
1013     if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1014                            li_->getInterval(CP.getDstReg()).ranges.size())
1015       CP.flip();
1016   }
1017
1018   // We need to be careful about coalescing a source physical register with a
1019   // virtual register. Once the coalescing is done, it cannot be broken and
1020   // these are not spillable! If the destination interval uses are far away,
1021   // think twice about coalescing them!
1022   // FIXME: Why are we skipping this test for partial copies?
1023   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1024   if (!CP.isPartial() && CP.isPhys()) {
1025     LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1026
1027     // Don't join with physregs that have a ridiculous number of live
1028     // ranges. The data structure performance is really bad when that
1029     // happens.
1030     if (li_->hasInterval(CP.getDstReg()) &&
1031         li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1032       ++numAborts;
1033       DEBUG(dbgs()
1034            << "\tPhysical register live interval too complicated, abort!\n");
1035       return false;
1036     }
1037
1038     const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1039     unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1040     unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1041     if (Length > Threshold &&
1042         std::distance(mri_->use_nodbg_begin(CP.getSrcReg()),
1043                       mri_->use_nodbg_end()) * Threshold < Length) {
1044       // Before giving up coalescing, if definition of source is defined by
1045       // trivial computation, try rematerializing it.
1046       if (!CP.isFlipped() &&
1047           ReMaterializeTrivialDef(JoinVInt, true, CP.getDstReg(), 0, CopyMI))
1048         return true;
1049
1050       ++numAborts;
1051       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1052       Again = true;  // May be possible to coalesce later.
1053       return false;
1054     }
1055   }
1056
1057   // Okay, attempt to join these two intervals.  On failure, this returns false.
1058   // Otherwise, if one of the intervals being joined is a physreg, this method
1059   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1060   // been modified, so we can use this information below to update aliases.
1061   if (!JoinIntervals(CP)) {
1062     // Coalescing failed.
1063
1064     // If definition of source is defined by trivial computation, try
1065     // rematerializing it.
1066     if (!CP.isFlipped() &&
1067         ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1068                                 CP.getDstReg(), 0, CopyMI))
1069       return true;
1070
1071     // If we can eliminate the copy without merging the live ranges, do so now.
1072     if (!CP.isPartial()) {
1073       if (AdjustCopiesBackFrom(CP, CopyMI) ||
1074           RemoveCopyByCommutingDef(CP, CopyMI)) {
1075         JoinedCopies.insert(CopyMI);
1076         DEBUG(dbgs() << "\tTrivial!\n");
1077         return true;
1078       }
1079     }
1080
1081     // Otherwise, we are unable to join the intervals.
1082     DEBUG(dbgs() << "\tInterference!\n");
1083     Again = true;  // May be possible to coalesce later.
1084     return false;
1085   }
1086
1087   // Coalescing to a virtual register that is of a sub-register class of the
1088   // other. Make sure the resulting register is set to the right register class.
1089   if (CP.isCrossClass()) {
1090     ++numCrossRCs;
1091     mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1092   }
1093
1094   // Remember to delete the copy instruction.
1095   JoinedCopies.insert(CopyMI);
1096
1097   UpdateRegDefsUses(CP);
1098
1099   // If we have extended the live range of a physical register, make sure we
1100   // update live-in lists as well.
1101   if (CP.isPhys()) {
1102     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1103     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1104     // ranges for this, and they are preserved.
1105     LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1106     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1107          I != E; ++I ) {
1108       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1109       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1110         MachineBasicBlock &block = *BlockSeq[idx];
1111         if (!block.isLiveIn(CP.getDstReg()))
1112           block.addLiveIn(CP.getDstReg());
1113       }
1114       BlockSeq.clear();
1115     }
1116   }
1117
1118   // SrcReg is guarateed to be the register whose live interval that is
1119   // being merged.
1120   li_->removeInterval(CP.getSrcReg());
1121
1122   // Update regalloc hint.
1123   tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1124
1125   DEBUG({
1126     LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1127     dbgs() << "\tJoined. Result = ";
1128     DstInt.print(dbgs(), tri_);
1129     dbgs() << "\n";
1130   });
1131
1132   ++numJoins;
1133   return true;
1134 }
1135
1136 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1137 /// compute what the resultant value numbers for each value in the input two
1138 /// ranges will be.  This is complicated by copies between the two which can
1139 /// and will commonly cause multiple value numbers to be merged into one.
1140 ///
1141 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1142 /// keeps track of the new InstDefiningValue assignment for the result
1143 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1144 /// whether a value in this or other is a copy from the opposite set.
1145 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1146 /// already been assigned.
1147 ///
1148 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1149 /// contains the value number the copy is from.
1150 ///
1151 static unsigned ComputeUltimateVN(VNInfo *VNI,
1152                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1153                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1154                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1155                                   SmallVector<int, 16> &ThisValNoAssignments,
1156                                   SmallVector<int, 16> &OtherValNoAssignments) {
1157   unsigned VN = VNI->id;
1158
1159   // If the VN has already been computed, just return it.
1160   if (ThisValNoAssignments[VN] >= 0)
1161     return ThisValNoAssignments[VN];
1162   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1163
1164   // If this val is not a copy from the other val, then it must be a new value
1165   // number in the destination.
1166   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1167   if (I == ThisFromOther.end()) {
1168     NewVNInfo.push_back(VNI);
1169     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1170   }
1171   VNInfo *OtherValNo = I->second;
1172
1173   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1174   // been computed, return it.
1175   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1176     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1177
1178   // Mark this value number as currently being computed, then ask what the
1179   // ultimate value # of the other value is.
1180   ThisValNoAssignments[VN] = -2;
1181   unsigned UltimateVN =
1182     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1183                       OtherValNoAssignments, ThisValNoAssignments);
1184   return ThisValNoAssignments[VN] = UltimateVN;
1185 }
1186
1187 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1188 /// returns false.
1189 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1190   LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1191   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1192
1193   // If a live interval is a physical register, check for interference with any
1194   // aliases. The interference check implemented here is a bit more conservative
1195   // than the full interfeence check below. We allow overlapping live ranges
1196   // only when one is a copy of the other.
1197   if (CP.isPhys()) {
1198     for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1199       if (!li_->hasInterval(*AS))
1200         continue;
1201       const LiveInterval &LHS = li_->getInterval(*AS);
1202       LiveInterval::const_iterator LI = LHS.begin();
1203       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1204            RI != RE; ++RI) {
1205         LI = std::lower_bound(LI, LHS.end(), RI->start);
1206         // Does LHS have an overlapping live range starting before RI?
1207         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1208             (RI->start != RI->valno->def ||
1209              !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1210           DEBUG({
1211             dbgs() << "\t\tInterference from alias: ";
1212             LHS.print(dbgs(), tri_);
1213             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1214           });
1215           return false;
1216         }
1217
1218         // Check that LHS ranges beginning in this range are copies.
1219         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1220           if (LI->start != LI->valno->def ||
1221               !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1222             DEBUG({
1223               dbgs() << "\t\tInterference from alias: ";
1224               LHS.print(dbgs(), tri_);
1225               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1226             });
1227             return false;
1228           }
1229         }
1230       }
1231     }
1232   }
1233
1234   // Compute the final value assignment, assuming that the live ranges can be
1235   // coalesced.
1236   SmallVector<int, 16> LHSValNoAssignments;
1237   SmallVector<int, 16> RHSValNoAssignments;
1238   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1239   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1240   SmallVector<VNInfo*, 16> NewVNInfo;
1241
1242   LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1243   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1244
1245   // Loop over the value numbers of the LHS, seeing if any are defined from
1246   // the RHS.
1247   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1248        i != e; ++i) {
1249     VNInfo *VNI = *i;
1250     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1251       continue;
1252
1253     // Never join with a register that has EarlyClobber redefs.
1254     if (VNI->hasRedefByEC())
1255       return false;
1256
1257     // DstReg is known to be a register in the LHS interval.  If the src is
1258     // from the RHS interval, we can use its value #.
1259     if (!CP.isCoalescable(VNI->getCopy()))
1260       continue;
1261
1262     // Figure out the value # from the RHS.
1263     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1264     // The copy could be to an aliased physreg.
1265     if (!lr) continue;
1266     LHSValsDefinedFromRHS[VNI] = lr->valno;
1267   }
1268
1269   // Loop over the value numbers of the RHS, seeing if any are defined from
1270   // the LHS.
1271   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1272        i != e; ++i) {
1273     VNInfo *VNI = *i;
1274     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1275       continue;
1276
1277     // Never join with a register that has EarlyClobber redefs.
1278     if (VNI->hasRedefByEC())
1279       return false;
1280
1281     // DstReg is known to be a register in the RHS interval.  If the src is
1282     // from the LHS interval, we can use its value #.
1283     if (!CP.isCoalescable(VNI->getCopy()))
1284       continue;
1285
1286     // Figure out the value # from the LHS.
1287     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1288     // The copy could be to an aliased physreg.
1289     if (!lr) continue;
1290     RHSValsDefinedFromLHS[VNI] = lr->valno;
1291   }
1292
1293   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1294   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1295   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1296
1297   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1298        i != e; ++i) {
1299     VNInfo *VNI = *i;
1300     unsigned VN = VNI->id;
1301     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1302       continue;
1303     ComputeUltimateVN(VNI, NewVNInfo,
1304                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1305                       LHSValNoAssignments, RHSValNoAssignments);
1306   }
1307   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1308        i != e; ++i) {
1309     VNInfo *VNI = *i;
1310     unsigned VN = VNI->id;
1311     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1312       continue;
1313     // If this value number isn't a copy from the LHS, it's a new number.
1314     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1315       NewVNInfo.push_back(VNI);
1316       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1317       continue;
1318     }
1319
1320     ComputeUltimateVN(VNI, NewVNInfo,
1321                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1322                       RHSValNoAssignments, LHSValNoAssignments);
1323   }
1324
1325   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1326   // interval lists to see if these intervals are coalescable.
1327   LiveInterval::const_iterator I = LHS.begin();
1328   LiveInterval::const_iterator IE = LHS.end();
1329   LiveInterval::const_iterator J = RHS.begin();
1330   LiveInterval::const_iterator JE = RHS.end();
1331
1332   // Skip ahead until the first place of potential sharing.
1333   if (I != IE && J != JE) {
1334     if (I->start < J->start) {
1335       I = std::upper_bound(I, IE, J->start);
1336       if (I != LHS.begin()) --I;
1337     } else if (J->start < I->start) {
1338       J = std::upper_bound(J, JE, I->start);
1339       if (J != RHS.begin()) --J;
1340     }
1341   }
1342
1343   while (I != IE && J != JE) {
1344     // Determine if these two live ranges overlap.
1345     bool Overlaps;
1346     if (I->start < J->start) {
1347       Overlaps = I->end > J->start;
1348     } else {
1349       Overlaps = J->end > I->start;
1350     }
1351
1352     // If so, check value # info to determine if they are really different.
1353     if (Overlaps) {
1354       // If the live range overlap will map to the same value number in the
1355       // result liverange, we can still coalesce them.  If not, we can't.
1356       if (LHSValNoAssignments[I->valno->id] !=
1357           RHSValNoAssignments[J->valno->id])
1358         return false;
1359       // If it's re-defined by an early clobber somewhere in the live range,
1360       // then conservatively abort coalescing.
1361       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1362         return false;
1363     }
1364
1365     if (I->end < J->end)
1366       ++I;
1367     else
1368       ++J;
1369   }
1370
1371   // Update kill info. Some live ranges are extended due to copy coalescing.
1372   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1373          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1374     VNInfo *VNI = I->first;
1375     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1376     if (VNI->hasPHIKill())
1377       NewVNInfo[LHSValID]->setHasPHIKill(true);
1378   }
1379
1380   // Update kill info. Some live ranges are extended due to copy coalescing.
1381   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1382          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1383     VNInfo *VNI = I->first;
1384     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1385     if (VNI->hasPHIKill())
1386       NewVNInfo[RHSValID]->setHasPHIKill(true);
1387   }
1388
1389   if (LHSValNoAssignments.empty())
1390     LHSValNoAssignments.push_back(-1);
1391   if (RHSValNoAssignments.empty())
1392     RHSValNoAssignments.push_back(-1);
1393
1394   // If we get here, we know that we can coalesce the live ranges.  Ask the
1395   // intervals to coalesce themselves now.
1396   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1397            mri_);
1398   return true;
1399 }
1400
1401 namespace {
1402   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1403   // depth of the basic block (the unsigned), and then on the MBB number.
1404   struct DepthMBBCompare {
1405     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1406     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1407       // Deeper loops first
1408       if (LHS.first != RHS.first)
1409         return LHS.first > RHS.first;
1410
1411       // Prefer blocks that are more connected in the CFG. This takes care of
1412       // the most difficult copies first while intervals are short.
1413       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1414       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1415       if (cl != cr)
1416         return cl > cr;
1417
1418       // As a last resort, sort by block number.
1419       return LHS.second->getNumber() < RHS.second->getNumber();
1420     }
1421   };
1422 }
1423
1424 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1425                                                std::vector<CopyRec> &TryAgain) {
1426   DEBUG(dbgs() << MBB->getName() << ":\n");
1427
1428   SmallVector<CopyRec, 8> VirtCopies;
1429   SmallVector<CopyRec, 8> PhysCopies;
1430   SmallVector<CopyRec, 8> ImpDefCopies;
1431   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1432        MII != E;) {
1433     MachineInstr *Inst = MII++;
1434
1435     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1436     unsigned SrcReg, DstReg;
1437     if (Inst->isCopy()) {
1438       DstReg = Inst->getOperand(0).getReg();
1439       SrcReg = Inst->getOperand(1).getReg();
1440     } else if (Inst->isSubregToReg()) {
1441       DstReg = Inst->getOperand(0).getReg();
1442       SrcReg = Inst->getOperand(2).getReg();
1443     } else
1444       continue;
1445
1446     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1447     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1448     if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1449       ImpDefCopies.push_back(CopyRec(Inst, 0));
1450     else if (SrcIsPhys || DstIsPhys)
1451       PhysCopies.push_back(CopyRec(Inst, 0));
1452     else
1453       VirtCopies.push_back(CopyRec(Inst, 0));
1454   }
1455
1456   // Try coalescing implicit copies and insert_subreg <undef> first,
1457   // followed by copies to / from physical registers, then finally copies
1458   // from virtual registers to virtual registers.
1459   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1460     CopyRec &TheCopy = ImpDefCopies[i];
1461     bool Again = false;
1462     if (!JoinCopy(TheCopy, Again))
1463       if (Again)
1464         TryAgain.push_back(TheCopy);
1465   }
1466   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1467     CopyRec &TheCopy = PhysCopies[i];
1468     bool Again = false;
1469     if (!JoinCopy(TheCopy, Again))
1470       if (Again)
1471         TryAgain.push_back(TheCopy);
1472   }
1473   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1474     CopyRec &TheCopy = VirtCopies[i];
1475     bool Again = false;
1476     if (!JoinCopy(TheCopy, Again))
1477       if (Again)
1478         TryAgain.push_back(TheCopy);
1479   }
1480 }
1481
1482 void SimpleRegisterCoalescing::joinIntervals() {
1483   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1484
1485   std::vector<CopyRec> TryAgainList;
1486   if (loopInfo->empty()) {
1487     // If there are no loops in the function, join intervals in function order.
1488     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1489          I != E; ++I)
1490       CopyCoalesceInMBB(I, TryAgainList);
1491   } else {
1492     // Otherwise, join intervals in inner loops before other intervals.
1493     // Unfortunately we can't just iterate over loop hierarchy here because
1494     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1495
1496     // Join intervals in the function prolog first. We want to join physical
1497     // registers with virtual registers before the intervals got too long.
1498     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1499     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1500       MachineBasicBlock *MBB = I;
1501       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1502     }
1503
1504     // Sort by loop depth.
1505     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1506
1507     // Finally, join intervals in loop nest order.
1508     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1509       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1510   }
1511
1512   // Joining intervals can allow other intervals to be joined.  Iteratively join
1513   // until we make no progress.
1514   bool ProgressMade = true;
1515   while (ProgressMade) {
1516     ProgressMade = false;
1517
1518     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1519       CopyRec &TheCopy = TryAgainList[i];
1520       if (!TheCopy.MI)
1521         continue;
1522
1523       bool Again = false;
1524       bool Success = JoinCopy(TheCopy, Again);
1525       if (Success || !Again) {
1526         TheCopy.MI = 0;   // Mark this one as done.
1527         ProgressMade = true;
1528       }
1529     }
1530   }
1531 }
1532
1533 /// Return true if the two specified registers belong to different register
1534 /// classes.  The registers may be either phys or virt regs.
1535 bool
1536 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1537                                                    unsigned RegB) const {
1538   // Get the register classes for the first reg.
1539   if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1540     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1541            "Shouldn't consider two physregs!");
1542     return !mri_->getRegClass(RegB)->contains(RegA);
1543   }
1544
1545   // Compare against the regclass for the second reg.
1546   const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1547   if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1548     const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1549     return RegClassA != RegClassB;
1550   }
1551   return !RegClassA->contains(RegB);
1552 }
1553
1554 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1555 /// between cycles Start and End or NULL if there are no uses.
1556 MachineOperand *
1557 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1558                                           SlotIndex End,
1559                                           unsigned Reg,
1560                                           SlotIndex &UseIdx) const{
1561   UseIdx = SlotIndex();
1562   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1563     MachineOperand *LastUse = NULL;
1564     for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1565            E = mri_->use_nodbg_end(); I != E; ++I) {
1566       MachineOperand &Use = I.getOperand();
1567       MachineInstr *UseMI = Use.getParent();
1568       if (UseMI->isIdentityCopy())
1569         continue;
1570       SlotIndex Idx = li_->getInstructionIndex(UseMI);
1571       if (Idx >= Start && Idx < End && (!UseIdx.isValid() || Idx >= UseIdx)) {
1572         LastUse = &Use;
1573         UseIdx = Idx.getUseIndex();
1574       }
1575     }
1576     return LastUse;
1577   }
1578
1579   SlotIndex s = Start;
1580   SlotIndex e = End.getPrevSlot().getBaseIndex();
1581   while (e >= s) {
1582     // Skip deleted instructions
1583     MachineInstr *MI = li_->getInstructionFromIndex(e);
1584     while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1585       e = e.getPrevIndex();
1586       MI = li_->getInstructionFromIndex(e);
1587     }
1588     if (e < s || MI == NULL)
1589       return NULL;
1590
1591     // Ignore identity copies.
1592     if (!MI->isIdentityCopy())
1593       for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1594         MachineOperand &Use = MI->getOperand(i);
1595         if (Use.isReg() && Use.isUse() && Use.getReg() &&
1596             tri_->regsOverlap(Use.getReg(), Reg)) {
1597           UseIdx = e.getUseIndex();
1598           return &Use;
1599         }
1600       }
1601
1602     e = e.getPrevIndex();
1603   }
1604
1605   return NULL;
1606 }
1607
1608 void SimpleRegisterCoalescing::releaseMemory() {
1609   JoinedCopies.clear();
1610   ReMatCopies.clear();
1611   ReMatDefs.clear();
1612 }
1613
1614 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1615   mf_ = &fn;
1616   mri_ = &fn.getRegInfo();
1617   tm_ = &fn.getTarget();
1618   tri_ = tm_->getRegisterInfo();
1619   tii_ = tm_->getInstrInfo();
1620   li_ = &getAnalysis<LiveIntervals>();
1621   ldv_ = &getAnalysis<LiveDebugVariables>();
1622   AA = &getAnalysis<AliasAnalysis>();
1623   loopInfo = &getAnalysis<MachineLoopInfo>();
1624
1625   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1626                << "********** Function: "
1627                << ((Value*)mf_->getFunction())->getName() << '\n');
1628
1629   if (VerifyCoalescing)
1630     mf_->verify(this, "Before register coalescing");
1631
1632   for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1633          E = tri_->regclass_end(); I != E; ++I)
1634     allocatableRCRegs_.insert(std::make_pair(*I,
1635                                              tri_->getAllocatableSet(fn, *I)));
1636
1637   // Join (coalesce) intervals if requested.
1638   if (EnableJoining) {
1639     joinIntervals();
1640     DEBUG({
1641         dbgs() << "********** INTERVALS POST JOINING **********\n";
1642         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1643              I != E; ++I){
1644           I->second->print(dbgs(), tri_);
1645           dbgs() << "\n";
1646         }
1647       });
1648   }
1649
1650   // Perform a final pass over the instructions and compute spill weights
1651   // and remove identity moves.
1652   SmallVector<unsigned, 4> DeadDefs;
1653   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1654        mbbi != mbbe; ++mbbi) {
1655     MachineBasicBlock* mbb = mbbi;
1656     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1657          mii != mie; ) {
1658       MachineInstr *MI = mii;
1659       if (JoinedCopies.count(MI)) {
1660         // Delete all coalesced copies.
1661         bool DoDelete = true;
1662         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1663         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1664         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1665             MI->getNumOperands() > 2)
1666           // Do not delete extract_subreg, insert_subreg of physical
1667           // registers unless the definition is dead. e.g.
1668           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1669           // or else the scavenger may complain. LowerSubregs will
1670           // delete them later.
1671           DoDelete = false;
1672         
1673         if (MI->allDefsAreDead()) {
1674           if (li_->hasInterval(SrcReg)) {
1675             LiveInterval &li = li_->getInterval(SrcReg);
1676             if (!ShortenDeadCopySrcLiveRange(li, MI))
1677               ShortenDeadCopyLiveRange(li, MI);
1678           }
1679           DoDelete = true;
1680         }
1681         if (!DoDelete) {
1682           // We need the instruction to adjust liveness, so make it a KILL.
1683           if (MI->isSubregToReg()) {
1684             MI->RemoveOperand(3);
1685             MI->RemoveOperand(1);
1686           }
1687           MI->setDesc(tii_->get(TargetOpcode::KILL));
1688           mii = llvm::next(mii);
1689         } else {
1690           li_->RemoveMachineInstrFromMaps(MI);
1691           mii = mbbi->erase(mii);
1692           ++numPeep;
1693         }
1694         continue;
1695       }
1696
1697       // Now check if this is a remat'ed def instruction which is now dead.
1698       if (ReMatDefs.count(MI)) {
1699         bool isDead = true;
1700         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1701           const MachineOperand &MO = MI->getOperand(i);
1702           if (!MO.isReg())
1703             continue;
1704           unsigned Reg = MO.getReg();
1705           if (!Reg)
1706             continue;
1707           if (TargetRegisterInfo::isVirtualRegister(Reg))
1708             DeadDefs.push_back(Reg);
1709           if (MO.isDead())
1710             continue;
1711           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1712               !mri_->use_nodbg_empty(Reg)) {
1713             isDead = false;
1714             break;
1715           }
1716         }
1717         if (isDead) {
1718           while (!DeadDefs.empty()) {
1719             unsigned DeadDef = DeadDefs.back();
1720             DeadDefs.pop_back();
1721             RemoveDeadDef(li_->getInterval(DeadDef), MI);
1722           }
1723           li_->RemoveMachineInstrFromMaps(mii);
1724           mii = mbbi->erase(mii);
1725           continue;
1726         } else
1727           DeadDefs.clear();
1728       }
1729
1730       // If the move will be an identity move delete it
1731       if (MI->isIdentityCopy()) {
1732         unsigned SrcReg = MI->getOperand(1).getReg();
1733         if (li_->hasInterval(SrcReg)) {
1734           LiveInterval &RegInt = li_->getInterval(SrcReg);
1735           // If def of this move instruction is dead, remove its live range
1736           // from the destination register's live interval.
1737           if (MI->allDefsAreDead()) {
1738             if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1739               ShortenDeadCopyLiveRange(RegInt, MI);
1740           }
1741         }
1742         li_->RemoveMachineInstrFromMaps(MI);
1743         mii = mbbi->erase(mii);
1744         ++numPeep;
1745         continue;
1746       }
1747
1748       ++mii;
1749
1750       // Check for now unnecessary kill flags.
1751       if (li_->isNotInMIMap(MI)) continue;
1752       SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1753       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1754         MachineOperand &MO = MI->getOperand(i);
1755         if (!MO.isReg() || !MO.isKill()) continue;
1756         unsigned reg = MO.getReg();
1757         if (!reg || !li_->hasInterval(reg)) continue;
1758         if (!li_->getInterval(reg).killedAt(DefIdx)) {
1759           MO.setIsKill(false);
1760           continue;
1761         }
1762         // When leaving a kill flag on a physreg, check if any subregs should
1763         // remain alive.
1764         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1765           continue;
1766         for (const unsigned *SR = tri_->getSubRegisters(reg);
1767              unsigned S = *SR; ++SR)
1768           if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1769             MI->addRegisterDefined(S, tri_);
1770       }
1771     }
1772   }
1773
1774   DEBUG(dump());
1775   DEBUG(ldv_->dump());
1776   if (VerifyCoalescing)
1777     mf_->verify(this, "After register coalescing");
1778   return true;
1779 }
1780
1781 /// print - Implement the dump method.
1782 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1783    li_->print(O, m);
1784 }
1785
1786 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1787   return new SimpleRegisterCoalescing();
1788 }
1789
1790 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1791 DEFINING_FILE_FOR(SimpleRegisterCoalescing)