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