Add a flag that indicates whether a target supports compact unwind info or not.
[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
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(CopyRec &TheCopy, bool &Again) {
843   MachineInstr *CopyMI = TheCopy.MI;
844
845   Again = false;
846   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
847     return false; // Already done.
848
849   DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
850
851   CoalescerPair CP(*tii_, *tri_);
852   if (!CP.setRegisters(CopyMI)) {
853     DEBUG(dbgs() << "\tNot coalescable.\n");
854     return false;
855   }
856
857   // If they are already joined we continue.
858   if (CP.getSrcReg() == CP.getDstReg()) {
859     markAsJoined(CopyMI);
860     DEBUG(dbgs() << "\tCopy already coalesced.\n");
861     return false;  // Not coalescable.
862   }
863
864   DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_)
865                << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
866                << "\n");
867
868   // Enforce policies.
869   if (CP.isPhys()) {
870     if (!shouldJoinPhys(CP)) {
871       // Before giving up coalescing, if definition of source is defined by
872       // trivial computation, try rematerializing it.
873       if (!CP.isFlipped() &&
874           ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
875                                   CP.getDstReg(), 0, CopyMI))
876         return true;
877       return false;
878     }
879   } else {
880     // Avoid constraining virtual register regclass too much.
881     if (CP.isCrossClass()) {
882       DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
883       if (DisableCrossClassJoin) {
884         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
885         return false;
886       }
887       if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
888                                  mri_->getRegClass(CP.getSrcReg()),
889                                  mri_->getRegClass(CP.getDstReg()),
890                                  CP.getNewRC())) {
891         DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
892         Again = true;  // May be possible to coalesce later.
893         return false;
894       }
895     }
896
897     // When possible, let DstReg be the larger interval.
898     if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
899                            li_->getInterval(CP.getDstReg()).ranges.size())
900       CP.flip();
901   }
902
903   // Okay, attempt to join these two intervals.  On failure, this returns false.
904   // Otherwise, if one of the intervals being joined is a physreg, this method
905   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
906   // been modified, so we can use this information below to update aliases.
907   if (!JoinIntervals(CP)) {
908     // Coalescing failed.
909
910     // If definition of source is defined by trivial computation, try
911     // rematerializing it.
912     if (!CP.isFlipped() &&
913         ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
914                                 CP.getDstReg(), 0, CopyMI))
915       return true;
916
917     // If we can eliminate the copy without merging the live ranges, do so now.
918     if (!CP.isPartial()) {
919       if (AdjustCopiesBackFrom(CP, CopyMI) ||
920           RemoveCopyByCommutingDef(CP, CopyMI)) {
921         markAsJoined(CopyMI);
922         DEBUG(dbgs() << "\tTrivial!\n");
923         return true;
924       }
925     }
926
927     // Otherwise, we are unable to join the intervals.
928     DEBUG(dbgs() << "\tInterference!\n");
929     Again = true;  // May be possible to coalesce later.
930     return false;
931   }
932
933   // Coalescing to a virtual register that is of a sub-register class of the
934   // other. Make sure the resulting register is set to the right register class.
935   if (CP.isCrossClass()) {
936     ++numCrossRCs;
937     mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
938   }
939
940   // Remember to delete the copy instruction.
941   markAsJoined(CopyMI);
942
943   UpdateRegDefsUses(CP);
944
945   // If we have extended the live range of a physical register, make sure we
946   // update live-in lists as well.
947   if (CP.isPhys()) {
948     SmallVector<MachineBasicBlock*, 16> BlockSeq;
949     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
950     // ranges for this, and they are preserved.
951     LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
952     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
953          I != E; ++I ) {
954       li_->findLiveInMBBs(I->start, I->end, BlockSeq);
955       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
956         MachineBasicBlock &block = *BlockSeq[idx];
957         if (!block.isLiveIn(CP.getDstReg()))
958           block.addLiveIn(CP.getDstReg());
959       }
960       BlockSeq.clear();
961     }
962   }
963
964   // SrcReg is guarateed to be the register whose live interval that is
965   // being merged.
966   li_->removeInterval(CP.getSrcReg());
967
968   // Update regalloc hint.
969   tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
970
971   DEBUG({
972     LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
973     dbgs() << "\tJoined. Result = ";
974     DstInt.print(dbgs(), tri_);
975     dbgs() << "\n";
976   });
977
978   ++numJoins;
979   return true;
980 }
981
982 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
983 /// compute what the resultant value numbers for each value in the input two
984 /// ranges will be.  This is complicated by copies between the two which can
985 /// and will commonly cause multiple value numbers to be merged into one.
986 ///
987 /// VN is the value number that we're trying to resolve.  InstDefiningValue
988 /// keeps track of the new InstDefiningValue assignment for the result
989 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
990 /// whether a value in this or other is a copy from the opposite set.
991 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
992 /// already been assigned.
993 ///
994 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
995 /// contains the value number the copy is from.
996 ///
997 static unsigned ComputeUltimateVN(VNInfo *VNI,
998                                   SmallVector<VNInfo*, 16> &NewVNInfo,
999                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1000                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1001                                   SmallVector<int, 16> &ThisValNoAssignments,
1002                                   SmallVector<int, 16> &OtherValNoAssignments) {
1003   unsigned VN = VNI->id;
1004
1005   // If the VN has already been computed, just return it.
1006   if (ThisValNoAssignments[VN] >= 0)
1007     return ThisValNoAssignments[VN];
1008   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1009
1010   // If this val is not a copy from the other val, then it must be a new value
1011   // number in the destination.
1012   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1013   if (I == ThisFromOther.end()) {
1014     NewVNInfo.push_back(VNI);
1015     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1016   }
1017   VNInfo *OtherValNo = I->second;
1018
1019   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1020   // been computed, return it.
1021   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1022     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1023
1024   // Mark this value number as currently being computed, then ask what the
1025   // ultimate value # of the other value is.
1026   ThisValNoAssignments[VN] = -2;
1027   unsigned UltimateVN =
1028     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1029                       OtherValNoAssignments, ThisValNoAssignments);
1030   return ThisValNoAssignments[VN] = UltimateVN;
1031 }
1032
1033 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1034 /// returns false.
1035 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1036   LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1037   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1038
1039   // If a live interval is a physical register, check for interference with any
1040   // aliases. The interference check implemented here is a bit more conservative
1041   // than the full interfeence check below. We allow overlapping live ranges
1042   // only when one is a copy of the other.
1043   if (CP.isPhys()) {
1044     for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1045       if (!li_->hasInterval(*AS))
1046         continue;
1047       const LiveInterval &LHS = li_->getInterval(*AS);
1048       LiveInterval::const_iterator LI = LHS.begin();
1049       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1050            RI != RE; ++RI) {
1051         LI = std::lower_bound(LI, LHS.end(), RI->start);
1052         // Does LHS have an overlapping live range starting before RI?
1053         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1054             (RI->start != RI->valno->def ||
1055              !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1056           DEBUG({
1057             dbgs() << "\t\tInterference from alias: ";
1058             LHS.print(dbgs(), tri_);
1059             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1060           });
1061           return false;
1062         }
1063
1064         // Check that LHS ranges beginning in this range are copies.
1065         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1066           if (LI->start != LI->valno->def ||
1067               !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1068             DEBUG({
1069               dbgs() << "\t\tInterference from alias: ";
1070               LHS.print(dbgs(), tri_);
1071               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1072             });
1073             return false;
1074           }
1075         }
1076       }
1077     }
1078   }
1079
1080   // Compute the final value assignment, assuming that the live ranges can be
1081   // coalesced.
1082   SmallVector<int, 16> LHSValNoAssignments;
1083   SmallVector<int, 16> RHSValNoAssignments;
1084   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1085   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1086   SmallVector<VNInfo*, 16> NewVNInfo;
1087
1088   LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1089   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1090
1091   // Loop over the value numbers of the LHS, seeing if any are defined from
1092   // the RHS.
1093   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1094        i != e; ++i) {
1095     VNInfo *VNI = *i;
1096     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1097       continue;
1098
1099     // Never join with a register that has EarlyClobber redefs.
1100     if (VNI->hasRedefByEC())
1101       return false;
1102
1103     // DstReg is known to be a register in the LHS interval.  If the src is
1104     // from the RHS interval, we can use its value #.
1105     if (!CP.isCoalescable(VNI->getCopy()))
1106       continue;
1107
1108     // Figure out the value # from the RHS.
1109     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1110     // The copy could be to an aliased physreg.
1111     if (!lr) continue;
1112     LHSValsDefinedFromRHS[VNI] = lr->valno;
1113   }
1114
1115   // Loop over the value numbers of the RHS, seeing if any are defined from
1116   // the LHS.
1117   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1118        i != e; ++i) {
1119     VNInfo *VNI = *i;
1120     if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a copy?
1121       continue;
1122
1123     // Never join with a register that has EarlyClobber redefs.
1124     if (VNI->hasRedefByEC())
1125       return false;
1126
1127     // DstReg is known to be a register in the RHS interval.  If the src is
1128     // from the LHS interval, we can use its value #.
1129     if (!CP.isCoalescable(VNI->getCopy()))
1130       continue;
1131
1132     // Figure out the value # from the LHS.
1133     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1134     // The copy could be to an aliased physreg.
1135     if (!lr) continue;
1136     RHSValsDefinedFromLHS[VNI] = lr->valno;
1137   }
1138
1139   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1140   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1141   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1142
1143   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1144        i != e; ++i) {
1145     VNInfo *VNI = *i;
1146     unsigned VN = VNI->id;
1147     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1148       continue;
1149     ComputeUltimateVN(VNI, NewVNInfo,
1150                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1151                       LHSValNoAssignments, RHSValNoAssignments);
1152   }
1153   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1154        i != e; ++i) {
1155     VNInfo *VNI = *i;
1156     unsigned VN = VNI->id;
1157     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1158       continue;
1159     // If this value number isn't a copy from the LHS, it's a new number.
1160     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1161       NewVNInfo.push_back(VNI);
1162       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1163       continue;
1164     }
1165
1166     ComputeUltimateVN(VNI, NewVNInfo,
1167                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1168                       RHSValNoAssignments, LHSValNoAssignments);
1169   }
1170
1171   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1172   // interval lists to see if these intervals are coalescable.
1173   LiveInterval::const_iterator I = LHS.begin();
1174   LiveInterval::const_iterator IE = LHS.end();
1175   LiveInterval::const_iterator J = RHS.begin();
1176   LiveInterval::const_iterator JE = RHS.end();
1177
1178   // Skip ahead until the first place of potential sharing.
1179   if (I != IE && J != JE) {
1180     if (I->start < J->start) {
1181       I = std::upper_bound(I, IE, J->start);
1182       if (I != LHS.begin()) --I;
1183     } else if (J->start < I->start) {
1184       J = std::upper_bound(J, JE, I->start);
1185       if (J != RHS.begin()) --J;
1186     }
1187   }
1188
1189   while (I != IE && J != JE) {
1190     // Determine if these two live ranges overlap.
1191     bool Overlaps;
1192     if (I->start < J->start) {
1193       Overlaps = I->end > J->start;
1194     } else {
1195       Overlaps = J->end > I->start;
1196     }
1197
1198     // If so, check value # info to determine if they are really different.
1199     if (Overlaps) {
1200       // If the live range overlap will map to the same value number in the
1201       // result liverange, we can still coalesce them.  If not, we can't.
1202       if (LHSValNoAssignments[I->valno->id] !=
1203           RHSValNoAssignments[J->valno->id])
1204         return false;
1205       // If it's re-defined by an early clobber somewhere in the live range,
1206       // then conservatively abort coalescing.
1207       if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1208         return false;
1209     }
1210
1211     if (I->end < J->end)
1212       ++I;
1213     else
1214       ++J;
1215   }
1216
1217   // Update kill info. Some live ranges are extended due to copy coalescing.
1218   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1219          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1220     VNInfo *VNI = I->first;
1221     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1222     if (VNI->hasPHIKill())
1223       NewVNInfo[LHSValID]->setHasPHIKill(true);
1224   }
1225
1226   // Update kill info. Some live ranges are extended due to copy coalescing.
1227   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1228          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1229     VNInfo *VNI = I->first;
1230     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1231     if (VNI->hasPHIKill())
1232       NewVNInfo[RHSValID]->setHasPHIKill(true);
1233   }
1234
1235   if (LHSValNoAssignments.empty())
1236     LHSValNoAssignments.push_back(-1);
1237   if (RHSValNoAssignments.empty())
1238     RHSValNoAssignments.push_back(-1);
1239
1240   // If we get here, we know that we can coalesce the live ranges.  Ask the
1241   // intervals to coalesce themselves now.
1242   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1243            mri_);
1244   return true;
1245 }
1246
1247 namespace {
1248   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1249   // depth of the basic block (the unsigned), and then on the MBB number.
1250   struct DepthMBBCompare {
1251     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1252     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1253       // Deeper loops first
1254       if (LHS.first != RHS.first)
1255         return LHS.first > RHS.first;
1256
1257       // Prefer blocks that are more connected in the CFG. This takes care of
1258       // the most difficult copies first while intervals are short.
1259       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1260       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1261       if (cl != cr)
1262         return cl > cr;
1263
1264       // As a last resort, sort by block number.
1265       return LHS.second->getNumber() < RHS.second->getNumber();
1266     }
1267   };
1268 }
1269
1270 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1271                                                std::vector<CopyRec> &TryAgain) {
1272   DEBUG(dbgs() << MBB->getName() << ":\n");
1273
1274   SmallVector<CopyRec, 8> VirtCopies;
1275   SmallVector<CopyRec, 8> PhysCopies;
1276   SmallVector<CopyRec, 8> ImpDefCopies;
1277   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1278        MII != E;) {
1279     MachineInstr *Inst = MII++;
1280
1281     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1282     unsigned SrcReg, DstReg;
1283     if (Inst->isCopy()) {
1284       DstReg = Inst->getOperand(0).getReg();
1285       SrcReg = Inst->getOperand(1).getReg();
1286     } else if (Inst->isSubregToReg()) {
1287       DstReg = Inst->getOperand(0).getReg();
1288       SrcReg = Inst->getOperand(2).getReg();
1289     } else
1290       continue;
1291
1292     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1293     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1294     if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1295       ImpDefCopies.push_back(CopyRec(Inst, 0));
1296     else if (SrcIsPhys || DstIsPhys)
1297       PhysCopies.push_back(CopyRec(Inst, 0));
1298     else
1299       VirtCopies.push_back(CopyRec(Inst, 0));
1300   }
1301
1302   // Try coalescing implicit copies and insert_subreg <undef> first,
1303   // followed by copies to / from physical registers, then finally copies
1304   // from virtual registers to virtual registers.
1305   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1306     CopyRec &TheCopy = ImpDefCopies[i];
1307     bool Again = false;
1308     if (!JoinCopy(TheCopy, Again))
1309       if (Again)
1310         TryAgain.push_back(TheCopy);
1311   }
1312   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1313     CopyRec &TheCopy = PhysCopies[i];
1314     bool Again = false;
1315     if (!JoinCopy(TheCopy, Again))
1316       if (Again)
1317         TryAgain.push_back(TheCopy);
1318   }
1319   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1320     CopyRec &TheCopy = VirtCopies[i];
1321     bool Again = false;
1322     if (!JoinCopy(TheCopy, Again))
1323       if (Again)
1324         TryAgain.push_back(TheCopy);
1325   }
1326 }
1327
1328 void SimpleRegisterCoalescing::joinIntervals() {
1329   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1330
1331   std::vector<CopyRec> TryAgainList;
1332   if (loopInfo->empty()) {
1333     // If there are no loops in the function, join intervals in function order.
1334     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1335          I != E; ++I)
1336       CopyCoalesceInMBB(I, TryAgainList);
1337   } else {
1338     // Otherwise, join intervals in inner loops before other intervals.
1339     // Unfortunately we can't just iterate over loop hierarchy here because
1340     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1341
1342     // Join intervals in the function prolog first. We want to join physical
1343     // registers with virtual registers before the intervals got too long.
1344     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1345     for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1346       MachineBasicBlock *MBB = I;
1347       MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1348     }
1349
1350     // Sort by loop depth.
1351     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1352
1353     // Finally, join intervals in loop nest order.
1354     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1355       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1356   }
1357
1358   // Joining intervals can allow other intervals to be joined.  Iteratively join
1359   // until we make no progress.
1360   bool ProgressMade = true;
1361   while (ProgressMade) {
1362     ProgressMade = false;
1363
1364     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1365       CopyRec &TheCopy = TryAgainList[i];
1366       if (!TheCopy.MI)
1367         continue;
1368
1369       bool Again = false;
1370       bool Success = JoinCopy(TheCopy, Again);
1371       if (Success || !Again) {
1372         TheCopy.MI = 0;   // Mark this one as done.
1373         ProgressMade = true;
1374       }
1375     }
1376   }
1377 }
1378
1379 void SimpleRegisterCoalescing::releaseMemory() {
1380   JoinedCopies.clear();
1381   ReMatCopies.clear();
1382   ReMatDefs.clear();
1383 }
1384
1385 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1386   mf_ = &fn;
1387   mri_ = &fn.getRegInfo();
1388   tm_ = &fn.getTarget();
1389   tri_ = tm_->getRegisterInfo();
1390   tii_ = tm_->getInstrInfo();
1391   li_ = &getAnalysis<LiveIntervals>();
1392   ldv_ = &getAnalysis<LiveDebugVariables>();
1393   AA = &getAnalysis<AliasAnalysis>();
1394   loopInfo = &getAnalysis<MachineLoopInfo>();
1395
1396   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1397                << "********** Function: "
1398                << ((Value*)mf_->getFunction())->getName() << '\n');
1399
1400   if (VerifyCoalescing)
1401     mf_->verify(this, "Before register coalescing");
1402
1403   RegClassInfo.runOnMachineFunction(fn);
1404
1405   // Join (coalesce) intervals if requested.
1406   if (EnableJoining) {
1407     joinIntervals();
1408     DEBUG({
1409         dbgs() << "********** INTERVALS POST JOINING **********\n";
1410         for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1411              I != E; ++I){
1412           I->second->print(dbgs(), tri_);
1413           dbgs() << "\n";
1414         }
1415       });
1416   }
1417
1418   // Perform a final pass over the instructions and compute spill weights
1419   // and remove identity moves.
1420   SmallVector<unsigned, 4> DeadDefs;
1421   for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1422        mbbi != mbbe; ++mbbi) {
1423     MachineBasicBlock* mbb = mbbi;
1424     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1425          mii != mie; ) {
1426       MachineInstr *MI = mii;
1427       if (JoinedCopies.count(MI)) {
1428         // Delete all coalesced copies.
1429         bool DoDelete = true;
1430         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1431         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1432         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1433             MI->getNumOperands() > 2)
1434           // Do not delete extract_subreg, insert_subreg of physical
1435           // registers unless the definition is dead. e.g.
1436           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1437           // or else the scavenger may complain. LowerSubregs will
1438           // delete them later.
1439           DoDelete = false;
1440
1441         if (MI->allDefsAreDead()) {
1442           if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1443               li_->hasInterval(SrcReg))
1444             li_->shrinkToUses(&li_->getInterval(SrcReg));
1445           DoDelete = true;
1446         }
1447         if (!DoDelete) {
1448           // We need the instruction to adjust liveness, so make it a KILL.
1449           if (MI->isSubregToReg()) {
1450             MI->RemoveOperand(3);
1451             MI->RemoveOperand(1);
1452           }
1453           MI->setDesc(tii_->get(TargetOpcode::KILL));
1454           mii = llvm::next(mii);
1455         } else {
1456           li_->RemoveMachineInstrFromMaps(MI);
1457           mii = mbbi->erase(mii);
1458           ++numPeep;
1459         }
1460         continue;
1461       }
1462
1463       // Now check if this is a remat'ed def instruction which is now dead.
1464       if (ReMatDefs.count(MI)) {
1465         bool isDead = true;
1466         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1467           const MachineOperand &MO = MI->getOperand(i);
1468           if (!MO.isReg())
1469             continue;
1470           unsigned Reg = MO.getReg();
1471           if (!Reg)
1472             continue;
1473           if (TargetRegisterInfo::isVirtualRegister(Reg))
1474             DeadDefs.push_back(Reg);
1475           if (MO.isDead())
1476             continue;
1477           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1478               !mri_->use_nodbg_empty(Reg)) {
1479             isDead = false;
1480             break;
1481           }
1482         }
1483         if (isDead) {
1484           while (!DeadDefs.empty()) {
1485             unsigned DeadDef = DeadDefs.back();
1486             DeadDefs.pop_back();
1487             RemoveDeadDef(li_->getInterval(DeadDef), MI);
1488           }
1489           li_->RemoveMachineInstrFromMaps(mii);
1490           mii = mbbi->erase(mii);
1491           continue;
1492         } else
1493           DeadDefs.clear();
1494       }
1495
1496       ++mii;
1497
1498       // Check for now unnecessary kill flags.
1499       if (li_->isNotInMIMap(MI)) continue;
1500       SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1501       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1502         MachineOperand &MO = MI->getOperand(i);
1503         if (!MO.isReg() || !MO.isKill()) continue;
1504         unsigned reg = MO.getReg();
1505         if (!reg || !li_->hasInterval(reg)) continue;
1506         if (!li_->getInterval(reg).killedAt(DefIdx)) {
1507           MO.setIsKill(false);
1508           continue;
1509         }
1510         // When leaving a kill flag on a physreg, check if any subregs should
1511         // remain alive.
1512         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1513           continue;
1514         for (const unsigned *SR = tri_->getSubRegisters(reg);
1515              unsigned S = *SR; ++SR)
1516           if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1517             MI->addRegisterDefined(S, tri_);
1518       }
1519     }
1520   }
1521
1522   DEBUG(dump());
1523   DEBUG(ldv_->dump());
1524   if (VerifyCoalescing)
1525     mf_->verify(this, "After register coalescing");
1526   return true;
1527 }
1528
1529 /// print - Implement the dump method.
1530 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1531    li_->print(O, m);
1532 }
1533
1534 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1535   return new SimpleRegisterCoalescing();
1536 }
1537
1538 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1539 DEFINING_FILE_FOR(SimpleRegisterCoalescing)