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