Delete merged physreg copies in joinReservedPhysReg().
[oota-llvm.git] / lib / CodeGen / RegisterCoalescer.cpp
1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
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 the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "LiveDebugVariables.h"
19 #include "VirtRegMap.h"
20
21 #include "llvm/Pass.h"
22 #include "llvm/Value.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/LiveRangeEdit.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegisterClassInfo.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegisterInfo.h"
48 #include <algorithm>
49 #include <cmath>
50 using namespace llvm;
51
52 STATISTIC(numJoins    , "Number of interval joins performed");
53 STATISTIC(numCrossRCs , "Number of cross class joins performed");
54 STATISTIC(numCommutes , "Number of instruction commuting performed");
55 STATISTIC(numExtends  , "Number of copies extended");
56 STATISTIC(NumReMats   , "Number of instructions re-materialized");
57 STATISTIC(NumInflated , "Number of register classes inflated");
58
59 static cl::opt<bool>
60 EnableJoining("join-liveintervals",
61               cl::desc("Coalesce copies (default=true)"),
62               cl::init(true));
63
64 static cl::opt<bool>
65 VerifyCoalescing("verify-coalescing",
66          cl::desc("Verify machine instrs before and after register coalescing"),
67          cl::Hidden);
68
69 namespace {
70   class RegisterCoalescer : public MachineFunctionPass,
71                             private LiveRangeEdit::Delegate {
72     MachineFunction* MF;
73     MachineRegisterInfo* MRI;
74     const TargetMachine* TM;
75     const TargetRegisterInfo* TRI;
76     const TargetInstrInfo* TII;
77     LiveIntervals *LIS;
78     LiveDebugVariables *LDV;
79     const MachineLoopInfo* Loops;
80     AliasAnalysis *AA;
81     RegisterClassInfo RegClassInfo;
82
83     /// WorkList - Copy instructions yet to be coalesced.
84     SmallVector<MachineInstr*, 8> WorkList;
85
86     /// ErasedInstrs - Set of instruction pointers that have been erased, and
87     /// that may be present in WorkList.
88     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
89
90     /// Dead instructions that are about to be deleted.
91     SmallVector<MachineInstr*, 8> DeadDefs;
92
93     /// Virtual registers to be considered for register class inflation.
94     SmallVector<unsigned, 8> InflateRegs;
95
96     /// Recursively eliminate dead defs in DeadDefs.
97     void eliminateDeadDefs();
98
99     /// LiveRangeEdit callback.
100     void LRE_WillEraseInstruction(MachineInstr *MI);
101
102     /// joinAllIntervals - join compatible live intervals
103     void joinAllIntervals();
104
105     /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
106     /// copies that cannot yet be coalesced into WorkList.
107     void copyCoalesceInMBB(MachineBasicBlock *MBB);
108
109     /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
110     /// position From. Return true if any progress was made.
111     bool copyCoalesceWorkList(unsigned From = 0);
112
113     /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
114     /// which are the src/dst of the copy instruction CopyMI.  This returns
115     /// true if the copy was successfully coalesced away. If it is not
116     /// currently possible to coalesce this interval, but it may be possible if
117     /// other things get coalesced, then it returns true by reference in
118     /// 'Again'.
119     bool joinCopy(MachineInstr *TheCopy, bool &Again);
120
121     /// joinIntervals - Attempt to join these two intervals.  On failure, this
122     /// returns false.  The output "SrcInt" will not have been modified, so we
123     /// can use this information below to update aliases.
124     bool joinIntervals(CoalescerPair &CP);
125
126     /// Attempt joining with a reserved physreg.
127     bool joinReservedPhysReg(CoalescerPair &CP);
128
129     /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
130     /// the source value number is defined by a copy from the destination reg
131     /// see if we can merge these two destination reg valno# into a single
132     /// value number, eliminating a copy.
133     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
134
135     /// hasOtherReachingDefs - Return true if there are definitions of IntB
136     /// other than BValNo val# that can reach uses of AValno val# of IntA.
137     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
138                               VNInfo *AValNo, VNInfo *BValNo);
139
140     /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
141     /// If the source value number is defined by a commutable instruction and
142     /// its other operand is coalesced to the copy dest register, see if we
143     /// can transform the copy into a noop by commuting the definition.
144     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
145
146     /// reMaterializeTrivialDef - If the source of a copy is defined by a
147     /// trivial computation, replace the copy by rematerialize the definition.
148     bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
149                                  MachineInstr *CopyMI);
150
151     /// canJoinPhys - Return true if a physreg copy should be joined.
152     bool canJoinPhys(CoalescerPair &CP);
153
154     /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
155     /// update the subregister number if it is not zero. If DstReg is a
156     /// physical register and the existing subregister number of the def / use
157     /// being updated is not zero, make sure to set it to the correct physical
158     /// subregister.
159     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
160
161     /// eliminateUndefCopy - Handle copies of undef values.
162     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
163
164   public:
165     static char ID; // Class identification, replacement for typeinfo
166     RegisterCoalescer() : MachineFunctionPass(ID) {
167       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
168     }
169
170     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
171
172     virtual void releaseMemory();
173
174     /// runOnMachineFunction - pass entry point
175     virtual bool runOnMachineFunction(MachineFunction&);
176
177     /// print - Implement the dump method.
178     virtual void print(raw_ostream &O, const Module* = 0) const;
179   };
180 } /// end anonymous namespace
181
182 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
183
184 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
185                       "Simple Register Coalescing", false, false)
186 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
187 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
188 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
189 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
190 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
191 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
192                     "Simple Register Coalescing", false, false)
193
194 char RegisterCoalescer::ID = 0;
195
196 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
197   if (!a) return b;
198   if (!b) return a;
199   return tri.composeSubRegIndices(a, b);
200 }
201
202 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
203                         unsigned &Src, unsigned &Dst,
204                         unsigned &SrcSub, unsigned &DstSub) {
205   if (MI->isCopy()) {
206     Dst = MI->getOperand(0).getReg();
207     DstSub = MI->getOperand(0).getSubReg();
208     Src = MI->getOperand(1).getReg();
209     SrcSub = MI->getOperand(1).getSubReg();
210   } else if (MI->isSubregToReg()) {
211     Dst = MI->getOperand(0).getReg();
212     DstSub = compose(tri, MI->getOperand(0).getSubReg(),
213                      MI->getOperand(3).getImm());
214     Src = MI->getOperand(2).getReg();
215     SrcSub = MI->getOperand(2).getSubReg();
216   } else
217     return false;
218   return true;
219 }
220
221 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
222   SrcReg = DstReg = 0;
223   SrcIdx = DstIdx = 0;
224   NewRC = 0;
225   Flipped = CrossClass = false;
226
227   unsigned Src, Dst, SrcSub, DstSub;
228   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
229     return false;
230   Partial = SrcSub || DstSub;
231
232   // If one register is a physreg, it must be Dst.
233   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
234     if (TargetRegisterInfo::isPhysicalRegister(Dst))
235       return false;
236     std::swap(Src, Dst);
237     std::swap(SrcSub, DstSub);
238     Flipped = true;
239   }
240
241   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
242
243   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
244     // Eliminate DstSub on a physreg.
245     if (DstSub) {
246       Dst = TRI.getSubReg(Dst, DstSub);
247       if (!Dst) return false;
248       DstSub = 0;
249     }
250
251     // Eliminate SrcSub by picking a corresponding Dst superregister.
252     if (SrcSub) {
253       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
254       if (!Dst) return false;
255       SrcSub = 0;
256     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
257       return false;
258     }
259   } else {
260     // Both registers are virtual.
261     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
262     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
263
264     // Both registers have subreg indices.
265     if (SrcSub && DstSub) {
266       // Copies between different sub-registers are never coalescable.
267       if (Src == Dst && SrcSub != DstSub)
268         return false;
269
270       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
271                                          SrcIdx, DstIdx);
272       if (!NewRC)
273         return false;
274     } else if (DstSub) {
275       // SrcReg will be merged with a sub-register of DstReg.
276       SrcIdx = DstSub;
277       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
278     } else if (SrcSub) {
279       // DstReg will be merged with a sub-register of SrcReg.
280       DstIdx = SrcSub;
281       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
282     } else {
283       // This is a straight copy without sub-registers.
284       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
285     }
286
287     // The combined constraint may be impossible to satisfy.
288     if (!NewRC)
289       return false;
290
291     // Prefer SrcReg to be a sub-register of DstReg.
292     // FIXME: Coalescer should support subregs symmetrically.
293     if (DstIdx && !SrcIdx) {
294       std::swap(Src, Dst);
295       std::swap(SrcIdx, DstIdx);
296       Flipped = !Flipped;
297     }
298
299     CrossClass = NewRC != DstRC || NewRC != SrcRC;
300   }
301   // Check our invariants
302   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
303   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
304          "Cannot have a physical SubIdx");
305   SrcReg = Src;
306   DstReg = Dst;
307   return true;
308 }
309
310 bool CoalescerPair::flip() {
311   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
312     return false;
313   std::swap(SrcReg, DstReg);
314   std::swap(SrcIdx, DstIdx);
315   Flipped = !Flipped;
316   return true;
317 }
318
319 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
320   if (!MI)
321     return false;
322   unsigned Src, Dst, SrcSub, DstSub;
323   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
324     return false;
325
326   // Find the virtual register that is SrcReg.
327   if (Dst == SrcReg) {
328     std::swap(Src, Dst);
329     std::swap(SrcSub, DstSub);
330   } else if (Src != SrcReg) {
331     return false;
332   }
333
334   // Now check that Dst matches DstReg.
335   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
336     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
337       return false;
338     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
339     // DstSub could be set for a physreg from INSERT_SUBREG.
340     if (DstSub)
341       Dst = TRI.getSubReg(Dst, DstSub);
342     // Full copy of Src.
343     if (!SrcSub)
344       return DstReg == Dst;
345     // This is a partial register copy. Check that the parts match.
346     return TRI.getSubReg(DstReg, SrcSub) == Dst;
347   } else {
348     // DstReg is virtual.
349     if (DstReg != Dst)
350       return false;
351     // Registers match, do the subregisters line up?
352     return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
353   }
354 }
355
356 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
357   AU.setPreservesCFG();
358   AU.addRequired<AliasAnalysis>();
359   AU.addRequired<LiveIntervals>();
360   AU.addPreserved<LiveIntervals>();
361   AU.addRequired<LiveDebugVariables>();
362   AU.addPreserved<LiveDebugVariables>();
363   AU.addPreserved<SlotIndexes>();
364   AU.addRequired<MachineLoopInfo>();
365   AU.addPreserved<MachineLoopInfo>();
366   AU.addPreservedID(MachineDominatorsID);
367   MachineFunctionPass::getAnalysisUsage(AU);
368 }
369
370 void RegisterCoalescer::eliminateDeadDefs() {
371   SmallVector<LiveInterval*, 8> NewRegs;
372   LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
373 }
374
375 // Callback from eliminateDeadDefs().
376 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
377   // MI may be in WorkList. Make sure we don't visit it.
378   ErasedInstrs.insert(MI);
379 }
380
381 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
382 /// being the source and IntB being the dest, thus this defines a value number
383 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
384 /// see if we can merge these two pieces of B into a single value number,
385 /// eliminating a copy.  For example:
386 ///
387 ///  A3 = B0
388 ///    ...
389 ///  B1 = A3      <- this copy
390 ///
391 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
392 /// value number to be replaced with B0 (which simplifies the B liveinterval).
393 ///
394 /// This returns true if an interval was modified.
395 ///
396 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
397                                              MachineInstr *CopyMI) {
398   assert(!CP.isPartial() && "This doesn't work for partial copies.");
399   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
400
401   LiveInterval &IntA =
402     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
403   LiveInterval &IntB =
404     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
405   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
406
407   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
408   // the example above.
409   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
410   if (BLR == IntB.end()) return false;
411   VNInfo *BValNo = BLR->valno;
412
413   // Get the location that B is defined at.  Two options: either this value has
414   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
415   // can't process it.
416   if (BValNo->def != CopyIdx) return false;
417
418   // AValNo is the value number in A that defines the copy, A3 in the example.
419   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
420   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
421   // The live range might not exist after fun with physreg coalescing.
422   if (ALR == IntA.end()) return false;
423   VNInfo *AValNo = ALR->valno;
424
425   // If AValNo is defined as a copy from IntB, we can potentially process this.
426   // Get the instruction that defines this value number.
427   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
428   if (!CP.isCoalescable(ACopyMI))
429     return false;
430
431   // Get the LiveRange in IntB that this value number starts with.
432   LiveInterval::iterator ValLR =
433     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
434   if (ValLR == IntB.end())
435     return false;
436
437   // Make sure that the end of the live range is inside the same block as
438   // CopyMI.
439   MachineInstr *ValLREndInst =
440     LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
441   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
442     return false;
443
444   // Okay, we now know that ValLR ends in the same block that the CopyMI
445   // live-range starts.  If there are no intervening live ranges between them in
446   // IntB, we can merge them.
447   if (ValLR+1 != BLR) return false;
448
449   DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
450
451   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
452   // We are about to delete CopyMI, so need to remove it as the 'instruction
453   // that defines this value #'. Update the valnum with the new defining
454   // instruction #.
455   BValNo->def = FillerStart;
456
457   // Okay, we can merge them.  We need to insert a new liverange:
458   // [ValLR.end, BLR.begin) of either value number, then we merge the
459   // two value numbers.
460   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
461
462   // Okay, merge "B1" into the same value number as "B0".
463   if (BValNo != ValLR->valno)
464     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
465   DEBUG(dbgs() << "   result = " << IntB << '\n');
466
467   // If the source instruction was killing the source register before the
468   // merge, unset the isKill marker given the live range has been extended.
469   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
470   if (UIdx != -1) {
471     ValLREndInst->getOperand(UIdx).setIsKill(false);
472   }
473
474   // Rewrite the copy. If the copy instruction was killing the destination
475   // register before the merge, find the last use and trim the live range. That
476   // will also add the isKill marker.
477   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
478   if (ALR->end == CopyIdx)
479     LIS->shrinkToUses(&IntA);
480
481   ++numExtends;
482   return true;
483 }
484
485 /// hasOtherReachingDefs - Return true if there are definitions of IntB
486 /// other than BValNo val# that can reach uses of AValno val# of IntA.
487 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
488                                              LiveInterval &IntB,
489                                              VNInfo *AValNo,
490                                              VNInfo *BValNo) {
491   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
492   // the PHI values.
493   if (LIS->hasPHIKill(IntA, AValNo))
494     return true;
495
496   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
497        AI != AE; ++AI) {
498     if (AI->valno != AValNo) continue;
499     LiveInterval::Ranges::iterator BI =
500       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
501     if (BI != IntB.ranges.begin())
502       --BI;
503     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
504       if (BI->valno == BValNo)
505         continue;
506       if (BI->start <= AI->start && BI->end > AI->start)
507         return true;
508       if (BI->start > AI->start && BI->start < AI->end)
509         return true;
510     }
511   }
512   return false;
513 }
514
515 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
516 /// IntA being the source and IntB being the dest, thus this defines a value
517 /// number in IntB.  If the source value number (in IntA) is defined by a
518 /// commutable instruction and its other operand is coalesced to the copy dest
519 /// register, see if we can transform the copy into a noop by commuting the
520 /// definition. For example,
521 ///
522 ///  A3 = op A2 B0<kill>
523 ///    ...
524 ///  B1 = A3      <- this copy
525 ///    ...
526 ///     = op A3   <- more uses
527 ///
528 /// ==>
529 ///
530 ///  B2 = op B0 A2<kill>
531 ///    ...
532 ///  B1 = B2      <- now an identify copy
533 ///    ...
534 ///     = op B2   <- more uses
535 ///
536 /// This returns true if an interval was modified.
537 ///
538 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
539                                                  MachineInstr *CopyMI) {
540   assert (!CP.isPhys());
541
542   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
543
544   LiveInterval &IntA =
545     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
546   LiveInterval &IntB =
547     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
548
549   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
550   // the example above.
551   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
552   if (!BValNo || BValNo->def != CopyIdx)
553     return false;
554
555   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
556
557   // AValNo is the value number in A that defines the copy, A3 in the example.
558   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
559   assert(AValNo && "COPY source not live");
560   if (AValNo->isPHIDef() || AValNo->isUnused())
561     return false;
562   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
563   if (!DefMI)
564     return false;
565   if (!DefMI->isCommutable())
566     return false;
567   // If DefMI is a two-address instruction then commuting it will change the
568   // destination register.
569   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
570   assert(DefIdx != -1);
571   unsigned UseOpIdx;
572   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
573     return false;
574   unsigned Op1, Op2, NewDstIdx;
575   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
576     return false;
577   if (Op1 == UseOpIdx)
578     NewDstIdx = Op2;
579   else if (Op2 == UseOpIdx)
580     NewDstIdx = Op1;
581   else
582     return false;
583
584   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
585   unsigned NewReg = NewDstMO.getReg();
586   if (NewReg != IntB.reg || !NewDstMO.isKill())
587     return false;
588
589   // Make sure there are no other definitions of IntB that would reach the
590   // uses which the new definition can reach.
591   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
592     return false;
593
594   // If some of the uses of IntA.reg is already coalesced away, return false.
595   // It's not possible to determine whether it's safe to perform the coalescing.
596   for (MachineRegisterInfo::use_nodbg_iterator UI =
597          MRI->use_nodbg_begin(IntA.reg),
598        UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
599     MachineInstr *UseMI = &*UI;
600     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
601     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
602     if (ULR == IntA.end() || ULR->valno != AValNo)
603       continue;
604     // If this use is tied to a def, we can't rewrite the register.
605     if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
606       return false;
607   }
608
609   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
610                << *DefMI);
611
612   // At this point we have decided that it is legal to do this
613   // transformation.  Start by commuting the instruction.
614   MachineBasicBlock *MBB = DefMI->getParent();
615   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
616   if (!NewMI)
617     return false;
618   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
619       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
620       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
621     return false;
622   if (NewMI != DefMI) {
623     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
624     MachineBasicBlock::iterator Pos = DefMI;
625     MBB->insert(Pos, NewMI);
626     MBB->erase(DefMI);
627   }
628   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
629   NewMI->getOperand(OpIdx).setIsKill();
630
631   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
632   // A = or A, B
633   // ...
634   // B = A
635   // ...
636   // C = A<kill>
637   // ...
638   //   = B
639
640   // Update uses of IntA of the specific Val# with IntB.
641   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
642          UE = MRI->use_end(); UI != UE;) {
643     MachineOperand &UseMO = UI.getOperand();
644     MachineInstr *UseMI = &*UI;
645     ++UI;
646     if (UseMI->isDebugValue()) {
647       // FIXME These don't have an instruction index.  Not clear we have enough
648       // info to decide whether to do this replacement or not.  For now do it.
649       UseMO.setReg(NewReg);
650       continue;
651     }
652     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
653     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
654     if (ULR == IntA.end() || ULR->valno != AValNo)
655       continue;
656     // Kill flags are no longer accurate. They are recomputed after RA.
657     UseMO.setIsKill(false);
658     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
659       UseMO.substPhysReg(NewReg, *TRI);
660     else
661       UseMO.setReg(NewReg);
662     if (UseMI == CopyMI)
663       continue;
664     if (!UseMI->isCopy())
665       continue;
666     if (UseMI->getOperand(0).getReg() != IntB.reg ||
667         UseMI->getOperand(0).getSubReg())
668       continue;
669
670     // This copy will become a noop. If it's defining a new val#, merge it into
671     // BValNo.
672     SlotIndex DefIdx = UseIdx.getRegSlot();
673     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
674     if (!DVNI)
675       continue;
676     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
677     assert(DVNI->def == DefIdx);
678     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
679     ErasedInstrs.insert(UseMI);
680     LIS->RemoveMachineInstrFromMaps(UseMI);
681     UseMI->eraseFromParent();
682   }
683
684   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
685   // is updated.
686   VNInfo *ValNo = BValNo;
687   ValNo->def = AValNo->def;
688   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
689        AI != AE; ++AI) {
690     if (AI->valno != AValNo) continue;
691     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
692   }
693   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
694
695   IntA.removeValNo(AValNo);
696   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
697   ++numCommutes;
698   return true;
699 }
700
701 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
702 /// computation, replace the copy by rematerialize the definition.
703 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
704                                                 unsigned DstReg,
705                                                 MachineInstr *CopyMI) {
706   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
707   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
708   assert(SrcLR != SrcInt.end() && "Live range not found!");
709   VNInfo *ValNo = SrcLR->valno;
710   if (ValNo->isPHIDef() || ValNo->isUnused())
711     return false;
712   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
713   if (!DefMI)
714     return false;
715   assert(DefMI && "Defining instruction disappeared");
716   if (!DefMI->isAsCheapAsAMove())
717     return false;
718   if (!TII->isTriviallyReMaterializable(DefMI, AA))
719     return false;
720   bool SawStore = false;
721   if (!DefMI->isSafeToMove(TII, AA, SawStore))
722     return false;
723   const MCInstrDesc &MCID = DefMI->getDesc();
724   if (MCID.getNumDefs() != 1)
725     return false;
726   if (!DefMI->isImplicitDef()) {
727     // Make sure the copy destination register class fits the instruction
728     // definition register class. The mismatch can happen as a result of earlier
729     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
730     const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
731     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
732       if (MRI->getRegClass(DstReg) != RC)
733         return false;
734     } else if (!RC->contains(DstReg))
735       return false;
736   }
737
738   MachineBasicBlock *MBB = CopyMI->getParent();
739   MachineBasicBlock::iterator MII =
740     llvm::next(MachineBasicBlock::iterator(CopyMI));
741   TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
742   MachineInstr *NewMI = prior(MII);
743
744   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
745   // We need to remember these so we can add intervals once we insert
746   // NewMI into SlotIndexes.
747   SmallVector<unsigned, 4> NewMIImplDefs;
748   for (unsigned i = NewMI->getDesc().getNumOperands(),
749          e = NewMI->getNumOperands(); i != e; ++i) {
750     MachineOperand &MO = NewMI->getOperand(i);
751     if (MO.isReg()) {
752       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
753              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
754       NewMIImplDefs.push_back(MO.getReg());
755     }
756   }
757
758   // CopyMI may have implicit operands, transfer them over to the newly
759   // rematerialized instruction. And update implicit def interval valnos.
760   for (unsigned i = CopyMI->getDesc().getNumOperands(),
761          e = CopyMI->getNumOperands(); i != e; ++i) {
762     MachineOperand &MO = CopyMI->getOperand(i);
763     if (MO.isReg()) {
764       assert(MO.isImplicit() && "No explicit operands after implict operands.");
765       // Discard VReg implicit defs.
766       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
767         NewMI->addOperand(MO);
768       }
769     }
770   }
771
772   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
773
774   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
775   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
776     unsigned Reg = NewMIImplDefs[i];
777     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
778       if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
779         LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
780   }
781
782   CopyMI->eraseFromParent();
783   ErasedInstrs.insert(CopyMI);
784   DEBUG(dbgs() << "Remat: " << *NewMI);
785   ++NumReMats;
786
787   // The source interval can become smaller because we removed a use.
788   LIS->shrinkToUses(&SrcInt, &DeadDefs);
789   if (!DeadDefs.empty())
790     eliminateDeadDefs();
791
792   return true;
793 }
794
795 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
796 /// values, it only removes local variables. When we have a copy like:
797 ///
798 ///   %vreg1 = COPY %vreg2<undef>
799 ///
800 /// We delete the copy and remove the corresponding value number from %vreg1.
801 /// Any uses of that value number are marked as <undef>.
802 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
803                                            const CoalescerPair &CP) {
804   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
805   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
806   if (SrcInt->liveAt(Idx))
807     return false;
808   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
809   if (DstInt->liveAt(Idx))
810     return false;
811
812   // No intervals are live-in to CopyMI - it is undef.
813   if (CP.isFlipped())
814     DstInt = SrcInt;
815   SrcInt = 0;
816
817   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
818   assert(DeadVNI && "No value defined in DstInt");
819   DstInt->removeValNo(DeadVNI);
820
821   // Find new undef uses.
822   for (MachineRegisterInfo::reg_nodbg_iterator
823          I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
824        I != E; ++I) {
825     MachineOperand &MO = I.getOperand();
826     if (MO.isDef() || MO.isUndef())
827       continue;
828     MachineInstr *MI = MO.getParent();
829     SlotIndex Idx = LIS->getInstructionIndex(MI);
830     if (DstInt->liveAt(Idx))
831       continue;
832     MO.setIsUndef(true);
833     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
834   }
835   return true;
836 }
837
838 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
839 /// update the subregister number if it is not zero. If DstReg is a
840 /// physical register and the existing subregister number of the def / use
841 /// being updated is not zero, make sure to set it to the correct physical
842 /// subregister.
843 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
844                                           unsigned DstReg,
845                                           unsigned SubIdx) {
846   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
847   LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
848
849   // Update LiveDebugVariables.
850   LDV->renameRegister(SrcReg, DstReg, SubIdx);
851
852   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
853        MachineInstr *UseMI = I.skipInstruction();) {
854     SmallVector<unsigned,8> Ops;
855     bool Reads, Writes;
856     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
857
858     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
859     // because SrcReg is a sub-register.
860     if (DstInt && !Reads && SubIdx)
861       Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
862
863     // Replace SrcReg with DstReg in all UseMI operands.
864     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
865       MachineOperand &MO = UseMI->getOperand(Ops[i]);
866
867       // Adjust <undef> flags in case of sub-register joins. We don't want to
868       // turn a full def into a read-modify-write sub-register def and vice
869       // versa.
870       if (SubIdx && MO.isDef())
871         MO.setIsUndef(!Reads);
872
873       if (DstIsPhys)
874         MO.substPhysReg(DstReg, *TRI);
875       else
876         MO.substVirtReg(DstReg, SubIdx, *TRI);
877     }
878
879     DEBUG({
880         dbgs() << "\t\tupdated: ";
881         if (!UseMI->isDebugValue())
882           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
883         dbgs() << *UseMI;
884       });
885   }
886 }
887
888 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
889 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
890   /// Always join simple intervals that are defined by a single copy from a
891   /// reserved register. This doesn't increase register pressure, so it is
892   /// always beneficial.
893   if (!RegClassInfo.isReserved(CP.getDstReg())) {
894     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
895     return false;
896   }
897
898   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
899   if (CP.isFlipped() && JoinVInt.containsOneValue())
900     return true;
901
902   DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
903   return false;
904 }
905
906 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
907 /// which are the src/dst of the copy instruction CopyMI.  This returns true
908 /// if the copy was successfully coalesced away. If it is not currently
909 /// possible to coalesce this interval, but it may be possible if other
910 /// things get coalesced, then it returns true by reference in 'Again'.
911 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
912
913   Again = false;
914   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
915
916   CoalescerPair CP(*TRI);
917   if (!CP.setRegisters(CopyMI)) {
918     DEBUG(dbgs() << "\tNot coalescable.\n");
919     return false;
920   }
921
922   // Dead code elimination. This really should be handled by MachineDCE, but
923   // sometimes dead copies slip through, and we can't generate invalid live
924   // ranges.
925   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
926     DEBUG(dbgs() << "\tCopy is dead.\n");
927     DeadDefs.push_back(CopyMI);
928     eliminateDeadDefs();
929     return true;
930   }
931
932   // Eliminate undefs.
933   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
934     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
935     LIS->RemoveMachineInstrFromMaps(CopyMI);
936     CopyMI->eraseFromParent();
937     return false;  // Not coalescable.
938   }
939
940   // Coalesced copies are normally removed immediately, but transformations
941   // like removeCopyByCommutingDef() can inadvertently create identity copies.
942   // When that happens, just join the values and remove the copy.
943   if (CP.getSrcReg() == CP.getDstReg()) {
944     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
945     DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
946     LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
947     if (VNInfo *DefVNI = LRQ.valueDefined()) {
948       VNInfo *ReadVNI = LRQ.valueIn();
949       assert(ReadVNI && "No value before copy and no <undef> flag.");
950       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
951       LI.MergeValueNumberInto(DefVNI, ReadVNI);
952       DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
953     }
954     LIS->RemoveMachineInstrFromMaps(CopyMI);
955     CopyMI->eraseFromParent();
956     return true;
957   }
958
959   // Enforce policies.
960   if (CP.isPhys()) {
961     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
962                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
963                  << '\n');
964     if (!canJoinPhys(CP)) {
965       // Before giving up coalescing, if definition of source is defined by
966       // trivial computation, try rematerializing it.
967       if (!CP.isFlipped() &&
968           reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
969                                   CP.getDstReg(), CopyMI))
970         return true;
971       return false;
972     }
973   } else {
974     DEBUG({
975       dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
976              << " with ";
977       if (CP.getDstIdx() && CP.getSrcIdx())
978         dbgs() << PrintReg(CP.getDstReg()) << " in "
979                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
980                << PrintReg(CP.getSrcReg()) << " in "
981                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
982       else
983         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
984                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
985     });
986
987     // When possible, let DstReg be the larger interval.
988     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
989                            LIS->getInterval(CP.getDstReg()).ranges.size())
990       CP.flip();
991   }
992
993   // Okay, attempt to join these two intervals.  On failure, this returns false.
994   // Otherwise, if one of the intervals being joined is a physreg, this method
995   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
996   // been modified, so we can use this information below to update aliases.
997   if (!joinIntervals(CP)) {
998     // Coalescing failed.
999
1000     // If definition of source is defined by trivial computation, try
1001     // rematerializing it.
1002     if (!CP.isFlipped() &&
1003         reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1004                                 CP.getDstReg(), CopyMI))
1005       return true;
1006
1007     // If we can eliminate the copy without merging the live ranges, do so now.
1008     if (!CP.isPartial() && !CP.isPhys()) {
1009       if (adjustCopiesBackFrom(CP, CopyMI) ||
1010           removeCopyByCommutingDef(CP, CopyMI)) {
1011         LIS->RemoveMachineInstrFromMaps(CopyMI);
1012         CopyMI->eraseFromParent();
1013         DEBUG(dbgs() << "\tTrivial!\n");
1014         return true;
1015       }
1016     }
1017
1018     // Otherwise, we are unable to join the intervals.
1019     DEBUG(dbgs() << "\tInterference!\n");
1020     Again = true;  // May be possible to coalesce later.
1021     return false;
1022   }
1023
1024   // Coalescing to a virtual register that is of a sub-register class of the
1025   // other. Make sure the resulting register is set to the right register class.
1026   if (CP.isCrossClass()) {
1027     ++numCrossRCs;
1028     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1029   }
1030
1031   // Removing sub-register copies can ease the register class constraints.
1032   // Make sure we attempt to inflate the register class of DstReg.
1033   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1034     InflateRegs.push_back(CP.getDstReg());
1035
1036   // CopyMI has been erased by joinIntervals at this point. Remove it from
1037   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1038   // to the work list. This keeps ErasedInstrs from growing needlessly.
1039   ErasedInstrs.erase(CopyMI);
1040
1041   // Rewrite all SrcReg operands to DstReg.
1042   // Also update DstReg operands to include DstIdx if it is set.
1043   if (CP.getDstIdx())
1044     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1045   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1046
1047   // SrcReg is guaranteed to be the register whose live interval that is
1048   // being merged.
1049   LIS->removeInterval(CP.getSrcReg());
1050
1051   // Update regalloc hint.
1052   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1053
1054   DEBUG({
1055     dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1056     if (!CP.isPhys())
1057       dbgs() << LIS->getInterval(CP.getDstReg());
1058      dbgs() << '\n';
1059   });
1060
1061   ++numJoins;
1062   return true;
1063 }
1064
1065 /// Attempt joining with a reserved physreg.
1066 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1067   assert(CP.isPhys() && "Must be a physreg copy");
1068   assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1069   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1070   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1071                << '\n');
1072
1073   assert(CP.isFlipped() && RHS.containsOneValue() &&
1074          "Invalid join with reserved register");
1075
1076   // Optimization for reserved registers like ESP. We can only merge with a
1077   // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1078   // The live range of the reserved register will look like a set of dead defs
1079   // - we don't properly track the live range of reserved registers.
1080
1081   // Deny any overlapping intervals.  This depends on all the reserved
1082   // register live ranges to look like dead defs.
1083   for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1084     if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1085       DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1086       return false;
1087     }
1088
1089   // Skip any value computations, we are not adding new values to the
1090   // reserved register.  Also skip merging the live ranges, the reserved
1091   // register live range doesn't need to be accurate as long as all the
1092   // defs are there.
1093
1094   // Delete the identity copy.
1095   MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1096   LIS->RemoveMachineInstrFromMaps(CopyMI);
1097   CopyMI->eraseFromParent();
1098
1099   // We don't track kills for reserved registers.
1100   MRI->clearKillFlags(CP.getSrcReg());
1101
1102   return true;
1103 }
1104
1105 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1106 /// compute what the resultant value numbers for each value in the input two
1107 /// ranges will be.  This is complicated by copies between the two which can
1108 /// and will commonly cause multiple value numbers to be merged into one.
1109 ///
1110 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1111 /// keeps track of the new InstDefiningValue assignment for the result
1112 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1113 /// whether a value in this or other is a copy from the opposite set.
1114 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1115 /// already been assigned.
1116 ///
1117 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1118 /// contains the value number the copy is from.
1119 ///
1120 static unsigned ComputeUltimateVN(VNInfo *VNI,
1121                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1122                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1123                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1124                                   SmallVector<int, 16> &ThisValNoAssignments,
1125                                   SmallVector<int, 16> &OtherValNoAssignments) {
1126   unsigned VN = VNI->id;
1127
1128   // If the VN has already been computed, just return it.
1129   if (ThisValNoAssignments[VN] >= 0)
1130     return ThisValNoAssignments[VN];
1131   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1132
1133   // If this val is not a copy from the other val, then it must be a new value
1134   // number in the destination.
1135   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1136   if (I == ThisFromOther.end()) {
1137     NewVNInfo.push_back(VNI);
1138     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1139   }
1140   VNInfo *OtherValNo = I->second;
1141
1142   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1143   // been computed, return it.
1144   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1145     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1146
1147   // Mark this value number as currently being computed, then ask what the
1148   // ultimate value # of the other value is.
1149   ThisValNoAssignments[VN] = -2;
1150   unsigned UltimateVN =
1151     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1152                       OtherValNoAssignments, ThisValNoAssignments);
1153   return ThisValNoAssignments[VN] = UltimateVN;
1154 }
1155
1156
1157 // Find out if we have something like
1158 // A = X
1159 // B = X
1160 // if so, we can pretend this is actually
1161 // A = X
1162 // B = A
1163 // which allows us to coalesce A and B.
1164 // VNI is the definition of B. LR is the life range of A that includes
1165 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1166 // This implies that A dominates B.
1167 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1168                                           const TargetRegisterInfo &tri,
1169                                           CoalescerPair &CP,
1170                                           VNInfo *VNI,
1171                                           VNInfo *OtherVNI,
1172                                      SmallVector<MachineInstr*, 8> &DupCopies) {
1173   // FIXME: This is very conservative. For example, we don't handle
1174   // physical registers.
1175
1176   MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1177
1178   if (!MI || CP.isPartial() || CP.isPhys())
1179     return false;
1180
1181   unsigned A = CP.getDstReg();
1182   if (!TargetRegisterInfo::isVirtualRegister(A))
1183     return false;
1184
1185   unsigned B = CP.getSrcReg();
1186   if (!TargetRegisterInfo::isVirtualRegister(B))
1187     return false;
1188
1189   MachineInstr *OtherMI = li.getInstructionFromIndex(OtherVNI->def);
1190   if (!OtherMI)
1191     return false;
1192
1193   if (MI->isImplicitDef()) {
1194     DupCopies.push_back(MI);
1195     return true;
1196   } else {
1197     if (!MI->isFullCopy())
1198       return false;
1199     unsigned Src = MI->getOperand(1).getReg();
1200     if (!TargetRegisterInfo::isVirtualRegister(Src))
1201       return false;
1202     if (!OtherMI->isFullCopy())
1203       return false;
1204     unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1205     if (!TargetRegisterInfo::isVirtualRegister(OtherSrc))
1206       return false;
1207
1208     if (Src != OtherSrc)
1209       return false;
1210
1211     // If the copies use two different value numbers of X, we cannot merge
1212     // A and B.
1213     LiveInterval &SrcInt = li.getInterval(Src);
1214     // getVNInfoBefore returns NULL for undef copies. In this case, the
1215     // optimization is still safe.
1216     if (SrcInt.getVNInfoBefore(OtherVNI->def) !=
1217         SrcInt.getVNInfoBefore(VNI->def))
1218       return false;
1219
1220     DupCopies.push_back(MI);
1221     return true;
1222   }
1223 }
1224
1225 /// joinIntervals - Attempt to join these two intervals.  On failure, this
1226 /// returns false.
1227 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1228   // Handle physreg joins separately.
1229   if (CP.isPhys())
1230     return joinReservedPhysReg(CP);
1231
1232   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1233   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1234                << '\n');
1235
1236   // Compute the final value assignment, assuming that the live ranges can be
1237   // coalesced.
1238   SmallVector<int, 16> LHSValNoAssignments;
1239   SmallVector<int, 16> RHSValNoAssignments;
1240   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1241   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1242   SmallVector<VNInfo*, 16> NewVNInfo;
1243
1244   SmallVector<MachineInstr*, 8> DupCopies;
1245   SmallVector<MachineInstr*, 8> DeadCopies;
1246
1247   LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1248   DEBUG(dbgs() << "\t\tLHS = " << PrintReg(CP.getDstReg(), TRI) << ' ' << LHS
1249                << '\n');
1250
1251   // Loop over the value numbers of the LHS, seeing if any are defined from
1252   // the RHS.
1253   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1254        i != e; ++i) {
1255     VNInfo *VNI = *i;
1256     if (VNI->isUnused() || VNI->isPHIDef())
1257       continue;
1258     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1259     assert(MI && "Missing def");
1260     if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1261       continue;
1262
1263     // Figure out the value # from the RHS.
1264     VNInfo *OtherVNI = RHS.getVNInfoBefore(VNI->def);
1265     // The copy could be to an aliased physreg.
1266     if (!OtherVNI)
1267       continue;
1268
1269     // DstReg is known to be a register in the LHS interval.  If the src is
1270     // from the RHS interval, we can use its value #.
1271     if (CP.isCoalescable(MI))
1272       DeadCopies.push_back(MI);
1273     else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1274                                             DupCopies))
1275       continue;
1276
1277     LHSValsDefinedFromRHS[VNI] = OtherVNI;
1278   }
1279
1280   // Loop over the value numbers of the RHS, seeing if any are defined from
1281   // the LHS.
1282   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1283        i != e; ++i) {
1284     VNInfo *VNI = *i;
1285     if (VNI->isUnused() || VNI->isPHIDef())
1286       continue;
1287     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1288     assert(MI && "Missing def");
1289     if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1290       continue;
1291
1292     // Figure out the value # from the LHS.
1293     VNInfo *OtherVNI = LHS.getVNInfoBefore(VNI->def);
1294     // The copy could be to an aliased physreg.
1295     if (!OtherVNI)
1296       continue;
1297
1298     // DstReg is known to be a register in the RHS interval.  If the src is
1299     // from the LHS interval, we can use its value #.
1300     if (CP.isCoalescable(MI))
1301       DeadCopies.push_back(MI);
1302     else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1303                                             DupCopies))
1304         continue;
1305
1306     RHSValsDefinedFromLHS[VNI] = OtherVNI;
1307   }
1308
1309   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1310   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1311   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1312
1313   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1314        i != e; ++i) {
1315     VNInfo *VNI = *i;
1316     unsigned VN = VNI->id;
1317     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1318       continue;
1319     ComputeUltimateVN(VNI, NewVNInfo,
1320                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1321                       LHSValNoAssignments, RHSValNoAssignments);
1322   }
1323   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1324        i != e; ++i) {
1325     VNInfo *VNI = *i;
1326     unsigned VN = VNI->id;
1327     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1328       continue;
1329     // If this value number isn't a copy from the LHS, it's a new number.
1330     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1331       NewVNInfo.push_back(VNI);
1332       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1333       continue;
1334     }
1335
1336     ComputeUltimateVN(VNI, NewVNInfo,
1337                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1338                       RHSValNoAssignments, LHSValNoAssignments);
1339   }
1340
1341   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1342   // interval lists to see if these intervals are coalescable.
1343   LiveInterval::const_iterator I = LHS.begin();
1344   LiveInterval::const_iterator IE = LHS.end();
1345   LiveInterval::const_iterator J = RHS.begin();
1346   LiveInterval::const_iterator JE = RHS.end();
1347
1348   // Collect interval end points that will no longer be kills.
1349   SmallVector<MachineInstr*, 8> LHSOldKills;
1350   SmallVector<MachineInstr*, 8> RHSOldKills;
1351
1352   // Skip ahead until the first place of potential sharing.
1353   if (I != IE && J != JE) {
1354     if (I->start < J->start) {
1355       I = std::upper_bound(I, IE, J->start);
1356       if (I != LHS.begin()) --I;
1357     } else if (J->start < I->start) {
1358       J = std::upper_bound(J, JE, I->start);
1359       if (J != RHS.begin()) --J;
1360     }
1361   }
1362
1363   while (I != IE && J != JE) {
1364     // Determine if these two live ranges overlap.
1365     // If so, check value # info to determine if they are really different.
1366     if (I->end > J->start && J->end > I->start) {
1367       // If the live range overlap will map to the same value number in the
1368       // result liverange, we can still coalesce them.  If not, we can't.
1369       if (LHSValNoAssignments[I->valno->id] !=
1370           RHSValNoAssignments[J->valno->id])
1371         return false;
1372
1373       // Extended live ranges should no longer be killed.
1374       if (!I->end.isBlock() && I->end < J->end)
1375         if (MachineInstr *MI = LIS->getInstructionFromIndex(I->end))
1376           LHSOldKills.push_back(MI);
1377       if (!J->end.isBlock() && J->end < I->end)
1378         if (MachineInstr *MI = LIS->getInstructionFromIndex(J->end))
1379           RHSOldKills.push_back(MI);
1380     }
1381
1382     if (I->end < J->end)
1383       ++I;
1384     else
1385       ++J;
1386   }
1387
1388   // Clear kill flags where live ranges are extended.
1389   while (!LHSOldKills.empty())
1390     LHSOldKills.pop_back_val()->clearRegisterKills(LHS.reg, TRI);
1391   while (!RHSOldKills.empty())
1392     RHSOldKills.pop_back_val()->clearRegisterKills(RHS.reg, TRI);
1393
1394   if (LHSValNoAssignments.empty())
1395     LHSValNoAssignments.push_back(-1);
1396   if (RHSValNoAssignments.empty())
1397     RHSValNoAssignments.push_back(-1);
1398
1399   // Now erase all the redundant copies.
1400   for (unsigned i = 0, e = DeadCopies.size(); i != e; ++i) {
1401     MachineInstr *MI = DeadCopies[i];
1402     if (!ErasedInstrs.insert(MI))
1403       continue;
1404     DEBUG(dbgs() << "\t\terased:\t" << LIS->getInstructionIndex(MI)
1405                  << '\t' << *MI);
1406     LIS->RemoveMachineInstrFromMaps(MI);
1407     MI->eraseFromParent();
1408   }
1409
1410   SmallVector<unsigned, 8> SourceRegisters;
1411   for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1412          E = DupCopies.end(); I != E; ++I) {
1413     MachineInstr *MI = *I;
1414     if (!ErasedInstrs.insert(MI))
1415       continue;
1416
1417     // If MI is a copy, then we have pretended that the assignment to B in
1418     // A = X
1419     // B = X
1420     // was actually a copy from A. Now that we decided to coalesce A and B,
1421     // transform the code into
1422     // A = X
1423     // In the case of the implicit_def, we just have to remove it.
1424     if (!MI->isImplicitDef()) {
1425       unsigned Src = MI->getOperand(1).getReg();
1426       SourceRegisters.push_back(Src);
1427     }
1428     LIS->RemoveMachineInstrFromMaps(MI);
1429     MI->eraseFromParent();
1430   }
1431
1432   // If B = X was the last use of X in a liverange, we have to shrink it now
1433   // that B = X is gone.
1434   for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1435          E = SourceRegisters.end(); I != E; ++I) {
1436     LIS->shrinkToUses(&LIS->getInterval(*I));
1437   }
1438
1439   // If we get here, we know that we can coalesce the live ranges.  Ask the
1440   // intervals to coalesce themselves now.
1441   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1442            MRI);
1443   return true;
1444 }
1445
1446 namespace {
1447   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1448   // depth of the basic block (the unsigned), and then on the MBB number.
1449   struct DepthMBBCompare {
1450     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1451     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1452       // Deeper loops first
1453       if (LHS.first != RHS.first)
1454         return LHS.first > RHS.first;
1455
1456       // Prefer blocks that are more connected in the CFG. This takes care of
1457       // the most difficult copies first while intervals are short.
1458       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1459       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1460       if (cl != cr)
1461         return cl > cr;
1462
1463       // As a last resort, sort by block number.
1464       return LHS.second->getNumber() < RHS.second->getNumber();
1465     }
1466   };
1467 }
1468
1469 // Try joining WorkList copies starting from index From.
1470 // Null out any successful joins.
1471 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
1472   assert(From <= WorkList.size() && "Out of range");
1473   bool Progress = false;
1474   for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
1475     if (!WorkList[i])
1476       continue;
1477     // Skip instruction pointers that have already been erased, for example by
1478     // dead code elimination.
1479     if (ErasedInstrs.erase(WorkList[i])) {
1480       WorkList[i] = 0;
1481       continue;
1482     }
1483     bool Again = false;
1484     bool Success = joinCopy(WorkList[i], Again);
1485     Progress |= Success;
1486     if (Success || !Again)
1487       WorkList[i] = 0;
1488   }
1489   return Progress;
1490 }
1491
1492 void
1493 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
1494   DEBUG(dbgs() << MBB->getName() << ":\n");
1495
1496   // Collect all copy-like instructions in MBB. Don't start coalescing anything
1497   // yet, it might invalidate the iterator.
1498   const unsigned PrevSize = WorkList.size();
1499   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1500        MII != E; ++MII)
1501     if (MII->isCopyLike())
1502       WorkList.push_back(MII);
1503
1504   // Try coalescing the collected copies immediately, and remove the nulls.
1505   // This prevents the WorkList from getting too large since most copies are
1506   // joinable on the first attempt.
1507   if (copyCoalesceWorkList(PrevSize))
1508     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
1509                                (MachineInstr*)0), WorkList.end());
1510 }
1511
1512 void RegisterCoalescer::joinAllIntervals() {
1513   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1514   assert(WorkList.empty() && "Old data still around.");
1515
1516   if (Loops->empty()) {
1517     // If there are no loops in the function, join intervals in function order.
1518     for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1519          I != E; ++I)
1520       copyCoalesceInMBB(I);
1521   } else {
1522     // Otherwise, join intervals in inner loops before other intervals.
1523     // Unfortunately we can't just iterate over loop hierarchy here because
1524     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1525
1526     // Join intervals in the function prolog first. We want to join physical
1527     // registers with virtual registers before the intervals got too long.
1528     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1529     for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1530       MachineBasicBlock *MBB = I;
1531       MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1532     }
1533
1534     // Sort by loop depth.
1535     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1536
1537     // Finally, join intervals in loop nest order.
1538     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1539       copyCoalesceInMBB(MBBs[i].second);
1540   }
1541
1542   // Joining intervals can allow other intervals to be joined.  Iteratively join
1543   // until we make no progress.
1544   while (copyCoalesceWorkList())
1545     /* empty */ ;
1546 }
1547
1548 void RegisterCoalescer::releaseMemory() {
1549   ErasedInstrs.clear();
1550   WorkList.clear();
1551   DeadDefs.clear();
1552   InflateRegs.clear();
1553 }
1554
1555 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1556   MF = &fn;
1557   MRI = &fn.getRegInfo();
1558   TM = &fn.getTarget();
1559   TRI = TM->getRegisterInfo();
1560   TII = TM->getInstrInfo();
1561   LIS = &getAnalysis<LiveIntervals>();
1562   LDV = &getAnalysis<LiveDebugVariables>();
1563   AA = &getAnalysis<AliasAnalysis>();
1564   Loops = &getAnalysis<MachineLoopInfo>();
1565
1566   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1567                << "********** Function: "
1568                << ((Value*)MF->getFunction())->getName() << '\n');
1569
1570   if (VerifyCoalescing)
1571     MF->verify(this, "Before register coalescing");
1572
1573   RegClassInfo.runOnMachineFunction(fn);
1574
1575   // Join (coalesce) intervals if requested.
1576   if (EnableJoining)
1577     joinAllIntervals();
1578
1579   // After deleting a lot of copies, register classes may be less constrained.
1580   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
1581   // DPR inflation.
1582   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1583   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1584                     InflateRegs.end());
1585   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1586   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1587     unsigned Reg = InflateRegs[i];
1588     if (MRI->reg_nodbg_empty(Reg))
1589       continue;
1590     if (MRI->recomputeRegClass(Reg, *TM)) {
1591       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1592                    << MRI->getRegClass(Reg)->getName() << '\n');
1593       ++NumInflated;
1594     }
1595   }
1596
1597   DEBUG(dump());
1598   DEBUG(LDV->dump());
1599   if (VerifyCoalescing)
1600     MF->verify(this, "After register coalescing");
1601   return true;
1602 }
1603
1604 /// print - Implement the dump method.
1605 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
1606    LIS->print(O, m);
1607 }