Extend -new-coalescer SSA update to handle mapped values as well.
[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 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
59 STATISTIC(NumLaneResolves,  "Number of dead lane conflicts resolved");
60
61 static cl::opt<bool>
62 EnableJoining("join-liveintervals",
63               cl::desc("Coalesce copies (default=true)"),
64               cl::init(true));
65
66 static cl::opt<bool>
67 VerifyCoalescing("verify-coalescing",
68          cl::desc("Verify machine instrs before and after register coalescing"),
69          cl::Hidden);
70
71 // Temporary option for testing new coalescer algo.
72 static cl::opt<bool>
73 NewCoalescer("new-coalescer", cl::Hidden,
74              cl::desc("Use new coalescer algorithm"));
75
76 namespace {
77   class RegisterCoalescer : public MachineFunctionPass,
78                             private LiveRangeEdit::Delegate {
79     MachineFunction* MF;
80     MachineRegisterInfo* MRI;
81     const TargetMachine* TM;
82     const TargetRegisterInfo* TRI;
83     const TargetInstrInfo* TII;
84     LiveIntervals *LIS;
85     LiveDebugVariables *LDV;
86     const MachineLoopInfo* Loops;
87     AliasAnalysis *AA;
88     RegisterClassInfo RegClassInfo;
89
90     /// WorkList - Copy instructions yet to be coalesced.
91     SmallVector<MachineInstr*, 8> WorkList;
92
93     /// ErasedInstrs - Set of instruction pointers that have been erased, and
94     /// that may be present in WorkList.
95     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
96
97     /// Dead instructions that are about to be deleted.
98     SmallVector<MachineInstr*, 8> DeadDefs;
99
100     /// Virtual registers to be considered for register class inflation.
101     SmallVector<unsigned, 8> InflateRegs;
102
103     /// Recursively eliminate dead defs in DeadDefs.
104     void eliminateDeadDefs();
105
106     /// LiveRangeEdit callback.
107     void LRE_WillEraseInstruction(MachineInstr *MI);
108
109     /// joinAllIntervals - join compatible live intervals
110     void joinAllIntervals();
111
112     /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
113     /// copies that cannot yet be coalesced into WorkList.
114     void copyCoalesceInMBB(MachineBasicBlock *MBB);
115
116     /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
117     /// position From. Return true if any progress was made.
118     bool copyCoalesceWorkList(unsigned From = 0);
119
120     /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
121     /// which are the src/dst of the copy instruction CopyMI.  This returns
122     /// true if the copy was successfully coalesced away. If it is not
123     /// currently possible to coalesce this interval, but it may be possible if
124     /// other things get coalesced, then it returns true by reference in
125     /// 'Again'.
126     bool joinCopy(MachineInstr *TheCopy, bool &Again);
127
128     /// joinIntervals - Attempt to join these two intervals.  On failure, this
129     /// returns false.  The output "SrcInt" will not have been modified, so we
130     /// can use this information below to update aliases.
131     bool joinIntervals(CoalescerPair &CP);
132
133     /// Attempt joining two virtual registers. Return true on success.
134     bool joinVirtRegs(CoalescerPair &CP);
135
136     /// Attempt joining with a reserved physreg.
137     bool joinReservedPhysReg(CoalescerPair &CP);
138
139     /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
140     /// the source value number is defined by a copy from the destination reg
141     /// see if we can merge these two destination reg valno# into a single
142     /// value number, eliminating a copy.
143     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
144
145     /// hasOtherReachingDefs - Return true if there are definitions of IntB
146     /// other than BValNo val# that can reach uses of AValno val# of IntA.
147     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
148                               VNInfo *AValNo, VNInfo *BValNo);
149
150     /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
151     /// If the source value number is defined by a commutable instruction and
152     /// its other operand is coalesced to the copy dest register, see if we
153     /// can transform the copy into a noop by commuting the definition.
154     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
155
156     /// reMaterializeTrivialDef - If the source of a copy is defined by a
157     /// trivial computation, replace the copy by rematerialize the definition.
158     bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
159                                  MachineInstr *CopyMI);
160
161     /// canJoinPhys - Return true if a physreg copy should be joined.
162     bool canJoinPhys(CoalescerPair &CP);
163
164     /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
165     /// update the subregister number if it is not zero. If DstReg is a
166     /// physical register and the existing subregister number of the def / use
167     /// being updated is not zero, make sure to set it to the correct physical
168     /// subregister.
169     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
170
171     /// eliminateUndefCopy - Handle copies of undef values.
172     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
173
174   public:
175     static char ID; // Class identification, replacement for typeinfo
176     RegisterCoalescer() : MachineFunctionPass(ID) {
177       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
178     }
179
180     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
181
182     virtual void releaseMemory();
183
184     /// runOnMachineFunction - pass entry point
185     virtual bool runOnMachineFunction(MachineFunction&);
186
187     /// print - Implement the dump method.
188     virtual void print(raw_ostream &O, const Module* = 0) const;
189   };
190 } /// end anonymous namespace
191
192 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
193
194 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
195                       "Simple Register Coalescing", false, false)
196 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
197 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
198 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
199 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
200 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
201 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
202                     "Simple Register Coalescing", false, false)
203
204 char RegisterCoalescer::ID = 0;
205
206 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
207   if (!a) return b;
208   if (!b) return a;
209   return tri.composeSubRegIndices(a, b);
210 }
211
212 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
213                         unsigned &Src, unsigned &Dst,
214                         unsigned &SrcSub, unsigned &DstSub) {
215   if (MI->isCopy()) {
216     Dst = MI->getOperand(0).getReg();
217     DstSub = MI->getOperand(0).getSubReg();
218     Src = MI->getOperand(1).getReg();
219     SrcSub = MI->getOperand(1).getSubReg();
220   } else if (MI->isSubregToReg()) {
221     Dst = MI->getOperand(0).getReg();
222     DstSub = compose(tri, MI->getOperand(0).getSubReg(),
223                      MI->getOperand(3).getImm());
224     Src = MI->getOperand(2).getReg();
225     SrcSub = MI->getOperand(2).getSubReg();
226   } else
227     return false;
228   return true;
229 }
230
231 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
232   SrcReg = DstReg = 0;
233   SrcIdx = DstIdx = 0;
234   NewRC = 0;
235   Flipped = CrossClass = false;
236
237   unsigned Src, Dst, SrcSub, DstSub;
238   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
239     return false;
240   Partial = SrcSub || DstSub;
241
242   // If one register is a physreg, it must be Dst.
243   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
244     if (TargetRegisterInfo::isPhysicalRegister(Dst))
245       return false;
246     std::swap(Src, Dst);
247     std::swap(SrcSub, DstSub);
248     Flipped = true;
249   }
250
251   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
252
253   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
254     // Eliminate DstSub on a physreg.
255     if (DstSub) {
256       Dst = TRI.getSubReg(Dst, DstSub);
257       if (!Dst) return false;
258       DstSub = 0;
259     }
260
261     // Eliminate SrcSub by picking a corresponding Dst superregister.
262     if (SrcSub) {
263       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
264       if (!Dst) return false;
265       SrcSub = 0;
266     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
267       return false;
268     }
269   } else {
270     // Both registers are virtual.
271     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
272     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
273
274     // Both registers have subreg indices.
275     if (SrcSub && DstSub) {
276       // Copies between different sub-registers are never coalescable.
277       if (Src == Dst && SrcSub != DstSub)
278         return false;
279
280       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
281                                          SrcIdx, DstIdx);
282       if (!NewRC)
283         return false;
284     } else if (DstSub) {
285       // SrcReg will be merged with a sub-register of DstReg.
286       SrcIdx = DstSub;
287       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
288     } else if (SrcSub) {
289       // DstReg will be merged with a sub-register of SrcReg.
290       DstIdx = SrcSub;
291       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
292     } else {
293       // This is a straight copy without sub-registers.
294       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
295     }
296
297     // The combined constraint may be impossible to satisfy.
298     if (!NewRC)
299       return false;
300
301     // Prefer SrcReg to be a sub-register of DstReg.
302     // FIXME: Coalescer should support subregs symmetrically.
303     if (DstIdx && !SrcIdx) {
304       std::swap(Src, Dst);
305       std::swap(SrcIdx, DstIdx);
306       Flipped = !Flipped;
307     }
308
309     CrossClass = NewRC != DstRC || NewRC != SrcRC;
310   }
311   // Check our invariants
312   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
313   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
314          "Cannot have a physical SubIdx");
315   SrcReg = Src;
316   DstReg = Dst;
317   return true;
318 }
319
320 bool CoalescerPair::flip() {
321   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
322     return false;
323   std::swap(SrcReg, DstReg);
324   std::swap(SrcIdx, DstIdx);
325   Flipped = !Flipped;
326   return true;
327 }
328
329 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
330   if (!MI)
331     return false;
332   unsigned Src, Dst, SrcSub, DstSub;
333   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
334     return false;
335
336   // Find the virtual register that is SrcReg.
337   if (Dst == SrcReg) {
338     std::swap(Src, Dst);
339     std::swap(SrcSub, DstSub);
340   } else if (Src != SrcReg) {
341     return false;
342   }
343
344   // Now check that Dst matches DstReg.
345   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
346     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
347       return false;
348     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
349     // DstSub could be set for a physreg from INSERT_SUBREG.
350     if (DstSub)
351       Dst = TRI.getSubReg(Dst, DstSub);
352     // Full copy of Src.
353     if (!SrcSub)
354       return DstReg == Dst;
355     // This is a partial register copy. Check that the parts match.
356     return TRI.getSubReg(DstReg, SrcSub) == Dst;
357   } else {
358     // DstReg is virtual.
359     if (DstReg != Dst)
360       return false;
361     // Registers match, do the subregisters line up?
362     return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
363   }
364 }
365
366 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
367   AU.setPreservesCFG();
368   AU.addRequired<AliasAnalysis>();
369   AU.addRequired<LiveIntervals>();
370   AU.addPreserved<LiveIntervals>();
371   AU.addRequired<LiveDebugVariables>();
372   AU.addPreserved<LiveDebugVariables>();
373   AU.addPreserved<SlotIndexes>();
374   AU.addRequired<MachineLoopInfo>();
375   AU.addPreserved<MachineLoopInfo>();
376   AU.addPreservedID(MachineDominatorsID);
377   MachineFunctionPass::getAnalysisUsage(AU);
378 }
379
380 void RegisterCoalescer::eliminateDeadDefs() {
381   SmallVector<LiveInterval*, 8> NewRegs;
382   LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
383 }
384
385 // Callback from eliminateDeadDefs().
386 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
387   // MI may be in WorkList. Make sure we don't visit it.
388   ErasedInstrs.insert(MI);
389 }
390
391 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
392 /// being the source and IntB being the dest, thus this defines a value number
393 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
394 /// see if we can merge these two pieces of B into a single value number,
395 /// eliminating a copy.  For example:
396 ///
397 ///  A3 = B0
398 ///    ...
399 ///  B1 = A3      <- this copy
400 ///
401 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
402 /// value number to be replaced with B0 (which simplifies the B liveinterval).
403 ///
404 /// This returns true if an interval was modified.
405 ///
406 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
407                                              MachineInstr *CopyMI) {
408   assert(!CP.isPartial() && "This doesn't work for partial copies.");
409   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
410
411   LiveInterval &IntA =
412     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
413   LiveInterval &IntB =
414     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
415   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
416
417   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
418   // the example above.
419   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
420   if (BLR == IntB.end()) return false;
421   VNInfo *BValNo = BLR->valno;
422
423   // Get the location that B is defined at.  Two options: either this value has
424   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
425   // can't process it.
426   if (BValNo->def != CopyIdx) return false;
427
428   // AValNo is the value number in A that defines the copy, A3 in the example.
429   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
430   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
431   // The live range might not exist after fun with physreg coalescing.
432   if (ALR == IntA.end()) return false;
433   VNInfo *AValNo = ALR->valno;
434
435   // If AValNo is defined as a copy from IntB, we can potentially process this.
436   // Get the instruction that defines this value number.
437   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
438   if (!CP.isCoalescable(ACopyMI))
439     return false;
440
441   // Get the LiveRange in IntB that this value number starts with.
442   LiveInterval::iterator ValLR =
443     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
444   if (ValLR == IntB.end())
445     return false;
446
447   // Make sure that the end of the live range is inside the same block as
448   // CopyMI.
449   MachineInstr *ValLREndInst =
450     LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
451   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
452     return false;
453
454   // Okay, we now know that ValLR ends in the same block that the CopyMI
455   // live-range starts.  If there are no intervening live ranges between them in
456   // IntB, we can merge them.
457   if (ValLR+1 != BLR) return false;
458
459   DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
460
461   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
462   // We are about to delete CopyMI, so need to remove it as the 'instruction
463   // that defines this value #'. Update the valnum with the new defining
464   // instruction #.
465   BValNo->def = FillerStart;
466
467   // Okay, we can merge them.  We need to insert a new liverange:
468   // [ValLR.end, BLR.begin) of either value number, then we merge the
469   // two value numbers.
470   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
471
472   // Okay, merge "B1" into the same value number as "B0".
473   if (BValNo != ValLR->valno)
474     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
475   DEBUG(dbgs() << "   result = " << IntB << '\n');
476
477   // If the source instruction was killing the source register before the
478   // merge, unset the isKill marker given the live range has been extended.
479   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
480   if (UIdx != -1) {
481     ValLREndInst->getOperand(UIdx).setIsKill(false);
482   }
483
484   // Rewrite the copy. If the copy instruction was killing the destination
485   // register before the merge, find the last use and trim the live range. That
486   // will also add the isKill marker.
487   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
488   if (ALR->end == CopyIdx)
489     LIS->shrinkToUses(&IntA);
490
491   ++numExtends;
492   return true;
493 }
494
495 /// hasOtherReachingDefs - Return true if there are definitions of IntB
496 /// other than BValNo val# that can reach uses of AValno val# of IntA.
497 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
498                                              LiveInterval &IntB,
499                                              VNInfo *AValNo,
500                                              VNInfo *BValNo) {
501   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
502   // the PHI values.
503   if (LIS->hasPHIKill(IntA, AValNo))
504     return true;
505
506   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
507        AI != AE; ++AI) {
508     if (AI->valno != AValNo) continue;
509     LiveInterval::Ranges::iterator BI =
510       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
511     if (BI != IntB.ranges.begin())
512       --BI;
513     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
514       if (BI->valno == BValNo)
515         continue;
516       if (BI->start <= AI->start && BI->end > AI->start)
517         return true;
518       if (BI->start > AI->start && BI->start < AI->end)
519         return true;
520     }
521   }
522   return false;
523 }
524
525 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
526 /// IntA being the source and IntB being the dest, thus this defines a value
527 /// number in IntB.  If the source value number (in IntA) is defined by a
528 /// commutable instruction and its other operand is coalesced to the copy dest
529 /// register, see if we can transform the copy into a noop by commuting the
530 /// definition. For example,
531 ///
532 ///  A3 = op A2 B0<kill>
533 ///    ...
534 ///  B1 = A3      <- this copy
535 ///    ...
536 ///     = op A3   <- more uses
537 ///
538 /// ==>
539 ///
540 ///  B2 = op B0 A2<kill>
541 ///    ...
542 ///  B1 = B2      <- now an identify copy
543 ///    ...
544 ///     = op B2   <- more uses
545 ///
546 /// This returns true if an interval was modified.
547 ///
548 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
549                                                  MachineInstr *CopyMI) {
550   assert (!CP.isPhys());
551
552   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
553
554   LiveInterval &IntA =
555     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
556   LiveInterval &IntB =
557     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
558
559   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
560   // the example above.
561   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
562   if (!BValNo || BValNo->def != CopyIdx)
563     return false;
564
565   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
566
567   // AValNo is the value number in A that defines the copy, A3 in the example.
568   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
569   assert(AValNo && "COPY source not live");
570   if (AValNo->isPHIDef() || AValNo->isUnused())
571     return false;
572   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
573   if (!DefMI)
574     return false;
575   if (!DefMI->isCommutable())
576     return false;
577   // If DefMI is a two-address instruction then commuting it will change the
578   // destination register.
579   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
580   assert(DefIdx != -1);
581   unsigned UseOpIdx;
582   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
583     return false;
584   unsigned Op1, Op2, NewDstIdx;
585   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
586     return false;
587   if (Op1 == UseOpIdx)
588     NewDstIdx = Op2;
589   else if (Op2 == UseOpIdx)
590     NewDstIdx = Op1;
591   else
592     return false;
593
594   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
595   unsigned NewReg = NewDstMO.getReg();
596   if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill())
597     return false;
598
599   // Make sure there are no other definitions of IntB that would reach the
600   // uses which the new definition can reach.
601   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
602     return false;
603
604   // If some of the uses of IntA.reg is already coalesced away, return false.
605   // It's not possible to determine whether it's safe to perform the coalescing.
606   for (MachineRegisterInfo::use_nodbg_iterator UI =
607          MRI->use_nodbg_begin(IntA.reg),
608        UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
609     MachineInstr *UseMI = &*UI;
610     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
611     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
612     if (ULR == IntA.end() || ULR->valno != AValNo)
613       continue;
614     // If this use is tied to a def, we can't rewrite the register.
615     if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
616       return false;
617   }
618
619   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
620                << *DefMI);
621
622   // At this point we have decided that it is legal to do this
623   // transformation.  Start by commuting the instruction.
624   MachineBasicBlock *MBB = DefMI->getParent();
625   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
626   if (!NewMI)
627     return false;
628   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
629       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
630       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
631     return false;
632   if (NewMI != DefMI) {
633     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
634     MachineBasicBlock::iterator Pos = DefMI;
635     MBB->insert(Pos, NewMI);
636     MBB->erase(DefMI);
637   }
638   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
639   NewMI->getOperand(OpIdx).setIsKill();
640
641   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
642   // A = or A, B
643   // ...
644   // B = A
645   // ...
646   // C = A<kill>
647   // ...
648   //   = B
649
650   // Update uses of IntA of the specific Val# with IntB.
651   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
652          UE = MRI->use_end(); UI != UE;) {
653     MachineOperand &UseMO = UI.getOperand();
654     MachineInstr *UseMI = &*UI;
655     ++UI;
656     if (UseMI->isDebugValue()) {
657       // FIXME These don't have an instruction index.  Not clear we have enough
658       // info to decide whether to do this replacement or not.  For now do it.
659       UseMO.setReg(NewReg);
660       continue;
661     }
662     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
663     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
664     if (ULR == IntA.end() || ULR->valno != AValNo)
665       continue;
666     // Kill flags are no longer accurate. They are recomputed after RA.
667     UseMO.setIsKill(false);
668     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
669       UseMO.substPhysReg(NewReg, *TRI);
670     else
671       UseMO.setReg(NewReg);
672     if (UseMI == CopyMI)
673       continue;
674     if (!UseMI->isCopy())
675       continue;
676     if (UseMI->getOperand(0).getReg() != IntB.reg ||
677         UseMI->getOperand(0).getSubReg())
678       continue;
679
680     // This copy will become a noop. If it's defining a new val#, merge it into
681     // BValNo.
682     SlotIndex DefIdx = UseIdx.getRegSlot();
683     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
684     if (!DVNI)
685       continue;
686     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
687     assert(DVNI->def == DefIdx);
688     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
689     ErasedInstrs.insert(UseMI);
690     LIS->RemoveMachineInstrFromMaps(UseMI);
691     UseMI->eraseFromParent();
692   }
693
694   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
695   // is updated.
696   VNInfo *ValNo = BValNo;
697   ValNo->def = AValNo->def;
698   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
699        AI != AE; ++AI) {
700     if (AI->valno != AValNo) continue;
701     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
702   }
703   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
704
705   IntA.removeValNo(AValNo);
706   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
707   ++numCommutes;
708   return true;
709 }
710
711 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
712 /// computation, replace the copy by rematerialize the definition.
713 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
714                                                 unsigned DstReg,
715                                                 MachineInstr *CopyMI) {
716   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
717   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
718   assert(SrcLR != SrcInt.end() && "Live range not found!");
719   VNInfo *ValNo = SrcLR->valno;
720   if (ValNo->isPHIDef() || ValNo->isUnused())
721     return false;
722   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
723   if (!DefMI)
724     return false;
725   assert(DefMI && "Defining instruction disappeared");
726   if (!DefMI->isAsCheapAsAMove())
727     return false;
728   if (!TII->isTriviallyReMaterializable(DefMI, AA))
729     return false;
730   bool SawStore = false;
731   if (!DefMI->isSafeToMove(TII, AA, SawStore))
732     return false;
733   const MCInstrDesc &MCID = DefMI->getDesc();
734   if (MCID.getNumDefs() != 1)
735     return false;
736   if (!DefMI->isImplicitDef()) {
737     // Make sure the copy destination register class fits the instruction
738     // definition register class. The mismatch can happen as a result of earlier
739     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
740     const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
741     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
742       if (MRI->getRegClass(DstReg) != RC)
743         return false;
744     } else if (!RC->contains(DstReg))
745       return false;
746   }
747
748   MachineBasicBlock *MBB = CopyMI->getParent();
749   MachineBasicBlock::iterator MII =
750     llvm::next(MachineBasicBlock::iterator(CopyMI));
751   TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
752   MachineInstr *NewMI = prior(MII);
753
754   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
755   // We need to remember these so we can add intervals once we insert
756   // NewMI into SlotIndexes.
757   SmallVector<unsigned, 4> NewMIImplDefs;
758   for (unsigned i = NewMI->getDesc().getNumOperands(),
759          e = NewMI->getNumOperands(); i != e; ++i) {
760     MachineOperand &MO = NewMI->getOperand(i);
761     if (MO.isReg()) {
762       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
763              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
764       NewMIImplDefs.push_back(MO.getReg());
765     }
766   }
767
768   // CopyMI may have implicit operands, transfer them over to the newly
769   // rematerialized instruction. And update implicit def interval valnos.
770   for (unsigned i = CopyMI->getDesc().getNumOperands(),
771          e = CopyMI->getNumOperands(); i != e; ++i) {
772     MachineOperand &MO = CopyMI->getOperand(i);
773     if (MO.isReg()) {
774       assert(MO.isImplicit() && "No explicit operands after implict operands.");
775       // Discard VReg implicit defs.
776       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
777         NewMI->addOperand(MO);
778       }
779     }
780   }
781
782   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
783
784   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
785   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
786     unsigned Reg = NewMIImplDefs[i];
787     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
788       if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
789         LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
790   }
791
792   CopyMI->eraseFromParent();
793   ErasedInstrs.insert(CopyMI);
794   DEBUG(dbgs() << "Remat: " << *NewMI);
795   ++NumReMats;
796
797   // The source interval can become smaller because we removed a use.
798   LIS->shrinkToUses(&SrcInt, &DeadDefs);
799   if (!DeadDefs.empty())
800     eliminateDeadDefs();
801
802   return true;
803 }
804
805 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
806 /// values, it only removes local variables. When we have a copy like:
807 ///
808 ///   %vreg1 = COPY %vreg2<undef>
809 ///
810 /// We delete the copy and remove the corresponding value number from %vreg1.
811 /// Any uses of that value number are marked as <undef>.
812 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
813                                            const CoalescerPair &CP) {
814   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
815   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
816   if (SrcInt->liveAt(Idx))
817     return false;
818   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
819   if (DstInt->liveAt(Idx))
820     return false;
821
822   // No intervals are live-in to CopyMI - it is undef.
823   if (CP.isFlipped())
824     DstInt = SrcInt;
825   SrcInt = 0;
826
827   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
828   assert(DeadVNI && "No value defined in DstInt");
829   DstInt->removeValNo(DeadVNI);
830
831   // Find new undef uses.
832   for (MachineRegisterInfo::reg_nodbg_iterator
833          I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
834        I != E; ++I) {
835     MachineOperand &MO = I.getOperand();
836     if (MO.isDef() || MO.isUndef())
837       continue;
838     MachineInstr *MI = MO.getParent();
839     SlotIndex Idx = LIS->getInstructionIndex(MI);
840     if (DstInt->liveAt(Idx))
841       continue;
842     MO.setIsUndef(true);
843     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
844   }
845   return true;
846 }
847
848 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
849 /// update the subregister number if it is not zero. If DstReg is a
850 /// physical register and the existing subregister number of the def / use
851 /// being updated is not zero, make sure to set it to the correct physical
852 /// subregister.
853 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
854                                           unsigned DstReg,
855                                           unsigned SubIdx) {
856   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
857   LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
858
859   // Update LiveDebugVariables.
860   LDV->renameRegister(SrcReg, DstReg, SubIdx);
861
862   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
863        MachineInstr *UseMI = I.skipInstruction();) {
864     SmallVector<unsigned,8> Ops;
865     bool Reads, Writes;
866     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
867
868     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
869     // because SrcReg is a sub-register.
870     if (DstInt && !Reads && SubIdx)
871       Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
872
873     // Replace SrcReg with DstReg in all UseMI operands.
874     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
875       MachineOperand &MO = UseMI->getOperand(Ops[i]);
876
877       // Adjust <undef> flags in case of sub-register joins. We don't want to
878       // turn a full def into a read-modify-write sub-register def and vice
879       // versa.
880       if (SubIdx && MO.isDef())
881         MO.setIsUndef(!Reads);
882
883       if (DstIsPhys)
884         MO.substPhysReg(DstReg, *TRI);
885       else
886         MO.substVirtReg(DstReg, SubIdx, *TRI);
887     }
888
889     DEBUG({
890         dbgs() << "\t\tupdated: ";
891         if (!UseMI->isDebugValue())
892           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
893         dbgs() << *UseMI;
894       });
895   }
896 }
897
898 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
899 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
900   /// Always join simple intervals that are defined by a single copy from a
901   /// reserved register. This doesn't increase register pressure, so it is
902   /// always beneficial.
903   if (!RegClassInfo.isReserved(CP.getDstReg())) {
904     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
905     return false;
906   }
907
908   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
909   if (CP.isFlipped() && JoinVInt.containsOneValue())
910     return true;
911
912   DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
913   return false;
914 }
915
916 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
917 /// which are the src/dst of the copy instruction CopyMI.  This returns true
918 /// if the copy was successfully coalesced away. If it is not currently
919 /// possible to coalesce this interval, but it may be possible if other
920 /// things get coalesced, then it returns true by reference in 'Again'.
921 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
922
923   Again = false;
924   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
925
926   CoalescerPair CP(*TRI);
927   if (!CP.setRegisters(CopyMI)) {
928     DEBUG(dbgs() << "\tNot coalescable.\n");
929     return false;
930   }
931
932   // Dead code elimination. This really should be handled by MachineDCE, but
933   // sometimes dead copies slip through, and we can't generate invalid live
934   // ranges.
935   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
936     DEBUG(dbgs() << "\tCopy is dead.\n");
937     DeadDefs.push_back(CopyMI);
938     eliminateDeadDefs();
939     return true;
940   }
941
942   // Eliminate undefs.
943   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
944     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
945     LIS->RemoveMachineInstrFromMaps(CopyMI);
946     CopyMI->eraseFromParent();
947     return false;  // Not coalescable.
948   }
949
950   // Coalesced copies are normally removed immediately, but transformations
951   // like removeCopyByCommutingDef() can inadvertently create identity copies.
952   // When that happens, just join the values and remove the copy.
953   if (CP.getSrcReg() == CP.getDstReg()) {
954     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
955     DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
956     LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
957     if (VNInfo *DefVNI = LRQ.valueDefined()) {
958       VNInfo *ReadVNI = LRQ.valueIn();
959       assert(ReadVNI && "No value before copy and no <undef> flag.");
960       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
961       LI.MergeValueNumberInto(DefVNI, ReadVNI);
962       DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
963     }
964     LIS->RemoveMachineInstrFromMaps(CopyMI);
965     CopyMI->eraseFromParent();
966     return true;
967   }
968
969   // Enforce policies.
970   if (CP.isPhys()) {
971     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
972                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
973                  << '\n');
974     if (!canJoinPhys(CP)) {
975       // Before giving up coalescing, if definition of source is defined by
976       // trivial computation, try rematerializing it.
977       if (!CP.isFlipped() &&
978           reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
979                                   CP.getDstReg(), CopyMI))
980         return true;
981       return false;
982     }
983   } else {
984     DEBUG({
985       dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
986              << " with ";
987       if (CP.getDstIdx() && CP.getSrcIdx())
988         dbgs() << PrintReg(CP.getDstReg()) << " in "
989                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
990                << PrintReg(CP.getSrcReg()) << " in "
991                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
992       else
993         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
994                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
995     });
996
997     // When possible, let DstReg be the larger interval.
998     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
999                            LIS->getInterval(CP.getDstReg()).ranges.size())
1000       CP.flip();
1001   }
1002
1003   // Okay, attempt to join these two intervals.  On failure, this returns false.
1004   // Otherwise, if one of the intervals being joined is a physreg, this method
1005   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1006   // been modified, so we can use this information below to update aliases.
1007   if (!joinIntervals(CP)) {
1008     // Coalescing failed.
1009
1010     // If definition of source is defined by trivial computation, try
1011     // rematerializing it.
1012     if (!CP.isFlipped() &&
1013         reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1014                                 CP.getDstReg(), CopyMI))
1015       return true;
1016
1017     // If we can eliminate the copy without merging the live ranges, do so now.
1018     if (!CP.isPartial() && !CP.isPhys()) {
1019       if (adjustCopiesBackFrom(CP, CopyMI) ||
1020           removeCopyByCommutingDef(CP, CopyMI)) {
1021         LIS->RemoveMachineInstrFromMaps(CopyMI);
1022         CopyMI->eraseFromParent();
1023         DEBUG(dbgs() << "\tTrivial!\n");
1024         return true;
1025       }
1026     }
1027
1028     // Otherwise, we are unable to join the intervals.
1029     DEBUG(dbgs() << "\tInterference!\n");
1030     Again = true;  // May be possible to coalesce later.
1031     return false;
1032   }
1033
1034   // Coalescing to a virtual register that is of a sub-register class of the
1035   // other. Make sure the resulting register is set to the right register class.
1036   if (CP.isCrossClass()) {
1037     ++numCrossRCs;
1038     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1039   }
1040
1041   // Removing sub-register copies can ease the register class constraints.
1042   // Make sure we attempt to inflate the register class of DstReg.
1043   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1044     InflateRegs.push_back(CP.getDstReg());
1045
1046   // CopyMI has been erased by joinIntervals at this point. Remove it from
1047   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1048   // to the work list. This keeps ErasedInstrs from growing needlessly.
1049   ErasedInstrs.erase(CopyMI);
1050
1051   // Rewrite all SrcReg operands to DstReg.
1052   // Also update DstReg operands to include DstIdx if it is set.
1053   if (CP.getDstIdx())
1054     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1055   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1056
1057   // SrcReg is guaranteed to be the register whose live interval that is
1058   // being merged.
1059   LIS->removeInterval(CP.getSrcReg());
1060
1061   // Update regalloc hint.
1062   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1063
1064   DEBUG({
1065     dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1066     if (!CP.isPhys())
1067       dbgs() << LIS->getInterval(CP.getDstReg());
1068      dbgs() << '\n';
1069   });
1070
1071   ++numJoins;
1072   return true;
1073 }
1074
1075 /// Attempt joining with a reserved physreg.
1076 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1077   assert(CP.isPhys() && "Must be a physreg copy");
1078   assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1079   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1080   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1081                << '\n');
1082
1083   assert(CP.isFlipped() && RHS.containsOneValue() &&
1084          "Invalid join with reserved register");
1085
1086   // Optimization for reserved registers like ESP. We can only merge with a
1087   // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1088   // The live range of the reserved register will look like a set of dead defs
1089   // - we don't properly track the live range of reserved registers.
1090
1091   // Deny any overlapping intervals.  This depends on all the reserved
1092   // register live ranges to look like dead defs.
1093   for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1094     if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1095       DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1096       return false;
1097     }
1098
1099   // Skip any value computations, we are not adding new values to the
1100   // reserved register.  Also skip merging the live ranges, the reserved
1101   // register live range doesn't need to be accurate as long as all the
1102   // defs are there.
1103
1104   // Delete the identity copy.
1105   MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1106   LIS->RemoveMachineInstrFromMaps(CopyMI);
1107   CopyMI->eraseFromParent();
1108
1109   // We don't track kills for reserved registers.
1110   MRI->clearKillFlags(CP.getSrcReg());
1111
1112   return true;
1113 }
1114
1115 //===----------------------------------------------------------------------===//
1116 //                 Interference checking and interval joining
1117 //===----------------------------------------------------------------------===//
1118 //
1119 // In the easiest case, the two live ranges being joined are disjoint, and
1120 // there is no interference to consider. It is quite common, though, to have
1121 // overlapping live ranges, and we need to check if the interference can be
1122 // resolved.
1123 //
1124 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1125 // This means that two SSA values overlap if and only if the def of one value
1126 // is contained in the live range of the other value. As a special case, the
1127 // overlapping values can be defined at the same index.
1128 //
1129 // The interference from an overlapping def can be resolved in these cases:
1130 //
1131 // 1. Coalescable copies. The value is defined by a copy that would become an
1132 //    identity copy after joining SrcReg and DstReg. The copy instruction will
1133 //    be removed, and the value will be merged with the source value.
1134 //
1135 //    There can be several copies back and forth, causing many values to be
1136 //    merged into one. We compute a list of ultimate values in the joined live
1137 //    range as well as a mappings from the old value numbers.
1138 //
1139 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1140 //    predecessors have a live out value. It doesn't cause real interference,
1141 //    and can be merged into the value it overlaps. Like a coalescable copy, it
1142 //    can be erased after joining.
1143 //
1144 // 3. Copy of external value. The overlapping def may be a copy of a value that
1145 //    is already in the other register. This is like a coalescable copy, but
1146 //    the live range of the source register must be trimmed after erasing the
1147 //    copy instruction:
1148 //
1149 //      %src = COPY %ext
1150 //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
1151 //
1152 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1153 //    defining one lane at a time:
1154 //
1155 //      %dst:ssub0<def,read-undef> = FOO
1156 //      %src = BAR
1157 //      %dst:ssub1<def> = COPY %src
1158 //
1159 //    The live range of %src overlaps the %dst value defined by FOO, but
1160 //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1161 //    which was undef anyway.
1162 //
1163 //    The value mapping is more complicated in this case. The final live range
1164 //    will have different value numbers for both FOO and BAR, but there is no
1165 //    simple mapping from old to new values. It may even be necessary to add
1166 //    new PHI values.
1167 //
1168 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1169 //    is live, but never read. This can happen because we don't compute
1170 //    individual live ranges per lane.
1171 //
1172 //      %dst<def> = FOO
1173 //      %src = BAR
1174 //      %dst:ssub1<def> = COPY %src
1175 //
1176 //    This kind of interference is only resolved locally. If the clobbered
1177 //    lane value escapes the block, the join is aborted.
1178
1179 namespace {
1180 /// Track information about values in a single virtual register about to be
1181 /// joined. Objects of this class are always created in pairs - one for each
1182 /// side of the CoalescerPair.
1183 class JoinVals {
1184   LiveInterval &LI;
1185
1186   // Location of this register in the final joined register.
1187   // Either CP.DstIdx or CP.SrcIdx.
1188   unsigned SubIdx;
1189
1190   // Values that will be present in the final live range.
1191   SmallVectorImpl<VNInfo*> &NewVNInfo;
1192
1193   const CoalescerPair &CP;
1194   LiveIntervals *LIS;
1195   SlotIndexes *Indexes;
1196   const TargetRegisterInfo *TRI;
1197
1198   // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1199   // This is suitable for passing to LiveInterval::join().
1200   SmallVector<int, 8> Assignments;
1201
1202   // Conflict resolution for overlapping values.
1203   enum ConflictResolution {
1204     // No overlap, simply keep this value.
1205     CR_Keep,
1206
1207     // Merge this value into OtherVNI and erase the defining instruction.
1208     // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1209     // values.
1210     CR_Erase,
1211
1212     // Merge this value into OtherVNI but keep the defining instruction.
1213     // This is for the special case where OtherVNI is defined by the same
1214     // instruction.
1215     CR_Merge,
1216
1217     // Keep this value, and have it replace OtherVNI where possible. This
1218     // complicates value mapping since OtherVNI maps to two different values
1219     // before and after this def.
1220     // Used when clobbering undefined or dead lanes.
1221     CR_Replace,
1222
1223     // Unresolved conflict. Visit later when all values have been mapped.
1224     CR_Unresolved,
1225
1226     // Unresolvable conflict. Abort the join.
1227     CR_Impossible
1228   };
1229
1230   // Per-value info for LI. The lane bit masks are all relative to the final
1231   // joined register, so they can be compared directly between SrcReg and
1232   // DstReg.
1233   struct Val {
1234     ConflictResolution Resolution;
1235
1236     // Lanes written by this def, 0 for unanalyzed values.
1237     unsigned WriteLanes;
1238
1239     // Lanes with defined values in this register. Other lanes are undef and
1240     // safe to clobber.
1241     unsigned ValidLanes;
1242
1243     // Value in LI being redefined by this def.
1244     VNInfo *RedefVNI;
1245
1246     // Value in the other live range that overlaps this def, if any.
1247     VNInfo *OtherVNI;
1248
1249     // True when the live range of this value will be pruned because of an
1250     // overlapping CR_Replace value in the other live range.
1251     bool Pruned;
1252
1253     // True once Pruned above has been computed.
1254     bool PrunedComputed;
1255
1256     Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1257             RedefVNI(0), OtherVNI(0), Pruned(false), PrunedComputed(false) {}
1258
1259     bool isAnalyzed() const { return WriteLanes != 0; }
1260   };
1261
1262   // One entry per value number in LI.
1263   SmallVector<Val, 8> Vals;
1264
1265   unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1266   VNInfo *stripCopies(VNInfo *VNI);
1267   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1268   void computeAssignment(unsigned ValNo, JoinVals &Other);
1269   bool taintExtent(unsigned, unsigned, JoinVals&,
1270                    SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1271   bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
1272   bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1273
1274 public:
1275   JoinVals(LiveInterval &li, unsigned subIdx,
1276            SmallVectorImpl<VNInfo*> &newVNInfo,
1277            const CoalescerPair &cp,
1278            LiveIntervals *lis,
1279            const TargetRegisterInfo *tri)
1280     : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1281       Indexes(LIS->getSlotIndexes()), TRI(tri),
1282       Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1283   {}
1284
1285   /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1286   /// Returns false if any conflicts were impossible to resolve.
1287   bool mapValues(JoinVals &Other);
1288
1289   /// Try to resolve conflicts that require all values to be mapped.
1290   /// Returns false if any conflicts were impossible to resolve.
1291   bool resolveConflicts(JoinVals &Other);
1292
1293   /// Prune the live range of values in Other.LI where they would conflict with
1294   /// CR_Replace values in LI. Collect end points for restoring the live range
1295   /// after joining.
1296   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1297
1298   /// Erase any machine instructions that have been coalesced away.
1299   /// Add erased instructions to ErasedInstrs.
1300   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1301   /// the erased instrs.
1302   void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1303                    SmallVectorImpl<unsigned> &ShrinkRegs);
1304
1305   /// Get the value assignments suitable for passing to LiveInterval::join.
1306   const int *getAssignments() const { return &Assignments[0]; }
1307 };
1308 } // end anonymous namespace
1309
1310 /// Compute the bitmask of lanes actually written by DefMI.
1311 /// Set Redef if there are any partial register definitions that depend on the
1312 /// previous value of the register.
1313 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1314   unsigned L = 0;
1315   for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1316     if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1317       continue;
1318     L |= TRI->getSubRegIndexLaneMask(compose(*TRI, SubIdx, MO->getSubReg()));
1319     if (MO->readsReg())
1320       Redef = true;
1321   }
1322   return L;
1323 }
1324
1325 /// Find the ultimate value that VNI was copied from.
1326 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1327   while (!VNI->isPHIDef()) {
1328     MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1329     assert(MI && "No defining instruction");
1330     if (!MI->isFullCopy())
1331       break;
1332     unsigned Reg = MI->getOperand(1).getReg();
1333     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1334       break;
1335     LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def);
1336     if (!LRQ.valueIn())
1337       break;
1338     VNI = LRQ.valueIn();
1339   }
1340   return VNI;
1341 }
1342
1343 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1344 /// Return a conflict resolution when possible, but leave the hard cases as
1345 /// CR_Unresolved.
1346 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1347 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1348 /// The recursion always goes upwards in the dominator tree, making loops
1349 /// impossible.
1350 JoinVals::ConflictResolution
1351 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1352   Val &V = Vals[ValNo];
1353   assert(!V.isAnalyzed() && "Value has already been analyzed!");
1354   VNInfo *VNI = LI.getValNumInfo(ValNo);
1355   if (VNI->isUnused()) {
1356     V.WriteLanes = ~0u;
1357     return CR_Keep;
1358   }
1359
1360   // Get the instruction defining this value, compute the lanes written.
1361   const MachineInstr *DefMI = 0;
1362   if (VNI->isPHIDef()) {
1363     // Conservatively assume that all lanes in a PHI are valid.
1364     V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1365   } else {
1366     DefMI = Indexes->getInstructionFromIndex(VNI->def);
1367     bool Redef = false;
1368     V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1369
1370     // If this is a read-modify-write instruction, there may be more valid
1371     // lanes than the ones written by this instruction.
1372     // This only covers partial redef operands. DefMI may have normal use
1373     // operands reading the register. They don't contribute valid lanes.
1374     //
1375     // This adds ssub1 to the set of valid lanes in %src:
1376     //
1377     //   %src:ssub1<def> = FOO
1378     //
1379     // This leaves only ssub1 valid, making any other lanes undef:
1380     //
1381     //   %src:ssub1<def,read-undef> = FOO %src:ssub2
1382     //
1383     // The <read-undef> flag on the def operand means that old lane values are
1384     // not important.
1385     if (Redef) {
1386       V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn();
1387       assert(V.RedefVNI && "Instruction is reading nonexistent value");
1388       computeAssignment(V.RedefVNI->id, Other);
1389       V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1390     }
1391
1392     // An IMPLICIT_DEF writes undef values.
1393     if (DefMI->isImplicitDef())
1394       V.ValidLanes &= ~V.WriteLanes;
1395   }
1396
1397   // Find the value in Other that overlaps VNI->def, if any.
1398   LiveRangeQuery OtherLRQ(Other.LI, VNI->def);
1399
1400   // It is possible that both values are defined by the same instruction, or
1401   // the values are PHIs defined in the same block. When that happens, the two
1402   // values should be merged into one, but not into any preceding value.
1403   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1404   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1405     DEBUG(dbgs() << "\t\tDouble def: " << VNI->def << '\n');
1406     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1407
1408     // One value stays, the other is merged. Keep the earlier one, or the first
1409     // one we see.
1410     if (OtherVNI->def < VNI->def)
1411       Other.computeAssignment(OtherVNI->id, *this);
1412     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1413       // This is an early-clobber def overlapping a live-in value in the other
1414       // register. Not mergeable.
1415       V.OtherVNI = OtherLRQ.valueIn();
1416       return CR_Impossible;
1417     }
1418     V.OtherVNI = OtherVNI;
1419     Val &OtherV = Other.Vals[OtherVNI->id];
1420     // Keep this value, check for conflicts when analyzing OtherVNI.
1421     if (!OtherV.isAnalyzed())
1422       return CR_Keep;
1423     // Both sides have been analyzed now. Do they conflict?
1424     if (V.ValidLanes & OtherV.ValidLanes)
1425       // Overlapping lanes can't be resolved.
1426       return CR_Impossible;
1427     else
1428       return CR_Merge;
1429   }
1430
1431   // No simultaneous def. Is Other live at the def?
1432   V.OtherVNI = OtherLRQ.valueIn();
1433   if (!V.OtherVNI)
1434     // No overlap, no conflict.
1435     return CR_Keep;
1436
1437   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1438
1439   // We have overlapping values, or possibly a kill of Other.
1440   // Recursively compute assignments up the dominator tree.
1441   Other.computeAssignment(V.OtherVNI->id, *this);
1442   const Val &OtherV = Other.Vals[V.OtherVNI->id];
1443
1444   // Don't attempt resolving PHI values for now.
1445   if (VNI->isPHIDef())
1446     return CR_Impossible;
1447
1448   // Check for simple erasable conflicts.
1449   if (DefMI->isImplicitDef())
1450     return CR_Erase;
1451
1452   // Include the non-conflict where DefMI is a coalescable copy that kills
1453   // OtherVNI. We still want the copy erased and value numbers merged.
1454   if (CP.isCoalescable(DefMI)) {
1455     // Some of the lanes copied from OtherVNI may be undef, making them undef
1456     // here too.
1457     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1458     return CR_Erase;
1459   }
1460
1461   // This may not be a real conflict if DefMI simply kills Other and defines
1462   // VNI.
1463   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1464     return CR_Keep;
1465
1466   // Handle the case where VNI and OtherVNI can be proven to be identical:
1467   //
1468   //   %other = COPY %ext
1469   //   %this  = COPY %ext <-- Erase this copy
1470   //
1471   if (DefMI->isFullCopy() && !CP.isPartial() &&
1472       stripCopies(VNI) == stripCopies(V.OtherVNI))
1473     return CR_Erase;
1474
1475   // If the lanes written by this instruction were all undef in OtherVNI, it is
1476   // still safe to join the live ranges. This can't be done with a simple value
1477   // mapping, though - OtherVNI will map to multiple values:
1478   //
1479   //   1 %dst:ssub0 = FOO                <-- OtherVNI
1480   //   2 %src = BAR                      <-- VNI
1481   //   3 %dst:ssub1 = COPY %src<kill>    <-- Eliminate this copy.
1482   //   4 BAZ %dst<kill>
1483   //   5 QUUX %src<kill>
1484   //
1485   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1486   // handles this complex value mapping.
1487   if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1488     return CR_Replace;
1489
1490   // VNI is clobbering live lanes in OtherVNI, but there is still the
1491   // possibility that no instructions actually read the clobbered lanes.
1492   // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1493   // Otherwise Other.LI wouldn't be live here.
1494   if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1495     return CR_Impossible;
1496
1497   // We need to verify that no instructions are reading the clobbered lanes. To
1498   // save compile time, we'll only check that locally. Don't allow the tainted
1499   // value to escape the basic block.
1500   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1501   if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1502     return CR_Impossible;
1503
1504   // There are still some things that could go wrong besides clobbered lanes
1505   // being read, for example OtherVNI may be only partially redefined in MBB,
1506   // and some clobbered lanes could escape the block. Save this analysis for
1507   // resolveConflicts() when all values have been mapped. We need to know
1508   // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1509   // that now - the recursive analyzeValue() calls must go upwards in the
1510   // dominator tree.
1511   return CR_Unresolved;
1512 }
1513
1514 /// Compute the value assignment for ValNo in LI.
1515 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1516 /// the stack.
1517 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1518   Val &V = Vals[ValNo];
1519   if (V.isAnalyzed()) {
1520     // Recursion should always move up the dominator tree, so ValNo is not
1521     // supposed to reappear before it has been assigned.
1522     assert(Assignments[ValNo] != -1 && "Bad recursion?");
1523     return;
1524   }
1525   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1526   case CR_Erase:
1527   case CR_Merge:
1528     // Merge this ValNo into OtherVNI.
1529     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1530     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1531     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1532     DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1533                  << LI.getValNumInfo(ValNo)->def << " into "
1534                  << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1535                  << V.OtherVNI->def << " --> @"
1536                  << NewVNInfo[Assignments[ValNo]]->def << '\n');
1537     break;
1538   case CR_Replace:
1539   case CR_Unresolved:
1540     // The other value is going to be pruned if this join is successful.
1541     assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1542     Other.Vals[V.OtherVNI->id].Pruned = true;
1543     // Fall through.
1544   default:
1545     // This value number needs to go in the final joined live range.
1546     Assignments[ValNo] = NewVNInfo.size();
1547     NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1548     break;
1549   }
1550 }
1551
1552 bool JoinVals::mapValues(JoinVals &Other) {
1553   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1554     computeAssignment(i, Other);
1555     if (Vals[i].Resolution == CR_Impossible) {
1556       DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1557                    << '@' << LI.getValNumInfo(i)->def << '\n');
1558       return false;
1559     }
1560   }
1561   return true;
1562 }
1563
1564 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
1565 /// the extent of the tainted lanes in the block.
1566 ///
1567 /// Multiple values in Other.LI can be affected since partial redefinitions can
1568 /// preserve previously tainted lanes.
1569 ///
1570 ///   1 %dst = VLOAD           <-- Define all lanes in %dst
1571 ///   2 %src = FOO             <-- ValNo to be joined with %dst:ssub0
1572 ///   3 %dst:ssub1 = BAR       <-- Partial redef doesn't clear taint in ssub0
1573 ///   4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1574 ///
1575 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1576 /// entry to TaintedVals.
1577 ///
1578 /// Returns false if the tainted lanes extend beyond the basic block.
1579 bool JoinVals::
1580 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1581             SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
1582   VNInfo *VNI = LI.getValNumInfo(ValNo);
1583   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1584   SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
1585
1586   // Scan Other.LI from VNI.def to MBBEnd.
1587   LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
1588   assert(OtherI != Other.LI.end() && "No conflict?");
1589   do {
1590     // OtherI is pointing to a tainted value. Abort the join if the tainted
1591     // lanes escape the block.
1592     SlotIndex End = OtherI->end;
1593     if (End >= MBBEnd) {
1594       DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
1595                    << OtherI->valno->id << '@' << OtherI->start << '\n');
1596       return false;
1597     }
1598     DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
1599                  << OtherI->valno->id << '@' << OtherI->start
1600                  << " to " << End << '\n');
1601     // A dead def is not a problem.
1602     if (End.isDead())
1603       break;
1604     TaintExtent.push_back(std::make_pair(End, TaintedLanes));
1605
1606     // Check for another def in the MBB.
1607     if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
1608       break;
1609
1610     // Lanes written by the new def are no longer tainted.
1611     const Val &OV = Other.Vals[OtherI->valno->id];
1612     TaintedLanes &= ~OV.WriteLanes;
1613     if (!OV.RedefVNI)
1614       break;
1615   } while (TaintedLanes);
1616   return true;
1617 }
1618
1619 /// Return true if MI uses any of the given Lanes from Reg.
1620 /// This does not include partial redefinitions of Reg.
1621 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
1622                          unsigned Lanes) {
1623   if (MI->isDebugValue())
1624     return false;
1625   for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1626     if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
1627       continue;
1628     if (!MO->readsReg())
1629       continue;
1630     if (Lanes &
1631         TRI->getSubRegIndexLaneMask(compose(*TRI, SubIdx, MO->getSubReg())))
1632       return true;
1633   }
1634   return false;
1635 }
1636
1637 bool JoinVals::resolveConflicts(JoinVals &Other) {
1638   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1639     Val &V = Vals[i];
1640     assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
1641     if (V.Resolution != CR_Unresolved)
1642       continue;
1643     DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1644                  << '@' << LI.getValNumInfo(i)->def << '\n');
1645     ++NumLaneConflicts;
1646     assert(V.OtherVNI && "Inconsistent conflict resolution.");
1647     VNInfo *VNI = LI.getValNumInfo(i);
1648     const Val &OtherV = Other.Vals[V.OtherVNI->id];
1649
1650     // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
1651     // join, those lanes will be tainted with a wrong value. Get the extent of
1652     // the tainted lanes.
1653     unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
1654     SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
1655     if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
1656       // Tainted lanes would extend beyond the basic block.
1657       return false;
1658
1659     assert(!TaintExtent.empty() && "There should be at least one conflict.");
1660
1661     // Now look at the instructions from VNI->def to TaintExtent (inclusive).
1662     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1663     MachineBasicBlock::iterator MI = MBB->begin();
1664     if (!VNI->isPHIDef()) {
1665       MI = Indexes->getInstructionFromIndex(VNI->def);
1666       // No need to check the instruction defining VNI for reads.
1667       ++MI;
1668     }
1669     assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
1670            "Interference ends on VNI->def. Should have been handled earlier");
1671     MachineInstr *LastMI =
1672       Indexes->getInstructionFromIndex(TaintExtent.front().first);
1673     assert(LastMI && "Range must end at a proper instruction");
1674     unsigned TaintNum = 0;
1675     for(;;) {
1676       assert(MI != MBB->end() && "Bad LastMI");
1677       if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
1678         DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
1679         return false;
1680       }
1681       // LastMI is the last instruction to use the current value.
1682       if (&*MI == LastMI) {
1683         if (++TaintNum == TaintExtent.size())
1684           break;
1685         LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
1686         assert(LastMI && "Range must end at a proper instruction");
1687         TaintedLanes = TaintExtent[TaintNum].second;
1688       }
1689       ++MI;
1690     }
1691
1692     // The tainted lanes are unused.
1693     V.Resolution = CR_Replace;
1694     ++NumLaneResolves;
1695   }
1696   return true;
1697 }
1698
1699 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
1700 // be pruned:
1701 //
1702 //   %dst = COPY %src
1703 //   %src = COPY %dst  <-- This value to be pruned.
1704 //   %dst = COPY %src  <-- This value is a copy of a pruned value.
1705 //
1706 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
1707   Val &V = Vals[ValNo];
1708   if (V.Pruned || V.PrunedComputed)
1709     return V.Pruned;
1710
1711   if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
1712     return V.Pruned;
1713
1714   // Follow copies up the dominator tree and check if any intermediate value
1715   // has been pruned.
1716   V.PrunedComputed = true;
1717   V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
1718   return V.Pruned;
1719 }
1720
1721 void JoinVals::pruneValues(JoinVals &Other,
1722                            SmallVectorImpl<SlotIndex> &EndPoints) {
1723   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1724     SlotIndex Def = LI.getValNumInfo(i)->def;
1725     switch (Vals[i].Resolution) {
1726     case CR_Keep:
1727       break;
1728     case CR_Replace:
1729       // This value takes precedence over the value in Other.LI.
1730       LIS->pruneValue(&Other.LI, Def, &EndPoints);
1731       DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1732                    << ": " << Other.LI << '\n');
1733       break;
1734     case CR_Erase:
1735     case CR_Merge:
1736       if (isPrunedValue(i, Other)) {
1737         // This value is ultimately a copy of a pruned value in LI or Other.LI.
1738         // We can no longer trust the value mapping computed by
1739         // computeAssignment(), the value that was originally copied could have
1740         // been replaced.
1741         LIS->pruneValue(&LI, Def, &EndPoints);
1742         DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
1743                      << Def << ": " << LI << '\n');
1744       }
1745       break;
1746     case CR_Unresolved:
1747     case CR_Impossible:
1748       llvm_unreachable("Unresolved conflicts");
1749     }
1750   }
1751 }
1752
1753 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1754                            SmallVectorImpl<unsigned> &ShrinkRegs) {
1755   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1756     if (Vals[i].Resolution != CR_Erase)
1757       continue;
1758     SlotIndex Def = LI.getValNumInfo(i)->def;
1759     MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1760     assert(MI && "No instruction to erase");
1761     if (MI->isCopy()) {
1762       unsigned Reg = MI->getOperand(1).getReg();
1763       if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1764           Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1765         ShrinkRegs.push_back(Reg);
1766     }
1767     ErasedInstrs.insert(MI);
1768     DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1769     LIS->RemoveMachineInstrFromMaps(MI);
1770     MI->eraseFromParent();
1771   }
1772 }
1773
1774 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1775   SmallVector<VNInfo*, 16> NewVNInfo;
1776   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1777   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1778   JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1779   JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1780
1781   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1782                << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS
1783                << '\n');
1784
1785   // First compute NewVNInfo and the simple value mappings.
1786   // Detect impossible conflicts early.
1787   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1788     return false;
1789
1790   // Some conflicts can only be resolved after all values have been mapped.
1791   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1792     return false;
1793
1794   // All clear, the live ranges can be merged.
1795
1796   // The merging algorithm in LiveInterval::join() can't handle conflicting
1797   // value mappings, so we need to remove any live ranges that overlap a
1798   // CR_Replace resolution. Collect a set of end points that can be used to
1799   // restore the live range after joining.
1800   SmallVector<SlotIndex, 8> EndPoints;
1801   LHSVals.pruneValues(RHSVals, EndPoints);
1802   RHSVals.pruneValues(LHSVals, EndPoints);
1803
1804   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1805   // registers to require trimming.
1806   SmallVector<unsigned, 8> ShrinkRegs;
1807   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1808   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1809   while (!ShrinkRegs.empty())
1810     LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1811
1812   // Join RHS into LHS.
1813   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo,
1814            MRI);
1815
1816   // Kill flags are going to be wrong if the live ranges were overlapping.
1817   // Eventually, we should simply clear all kill flags when computing live
1818   // ranges. They are reinserted after register allocation.
1819   MRI->clearKillFlags(LHS.reg);
1820   MRI->clearKillFlags(RHS.reg);
1821
1822   if (EndPoints.empty())
1823     return true;
1824
1825   // Recompute the parts of the live range we had to remove because of
1826   // CR_Replace conflicts.
1827   DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
1828                << " points: " << LHS << '\n');
1829   LIS->extendToIndices(&LHS, EndPoints);
1830   return true;
1831 }
1832
1833 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1834 /// compute what the resultant value numbers for each value in the input two
1835 /// ranges will be.  This is complicated by copies between the two which can
1836 /// and will commonly cause multiple value numbers to be merged into one.
1837 ///
1838 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1839 /// keeps track of the new InstDefiningValue assignment for the result
1840 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1841 /// whether a value in this or other is a copy from the opposite set.
1842 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1843 /// already been assigned.
1844 ///
1845 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1846 /// contains the value number the copy is from.
1847 ///
1848 static unsigned ComputeUltimateVN(VNInfo *VNI,
1849                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1850                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1851                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1852                                   SmallVector<int, 16> &ThisValNoAssignments,
1853                                   SmallVector<int, 16> &OtherValNoAssignments) {
1854   unsigned VN = VNI->id;
1855
1856   // If the VN has already been computed, just return it.
1857   if (ThisValNoAssignments[VN] >= 0)
1858     return ThisValNoAssignments[VN];
1859   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1860
1861   // If this val is not a copy from the other val, then it must be a new value
1862   // number in the destination.
1863   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1864   if (I == ThisFromOther.end()) {
1865     NewVNInfo.push_back(VNI);
1866     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1867   }
1868   VNInfo *OtherValNo = I->second;
1869
1870   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1871   // been computed, return it.
1872   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1873     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1874
1875   // Mark this value number as currently being computed, then ask what the
1876   // ultimate value # of the other value is.
1877   ThisValNoAssignments[VN] = -2;
1878   unsigned UltimateVN =
1879     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1880                       OtherValNoAssignments, ThisValNoAssignments);
1881   return ThisValNoAssignments[VN] = UltimateVN;
1882 }
1883
1884
1885 // Find out if we have something like
1886 // A = X
1887 // B = X
1888 // if so, we can pretend this is actually
1889 // A = X
1890 // B = A
1891 // which allows us to coalesce A and B.
1892 // VNI is the definition of B. LR is the life range of A that includes
1893 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1894 // This implies that A dominates B.
1895 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1896                                           const TargetRegisterInfo &tri,
1897                                           CoalescerPair &CP,
1898                                           VNInfo *VNI,
1899                                           VNInfo *OtherVNI,
1900                                      SmallVector<MachineInstr*, 8> &DupCopies) {
1901   // FIXME: This is very conservative. For example, we don't handle
1902   // physical registers.
1903
1904   MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1905
1906   if (!MI || CP.isPartial() || CP.isPhys())
1907     return false;
1908
1909   unsigned A = CP.getDstReg();
1910   if (!TargetRegisterInfo::isVirtualRegister(A))
1911     return false;
1912
1913   unsigned B = CP.getSrcReg();
1914   if (!TargetRegisterInfo::isVirtualRegister(B))
1915     return false;
1916
1917   MachineInstr *OtherMI = li.getInstructionFromIndex(OtherVNI->def);
1918   if (!OtherMI)
1919     return false;
1920
1921   if (MI->isImplicitDef()) {
1922     DupCopies.push_back(MI);
1923     return true;
1924   } else {
1925     if (!MI->isFullCopy())
1926       return false;
1927     unsigned Src = MI->getOperand(1).getReg();
1928     if (!TargetRegisterInfo::isVirtualRegister(Src))
1929       return false;
1930     if (!OtherMI->isFullCopy())
1931       return false;
1932     unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1933     if (!TargetRegisterInfo::isVirtualRegister(OtherSrc))
1934       return false;
1935
1936     if (Src != OtherSrc)
1937       return false;
1938
1939     // If the copies use two different value numbers of X, we cannot merge
1940     // A and B.
1941     LiveInterval &SrcInt = li.getInterval(Src);
1942     // getVNInfoBefore returns NULL for undef copies. In this case, the
1943     // optimization is still safe.
1944     if (SrcInt.getVNInfoBefore(OtherVNI->def) !=
1945         SrcInt.getVNInfoBefore(VNI->def))
1946       return false;
1947
1948     DupCopies.push_back(MI);
1949     return true;
1950   }
1951 }
1952
1953 /// joinIntervals - Attempt to join these two intervals.  On failure, this
1954 /// returns false.
1955 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1956   // Handle physreg joins separately.
1957   if (CP.isPhys())
1958     return joinReservedPhysReg(CP);
1959
1960   if (NewCoalescer)
1961     return joinVirtRegs(CP);
1962
1963   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1964   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1965                << '\n');
1966
1967   // Compute the final value assignment, assuming that the live ranges can be
1968   // coalesced.
1969   SmallVector<int, 16> LHSValNoAssignments;
1970   SmallVector<int, 16> RHSValNoAssignments;
1971   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1972   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1973   SmallVector<VNInfo*, 16> NewVNInfo;
1974
1975   SmallVector<MachineInstr*, 8> DupCopies;
1976   SmallVector<MachineInstr*, 8> DeadCopies;
1977
1978   LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1979   DEBUG(dbgs() << "\t\tLHS = " << PrintReg(CP.getDstReg(), TRI) << ' ' << LHS
1980                << '\n');
1981
1982   // Loop over the value numbers of the LHS, seeing if any are defined from
1983   // the RHS.
1984   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1985        i != e; ++i) {
1986     VNInfo *VNI = *i;
1987     if (VNI->isUnused() || VNI->isPHIDef())
1988       continue;
1989     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1990     assert(MI && "Missing def");
1991     if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1992       continue;
1993
1994     // Figure out the value # from the RHS.
1995     VNInfo *OtherVNI = RHS.getVNInfoBefore(VNI->def);
1996     // The copy could be to an aliased physreg.
1997     if (!OtherVNI)
1998       continue;
1999
2000     // DstReg is known to be a register in the LHS interval.  If the src is
2001     // from the RHS interval, we can use its value #.
2002     if (CP.isCoalescable(MI))
2003       DeadCopies.push_back(MI);
2004     else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
2005                                             DupCopies))
2006       continue;
2007
2008     LHSValsDefinedFromRHS[VNI] = OtherVNI;
2009   }
2010
2011   // Loop over the value numbers of the RHS, seeing if any are defined from
2012   // the LHS.
2013   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2014        i != e; ++i) {
2015     VNInfo *VNI = *i;
2016     if (VNI->isUnused() || VNI->isPHIDef())
2017       continue;
2018     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
2019     assert(MI && "Missing def");
2020     if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
2021       continue;
2022
2023     // Figure out the value # from the LHS.
2024     VNInfo *OtherVNI = LHS.getVNInfoBefore(VNI->def);
2025     // The copy could be to an aliased physreg.
2026     if (!OtherVNI)
2027       continue;
2028
2029     // DstReg is known to be a register in the RHS interval.  If the src is
2030     // from the LHS interval, we can use its value #.
2031     if (CP.isCoalescable(MI))
2032       DeadCopies.push_back(MI);
2033     else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
2034                                             DupCopies))
2035         continue;
2036
2037     RHSValsDefinedFromLHS[VNI] = OtherVNI;
2038   }
2039
2040   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2041   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2042   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2043
2044   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2045        i != e; ++i) {
2046     VNInfo *VNI = *i;
2047     unsigned VN = VNI->id;
2048     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2049       continue;
2050     ComputeUltimateVN(VNI, NewVNInfo,
2051                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2052                       LHSValNoAssignments, RHSValNoAssignments);
2053   }
2054   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2055        i != e; ++i) {
2056     VNInfo *VNI = *i;
2057     unsigned VN = VNI->id;
2058     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2059       continue;
2060     // If this value number isn't a copy from the LHS, it's a new number.
2061     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2062       NewVNInfo.push_back(VNI);
2063       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2064       continue;
2065     }
2066
2067     ComputeUltimateVN(VNI, NewVNInfo,
2068                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2069                       RHSValNoAssignments, LHSValNoAssignments);
2070   }
2071
2072   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2073   // interval lists to see if these intervals are coalescable.
2074   LiveInterval::const_iterator I = LHS.begin();
2075   LiveInterval::const_iterator IE = LHS.end();
2076   LiveInterval::const_iterator J = RHS.begin();
2077   LiveInterval::const_iterator JE = RHS.end();
2078
2079   // Collect interval end points that will no longer be kills.
2080   SmallVector<MachineInstr*, 8> LHSOldKills;
2081   SmallVector<MachineInstr*, 8> RHSOldKills;
2082
2083   // Skip ahead until the first place of potential sharing.
2084   if (I != IE && J != JE) {
2085     if (I->start < J->start) {
2086       I = std::upper_bound(I, IE, J->start);
2087       if (I != LHS.begin()) --I;
2088     } else if (J->start < I->start) {
2089       J = std::upper_bound(J, JE, I->start);
2090       if (J != RHS.begin()) --J;
2091     }
2092   }
2093
2094   while (I != IE && J != JE) {
2095     // Determine if these two live ranges overlap.
2096     // If so, check value # info to determine if they are really different.
2097     if (I->end > J->start && J->end > I->start) {
2098       // If the live range overlap will map to the same value number in the
2099       // result liverange, we can still coalesce them.  If not, we can't.
2100       if (LHSValNoAssignments[I->valno->id] !=
2101           RHSValNoAssignments[J->valno->id])
2102         return false;
2103
2104       // Extended live ranges should no longer be killed.
2105       if (!I->end.isBlock() && I->end < J->end)
2106         if (MachineInstr *MI = LIS->getInstructionFromIndex(I->end))
2107           LHSOldKills.push_back(MI);
2108       if (!J->end.isBlock() && J->end < I->end)
2109         if (MachineInstr *MI = LIS->getInstructionFromIndex(J->end))
2110           RHSOldKills.push_back(MI);
2111     }
2112
2113     if (I->end < J->end)
2114       ++I;
2115     else
2116       ++J;
2117   }
2118
2119   // Clear kill flags where live ranges are extended.
2120   while (!LHSOldKills.empty())
2121     LHSOldKills.pop_back_val()->clearRegisterKills(LHS.reg, TRI);
2122   while (!RHSOldKills.empty())
2123     RHSOldKills.pop_back_val()->clearRegisterKills(RHS.reg, TRI);
2124
2125   if (LHSValNoAssignments.empty())
2126     LHSValNoAssignments.push_back(-1);
2127   if (RHSValNoAssignments.empty())
2128     RHSValNoAssignments.push_back(-1);
2129
2130   // Now erase all the redundant copies.
2131   for (unsigned i = 0, e = DeadCopies.size(); i != e; ++i) {
2132     MachineInstr *MI = DeadCopies[i];
2133     if (!ErasedInstrs.insert(MI))
2134       continue;
2135     DEBUG(dbgs() << "\t\terased:\t" << LIS->getInstructionIndex(MI)
2136                  << '\t' << *MI);
2137     LIS->RemoveMachineInstrFromMaps(MI);
2138     MI->eraseFromParent();
2139   }
2140
2141   SmallVector<unsigned, 8> SourceRegisters;
2142   for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
2143          E = DupCopies.end(); I != E; ++I) {
2144     MachineInstr *MI = *I;
2145     if (!ErasedInstrs.insert(MI))
2146       continue;
2147
2148     // If MI is a copy, then we have pretended that the assignment to B in
2149     // A = X
2150     // B = X
2151     // was actually a copy from A. Now that we decided to coalesce A and B,
2152     // transform the code into
2153     // A = X
2154     // In the case of the implicit_def, we just have to remove it.
2155     if (!MI->isImplicitDef()) {
2156       unsigned Src = MI->getOperand(1).getReg();
2157       SourceRegisters.push_back(Src);
2158     }
2159     LIS->RemoveMachineInstrFromMaps(MI);
2160     MI->eraseFromParent();
2161   }
2162
2163   // If B = X was the last use of X in a liverange, we have to shrink it now
2164   // that B = X is gone.
2165   for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
2166          E = SourceRegisters.end(); I != E; ++I) {
2167     LIS->shrinkToUses(&LIS->getInterval(*I));
2168   }
2169
2170   // If we get here, we know that we can coalesce the live ranges.  Ask the
2171   // intervals to coalesce themselves now.
2172   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2173            MRI);
2174   return true;
2175 }
2176
2177 namespace {
2178   // DepthMBBCompare - Comparison predicate that sort first based on the loop
2179   // depth of the basic block (the unsigned), and then on the MBB number.
2180   struct DepthMBBCompare {
2181     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2182     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2183       // Deeper loops first
2184       if (LHS.first != RHS.first)
2185         return LHS.first > RHS.first;
2186
2187       // Prefer blocks that are more connected in the CFG. This takes care of
2188       // the most difficult copies first while intervals are short.
2189       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
2190       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
2191       if (cl != cr)
2192         return cl > cr;
2193
2194       // As a last resort, sort by block number.
2195       return LHS.second->getNumber() < RHS.second->getNumber();
2196     }
2197   };
2198 }
2199
2200 // Try joining WorkList copies starting from index From.
2201 // Null out any successful joins.
2202 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
2203   assert(From <= WorkList.size() && "Out of range");
2204   bool Progress = false;
2205   for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
2206     if (!WorkList[i])
2207       continue;
2208     // Skip instruction pointers that have already been erased, for example by
2209     // dead code elimination.
2210     if (ErasedInstrs.erase(WorkList[i])) {
2211       WorkList[i] = 0;
2212       continue;
2213     }
2214     bool Again = false;
2215     bool Success = joinCopy(WorkList[i], Again);
2216     Progress |= Success;
2217     if (Success || !Again)
2218       WorkList[i] = 0;
2219   }
2220   return Progress;
2221 }
2222
2223 void
2224 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2225   DEBUG(dbgs() << MBB->getName() << ":\n");
2226
2227   // Collect all copy-like instructions in MBB. Don't start coalescing anything
2228   // yet, it might invalidate the iterator.
2229   const unsigned PrevSize = WorkList.size();
2230   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2231        MII != E; ++MII)
2232     if (MII->isCopyLike())
2233       WorkList.push_back(MII);
2234
2235   // Try coalescing the collected copies immediately, and remove the nulls.
2236   // This prevents the WorkList from getting too large since most copies are
2237   // joinable on the first attempt.
2238   if (copyCoalesceWorkList(PrevSize))
2239     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2240                                (MachineInstr*)0), WorkList.end());
2241 }
2242
2243 void RegisterCoalescer::joinAllIntervals() {
2244   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2245   assert(WorkList.empty() && "Old data still around.");
2246
2247   if (Loops->empty()) {
2248     // If there are no loops in the function, join intervals in function order.
2249     for (MachineFunction::iterator I = MF->begin(), E = MF->end();
2250          I != E; ++I)
2251       copyCoalesceInMBB(I);
2252   } else {
2253     // Otherwise, join intervals in inner loops before other intervals.
2254     // Unfortunately we can't just iterate over loop hierarchy here because
2255     // there may be more MBB's than BB's.  Collect MBB's for sorting.
2256
2257     // Join intervals in the function prolog first. We want to join physical
2258     // registers with virtual registers before the intervals got too long.
2259     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2260     for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2261       MachineBasicBlock *MBB = I;
2262       MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
2263     }
2264
2265     // Sort by loop depth.
2266     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2267
2268     // Finally, join intervals in loop nest order.
2269     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2270       copyCoalesceInMBB(MBBs[i].second);
2271   }
2272
2273   // Joining intervals can allow other intervals to be joined.  Iteratively join
2274   // until we make no progress.
2275   while (copyCoalesceWorkList())
2276     /* empty */ ;
2277 }
2278
2279 void RegisterCoalescer::releaseMemory() {
2280   ErasedInstrs.clear();
2281   WorkList.clear();
2282   DeadDefs.clear();
2283   InflateRegs.clear();
2284 }
2285
2286 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2287   MF = &fn;
2288   MRI = &fn.getRegInfo();
2289   TM = &fn.getTarget();
2290   TRI = TM->getRegisterInfo();
2291   TII = TM->getInstrInfo();
2292   LIS = &getAnalysis<LiveIntervals>();
2293   LDV = &getAnalysis<LiveDebugVariables>();
2294   AA = &getAnalysis<AliasAnalysis>();
2295   Loops = &getAnalysis<MachineLoopInfo>();
2296
2297   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2298                << "********** Function: " << MF->getName() << '\n');
2299
2300   if (VerifyCoalescing)
2301     MF->verify(this, "Before register coalescing");
2302
2303   RegClassInfo.runOnMachineFunction(fn);
2304
2305   // Join (coalesce) intervals if requested.
2306   if (EnableJoining)
2307     joinAllIntervals();
2308
2309   // After deleting a lot of copies, register classes may be less constrained.
2310   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2311   // DPR inflation.
2312   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2313   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2314                     InflateRegs.end());
2315   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2316   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2317     unsigned Reg = InflateRegs[i];
2318     if (MRI->reg_nodbg_empty(Reg))
2319       continue;
2320     if (MRI->recomputeRegClass(Reg, *TM)) {
2321       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2322                    << MRI->getRegClass(Reg)->getName() << '\n');
2323       ++NumInflated;
2324     }
2325   }
2326
2327   DEBUG(dump());
2328   DEBUG(LDV->dump());
2329   if (VerifyCoalescing)
2330     MF->verify(this, "After register coalescing");
2331   return true;
2332 }
2333
2334 /// print - Implement the dump method.
2335 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
2336    LIS->print(O, m);
2337 }