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