1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the generic RegisterCoalescer interface which
10 // is used as the common interface used by all clients and
11 // implementations of register coalescing.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "RegisterCoalescer.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/LiveInterval.h"
25 #include "llvm/CodeGen/LiveIntervals.h"
26 #include "llvm/CodeGen/LiveRangeEdit.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/RegisterClassInfo.h"
37 #include "llvm/CodeGen/SlotIndexes.h"
38 #include "llvm/CodeGen/TargetInstrInfo.h"
39 #include "llvm/CodeGen/TargetOpcodes.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/InitializePasses.h"
44 #include "llvm/MC/LaneBitmask.h"
45 #include "llvm/MC/MCInstrDesc.h"
46 #include "llvm/MC/MCRegisterInfo.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <iterator>
56 #include <limits>
57 #include <tuple>
58 #include <utility>
59 #include <vector>
60 
61 using namespace llvm;
62 
63 #define DEBUG_TYPE "regalloc"
64 
65 STATISTIC(numJoins    , "Number of interval joins performed");
66 STATISTIC(numCrossRCs , "Number of cross class joins performed");
67 STATISTIC(numCommutes , "Number of instruction commuting performed");
68 STATISTIC(numExtends  , "Number of copies extended");
69 STATISTIC(NumReMats   , "Number of instructions re-materialized");
70 STATISTIC(NumInflated , "Number of register classes inflated");
71 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
72 STATISTIC(NumLaneResolves,  "Number of dead lane conflicts resolved");
73 STATISTIC(NumShrinkToUses,  "Number of shrinkToUses called");
74 
75 static cl::opt<bool> EnableJoining("join-liveintervals",
76                                    cl::desc("Coalesce copies (default=true)"),
77                                    cl::init(true), cl::Hidden);
78 
79 static cl::opt<bool> UseTerminalRule("terminal-rule",
80                                      cl::desc("Apply the terminal rule"),
81                                      cl::init(false), cl::Hidden);
82 
83 /// Temporary flag to test critical edge unsplitting.
84 static cl::opt<bool>
85 EnableJoinSplits("join-splitedges",
86   cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
87 
88 /// Temporary flag to test global copy optimization.
89 static cl::opt<cl::boolOrDefault>
90 EnableGlobalCopies("join-globalcopies",
91   cl::desc("Coalesce copies that span blocks (default=subtarget)"),
92   cl::init(cl::BOU_UNSET), cl::Hidden);
93 
94 static cl::opt<bool>
95 VerifyCoalescing("verify-coalescing",
96          cl::desc("Verify machine instrs before and after register coalescing"),
97          cl::Hidden);
98 
99 static cl::opt<unsigned> LateRematUpdateThreshold(
100     "late-remat-update-threshold", cl::Hidden,
101     cl::desc("During rematerialization for a copy, if the def instruction has "
102              "many other copy uses to be rematerialized, delay the multiple "
103              "separate live interval update work and do them all at once after "
104              "all those rematerialization are done. It will save a lot of "
105              "repeated work. "),
106     cl::init(100));
107 
108 static cl::opt<unsigned> LargeIntervalSizeThreshold(
109     "large-interval-size-threshold", cl::Hidden,
110     cl::desc("If the valnos size of an interval is larger than the threshold, "
111              "it is regarded as a large interval. "),
112     cl::init(100));
113 
114 static cl::opt<unsigned> LargeIntervalFreqThreshold(
115     "large-interval-freq-threshold", cl::Hidden,
116     cl::desc("For a large interval, if it is coalesed with other live "
117              "intervals many times more than the threshold, stop its "
118              "coalescing to control the compile time. "),
119     cl::init(100));
120 
121 namespace {
122 
123   class JoinVals;
124 
125   class RegisterCoalescer : public MachineFunctionPass,
126                             private LiveRangeEdit::Delegate {
127     MachineFunction* MF = nullptr;
128     MachineRegisterInfo* MRI = nullptr;
129     const TargetRegisterInfo* TRI = nullptr;
130     const TargetInstrInfo* TII = nullptr;
131     LiveIntervals *LIS = nullptr;
132     const MachineLoopInfo* Loops = nullptr;
133     AliasAnalysis *AA = nullptr;
134     RegisterClassInfo RegClassInfo;
135 
136     /// Debug variable location tracking -- for each VReg, maintain an
137     /// ordered-by-slot-index set of DBG_VALUEs, to help quick
138     /// identification of whether coalescing may change location validity.
139     using DbgValueLoc = std::pair<SlotIndex, MachineInstr*>;
140     DenseMap<unsigned, std::vector<DbgValueLoc>> DbgVRegToValues;
141 
142     /// VRegs may be repeatedly coalesced, and have many DBG_VALUEs attached.
143     /// To avoid repeatedly merging sets of DbgValueLocs, instead record
144     /// which vregs have been coalesced, and where to. This map is from
145     /// vreg => {set of vregs merged in}.
146     DenseMap<unsigned, SmallVector<unsigned, 4>> DbgMergedVRegNums;
147 
148     /// A LaneMask to remember on which subregister live ranges we need to call
149     /// shrinkToUses() later.
150     LaneBitmask ShrinkMask;
151 
152     /// True if the main range of the currently coalesced intervals should be
153     /// checked for smaller live intervals.
154     bool ShrinkMainRange = false;
155 
156     /// True if the coalescer should aggressively coalesce global copies
157     /// in favor of keeping local copies.
158     bool JoinGlobalCopies = false;
159 
160     /// True if the coalescer should aggressively coalesce fall-thru
161     /// blocks exclusively containing copies.
162     bool JoinSplitEdges = false;
163 
164     /// Copy instructions yet to be coalesced.
165     SmallVector<MachineInstr*, 8> WorkList;
166     SmallVector<MachineInstr*, 8> LocalWorkList;
167 
168     /// Set of instruction pointers that have been erased, and
169     /// that may be present in WorkList.
170     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
171 
172     /// Dead instructions that are about to be deleted.
173     SmallVector<MachineInstr*, 8> DeadDefs;
174 
175     /// Virtual registers to be considered for register class inflation.
176     SmallVector<unsigned, 8> InflateRegs;
177 
178     /// The collection of live intervals which should have been updated
179     /// immediately after rematerialiation but delayed until
180     /// lateLiveIntervalUpdate is called.
181     DenseSet<unsigned> ToBeUpdated;
182 
183     /// Record how many times the large live interval with many valnos
184     /// has been tried to join with other live interval.
185     DenseMap<unsigned, unsigned long> LargeLIVisitCounter;
186 
187     /// Recursively eliminate dead defs in DeadDefs.
188     void eliminateDeadDefs();
189 
190     /// LiveRangeEdit callback for eliminateDeadDefs().
191     void LRE_WillEraseInstruction(MachineInstr *MI) override;
192 
193     /// Coalesce the LocalWorkList.
194     void coalesceLocals();
195 
196     /// Join compatible live intervals
197     void joinAllIntervals();
198 
199     /// Coalesce copies in the specified MBB, putting
200     /// copies that cannot yet be coalesced into WorkList.
201     void copyCoalesceInMBB(MachineBasicBlock *MBB);
202 
203     /// Tries to coalesce all copies in CurrList. Returns true if any progress
204     /// was made.
205     bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
206 
207     /// If one def has many copy like uses, and those copy uses are all
208     /// rematerialized, the live interval update needed for those
209     /// rematerializations will be delayed and done all at once instead
210     /// of being done multiple times. This is to save compile cost because
211     /// live interval update is costly.
212     void lateLiveIntervalUpdate();
213 
214     /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
215     /// src/dst of the copy instruction CopyMI.  This returns true if the copy
216     /// was successfully coalesced away. If it is not currently possible to
217     /// coalesce this interval, but it may be possible if other things get
218     /// coalesced, then it returns true by reference in 'Again'.
219     bool joinCopy(MachineInstr *CopyMI, bool &Again);
220 
221     /// Attempt to join these two intervals.  On failure, this
222     /// returns false.  The output "SrcInt" will not have been modified, so we
223     /// can use this information below to update aliases.
224     bool joinIntervals(CoalescerPair &CP);
225 
226     /// Attempt joining two virtual registers. Return true on success.
227     bool joinVirtRegs(CoalescerPair &CP);
228 
229     /// If a live interval has many valnos and is coalesced with other
230     /// live intervals many times, we regard such live interval as having
231     /// high compile time cost.
232     bool isHighCostLiveInterval(LiveInterval &LI);
233 
234     /// Attempt joining with a reserved physreg.
235     bool joinReservedPhysReg(CoalescerPair &CP);
236 
237     /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
238     /// Subranges in @p LI which only partially interfere with the desired
239     /// LaneMask are split as necessary. @p LaneMask are the lanes that
240     /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
241     /// lanemasks already adjusted to the coalesced register.
242     void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
243                            LaneBitmask LaneMask, CoalescerPair &CP,
244                            unsigned DstIdx);
245 
246     /// Join the liveranges of two subregisters. Joins @p RRange into
247     /// @p LRange, @p RRange may be invalid afterwards.
248     void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
249                           LaneBitmask LaneMask, const CoalescerPair &CP);
250 
251     /// We found a non-trivially-coalescable copy. If the source value number is
252     /// defined by a copy from the destination reg see if we can merge these two
253     /// destination reg valno# into a single value number, eliminating a copy.
254     /// This returns true if an interval was modified.
255     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
256 
257     /// Return true if there are definitions of IntB
258     /// other than BValNo val# that can reach uses of AValno val# of IntA.
259     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
260                               VNInfo *AValNo, VNInfo *BValNo);
261 
262     /// We found a non-trivially-coalescable copy.
263     /// If the source value number is defined by a commutable instruction and
264     /// its other operand is coalesced to the copy dest register, see if we
265     /// can transform the copy into a noop by commuting the definition.
266     /// This returns a pair of two flags:
267     /// - the first element is true if an interval was modified,
268     /// - the second element is true if the destination interval needs
269     ///   to be shrunk after deleting the copy.
270     std::pair<bool,bool> removeCopyByCommutingDef(const CoalescerPair &CP,
271                                                   MachineInstr *CopyMI);
272 
273     /// We found a copy which can be moved to its less frequent predecessor.
274     bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
275 
276     /// If the source of a copy is defined by a
277     /// trivial computation, replace the copy by rematerialize the definition.
278     bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
279                                  bool &IsDefCopy);
280 
281     /// Return true if a copy involving a physreg should be joined.
282     bool canJoinPhys(const CoalescerPair &CP);
283 
284     /// Replace all defs and uses of SrcReg to DstReg and update the subregister
285     /// number if it is not zero. If DstReg is a physical register and the
286     /// existing subregister number of the def / use being updated is not zero,
287     /// make sure to set it to the correct physical subregister.
288     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
289 
290     /// If the given machine operand reads only undefined lanes add an undef
291     /// flag.
292     /// This can happen when undef uses were previously concealed by a copy
293     /// which we coalesced. Example:
294     ///    %0:sub0<def,read-undef> = ...
295     ///    %1 = COPY %0           <-- Coalescing COPY reveals undef
296     ///       = use %1:sub1       <-- hidden undef use
297     void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
298                       MachineOperand &MO, unsigned SubRegIdx);
299 
300     /// Handle copies of undef values. If the undef value is an incoming
301     /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF.
302     /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise,
303     /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point).
304     MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI);
305 
306     /// Check whether or not we should apply the terminal rule on the
307     /// destination (Dst) of \p Copy.
308     /// When the terminal rule applies, Copy is not profitable to
309     /// coalesce.
310     /// Dst is terminal if it has exactly one affinity (Dst, Src) and
311     /// at least one interference (Dst, Dst2). If Dst is terminal, the
312     /// terminal rule consists in checking that at least one of
313     /// interfering node, say Dst2, has an affinity of equal or greater
314     /// weight with Src.
315     /// In that case, Dst2 and Dst will not be able to be both coalesced
316     /// with Src. Since Dst2 exposes more coalescing opportunities than
317     /// Dst, we can drop \p Copy.
318     bool applyTerminalRule(const MachineInstr &Copy) const;
319 
320     /// Wrapper method for \see LiveIntervals::shrinkToUses.
321     /// This method does the proper fixing of the live-ranges when the afore
322     /// mentioned method returns true.
323     void shrinkToUses(LiveInterval *LI,
324                       SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
325       NumShrinkToUses++;
326       if (LIS->shrinkToUses(LI, Dead)) {
327         /// Check whether or not \p LI is composed by multiple connected
328         /// components and if that is the case, fix that.
329         SmallVector<LiveInterval*, 8> SplitLIs;
330         LIS->splitSeparateComponents(*LI, SplitLIs);
331       }
332     }
333 
334     /// Wrapper Method to do all the necessary work when an Instruction is
335     /// deleted.
336     /// Optimizations should use this to make sure that deleted instructions
337     /// are always accounted for.
338     void deleteInstr(MachineInstr* MI) {
339       ErasedInstrs.insert(MI);
340       LIS->RemoveMachineInstrFromMaps(*MI);
341       MI->eraseFromParent();
342     }
343 
344     /// Walk over function and initialize the DbgVRegToValues map.
345     void buildVRegToDbgValueMap(MachineFunction &MF);
346 
347     /// Test whether, after merging, any DBG_VALUEs would refer to a
348     /// different value number than before merging, and whether this can
349     /// be resolved. If not, mark the DBG_VALUE as being undef.
350     void checkMergingChangesDbgValues(CoalescerPair &CP, LiveRange &LHS,
351                                       JoinVals &LHSVals, LiveRange &RHS,
352                                       JoinVals &RHSVals);
353 
354     void checkMergingChangesDbgValuesImpl(unsigned Reg, LiveRange &OtherRange,
355                                           LiveRange &RegRange, JoinVals &Vals2);
356 
357   public:
358     static char ID; ///< Class identification, replacement for typeinfo
359 
360     RegisterCoalescer() : MachineFunctionPass(ID) {
361       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
362     }
363 
364     void getAnalysisUsage(AnalysisUsage &AU) const override;
365 
366     void releaseMemory() override;
367 
368     /// This is the pass entry point.
369     bool runOnMachineFunction(MachineFunction&) override;
370 
371     /// Implement the dump method.
372     void print(raw_ostream &O, const Module* = nullptr) const override;
373   };
374 
375 } // end anonymous namespace
376 
377 char RegisterCoalescer::ID = 0;
378 
379 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
380 
381 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
382                       "Simple Register Coalescing", false, false)
383 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
384 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
385 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
386 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
387 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
388                     "Simple Register Coalescing", false, false)
389 
390 LLVM_NODISCARD static bool isMoveInstr(const TargetRegisterInfo &tri,
391                                        const MachineInstr *MI, unsigned &Src,
392                                        unsigned &Dst, unsigned &SrcSub,
393                                        unsigned &DstSub) {
394   if (MI->isCopy()) {
395     Dst = MI->getOperand(0).getReg();
396     DstSub = MI->getOperand(0).getSubReg();
397     Src = MI->getOperand(1).getReg();
398     SrcSub = MI->getOperand(1).getSubReg();
399   } else if (MI->isSubregToReg()) {
400     Dst = MI->getOperand(0).getReg();
401     DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
402                                       MI->getOperand(3).getImm());
403     Src = MI->getOperand(2).getReg();
404     SrcSub = MI->getOperand(2).getSubReg();
405   } else
406     return false;
407   return true;
408 }
409 
410 /// Return true if this block should be vacated by the coalescer to eliminate
411 /// branches. The important cases to handle in the coalescer are critical edges
412 /// split during phi elimination which contain only copies. Simple blocks that
413 /// contain non-branches should also be vacated, but this can be handled by an
414 /// earlier pass similar to early if-conversion.
415 static bool isSplitEdge(const MachineBasicBlock *MBB) {
416   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
417     return false;
418 
419   for (const auto &MI : *MBB) {
420     if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
421       return false;
422   }
423   return true;
424 }
425 
426 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
427   SrcReg = DstReg = 0;
428   SrcIdx = DstIdx = 0;
429   NewRC = nullptr;
430   Flipped = CrossClass = false;
431 
432   unsigned Src, Dst, SrcSub, DstSub;
433   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
434     return false;
435   Partial = SrcSub || DstSub;
436 
437   // If one register is a physreg, it must be Dst.
438   if (Register::isPhysicalRegister(Src)) {
439     if (Register::isPhysicalRegister(Dst))
440       return false;
441     std::swap(Src, Dst);
442     std::swap(SrcSub, DstSub);
443     Flipped = true;
444   }
445 
446   const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
447 
448   if (Register::isPhysicalRegister(Dst)) {
449     // Eliminate DstSub on a physreg.
450     if (DstSub) {
451       Dst = TRI.getSubReg(Dst, DstSub);
452       if (!Dst) return false;
453       DstSub = 0;
454     }
455 
456     // Eliminate SrcSub by picking a corresponding Dst superregister.
457     if (SrcSub) {
458       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
459       if (!Dst) return false;
460     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
461       return false;
462     }
463   } else {
464     // Both registers are virtual.
465     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
466     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
467 
468     // Both registers have subreg indices.
469     if (SrcSub && DstSub) {
470       // Copies between different sub-registers are never coalescable.
471       if (Src == Dst && SrcSub != DstSub)
472         return false;
473 
474       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
475                                          SrcIdx, DstIdx);
476       if (!NewRC)
477         return false;
478     } else if (DstSub) {
479       // SrcReg will be merged with a sub-register of DstReg.
480       SrcIdx = DstSub;
481       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
482     } else if (SrcSub) {
483       // DstReg will be merged with a sub-register of SrcReg.
484       DstIdx = SrcSub;
485       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
486     } else {
487       // This is a straight copy without sub-registers.
488       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
489     }
490 
491     // The combined constraint may be impossible to satisfy.
492     if (!NewRC)
493       return false;
494 
495     // Prefer SrcReg to be a sub-register of DstReg.
496     // FIXME: Coalescer should support subregs symmetrically.
497     if (DstIdx && !SrcIdx) {
498       std::swap(Src, Dst);
499       std::swap(SrcIdx, DstIdx);
500       Flipped = !Flipped;
501     }
502 
503     CrossClass = NewRC != DstRC || NewRC != SrcRC;
504   }
505   // Check our invariants
506   assert(Register::isVirtualRegister(Src) && "Src must be virtual");
507   assert(!(Register::isPhysicalRegister(Dst) && DstSub) &&
508          "Cannot have a physical SubIdx");
509   SrcReg = Src;
510   DstReg = Dst;
511   return true;
512 }
513 
514 bool CoalescerPair::flip() {
515   if (Register::isPhysicalRegister(DstReg))
516     return false;
517   std::swap(SrcReg, DstReg);
518   std::swap(SrcIdx, DstIdx);
519   Flipped = !Flipped;
520   return true;
521 }
522 
523 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
524   if (!MI)
525     return false;
526   unsigned Src, Dst, SrcSub, DstSub;
527   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
528     return false;
529 
530   // Find the virtual register that is SrcReg.
531   if (Dst == SrcReg) {
532     std::swap(Src, Dst);
533     std::swap(SrcSub, DstSub);
534   } else if (Src != SrcReg) {
535     return false;
536   }
537 
538   // Now check that Dst matches DstReg.
539   if (Register::isPhysicalRegister(DstReg)) {
540     if (!Register::isPhysicalRegister(Dst))
541       return false;
542     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
543     // DstSub could be set for a physreg from INSERT_SUBREG.
544     if (DstSub)
545       Dst = TRI.getSubReg(Dst, DstSub);
546     // Full copy of Src.
547     if (!SrcSub)
548       return DstReg == Dst;
549     // This is a partial register copy. Check that the parts match.
550     return TRI.getSubReg(DstReg, SrcSub) == Dst;
551   } else {
552     // DstReg is virtual.
553     if (DstReg != Dst)
554       return false;
555     // Registers match, do the subregisters line up?
556     return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
557            TRI.composeSubRegIndices(DstIdx, DstSub);
558   }
559 }
560 
561 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
562   AU.setPreservesCFG();
563   AU.addRequired<AAResultsWrapperPass>();
564   AU.addRequired<LiveIntervals>();
565   AU.addPreserved<LiveIntervals>();
566   AU.addPreserved<SlotIndexes>();
567   AU.addRequired<MachineLoopInfo>();
568   AU.addPreserved<MachineLoopInfo>();
569   AU.addPreservedID(MachineDominatorsID);
570   MachineFunctionPass::getAnalysisUsage(AU);
571 }
572 
573 void RegisterCoalescer::eliminateDeadDefs() {
574   SmallVector<unsigned, 8> NewRegs;
575   LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
576                 nullptr, this).eliminateDeadDefs(DeadDefs);
577 }
578 
579 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
580   // MI may be in WorkList. Make sure we don't visit it.
581   ErasedInstrs.insert(MI);
582 }
583 
584 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
585                                              MachineInstr *CopyMI) {
586   assert(!CP.isPartial() && "This doesn't work for partial copies.");
587   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
588 
589   LiveInterval &IntA =
590     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
591   LiveInterval &IntB =
592     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
593   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
594 
595   // We have a non-trivially-coalescable copy with IntA being the source and
596   // IntB being the dest, thus this defines a value number in IntB.  If the
597   // source value number (in IntA) is defined by a copy from B, see if we can
598   // merge these two pieces of B into a single value number, eliminating a copy.
599   // For example:
600   //
601   //  A3 = B0
602   //    ...
603   //  B1 = A3      <- this copy
604   //
605   // In this case, B0 can be extended to where the B1 copy lives, allowing the
606   // B1 value number to be replaced with B0 (which simplifies the B
607   // liveinterval).
608 
609   // BValNo is a value number in B that is defined by a copy from A.  'B1' in
610   // the example above.
611   LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
612   if (BS == IntB.end()) return false;
613   VNInfo *BValNo = BS->valno;
614 
615   // Get the location that B is defined at.  Two options: either this value has
616   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
617   // can't process it.
618   if (BValNo->def != CopyIdx) return false;
619 
620   // AValNo is the value number in A that defines the copy, A3 in the example.
621   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
622   LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
623   // The live segment might not exist after fun with physreg coalescing.
624   if (AS == IntA.end()) return false;
625   VNInfo *AValNo = AS->valno;
626 
627   // If AValNo is defined as a copy from IntB, we can potentially process this.
628   // Get the instruction that defines this value number.
629   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
630   // Don't allow any partial copies, even if isCoalescable() allows them.
631   if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
632     return false;
633 
634   // Get the Segment in IntB that this value number starts with.
635   LiveInterval::iterator ValS =
636     IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
637   if (ValS == IntB.end())
638     return false;
639 
640   // Make sure that the end of the live segment is inside the same block as
641   // CopyMI.
642   MachineInstr *ValSEndInst =
643     LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
644   if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
645     return false;
646 
647   // Okay, we now know that ValS ends in the same block that the CopyMI
648   // live-range starts.  If there are no intervening live segments between them
649   // in IntB, we can merge them.
650   if (ValS+1 != BS) return false;
651 
652   LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg, TRI));
653 
654   SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
655   // We are about to delete CopyMI, so need to remove it as the 'instruction
656   // that defines this value #'. Update the valnum with the new defining
657   // instruction #.
658   BValNo->def = FillerStart;
659 
660   // Okay, we can merge them.  We need to insert a new liverange:
661   // [ValS.end, BS.begin) of either value number, then we merge the
662   // two value numbers.
663   IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
664 
665   // Okay, merge "B1" into the same value number as "B0".
666   if (BValNo != ValS->valno)
667     IntB.MergeValueNumberInto(BValNo, ValS->valno);
668 
669   // Do the same for the subregister segments.
670   for (LiveInterval::SubRange &S : IntB.subranges()) {
671     // Check for SubRange Segments of the form [1234r,1234d:0) which can be
672     // removed to prevent creating bogus SubRange Segments.
673     LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx);
674     if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) {
675       S.removeSegment(*SS, true);
676       continue;
677     }
678     // The subrange may have ended before FillerStart. If so, extend it.
679     if (!S.getVNInfoAt(FillerStart)) {
680       SlotIndex BBStart =
681           LIS->getMBBStartIdx(LIS->getMBBFromIndex(FillerStart));
682       S.extendInBlock(BBStart, FillerStart);
683     }
684     VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
685     S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
686     VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
687     if (SubBValNo != SubValSNo)
688       S.MergeValueNumberInto(SubBValNo, SubValSNo);
689   }
690 
691   LLVM_DEBUG(dbgs() << "   result = " << IntB << '\n');
692 
693   // If the source instruction was killing the source register before the
694   // merge, unset the isKill marker given the live range has been extended.
695   int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
696   if (UIdx != -1) {
697     ValSEndInst->getOperand(UIdx).setIsKill(false);
698   }
699 
700   // Rewrite the copy.
701   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
702   // If the copy instruction was killing the destination register or any
703   // subrange before the merge trim the live range.
704   bool RecomputeLiveRange = AS->end == CopyIdx;
705   if (!RecomputeLiveRange) {
706     for (LiveInterval::SubRange &S : IntA.subranges()) {
707       LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx);
708       if (SS != S.end() && SS->end == CopyIdx) {
709         RecomputeLiveRange = true;
710         break;
711       }
712     }
713   }
714   if (RecomputeLiveRange)
715     shrinkToUses(&IntA);
716 
717   ++numExtends;
718   return true;
719 }
720 
721 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
722                                              LiveInterval &IntB,
723                                              VNInfo *AValNo,
724                                              VNInfo *BValNo) {
725   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
726   // the PHI values.
727   if (LIS->hasPHIKill(IntA, AValNo))
728     return true;
729 
730   for (LiveRange::Segment &ASeg : IntA.segments) {
731     if (ASeg.valno != AValNo) continue;
732     LiveInterval::iterator BI = llvm::upper_bound(IntB, ASeg.start);
733     if (BI != IntB.begin())
734       --BI;
735     for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
736       if (BI->valno == BValNo)
737         continue;
738       if (BI->start <= ASeg.start && BI->end > ASeg.start)
739         return true;
740       if (BI->start > ASeg.start && BI->start < ASeg.end)
741         return true;
742     }
743   }
744   return false;
745 }
746 
747 /// Copy segments with value number @p SrcValNo from liverange @p Src to live
748 /// range @Dst and use value number @p DstValNo there.
749 static std::pair<bool,bool>
750 addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src,
751                      const VNInfo *SrcValNo) {
752   bool Changed = false;
753   bool MergedWithDead = false;
754   for (const LiveRange::Segment &S : Src.segments) {
755     if (S.valno != SrcValNo)
756       continue;
757     // This is adding a segment from Src that ends in a copy that is about
758     // to be removed. This segment is going to be merged with a pre-existing
759     // segment in Dst. This works, except in cases when the corresponding
760     // segment in Dst is dead. For example: adding [192r,208r:1) from Src
761     // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst.
762     // Recognized such cases, so that the segments can be shrunk.
763     LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo);
764     LiveRange::Segment &Merged = *Dst.addSegment(Added);
765     if (Merged.end.isDead())
766       MergedWithDead = true;
767     Changed = true;
768   }
769   return std::make_pair(Changed, MergedWithDead);
770 }
771 
772 std::pair<bool,bool>
773 RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
774                                             MachineInstr *CopyMI) {
775   assert(!CP.isPhys());
776 
777   LiveInterval &IntA =
778       LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
779   LiveInterval &IntB =
780       LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
781 
782   // We found a non-trivially-coalescable copy with IntA being the source and
783   // IntB being the dest, thus this defines a value number in IntB.  If the
784   // source value number (in IntA) is defined by a commutable instruction and
785   // its other operand is coalesced to the copy dest register, see if we can
786   // transform the copy into a noop by commuting the definition. For example,
787   //
788   //  A3 = op A2 killed B0
789   //    ...
790   //  B1 = A3      <- this copy
791   //    ...
792   //     = op A3   <- more uses
793   //
794   // ==>
795   //
796   //  B2 = op B0 killed A2
797   //    ...
798   //  B1 = B2      <- now an identity copy
799   //    ...
800   //     = op B2   <- more uses
801 
802   // BValNo is a value number in B that is defined by a copy from A. 'B1' in
803   // the example above.
804   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
805   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
806   assert(BValNo != nullptr && BValNo->def == CopyIdx);
807 
808   // AValNo is the value number in A that defines the copy, A3 in the example.
809   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
810   assert(AValNo && !AValNo->isUnused() && "COPY source not live");
811   if (AValNo->isPHIDef())
812     return { false, false };
813   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
814   if (!DefMI)
815     return { false, false };
816   if (!DefMI->isCommutable())
817     return { false, false };
818   // If DefMI is a two-address instruction then commuting it will change the
819   // destination register.
820   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
821   assert(DefIdx != -1);
822   unsigned UseOpIdx;
823   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
824     return { false, false };
825 
826   // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
827   // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
828   // passed to the method. That _other_ operand is chosen by
829   // the findCommutedOpIndices() method.
830   //
831   // That is obviously an area for improvement in case of instructions having
832   // more than 2 operands. For example, if some instruction has 3 commutable
833   // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
834   // op#2<->op#3) of commute transformation should be considered/tried here.
835   unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
836   if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
837     return { false, false };
838 
839   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
840   Register NewReg = NewDstMO.getReg();
841   if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
842     return { false, false };
843 
844   // Make sure there are no other definitions of IntB that would reach the
845   // uses which the new definition can reach.
846   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
847     return { false, false };
848 
849   // If some of the uses of IntA.reg is already coalesced away, return false.
850   // It's not possible to determine whether it's safe to perform the coalescing.
851   for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
852     MachineInstr *UseMI = MO.getParent();
853     unsigned OpNo = &MO - &UseMI->getOperand(0);
854     SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
855     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
856     if (US == IntA.end() || US->valno != AValNo)
857       continue;
858     // If this use is tied to a def, we can't rewrite the register.
859     if (UseMI->isRegTiedToDefOperand(OpNo))
860       return { false, false };
861   }
862 
863   LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
864                     << *DefMI);
865 
866   // At this point we have decided that it is legal to do this
867   // transformation.  Start by commuting the instruction.
868   MachineBasicBlock *MBB = DefMI->getParent();
869   MachineInstr *NewMI =
870       TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
871   if (!NewMI)
872     return { false, false };
873   if (Register::isVirtualRegister(IntA.reg) &&
874       Register::isVirtualRegister(IntB.reg) &&
875       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
876     return { false, false };
877   if (NewMI != DefMI) {
878     LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
879     MachineBasicBlock::iterator Pos = DefMI;
880     MBB->insert(Pos, NewMI);
881     MBB->erase(DefMI);
882   }
883 
884   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
885   // A = or A, B
886   // ...
887   // B = A
888   // ...
889   // C = killed A
890   // ...
891   //   = B
892 
893   // Update uses of IntA of the specific Val# with IntB.
894   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
895                                          UE = MRI->use_end();
896        UI != UE; /* ++UI is below because of possible MI removal */) {
897     MachineOperand &UseMO = *UI;
898     ++UI;
899     if (UseMO.isUndef())
900       continue;
901     MachineInstr *UseMI = UseMO.getParent();
902     if (UseMI->isDebugValue()) {
903       // FIXME These don't have an instruction index.  Not clear we have enough
904       // info to decide whether to do this replacement or not.  For now do it.
905       UseMO.setReg(NewReg);
906       continue;
907     }
908     SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
909     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
910     assert(US != IntA.end() && "Use must be live");
911     if (US->valno != AValNo)
912       continue;
913     // Kill flags are no longer accurate. They are recomputed after RA.
914     UseMO.setIsKill(false);
915     if (Register::isPhysicalRegister(NewReg))
916       UseMO.substPhysReg(NewReg, *TRI);
917     else
918       UseMO.setReg(NewReg);
919     if (UseMI == CopyMI)
920       continue;
921     if (!UseMI->isCopy())
922       continue;
923     if (UseMI->getOperand(0).getReg() != IntB.reg ||
924         UseMI->getOperand(0).getSubReg())
925       continue;
926 
927     // This copy will become a noop. If it's defining a new val#, merge it into
928     // BValNo.
929     SlotIndex DefIdx = UseIdx.getRegSlot();
930     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
931     if (!DVNI)
932       continue;
933     LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
934     assert(DVNI->def == DefIdx);
935     BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
936     for (LiveInterval::SubRange &S : IntB.subranges()) {
937       VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
938       if (!SubDVNI)
939         continue;
940       VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
941       assert(SubBValNo->def == CopyIdx);
942       S.MergeValueNumberInto(SubDVNI, SubBValNo);
943     }
944 
945     deleteInstr(UseMI);
946   }
947 
948   // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
949   // is updated.
950   bool ShrinkB = false;
951   BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
952   if (IntA.hasSubRanges() || IntB.hasSubRanges()) {
953     if (!IntA.hasSubRanges()) {
954       LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
955       IntA.createSubRangeFrom(Allocator, Mask, IntA);
956     } else if (!IntB.hasSubRanges()) {
957       LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntB.reg);
958       IntB.createSubRangeFrom(Allocator, Mask, IntB);
959     }
960     SlotIndex AIdx = CopyIdx.getRegSlot(true);
961     LaneBitmask MaskA;
962     const SlotIndexes &Indexes = *LIS->getSlotIndexes();
963     for (LiveInterval::SubRange &SA : IntA.subranges()) {
964       VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
965       // Even if we are dealing with a full copy, some lanes can
966       // still be undefined.
967       // E.g.,
968       // undef A.subLow = ...
969       // B = COPY A <== A.subHigh is undefined here and does
970       //                not have a value number.
971       if (!ASubValNo)
972         continue;
973       MaskA |= SA.LaneMask;
974 
975       IntB.refineSubRanges(
976           Allocator, SA.LaneMask,
977           [&Allocator, &SA, CopyIdx, ASubValNo,
978            &ShrinkB](LiveInterval::SubRange &SR) {
979             VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator)
980                                            : SR.getVNInfoAt(CopyIdx);
981             assert(BSubValNo != nullptr);
982             auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
983             ShrinkB |= P.second;
984             if (P.first)
985               BSubValNo->def = ASubValNo->def;
986           },
987           Indexes, *TRI);
988     }
989     // Go over all subranges of IntB that have not been covered by IntA,
990     // and delete the segments starting at CopyIdx. This can happen if
991     // IntA has undef lanes that are defined in IntB.
992     for (LiveInterval::SubRange &SB : IntB.subranges()) {
993       if ((SB.LaneMask & MaskA).any())
994         continue;
995       if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx))
996         if (S->start.getBaseIndex() == CopyIdx.getBaseIndex())
997           SB.removeSegment(*S, true);
998     }
999   }
1000 
1001   BValNo->def = AValNo->def;
1002   auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
1003   ShrinkB |= P.second;
1004   LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
1005 
1006   LIS->removeVRegDefAt(IntA, AValNo->def);
1007 
1008   LLVM_DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
1009   ++numCommutes;
1010   return { true, ShrinkB };
1011 }
1012 
1013 /// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
1014 /// predecessor of BB2, and if B is not redefined on the way from A = B
1015 /// in BB0 to B = A in BB2, B = A in BB2 is partially redundant if the
1016 /// execution goes through the path from BB0 to BB2. We may move B = A
1017 /// to the predecessor without such reversed copy.
1018 /// So we will transform the program from:
1019 ///   BB0:
1020 ///      A = B;    BB1:
1021 ///       ...         ...
1022 ///     /     \      /
1023 ///             BB2:
1024 ///               ...
1025 ///               B = A;
1026 ///
1027 /// to:
1028 ///
1029 ///   BB0:         BB1:
1030 ///      A = B;        ...
1031 ///       ...          B = A;
1032 ///     /     \       /
1033 ///             BB2:
1034 ///               ...
1035 ///
1036 /// A special case is when BB0 and BB2 are the same BB which is the only
1037 /// BB in a loop:
1038 ///   BB1:
1039 ///        ...
1040 ///   BB0/BB2:  ----
1041 ///        B = A;   |
1042 ///        ...      |
1043 ///        A = B;   |
1044 ///          |-------
1045 ///          |
1046 /// We may hoist B = A from BB0/BB2 to BB1.
1047 ///
1048 /// The major preconditions for correctness to remove such partial
1049 /// redundancy include:
1050 /// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
1051 ///    the PHI is defined by the reversed copy A = B in BB0.
1052 /// 2. No B is referenced from the start of BB2 to B = A.
1053 /// 3. No B is defined from A = B to the end of BB0.
1054 /// 4. BB1 has only one successor.
1055 ///
1056 /// 2 and 4 implicitly ensure B is not live at the end of BB1.
1057 /// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
1058 /// colder place, which not only prevent endless loop, but also make sure
1059 /// the movement of copy is beneficial.
1060 bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
1061                                                 MachineInstr &CopyMI) {
1062   assert(!CP.isPhys());
1063   if (!CopyMI.isFullCopy())
1064     return false;
1065 
1066   MachineBasicBlock &MBB = *CopyMI.getParent();
1067   if (MBB.isEHPad())
1068     return false;
1069 
1070   if (MBB.pred_size() != 2)
1071     return false;
1072 
1073   LiveInterval &IntA =
1074       LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
1075   LiveInterval &IntB =
1076       LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
1077 
1078   // A is defined by PHI at the entry of MBB.
1079   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
1080   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
1081   assert(AValNo && !AValNo->isUnused() && "COPY source not live");
1082   if (!AValNo->isPHIDef())
1083     return false;
1084 
1085   // No B is referenced before CopyMI in MBB.
1086   if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
1087     return false;
1088 
1089   // MBB has two predecessors: one contains A = B so no copy will be inserted
1090   // for it. The other one will have a copy moved from MBB.
1091   bool FoundReverseCopy = false;
1092   MachineBasicBlock *CopyLeftBB = nullptr;
1093   for (MachineBasicBlock *Pred : MBB.predecessors()) {
1094     VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
1095     MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def);
1096     if (!DefMI || !DefMI->isFullCopy()) {
1097       CopyLeftBB = Pred;
1098       continue;
1099     }
1100     // Check DefMI is a reverse copy and it is in BB Pred.
1101     if (DefMI->getOperand(0).getReg() != IntA.reg ||
1102         DefMI->getOperand(1).getReg() != IntB.reg ||
1103         DefMI->getParent() != Pred) {
1104       CopyLeftBB = Pred;
1105       continue;
1106     }
1107     // If there is any other def of B after DefMI and before the end of Pred,
1108     // we need to keep the copy of B = A at the end of Pred if we remove
1109     // B = A from MBB.
1110     bool ValB_Changed = false;
1111     for (auto VNI : IntB.valnos) {
1112       if (VNI->isUnused())
1113         continue;
1114       if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
1115         ValB_Changed = true;
1116         break;
1117       }
1118     }
1119     if (ValB_Changed) {
1120       CopyLeftBB = Pred;
1121       continue;
1122     }
1123     FoundReverseCopy = true;
1124   }
1125 
1126   // If no reverse copy is found in predecessors, nothing to do.
1127   if (!FoundReverseCopy)
1128     return false;
1129 
1130   // If CopyLeftBB is nullptr, it means every predecessor of MBB contains
1131   // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
1132   // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
1133   // update IntA/IntB.
1134   //
1135   // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
1136   // MBB is hotter than CopyLeftBB.
1137   if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
1138     return false;
1139 
1140   // Now (almost sure it's) ok to move copy.
1141   if (CopyLeftBB) {
1142     // Position in CopyLeftBB where we should insert new copy.
1143     auto InsPos = CopyLeftBB->getFirstTerminator();
1144 
1145     // Make sure that B isn't referenced in the terminators (if any) at the end
1146     // of the predecessor since we're about to insert a new definition of B
1147     // before them.
1148     if (InsPos != CopyLeftBB->end()) {
1149       SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true);
1150       if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB)))
1151         return false;
1152     }
1153 
1154     LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "
1155                       << printMBBReference(*CopyLeftBB) << '\t' << CopyMI);
1156 
1157     // Insert new copy to CopyLeftBB.
1158     MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
1159                                       TII->get(TargetOpcode::COPY), IntB.reg)
1160                                   .addReg(IntA.reg);
1161     SlotIndex NewCopyIdx =
1162         LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
1163     IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1164     for (LiveInterval::SubRange &SR : IntB.subranges())
1165       SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1166 
1167     // If the newly created Instruction has an address of an instruction that was
1168     // deleted before (object recycled by the allocator) it needs to be removed from
1169     // the deleted list.
1170     ErasedInstrs.erase(NewCopyMI);
1171   } else {
1172     LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "
1173                       << printMBBReference(MBB) << '\t' << CopyMI);
1174   }
1175 
1176   // Remove CopyMI.
1177   // Note: This is fine to remove the copy before updating the live-ranges.
1178   // While updating the live-ranges, we only look at slot indices and
1179   // never go back to the instruction.
1180   // Mark instructions as deleted.
1181   deleteInstr(&CopyMI);
1182 
1183   // Update the liveness.
1184   SmallVector<SlotIndex, 8> EndPoints;
1185   VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead();
1186   LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(),
1187                   &EndPoints);
1188   BValNo->markUnused();
1189   // Extend IntB to the EndPoints of its original live interval.
1190   LIS->extendToIndices(IntB, EndPoints);
1191 
1192   // Now, do the same for its subranges.
1193   for (LiveInterval::SubRange &SR : IntB.subranges()) {
1194     EndPoints.clear();
1195     VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
1196     assert(BValNo && "All sublanes should be live");
1197     LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints);
1198     BValNo->markUnused();
1199     // We can have a situation where the result of the original copy is live,
1200     // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes
1201     // the copy appear as an endpoint from pruneValue(), but we don't want it
1202     // to because the copy has been removed.  We can go ahead and remove that
1203     // endpoint; there is no other situation here that there could be a use at
1204     // the same place as we know that the copy is a full copy.
1205     for (unsigned I = 0; I != EndPoints.size(); ) {
1206       if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) {
1207         EndPoints[I] = EndPoints.back();
1208         EndPoints.pop_back();
1209         continue;
1210       }
1211       ++I;
1212     }
1213     LIS->extendToIndices(SR, EndPoints);
1214   }
1215   // If any dead defs were extended, truncate them.
1216   shrinkToUses(&IntB);
1217 
1218   // Finally, update the live-range of IntA.
1219   shrinkToUses(&IntA);
1220   return true;
1221 }
1222 
1223 /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
1224 /// defining a subregister.
1225 static bool definesFullReg(const MachineInstr &MI, unsigned Reg) {
1226   assert(!Register::isPhysicalRegister(Reg) &&
1227          "This code cannot handle physreg aliasing");
1228   for (const MachineOperand &Op : MI.operands()) {
1229     if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
1230       continue;
1231     // Return true if we define the full register or don't care about the value
1232     // inside other subregisters.
1233     if (Op.getSubReg() == 0 || Op.isUndef())
1234       return true;
1235   }
1236   return false;
1237 }
1238 
1239 bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
1240                                                 MachineInstr *CopyMI,
1241                                                 bool &IsDefCopy) {
1242   IsDefCopy = false;
1243   unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
1244   unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
1245   unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
1246   unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
1247   if (Register::isPhysicalRegister(SrcReg))
1248     return false;
1249 
1250   LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1251   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1252   VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
1253   if (!ValNo)
1254     return false;
1255   if (ValNo->isPHIDef() || ValNo->isUnused())
1256     return false;
1257   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
1258   if (!DefMI)
1259     return false;
1260   if (DefMI->isCopyLike()) {
1261     IsDefCopy = true;
1262     return false;
1263   }
1264   if (!TII->isAsCheapAsAMove(*DefMI))
1265     return false;
1266   if (!TII->isTriviallyReMaterializable(*DefMI, AA))
1267     return false;
1268   if (!definesFullReg(*DefMI, SrcReg))
1269     return false;
1270   bool SawStore = false;
1271   if (!DefMI->isSafeToMove(AA, SawStore))
1272     return false;
1273   const MCInstrDesc &MCID = DefMI->getDesc();
1274   if (MCID.getNumDefs() != 1)
1275     return false;
1276   // Only support subregister destinations when the def is read-undef.
1277   MachineOperand &DstOperand = CopyMI->getOperand(0);
1278   Register CopyDstReg = DstOperand.getReg();
1279   if (DstOperand.getSubReg() && !DstOperand.isUndef())
1280     return false;
1281 
1282   // If both SrcIdx and DstIdx are set, correct rematerialization would widen
1283   // the register substantially (beyond both source and dest size). This is bad
1284   // for performance since it can cascade through a function, introducing many
1285   // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
1286   // around after a few subreg copies).
1287   if (SrcIdx && DstIdx)
1288     return false;
1289 
1290   const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
1291   if (!DefMI->isImplicitDef()) {
1292     if (Register::isPhysicalRegister(DstReg)) {
1293       unsigned NewDstReg = DstReg;
1294 
1295       unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
1296                                               DefMI->getOperand(0).getSubReg());
1297       if (NewDstIdx)
1298         NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
1299 
1300       // Finally, make sure that the physical subregister that will be
1301       // constructed later is permitted for the instruction.
1302       if (!DefRC->contains(NewDstReg))
1303         return false;
1304     } else {
1305       // Theoretically, some stack frame reference could exist. Just make sure
1306       // it hasn't actually happened.
1307       assert(Register::isVirtualRegister(DstReg) &&
1308              "Only expect to deal with virtual or physical registers");
1309     }
1310   }
1311 
1312   DebugLoc DL = CopyMI->getDebugLoc();
1313   MachineBasicBlock *MBB = CopyMI->getParent();
1314   MachineBasicBlock::iterator MII =
1315     std::next(MachineBasicBlock::iterator(CopyMI));
1316   TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI);
1317   MachineInstr &NewMI = *std::prev(MII);
1318   NewMI.setDebugLoc(DL);
1319 
1320   // In a situation like the following:
1321   //     %0:subreg = instr              ; DefMI, subreg = DstIdx
1322   //     %1        = copy %0:subreg ; CopyMI, SrcIdx = 0
1323   // instead of widening %1 to the register class of %0 simply do:
1324   //     %1 = instr
1325   const TargetRegisterClass *NewRC = CP.getNewRC();
1326   if (DstIdx != 0) {
1327     MachineOperand &DefMO = NewMI.getOperand(0);
1328     if (DefMO.getSubReg() == DstIdx) {
1329       assert(SrcIdx == 0 && CP.isFlipped()
1330              && "Shouldn't have SrcIdx+DstIdx at this point");
1331       const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
1332       const TargetRegisterClass *CommonRC =
1333         TRI->getCommonSubClass(DefRC, DstRC);
1334       if (CommonRC != nullptr) {
1335         NewRC = CommonRC;
1336         DstIdx = 0;
1337         DefMO.setSubReg(0);
1338         DefMO.setIsUndef(false); // Only subregs can have def+undef.
1339       }
1340     }
1341   }
1342 
1343   // CopyMI may have implicit operands, save them so that we can transfer them
1344   // over to the newly materialized instruction after CopyMI is removed.
1345   SmallVector<MachineOperand, 4> ImplicitOps;
1346   ImplicitOps.reserve(CopyMI->getNumOperands() -
1347                       CopyMI->getDesc().getNumOperands());
1348   for (unsigned I = CopyMI->getDesc().getNumOperands(),
1349                 E = CopyMI->getNumOperands();
1350        I != E; ++I) {
1351     MachineOperand &MO = CopyMI->getOperand(I);
1352     if (MO.isReg()) {
1353       assert(MO.isImplicit() && "No explicit operands after implicit operands.");
1354       // Discard VReg implicit defs.
1355       if (Register::isPhysicalRegister(MO.getReg()))
1356         ImplicitOps.push_back(MO);
1357     }
1358   }
1359 
1360   LIS->ReplaceMachineInstrInMaps(*CopyMI, NewMI);
1361   CopyMI->eraseFromParent();
1362   ErasedInstrs.insert(CopyMI);
1363 
1364   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
1365   // We need to remember these so we can add intervals once we insert
1366   // NewMI into SlotIndexes.
1367   SmallVector<unsigned, 4> NewMIImplDefs;
1368   for (unsigned i = NewMI.getDesc().getNumOperands(),
1369                 e = NewMI.getNumOperands();
1370        i != e; ++i) {
1371     MachineOperand &MO = NewMI.getOperand(i);
1372     if (MO.isReg() && MO.isDef()) {
1373       assert(MO.isImplicit() && MO.isDead() &&
1374              Register::isPhysicalRegister(MO.getReg()));
1375       NewMIImplDefs.push_back(MO.getReg());
1376     }
1377   }
1378 
1379   if (Register::isVirtualRegister(DstReg)) {
1380     unsigned NewIdx = NewMI.getOperand(0).getSubReg();
1381 
1382     if (DefRC != nullptr) {
1383       if (NewIdx)
1384         NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
1385       else
1386         NewRC = TRI->getCommonSubClass(NewRC, DefRC);
1387       assert(NewRC && "subreg chosen for remat incompatible with instruction");
1388     }
1389     // Remap subranges to new lanemask and change register class.
1390     LiveInterval &DstInt = LIS->getInterval(DstReg);
1391     for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1392       SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
1393     }
1394     MRI->setRegClass(DstReg, NewRC);
1395 
1396     // Update machine operands and add flags.
1397     updateRegDefsUses(DstReg, DstReg, DstIdx);
1398     NewMI.getOperand(0).setSubReg(NewIdx);
1399     // updateRegDefUses can add an "undef" flag to the definition, since
1400     // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make
1401     // sure that "undef" is not set.
1402     if (NewIdx == 0)
1403       NewMI.getOperand(0).setIsUndef(false);
1404     // Add dead subregister definitions if we are defining the whole register
1405     // but only part of it is live.
1406     // This could happen if the rematerialization instruction is rematerializing
1407     // more than actually is used in the register.
1408     // An example would be:
1409     // %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
1410     // ; Copying only part of the register here, but the rest is undef.
1411     // %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit
1412     // ==>
1413     // ; Materialize all the constants but only using one
1414     // %2 = LOAD_CONSTANTS 5, 8
1415     //
1416     // at this point for the part that wasn't defined before we could have
1417     // subranges missing the definition.
1418     if (NewIdx == 0 && DstInt.hasSubRanges()) {
1419       SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1420       SlotIndex DefIndex =
1421           CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1422       LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg);
1423       VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator();
1424       for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1425         if (!SR.liveAt(DefIndex))
1426           SR.createDeadDef(DefIndex, Alloc);
1427         MaxMask &= ~SR.LaneMask;
1428       }
1429       if (MaxMask.any()) {
1430         LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask);
1431         SR->createDeadDef(DefIndex, Alloc);
1432       }
1433     }
1434 
1435     // Make sure that the subrange for resultant undef is removed
1436     // For example:
1437     //   %1:sub1<def,read-undef> = LOAD CONSTANT 1
1438     //   %2 = COPY %1
1439     // ==>
1440     //   %2:sub1<def, read-undef> = LOAD CONSTANT 1
1441     //     ; Correct but need to remove the subrange for %2:sub0
1442     //     ; as it is now undef
1443     if (NewIdx != 0 && DstInt.hasSubRanges()) {
1444       // The affected subregister segments can be removed.
1445       SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1446       LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx);
1447       bool UpdatedSubRanges = false;
1448       for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1449         if ((SR.LaneMask & DstMask).none()) {
1450           LLVM_DEBUG(dbgs()
1451                      << "Removing undefined SubRange "
1452                      << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n");
1453           // VNI is in ValNo - remove any segments in this SubRange that have this ValNo
1454           if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) {
1455             SR.removeValNo(RmValNo);
1456             UpdatedSubRanges = true;
1457           }
1458         }
1459       }
1460       if (UpdatedSubRanges)
1461         DstInt.removeEmptySubRanges();
1462     }
1463   } else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
1464     // The New instruction may be defining a sub-register of what's actually
1465     // been asked for. If so it must implicitly define the whole thing.
1466     assert(Register::isPhysicalRegister(DstReg) &&
1467            "Only expect virtual or physical registers in remat");
1468     NewMI.getOperand(0).setIsDead(true);
1469     NewMI.addOperand(MachineOperand::CreateReg(
1470         CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
1471     // Record small dead def live-ranges for all the subregisters
1472     // of the destination register.
1473     // Otherwise, variables that live through may miss some
1474     // interferences, thus creating invalid allocation.
1475     // E.g., i386 code:
1476     // %1 = somedef ; %1 GR8
1477     // %2 = remat ; %2 GR32
1478     // CL = COPY %2.sub_8bit
1479     // = somedef %1 ; %1 GR8
1480     // =>
1481     // %1 = somedef ; %1 GR8
1482     // dead ECX = remat ; implicit-def CL
1483     // = somedef %1 ; %1 GR8
1484     // %1 will see the interferences with CL but not with CH since
1485     // no live-ranges would have been created for ECX.
1486     // Fix that!
1487     SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1488     for (MCRegUnitIterator Units(NewMI.getOperand(0).getReg(), TRI);
1489          Units.isValid(); ++Units)
1490       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1491         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1492   }
1493 
1494   if (NewMI.getOperand(0).getSubReg())
1495     NewMI.getOperand(0).setIsUndef();
1496 
1497   // Transfer over implicit operands to the rematerialized instruction.
1498   for (MachineOperand &MO : ImplicitOps)
1499     NewMI.addOperand(MO);
1500 
1501   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1502   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
1503     unsigned Reg = NewMIImplDefs[i];
1504     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1505       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1506         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1507   }
1508 
1509   LLVM_DEBUG(dbgs() << "Remat: " << NewMI);
1510   ++NumReMats;
1511 
1512   // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1513   // to describe DstReg instead.
1514   if (MRI->use_nodbg_empty(SrcReg)) {
1515     for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
1516       MachineInstr *UseMI = UseMO.getParent();
1517       if (UseMI->isDebugValue()) {
1518         if (Register::isPhysicalRegister(DstReg))
1519           UseMO.substPhysReg(DstReg, *TRI);
1520         else
1521           UseMO.setReg(DstReg);
1522         // Move the debug value directly after the def of the rematerialized
1523         // value in DstReg.
1524         MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI);
1525         LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1526       }
1527     }
1528   }
1529 
1530   if (ToBeUpdated.count(SrcReg))
1531     return true;
1532 
1533   unsigned NumCopyUses = 0;
1534   for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
1535     if (UseMO.getParent()->isCopyLike())
1536       NumCopyUses++;
1537   }
1538   if (NumCopyUses < LateRematUpdateThreshold) {
1539     // The source interval can become smaller because we removed a use.
1540     shrinkToUses(&SrcInt, &DeadDefs);
1541     if (!DeadDefs.empty())
1542       eliminateDeadDefs();
1543   } else {
1544     ToBeUpdated.insert(SrcReg);
1545   }
1546   return true;
1547 }
1548 
1549 MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1550   // ProcessImplicitDefs may leave some copies of <undef> values, it only
1551   // removes local variables. When we have a copy like:
1552   //
1553   //   %1 = COPY undef %2
1554   //
1555   // We delete the copy and remove the corresponding value number from %1.
1556   // Any uses of that value number are marked as <undef>.
1557 
1558   // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1559   // CoalescerPair may have a new register class with adjusted subreg indices
1560   // at this point.
1561   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1562   if(!isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1563     return nullptr;
1564 
1565   SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
1566   const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1567   // CopyMI is undef iff SrcReg is not live before the instruction.
1568   if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1569     LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1570     for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1571       if ((SR.LaneMask & SrcMask).none())
1572         continue;
1573       if (SR.liveAt(Idx))
1574         return nullptr;
1575     }
1576   } else if (SrcLI.liveAt(Idx))
1577     return nullptr;
1578 
1579   // If the undef copy defines a live-out value (i.e. an input to a PHI def),
1580   // then replace it with an IMPLICIT_DEF.
1581   LiveInterval &DstLI = LIS->getInterval(DstReg);
1582   SlotIndex RegIndex = Idx.getRegSlot();
1583   LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex);
1584   assert(Seg != nullptr && "No segment for defining instruction");
1585   if (VNInfo *V = DstLI.getVNInfoAt(Seg->end)) {
1586     if (V->isPHIDef()) {
1587       CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1588       for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) {
1589         MachineOperand &MO = CopyMI->getOperand(i-1);
1590         if (MO.isReg() && MO.isUse())
1591           CopyMI->RemoveOperand(i-1);
1592       }
1593       LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "
1594                            "implicit def\n");
1595       return CopyMI;
1596     }
1597   }
1598 
1599   // Remove any DstReg segments starting at the instruction.
1600   LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1601 
1602   // Remove value or merge with previous one in case of a subregister def.
1603   if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1604     VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1605     DstLI.MergeValueNumberInto(VNI, PrevVNI);
1606 
1607     // The affected subregister segments can be removed.
1608     LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1609     for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1610       if ((SR.LaneMask & DstMask).none())
1611         continue;
1612 
1613       VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1614       assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
1615       SR.removeValNo(SVNI);
1616     }
1617     DstLI.removeEmptySubRanges();
1618   } else
1619     LIS->removeVRegDefAt(DstLI, RegIndex);
1620 
1621   // Mark uses as undef.
1622   for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1623     if (MO.isDef() /*|| MO.isUndef()*/)
1624       continue;
1625     const MachineInstr &MI = *MO.getParent();
1626     SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1627     LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1628     bool isLive;
1629     if (!UseMask.all() && DstLI.hasSubRanges()) {
1630       isLive = false;
1631       for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1632         if ((SR.LaneMask & UseMask).none())
1633           continue;
1634         if (SR.liveAt(UseIdx)) {
1635           isLive = true;
1636           break;
1637         }
1638       }
1639     } else
1640       isLive = DstLI.liveAt(UseIdx);
1641     if (isLive)
1642       continue;
1643     MO.setIsUndef(true);
1644     LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1645   }
1646 
1647   // A def of a subregister may be a use of the other subregisters, so
1648   // deleting a def of a subregister may also remove uses. Since CopyMI
1649   // is still part of the function (but about to be erased), mark all
1650   // defs of DstReg in it as <undef>, so that shrinkToUses would
1651   // ignore them.
1652   for (MachineOperand &MO : CopyMI->operands())
1653     if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1654       MO.setIsUndef(true);
1655   LIS->shrinkToUses(&DstLI);
1656 
1657   return CopyMI;
1658 }
1659 
1660 void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
1661                                      MachineOperand &MO, unsigned SubRegIdx) {
1662   LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1663   if (MO.isDef())
1664     Mask = ~Mask;
1665   bool IsUndef = true;
1666   for (const LiveInterval::SubRange &S : Int.subranges()) {
1667     if ((S.LaneMask & Mask).none())
1668       continue;
1669     if (S.liveAt(UseIdx)) {
1670       IsUndef = false;
1671       break;
1672     }
1673   }
1674   if (IsUndef) {
1675     MO.setIsUndef(true);
1676     // We found out some subregister use is actually reading an undefined
1677     // value. In some cases the whole vreg has become undefined at this
1678     // point so we have to potentially shrink the main range if the
1679     // use was ending a live segment there.
1680     LiveQueryResult Q = Int.Query(UseIdx);
1681     if (Q.valueOut() == nullptr)
1682       ShrinkMainRange = true;
1683   }
1684 }
1685 
1686 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg, unsigned DstReg,
1687                                           unsigned SubIdx) {
1688   bool DstIsPhys = Register::isPhysicalRegister(DstReg);
1689   LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1690 
1691   if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) {
1692     for (MachineOperand &MO : MRI->reg_operands(DstReg)) {
1693       unsigned SubReg = MO.getSubReg();
1694       if (SubReg == 0 || MO.isUndef())
1695         continue;
1696       MachineInstr &MI = *MO.getParent();
1697       if (MI.isDebugValue())
1698         continue;
1699       SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true);
1700       addUndefFlag(*DstInt, UseIdx, MO, SubReg);
1701     }
1702   }
1703 
1704   SmallPtrSet<MachineInstr*, 8> Visited;
1705   for (MachineRegisterInfo::reg_instr_iterator
1706        I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1707        I != E; ) {
1708     MachineInstr *UseMI = &*(I++);
1709 
1710     // Each instruction can only be rewritten once because sub-register
1711     // composition is not always idempotent. When SrcReg != DstReg, rewriting
1712     // the UseMI operands removes them from the SrcReg use-def chain, but when
1713     // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1714     // operands mentioning the virtual register.
1715     if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1716       continue;
1717 
1718     SmallVector<unsigned,8> Ops;
1719     bool Reads, Writes;
1720     std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1721 
1722     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1723     // because SrcReg is a sub-register.
1724     if (DstInt && !Reads && SubIdx && !UseMI->isDebugValue())
1725       Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
1726 
1727     // Replace SrcReg with DstReg in all UseMI operands.
1728     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1729       MachineOperand &MO = UseMI->getOperand(Ops[i]);
1730 
1731       // Adjust <undef> flags in case of sub-register joins. We don't want to
1732       // turn a full def into a read-modify-write sub-register def and vice
1733       // versa.
1734       if (SubIdx && MO.isDef())
1735         MO.setIsUndef(!Reads);
1736 
1737       // A subreg use of a partially undef (super) register may be a complete
1738       // undef use now and then has to be marked that way.
1739       if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) {
1740         if (!DstInt->hasSubRanges()) {
1741           BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1742           LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
1743           LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1744           LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
1745           DstInt->createSubRangeFrom(Allocator, UsedLanes, *DstInt);
1746           // The unused lanes are just empty live-ranges at this point.
1747           // It is the caller responsibility to set the proper
1748           // dead segments if there is an actual dead def of the
1749           // unused lanes. This may happen with rematerialization.
1750           DstInt->createSubRange(Allocator, UnusedLanes);
1751         }
1752         SlotIndex MIIdx = UseMI->isDebugValue()
1753                               ? LIS->getSlotIndexes()->getIndexBefore(*UseMI)
1754                               : LIS->getInstructionIndex(*UseMI);
1755         SlotIndex UseIdx = MIIdx.getRegSlot(true);
1756         addUndefFlag(*DstInt, UseIdx, MO, SubIdx);
1757       }
1758 
1759       if (DstIsPhys)
1760         MO.substPhysReg(DstReg, *TRI);
1761       else
1762         MO.substVirtReg(DstReg, SubIdx, *TRI);
1763     }
1764 
1765     LLVM_DEBUG({
1766       dbgs() << "\t\tupdated: ";
1767       if (!UseMI->isDebugValue())
1768         dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";
1769       dbgs() << *UseMI;
1770     });
1771   }
1772 }
1773 
1774 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1775   // Always join simple intervals that are defined by a single copy from a
1776   // reserved register. This doesn't increase register pressure, so it is
1777   // always beneficial.
1778   if (!MRI->isReserved(CP.getDstReg())) {
1779     LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1780     return false;
1781   }
1782 
1783   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1784   if (JoinVInt.containsOneValue())
1785     return true;
1786 
1787   LLVM_DEBUG(
1788       dbgs() << "\tCannot join complex intervals into reserved register.\n");
1789   return false;
1790 }
1791 
1792 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1793   Again = false;
1794   LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
1795 
1796   CoalescerPair CP(*TRI);
1797   if (!CP.setRegisters(CopyMI)) {
1798     LLVM_DEBUG(dbgs() << "\tNot coalescable.\n");
1799     return false;
1800   }
1801 
1802   if (CP.getNewRC()) {
1803     auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1804     auto DstRC = MRI->getRegClass(CP.getDstReg());
1805     unsigned SrcIdx = CP.getSrcIdx();
1806     unsigned DstIdx = CP.getDstIdx();
1807     if (CP.isFlipped()) {
1808       std::swap(SrcIdx, DstIdx);
1809       std::swap(SrcRC, DstRC);
1810     }
1811     if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1812                              CP.getNewRC(), *LIS)) {
1813       LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1814       return false;
1815     }
1816   }
1817 
1818   // Dead code elimination. This really should be handled by MachineDCE, but
1819   // sometimes dead copies slip through, and we can't generate invalid live
1820   // ranges.
1821   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1822     LLVM_DEBUG(dbgs() << "\tCopy is dead.\n");
1823     DeadDefs.push_back(CopyMI);
1824     eliminateDeadDefs();
1825     return true;
1826   }
1827 
1828   // Eliminate undefs.
1829   if (!CP.isPhys()) {
1830     // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce.
1831     if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
1832       if (UndefMI->isImplicitDef())
1833         return false;
1834       deleteInstr(CopyMI);
1835       return false;  // Not coalescable.
1836     }
1837   }
1838 
1839   // Coalesced copies are normally removed immediately, but transformations
1840   // like removeCopyByCommutingDef() can inadvertently create identity copies.
1841   // When that happens, just join the values and remove the copy.
1842   if (CP.getSrcReg() == CP.getDstReg()) {
1843     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1844     LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1845     const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1846     LiveQueryResult LRQ = LI.Query(CopyIdx);
1847     if (VNInfo *DefVNI = LRQ.valueDefined()) {
1848       VNInfo *ReadVNI = LRQ.valueIn();
1849       assert(ReadVNI && "No value before copy and no <undef> flag.");
1850       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1851       LI.MergeValueNumberInto(DefVNI, ReadVNI);
1852 
1853       // Process subregister liveranges.
1854       for (LiveInterval::SubRange &S : LI.subranges()) {
1855         LiveQueryResult SLRQ = S.Query(CopyIdx);
1856         if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1857           VNInfo *SReadVNI = SLRQ.valueIn();
1858           S.MergeValueNumberInto(SDefVNI, SReadVNI);
1859         }
1860       }
1861       LLVM_DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
1862     }
1863     deleteInstr(CopyMI);
1864     return true;
1865   }
1866 
1867   // Enforce policies.
1868   if (CP.isPhys()) {
1869     LLVM_DEBUG(dbgs() << "\tConsidering merging "
1870                       << printReg(CP.getSrcReg(), TRI) << " with "
1871                       << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n');
1872     if (!canJoinPhys(CP)) {
1873       // Before giving up coalescing, if definition of source is defined by
1874       // trivial computation, try rematerializing it.
1875       bool IsDefCopy;
1876       if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1877         return true;
1878       if (IsDefCopy)
1879         Again = true;  // May be possible to coalesce later.
1880       return false;
1881     }
1882   } else {
1883     // When possible, let DstReg be the larger interval.
1884     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1885                            LIS->getInterval(CP.getDstReg()).size())
1886       CP.flip();
1887 
1888     LLVM_DEBUG({
1889       dbgs() << "\tConsidering merging to "
1890              << TRI->getRegClassName(CP.getNewRC()) << " with ";
1891       if (CP.getDstIdx() && CP.getSrcIdx())
1892         dbgs() << printReg(CP.getDstReg()) << " in "
1893                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1894                << printReg(CP.getSrcReg()) << " in "
1895                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1896       else
1897         dbgs() << printReg(CP.getSrcReg(), TRI) << " in "
1898                << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1899     });
1900   }
1901 
1902   ShrinkMask = LaneBitmask::getNone();
1903   ShrinkMainRange = false;
1904 
1905   // Okay, attempt to join these two intervals.  On failure, this returns false.
1906   // Otherwise, if one of the intervals being joined is a physreg, this method
1907   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1908   // been modified, so we can use this information below to update aliases.
1909   if (!joinIntervals(CP)) {
1910     // Coalescing failed.
1911 
1912     // If definition of source is defined by trivial computation, try
1913     // rematerializing it.
1914     bool IsDefCopy;
1915     if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1916       return true;
1917 
1918     // If we can eliminate the copy without merging the live segments, do so
1919     // now.
1920     if (!CP.isPartial() && !CP.isPhys()) {
1921       bool Changed = adjustCopiesBackFrom(CP, CopyMI);
1922       bool Shrink = false;
1923       if (!Changed)
1924         std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI);
1925       if (Changed) {
1926         deleteInstr(CopyMI);
1927         if (Shrink) {
1928           unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
1929           LiveInterval &DstLI = LIS->getInterval(DstReg);
1930           shrinkToUses(&DstLI);
1931           LLVM_DEBUG(dbgs() << "\t\tshrunk:   " << DstLI << '\n');
1932         }
1933         LLVM_DEBUG(dbgs() << "\tTrivial!\n");
1934         return true;
1935       }
1936     }
1937 
1938     // Try and see if we can partially eliminate the copy by moving the copy to
1939     // its predecessor.
1940     if (!CP.isPartial() && !CP.isPhys())
1941       if (removePartialRedundancy(CP, *CopyMI))
1942         return true;
1943 
1944     // Otherwise, we are unable to join the intervals.
1945     LLVM_DEBUG(dbgs() << "\tInterference!\n");
1946     Again = true;  // May be possible to coalesce later.
1947     return false;
1948   }
1949 
1950   // Coalescing to a virtual register that is of a sub-register class of the
1951   // other. Make sure the resulting register is set to the right register class.
1952   if (CP.isCrossClass()) {
1953     ++numCrossRCs;
1954     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1955   }
1956 
1957   // Removing sub-register copies can ease the register class constraints.
1958   // Make sure we attempt to inflate the register class of DstReg.
1959   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1960     InflateRegs.push_back(CP.getDstReg());
1961 
1962   // CopyMI has been erased by joinIntervals at this point. Remove it from
1963   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1964   // to the work list. This keeps ErasedInstrs from growing needlessly.
1965   ErasedInstrs.erase(CopyMI);
1966 
1967   // Rewrite all SrcReg operands to DstReg.
1968   // Also update DstReg operands to include DstIdx if it is set.
1969   if (CP.getDstIdx())
1970     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1971   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1972 
1973   // Shrink subregister ranges if necessary.
1974   if (ShrinkMask.any()) {
1975     LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1976     for (LiveInterval::SubRange &S : LI.subranges()) {
1977       if ((S.LaneMask & ShrinkMask).none())
1978         continue;
1979       LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
1980                         << ")\n");
1981       LIS->shrinkToUses(S, LI.reg);
1982     }
1983     LI.removeEmptySubRanges();
1984   }
1985 
1986   // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live
1987   // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval
1988   // is not up-to-date, need to update the merged live interval here.
1989   if (ToBeUpdated.count(CP.getSrcReg()))
1990     ShrinkMainRange = true;
1991 
1992   if (ShrinkMainRange) {
1993     LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1994     shrinkToUses(&LI);
1995   }
1996 
1997   // SrcReg is guaranteed to be the register whose live interval that is
1998   // being merged.
1999   LIS->removeInterval(CP.getSrcReg());
2000 
2001   // Update regalloc hint.
2002   TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
2003 
2004   LLVM_DEBUG({
2005     dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
2006            << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
2007     dbgs() << "\tResult = ";
2008     if (CP.isPhys())
2009       dbgs() << printReg(CP.getDstReg(), TRI);
2010     else
2011       dbgs() << LIS->getInterval(CP.getDstReg());
2012     dbgs() << '\n';
2013   });
2014 
2015   ++numJoins;
2016   return true;
2017 }
2018 
2019 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
2020   unsigned DstReg = CP.getDstReg();
2021   unsigned SrcReg = CP.getSrcReg();
2022   assert(CP.isPhys() && "Must be a physreg copy");
2023   assert(MRI->isReserved(DstReg) && "Not a reserved register");
2024   LiveInterval &RHS = LIS->getInterval(SrcReg);
2025   LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
2026 
2027   assert(RHS.containsOneValue() && "Invalid join with reserved register");
2028 
2029   // Optimization for reserved registers like ESP. We can only merge with a
2030   // reserved physreg if RHS has a single value that is a copy of DstReg.
2031   // The live range of the reserved register will look like a set of dead defs
2032   // - we don't properly track the live range of reserved registers.
2033 
2034   // Deny any overlapping intervals.  This depends on all the reserved
2035   // register live ranges to look like dead defs.
2036   if (!MRI->isConstantPhysReg(DstReg)) {
2037     for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
2038       // Abort if not all the regunits are reserved.
2039       for (MCRegUnitRootIterator RI(*UI, TRI); RI.isValid(); ++RI) {
2040         if (!MRI->isReserved(*RI))
2041           return false;
2042       }
2043       if (RHS.overlaps(LIS->getRegUnit(*UI))) {
2044         LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(*UI, TRI)
2045                           << '\n');
2046         return false;
2047       }
2048     }
2049 
2050     // We must also check for overlaps with regmask clobbers.
2051     BitVector RegMaskUsable;
2052     if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
2053         !RegMaskUsable.test(DstReg)) {
2054       LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n");
2055       return false;
2056     }
2057   }
2058 
2059   // Skip any value computations, we are not adding new values to the
2060   // reserved register.  Also skip merging the live ranges, the reserved
2061   // register live range doesn't need to be accurate as long as all the
2062   // defs are there.
2063 
2064   // Delete the identity copy.
2065   MachineInstr *CopyMI;
2066   if (CP.isFlipped()) {
2067     // Physreg is copied into vreg
2068     //   %y = COPY %physreg_x
2069     //   ...  //< no other def of %physreg_x here
2070     //   use %y
2071     // =>
2072     //   ...
2073     //   use %physreg_x
2074     CopyMI = MRI->getVRegDef(SrcReg);
2075   } else {
2076     // VReg is copied into physreg:
2077     //   %y = def
2078     //   ... //< no other def or use of %physreg_x here
2079     //   %physreg_x = COPY %y
2080     // =>
2081     //   %physreg_x = def
2082     //   ...
2083     if (!MRI->hasOneNonDBGUse(SrcReg)) {
2084       LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
2085       return false;
2086     }
2087 
2088     if (!LIS->intervalIsInOneMBB(RHS)) {
2089       LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n");
2090       return false;
2091     }
2092 
2093     MachineInstr &DestMI = *MRI->getVRegDef(SrcReg);
2094     CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg);
2095     SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
2096     SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
2097 
2098     if (!MRI->isConstantPhysReg(DstReg)) {
2099       // We checked above that there are no interfering defs of the physical
2100       // register. However, for this case, where we intend to move up the def of
2101       // the physical register, we also need to check for interfering uses.
2102       SlotIndexes *Indexes = LIS->getSlotIndexes();
2103       for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
2104            SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
2105         MachineInstr *MI = LIS->getInstructionFromIndex(SI);
2106         if (MI->readsRegister(DstReg, TRI)) {
2107           LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
2108           return false;
2109         }
2110       }
2111     }
2112 
2113     // We're going to remove the copy which defines a physical reserved
2114     // register, so remove its valno, etc.
2115     LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "
2116                       << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n");
2117 
2118     LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
2119     // Create a new dead def at the new def location.
2120     for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
2121       LiveRange &LR = LIS->getRegUnit(*UI);
2122       LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
2123     }
2124   }
2125 
2126   deleteInstr(CopyMI);
2127 
2128   // We don't track kills for reserved registers.
2129   MRI->clearKillFlags(CP.getSrcReg());
2130 
2131   return true;
2132 }
2133 
2134 //===----------------------------------------------------------------------===//
2135 //                 Interference checking and interval joining
2136 //===----------------------------------------------------------------------===//
2137 //
2138 // In the easiest case, the two live ranges being joined are disjoint, and
2139 // there is no interference to consider. It is quite common, though, to have
2140 // overlapping live ranges, and we need to check if the interference can be
2141 // resolved.
2142 //
2143 // The live range of a single SSA value forms a sub-tree of the dominator tree.
2144 // This means that two SSA values overlap if and only if the def of one value
2145 // is contained in the live range of the other value. As a special case, the
2146 // overlapping values can be defined at the same index.
2147 //
2148 // The interference from an overlapping def can be resolved in these cases:
2149 //
2150 // 1. Coalescable copies. The value is defined by a copy that would become an
2151 //    identity copy after joining SrcReg and DstReg. The copy instruction will
2152 //    be removed, and the value will be merged with the source value.
2153 //
2154 //    There can be several copies back and forth, causing many values to be
2155 //    merged into one. We compute a list of ultimate values in the joined live
2156 //    range as well as a mappings from the old value numbers.
2157 //
2158 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
2159 //    predecessors have a live out value. It doesn't cause real interference,
2160 //    and can be merged into the value it overlaps. Like a coalescable copy, it
2161 //    can be erased after joining.
2162 //
2163 // 3. Copy of external value. The overlapping def may be a copy of a value that
2164 //    is already in the other register. This is like a coalescable copy, but
2165 //    the live range of the source register must be trimmed after erasing the
2166 //    copy instruction:
2167 //
2168 //      %src = COPY %ext
2169 //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
2170 //
2171 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
2172 //    defining one lane at a time:
2173 //
2174 //      %dst:ssub0<def,read-undef> = FOO
2175 //      %src = BAR
2176 //      %dst:ssub1 = COPY %src
2177 //
2178 //    The live range of %src overlaps the %dst value defined by FOO, but
2179 //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
2180 //    which was undef anyway.
2181 //
2182 //    The value mapping is more complicated in this case. The final live range
2183 //    will have different value numbers for both FOO and BAR, but there is no
2184 //    simple mapping from old to new values. It may even be necessary to add
2185 //    new PHI values.
2186 //
2187 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
2188 //    is live, but never read. This can happen because we don't compute
2189 //    individual live ranges per lane.
2190 //
2191 //      %dst = FOO
2192 //      %src = BAR
2193 //      %dst:ssub1 = COPY %src
2194 //
2195 //    This kind of interference is only resolved locally. If the clobbered
2196 //    lane value escapes the block, the join is aborted.
2197 
2198 namespace {
2199 
2200 /// Track information about values in a single virtual register about to be
2201 /// joined. Objects of this class are always created in pairs - one for each
2202 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
2203 /// pair)
2204 class JoinVals {
2205   /// Live range we work on.
2206   LiveRange &LR;
2207 
2208   /// (Main) register we work on.
2209   const unsigned Reg;
2210 
2211   /// Reg (and therefore the values in this liverange) will end up as
2212   /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
2213   /// CP.SrcIdx.
2214   const unsigned SubIdx;
2215 
2216   /// The LaneMask that this liverange will occupy the coalesced register. May
2217   /// be smaller than the lanemask produced by SubIdx when merging subranges.
2218   const LaneBitmask LaneMask;
2219 
2220   /// This is true when joining sub register ranges, false when joining main
2221   /// ranges.
2222   const bool SubRangeJoin;
2223 
2224   /// Whether the current LiveInterval tracks subregister liveness.
2225   const bool TrackSubRegLiveness;
2226 
2227   /// Values that will be present in the final live range.
2228   SmallVectorImpl<VNInfo*> &NewVNInfo;
2229 
2230   const CoalescerPair &CP;
2231   LiveIntervals *LIS;
2232   SlotIndexes *Indexes;
2233   const TargetRegisterInfo *TRI;
2234 
2235   /// Value number assignments. Maps value numbers in LI to entries in
2236   /// NewVNInfo. This is suitable for passing to LiveInterval::join().
2237   SmallVector<int, 8> Assignments;
2238 
2239   public:
2240   /// Conflict resolution for overlapping values.
2241   enum ConflictResolution {
2242     /// No overlap, simply keep this value.
2243     CR_Keep,
2244 
2245     /// Merge this value into OtherVNI and erase the defining instruction.
2246     /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
2247     /// values.
2248     CR_Erase,
2249 
2250     /// Merge this value into OtherVNI but keep the defining instruction.
2251     /// This is for the special case where OtherVNI is defined by the same
2252     /// instruction.
2253     CR_Merge,
2254 
2255     /// Keep this value, and have it replace OtherVNI where possible. This
2256     /// complicates value mapping since OtherVNI maps to two different values
2257     /// before and after this def.
2258     /// Used when clobbering undefined or dead lanes.
2259     CR_Replace,
2260 
2261     /// Unresolved conflict. Visit later when all values have been mapped.
2262     CR_Unresolved,
2263 
2264     /// Unresolvable conflict. Abort the join.
2265     CR_Impossible
2266   };
2267 
2268   private:
2269   /// Per-value info for LI. The lane bit masks are all relative to the final
2270   /// joined register, so they can be compared directly between SrcReg and
2271   /// DstReg.
2272   struct Val {
2273     ConflictResolution Resolution = CR_Keep;
2274 
2275     /// Lanes written by this def, 0 for unanalyzed values.
2276     LaneBitmask WriteLanes;
2277 
2278     /// Lanes with defined values in this register. Other lanes are undef and
2279     /// safe to clobber.
2280     LaneBitmask ValidLanes;
2281 
2282     /// Value in LI being redefined by this def.
2283     VNInfo *RedefVNI = nullptr;
2284 
2285     /// Value in the other live range that overlaps this def, if any.
2286     VNInfo *OtherVNI = nullptr;
2287 
2288     /// Is this value an IMPLICIT_DEF that can be erased?
2289     ///
2290     /// IMPLICIT_DEF values should only exist at the end of a basic block that
2291     /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
2292     /// safely erased if they are overlapping a live value in the other live
2293     /// interval.
2294     ///
2295     /// Weird control flow graphs and incomplete PHI handling in
2296     /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
2297     /// longer live ranges. Such IMPLICIT_DEF values should be treated like
2298     /// normal values.
2299     bool ErasableImplicitDef = false;
2300 
2301     /// True when the live range of this value will be pruned because of an
2302     /// overlapping CR_Replace value in the other live range.
2303     bool Pruned = false;
2304 
2305     /// True once Pruned above has been computed.
2306     bool PrunedComputed = false;
2307 
2308     /// True if this value is determined to be identical to OtherVNI
2309     /// (in valuesIdentical). This is used with CR_Erase where the erased
2310     /// copy is redundant, i.e. the source value is already the same as
2311     /// the destination. In such cases the subranges need to be updated
2312     /// properly. See comment at pruneSubRegValues for more info.
2313     bool Identical = false;
2314 
2315     Val() = default;
2316 
2317     bool isAnalyzed() const { return WriteLanes.any(); }
2318   };
2319 
2320   /// One entry per value number in LI.
2321   SmallVector<Val, 8> Vals;
2322 
2323   /// Compute the bitmask of lanes actually written by DefMI.
2324   /// Set Redef if there are any partial register definitions that depend on the
2325   /// previous value of the register.
2326   LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
2327 
2328   /// Find the ultimate value that VNI was copied from.
2329   std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const;
2330 
2331   bool valuesIdentical(VNInfo *Value0, VNInfo *Value1, const JoinVals &Other) const;
2332 
2333   /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
2334   /// Return a conflict resolution when possible, but leave the hard cases as
2335   /// CR_Unresolved.
2336   /// Recursively calls computeAssignment() on this and Other, guaranteeing that
2337   /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
2338   /// The recursion always goes upwards in the dominator tree, making loops
2339   /// impossible.
2340   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
2341 
2342   /// Compute the value assignment for ValNo in RI.
2343   /// This may be called recursively by analyzeValue(), but never for a ValNo on
2344   /// the stack.
2345   void computeAssignment(unsigned ValNo, JoinVals &Other);
2346 
2347   /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
2348   /// the extent of the tainted lanes in the block.
2349   ///
2350   /// Multiple values in Other.LR can be affected since partial redefinitions
2351   /// can preserve previously tainted lanes.
2352   ///
2353   ///   1 %dst = VLOAD           <-- Define all lanes in %dst
2354   ///   2 %src = FOO             <-- ValNo to be joined with %dst:ssub0
2355   ///   3 %dst:ssub1 = BAR       <-- Partial redef doesn't clear taint in ssub0
2356   ///   4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
2357   ///
2358   /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
2359   /// entry to TaintedVals.
2360   ///
2361   /// Returns false if the tainted lanes extend beyond the basic block.
2362   bool
2363   taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2364               SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent);
2365 
2366   /// Return true if MI uses any of the given Lanes from Reg.
2367   /// This does not include partial redefinitions of Reg.
2368   bool usesLanes(const MachineInstr &MI, unsigned, unsigned, LaneBitmask) const;
2369 
2370   /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
2371   /// be pruned:
2372   ///
2373   ///   %dst = COPY %src
2374   ///   %src = COPY %dst  <-- This value to be pruned.
2375   ///   %dst = COPY %src  <-- This value is a copy of a pruned value.
2376   bool isPrunedValue(unsigned ValNo, JoinVals &Other);
2377 
2378 public:
2379   JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, LaneBitmask LaneMask,
2380            SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp,
2381            LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
2382            bool TrackSubRegLiveness)
2383     : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
2384       SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
2385       NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
2386       TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums()) {}
2387 
2388   /// Analyze defs in LR and compute a value mapping in NewVNInfo.
2389   /// Returns false if any conflicts were impossible to resolve.
2390   bool mapValues(JoinVals &Other);
2391 
2392   /// Try to resolve conflicts that require all values to be mapped.
2393   /// Returns false if any conflicts were impossible to resolve.
2394   bool resolveConflicts(JoinVals &Other);
2395 
2396   /// Prune the live range of values in Other.LR where they would conflict with
2397   /// CR_Replace values in LR. Collect end points for restoring the live range
2398   /// after joining.
2399   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
2400                    bool changeInstrs);
2401 
2402   /// Removes subranges starting at copies that get removed. This sometimes
2403   /// happens when undefined subranges are copied around. These ranges contain
2404   /// no useful information and can be removed.
2405   void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
2406 
2407   /// Pruning values in subranges can lead to removing segments in these
2408   /// subranges started by IMPLICIT_DEFs. The corresponding segments in
2409   /// the main range also need to be removed. This function will mark
2410   /// the corresponding values in the main range as pruned, so that
2411   /// eraseInstrs can do the final cleanup.
2412   /// The parameter @p LI must be the interval whose main range is the
2413   /// live range LR.
2414   void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
2415 
2416   /// Erase any machine instructions that have been coalesced away.
2417   /// Add erased instructions to ErasedInstrs.
2418   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
2419   /// the erased instrs.
2420   void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2421                    SmallVectorImpl<unsigned> &ShrinkRegs,
2422                    LiveInterval *LI = nullptr);
2423 
2424   /// Remove liverange defs at places where implicit defs will be removed.
2425   void removeImplicitDefs();
2426 
2427   /// Get the value assignments suitable for passing to LiveInterval::join.
2428   const int *getAssignments() const { return Assignments.data(); }
2429 
2430   /// Get the conflict resolution for a value number.
2431   ConflictResolution getResolution(unsigned Num) const {
2432     return Vals[Num].Resolution;
2433   }
2434 };
2435 
2436 } // end anonymous namespace
2437 
2438 LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
2439   const {
2440   LaneBitmask L;
2441   for (const MachineOperand &MO : DefMI->operands()) {
2442     if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef())
2443       continue;
2444     L |= TRI->getSubRegIndexLaneMask(
2445            TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
2446     if (MO.readsReg())
2447       Redef = true;
2448   }
2449   return L;
2450 }
2451 
2452 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
2453     const VNInfo *VNI) const {
2454   unsigned TrackReg = Reg;
2455 
2456   while (!VNI->isPHIDef()) {
2457     SlotIndex Def = VNI->def;
2458     MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2459     assert(MI && "No defining instruction");
2460     if (!MI->isFullCopy())
2461       return std::make_pair(VNI, TrackReg);
2462     Register SrcReg = MI->getOperand(1).getReg();
2463     if (!Register::isVirtualRegister(SrcReg))
2464       return std::make_pair(VNI, TrackReg);
2465 
2466     const LiveInterval &LI = LIS->getInterval(SrcReg);
2467     const VNInfo *ValueIn;
2468     // No subrange involved.
2469     if (!SubRangeJoin || !LI.hasSubRanges()) {
2470       LiveQueryResult LRQ = LI.Query(Def);
2471       ValueIn = LRQ.valueIn();
2472     } else {
2473       // Query subranges. Ensure that all matching ones take us to the same def
2474       // (allowing some of them to be undef).
2475       ValueIn = nullptr;
2476       for (const LiveInterval::SubRange &S : LI.subranges()) {
2477         // Transform lanemask to a mask in the joined live interval.
2478         LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
2479         if ((SMask & LaneMask).none())
2480           continue;
2481         LiveQueryResult LRQ = S.Query(Def);
2482         if (!ValueIn) {
2483           ValueIn = LRQ.valueIn();
2484           continue;
2485         }
2486         if (LRQ.valueIn() && ValueIn != LRQ.valueIn())
2487           return std::make_pair(VNI, TrackReg);
2488       }
2489     }
2490     if (ValueIn == nullptr) {
2491       // Reaching an undefined value is legitimate, for example:
2492       //
2493       // 1   undef %0.sub1 = ...  ;; %0.sub0 == undef
2494       // 2   %1 = COPY %0         ;; %1 is defined here.
2495       // 3   %0 = COPY %1         ;; Now %0.sub0 has a definition,
2496       //                          ;; but it's equivalent to "undef".
2497       return std::make_pair(nullptr, SrcReg);
2498     }
2499     VNI = ValueIn;
2500     TrackReg = SrcReg;
2501   }
2502   return std::make_pair(VNI, TrackReg);
2503 }
2504 
2505 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
2506                                const JoinVals &Other) const {
2507   const VNInfo *Orig0;
2508   unsigned Reg0;
2509   std::tie(Orig0, Reg0) = followCopyChain(Value0);
2510   if (Orig0 == Value1 && Reg0 == Other.Reg)
2511     return true;
2512 
2513   const VNInfo *Orig1;
2514   unsigned Reg1;
2515   std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
2516   // If both values are undefined, and the source registers are the same
2517   // register, the values are identical. Filter out cases where only one
2518   // value is defined.
2519   if (Orig0 == nullptr || Orig1 == nullptr)
2520     return Orig0 == Orig1 && Reg0 == Reg1;
2521 
2522   // The values are equal if they are defined at the same place and use the
2523   // same register. Note that we cannot compare VNInfos directly as some of
2524   // them might be from a copy created in mergeSubRangeInto()  while the other
2525   // is from the original LiveInterval.
2526   return Orig0->def == Orig1->def && Reg0 == Reg1;
2527 }
2528 
2529 JoinVals::ConflictResolution
2530 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
2531   Val &V = Vals[ValNo];
2532   assert(!V.isAnalyzed() && "Value has already been analyzed!");
2533   VNInfo *VNI = LR.getValNumInfo(ValNo);
2534   if (VNI->isUnused()) {
2535     V.WriteLanes = LaneBitmask::getAll();
2536     return CR_Keep;
2537   }
2538 
2539   // Get the instruction defining this value, compute the lanes written.
2540   const MachineInstr *DefMI = nullptr;
2541   if (VNI->isPHIDef()) {
2542     // Conservatively assume that all lanes in a PHI are valid.
2543     LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0)
2544                                      : TRI->getSubRegIndexLaneMask(SubIdx);
2545     V.ValidLanes = V.WriteLanes = Lanes;
2546   } else {
2547     DefMI = Indexes->getInstructionFromIndex(VNI->def);
2548     assert(DefMI != nullptr);
2549     if (SubRangeJoin) {
2550       // We don't care about the lanes when joining subregister ranges.
2551       V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0);
2552       if (DefMI->isImplicitDef()) {
2553         V.ValidLanes = LaneBitmask::getNone();
2554         V.ErasableImplicitDef = true;
2555       }
2556     } else {
2557       bool Redef = false;
2558       V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
2559 
2560       // If this is a read-modify-write instruction, there may be more valid
2561       // lanes than the ones written by this instruction.
2562       // This only covers partial redef operands. DefMI may have normal use
2563       // operands reading the register. They don't contribute valid lanes.
2564       //
2565       // This adds ssub1 to the set of valid lanes in %src:
2566       //
2567       //   %src:ssub1 = FOO
2568       //
2569       // This leaves only ssub1 valid, making any other lanes undef:
2570       //
2571       //   %src:ssub1<def,read-undef> = FOO %src:ssub2
2572       //
2573       // The <read-undef> flag on the def operand means that old lane values are
2574       // not important.
2575       if (Redef) {
2576         V.RedefVNI = LR.Query(VNI->def).valueIn();
2577         assert((TrackSubRegLiveness || V.RedefVNI) &&
2578                "Instruction is reading nonexistent value");
2579         if (V.RedefVNI != nullptr) {
2580           computeAssignment(V.RedefVNI->id, Other);
2581           V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
2582         }
2583       }
2584 
2585       // An IMPLICIT_DEF writes undef values.
2586       if (DefMI->isImplicitDef()) {
2587         // We normally expect IMPLICIT_DEF values to be live only until the end
2588         // of their block. If the value is really live longer and gets pruned in
2589         // another block, this flag is cleared again.
2590         //
2591         // Clearing the valid lanes is deferred until it is sure this can be
2592         // erased.
2593         V.ErasableImplicitDef = true;
2594       }
2595     }
2596   }
2597 
2598   // Find the value in Other that overlaps VNI->def, if any.
2599   LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
2600 
2601   // It is possible that both values are defined by the same instruction, or
2602   // the values are PHIs defined in the same block. When that happens, the two
2603   // values should be merged into one, but not into any preceding value.
2604   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
2605   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
2606     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
2607 
2608     // One value stays, the other is merged. Keep the earlier one, or the first
2609     // one we see.
2610     if (OtherVNI->def < VNI->def)
2611       Other.computeAssignment(OtherVNI->id, *this);
2612     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
2613       // This is an early-clobber def overlapping a live-in value in the other
2614       // register. Not mergeable.
2615       V.OtherVNI = OtherLRQ.valueIn();
2616       return CR_Impossible;
2617     }
2618     V.OtherVNI = OtherVNI;
2619     Val &OtherV = Other.Vals[OtherVNI->id];
2620     // Keep this value, check for conflicts when analyzing OtherVNI.
2621     if (!OtherV.isAnalyzed())
2622       return CR_Keep;
2623     // Both sides have been analyzed now.
2624     // Allow overlapping PHI values. Any real interference would show up in a
2625     // predecessor, the PHI itself can't introduce any conflicts.
2626     if (VNI->isPHIDef())
2627       return CR_Merge;
2628     if ((V.ValidLanes & OtherV.ValidLanes).any())
2629       // Overlapping lanes can't be resolved.
2630       return CR_Impossible;
2631     else
2632       return CR_Merge;
2633   }
2634 
2635   // No simultaneous def. Is Other live at the def?
2636   V.OtherVNI = OtherLRQ.valueIn();
2637   if (!V.OtherVNI)
2638     // No overlap, no conflict.
2639     return CR_Keep;
2640 
2641   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
2642 
2643   // We have overlapping values, or possibly a kill of Other.
2644   // Recursively compute assignments up the dominator tree.
2645   Other.computeAssignment(V.OtherVNI->id, *this);
2646   Val &OtherV = Other.Vals[V.OtherVNI->id];
2647 
2648   if (OtherV.ErasableImplicitDef) {
2649     // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
2650     // This shouldn't normally happen, but ProcessImplicitDefs can leave such
2651     // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
2652     // technically.
2653     //
2654     // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
2655     // to erase the IMPLICIT_DEF instruction.
2656     if (DefMI &&
2657         DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
2658       LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2659                  << " extends into "
2660                  << printMBBReference(*DefMI->getParent())
2661                  << ", keeping it.\n");
2662       OtherV.ErasableImplicitDef = false;
2663     } else {
2664       // We deferred clearing these lanes in case we needed to save them
2665       OtherV.ValidLanes &= ~OtherV.WriteLanes;
2666     }
2667   }
2668 
2669   // Allow overlapping PHI values. Any real interference would show up in a
2670   // predecessor, the PHI itself can't introduce any conflicts.
2671   if (VNI->isPHIDef())
2672     return CR_Replace;
2673 
2674   // Check for simple erasable conflicts.
2675   if (DefMI->isImplicitDef()) {
2676     // We need the def for the subregister if there is nothing else live at the
2677     // subrange at this point.
2678     if (TrackSubRegLiveness
2679         && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)).none())
2680       return CR_Replace;
2681     return CR_Erase;
2682   }
2683 
2684   // Include the non-conflict where DefMI is a coalescable copy that kills
2685   // OtherVNI. We still want the copy erased and value numbers merged.
2686   if (CP.isCoalescable(DefMI)) {
2687     // Some of the lanes copied from OtherVNI may be undef, making them undef
2688     // here too.
2689     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2690     return CR_Erase;
2691   }
2692 
2693   // This may not be a real conflict if DefMI simply kills Other and defines
2694   // VNI.
2695   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
2696     return CR_Keep;
2697 
2698   // Handle the case where VNI and OtherVNI can be proven to be identical:
2699   //
2700   //   %other = COPY %ext
2701   //   %this  = COPY %ext <-- Erase this copy
2702   //
2703   if (DefMI->isFullCopy() && !CP.isPartial() &&
2704       valuesIdentical(VNI, V.OtherVNI, Other)) {
2705     V.Identical = true;
2706     return CR_Erase;
2707   }
2708 
2709   // The remaining checks apply to the lanes, which aren't tracked here.  This
2710   // was already decided to be OK via the following CR_Replace condition.
2711   // CR_Replace.
2712   if (SubRangeJoin)
2713     return CR_Replace;
2714 
2715   // If the lanes written by this instruction were all undef in OtherVNI, it is
2716   // still safe to join the live ranges. This can't be done with a simple value
2717   // mapping, though - OtherVNI will map to multiple values:
2718   //
2719   //   1 %dst:ssub0 = FOO                <-- OtherVNI
2720   //   2 %src = BAR                      <-- VNI
2721   //   3 %dst:ssub1 = COPY killed %src    <-- Eliminate this copy.
2722   //   4 BAZ killed %dst
2723   //   5 QUUX killed %src
2724   //
2725   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
2726   // handles this complex value mapping.
2727   if ((V.WriteLanes & OtherV.ValidLanes).none())
2728     return CR_Replace;
2729 
2730   // If the other live range is killed by DefMI and the live ranges are still
2731   // overlapping, it must be because we're looking at an early clobber def:
2732   //
2733   //   %dst<def,early-clobber> = ASM killed %src
2734   //
2735   // In this case, it is illegal to merge the two live ranges since the early
2736   // clobber def would clobber %src before it was read.
2737   if (OtherLRQ.isKill()) {
2738     // This case where the def doesn't overlap the kill is handled above.
2739     assert(VNI->def.isEarlyClobber() &&
2740            "Only early clobber defs can overlap a kill");
2741     return CR_Impossible;
2742   }
2743 
2744   // VNI is clobbering live lanes in OtherVNI, but there is still the
2745   // possibility that no instructions actually read the clobbered lanes.
2746   // If we're clobbering all the lanes in OtherVNI, at least one must be read.
2747   // Otherwise Other.RI wouldn't be live here.
2748   if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
2749     return CR_Impossible;
2750 
2751   // We need to verify that no instructions are reading the clobbered lanes. To
2752   // save compile time, we'll only check that locally. Don't allow the tainted
2753   // value to escape the basic block.
2754   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2755   if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
2756     return CR_Impossible;
2757 
2758   // There are still some things that could go wrong besides clobbered lanes
2759   // being read, for example OtherVNI may be only partially redefined in MBB,
2760   // and some clobbered lanes could escape the block. Save this analysis for
2761   // resolveConflicts() when all values have been mapped. We need to know
2762   // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
2763   // that now - the recursive analyzeValue() calls must go upwards in the
2764   // dominator tree.
2765   return CR_Unresolved;
2766 }
2767 
2768 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
2769   Val &V = Vals[ValNo];
2770   if (V.isAnalyzed()) {
2771     // Recursion should always move up the dominator tree, so ValNo is not
2772     // supposed to reappear before it has been assigned.
2773     assert(Assignments[ValNo] != -1 && "Bad recursion?");
2774     return;
2775   }
2776   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2777   case CR_Erase:
2778   case CR_Merge:
2779     // Merge this ValNo into OtherVNI.
2780     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
2781     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
2782     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2783     LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'
2784                       << LR.getValNumInfo(ValNo)->def << " into "
2785                       << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
2786                       << V.OtherVNI->def << " --> @"
2787                       << NewVNInfo[Assignments[ValNo]]->def << '\n');
2788     break;
2789   case CR_Replace:
2790   case CR_Unresolved: {
2791     // The other value is going to be pruned if this join is successful.
2792     assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
2793     Val &OtherV = Other.Vals[V.OtherVNI->id];
2794     // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
2795     // its lanes.
2796     if (OtherV.ErasableImplicitDef &&
2797         TrackSubRegLiveness &&
2798         (OtherV.WriteLanes & ~V.ValidLanes).any()) {
2799       LLVM_DEBUG(dbgs() << "Cannot erase implicit_def with missing values\n");
2800 
2801       OtherV.ErasableImplicitDef = false;
2802       // The valid lanes written by the implicit_def were speculatively cleared
2803       // before, so make this more conservative. It may be better to track this,
2804       // I haven't found a testcase where it matters.
2805       OtherV.ValidLanes = LaneBitmask::getAll();
2806     }
2807 
2808     OtherV.Pruned = true;
2809     LLVM_FALLTHROUGH;
2810   }
2811   default:
2812     // This value number needs to go in the final joined live range.
2813     Assignments[ValNo] = NewVNInfo.size();
2814     NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2815     break;
2816   }
2817 }
2818 
2819 bool JoinVals::mapValues(JoinVals &Other) {
2820   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2821     computeAssignment(i, Other);
2822     if (Vals[i].Resolution == CR_Impossible) {
2823       LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i
2824                         << '@' << LR.getValNumInfo(i)->def << '\n');
2825       return false;
2826     }
2827   }
2828   return true;
2829 }
2830 
2831 bool JoinVals::
2832 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2833             SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) {
2834   VNInfo *VNI = LR.getValNumInfo(ValNo);
2835   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2836   SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2837 
2838   // Scan Other.LR from VNI.def to MBBEnd.
2839   LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2840   assert(OtherI != Other.LR.end() && "No conflict?");
2841   do {
2842     // OtherI is pointing to a tainted value. Abort the join if the tainted
2843     // lanes escape the block.
2844     SlotIndex End = OtherI->end;
2845     if (End >= MBBEnd) {
2846       LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'
2847                         << OtherI->valno->id << '@' << OtherI->start << '\n');
2848       return false;
2849     }
2850     LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'
2851                       << OtherI->valno->id << '@' << OtherI->start << " to "
2852                       << End << '\n');
2853     // A dead def is not a problem.
2854     if (End.isDead())
2855       break;
2856     TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2857 
2858     // Check for another def in the MBB.
2859     if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2860       break;
2861 
2862     // Lanes written by the new def are no longer tainted.
2863     const Val &OV = Other.Vals[OtherI->valno->id];
2864     TaintedLanes &= ~OV.WriteLanes;
2865     if (!OV.RedefVNI)
2866       break;
2867   } while (TaintedLanes.any());
2868   return true;
2869 }
2870 
2871 bool JoinVals::usesLanes(const MachineInstr &MI, unsigned Reg, unsigned SubIdx,
2872                          LaneBitmask Lanes) const {
2873   if (MI.isDebugInstr())
2874     return false;
2875   for (const MachineOperand &MO : MI.operands()) {
2876     if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg)
2877       continue;
2878     if (!MO.readsReg())
2879       continue;
2880     unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
2881     if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
2882       return true;
2883   }
2884   return false;
2885 }
2886 
2887 bool JoinVals::resolveConflicts(JoinVals &Other) {
2888   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2889     Val &V = Vals[i];
2890     assert(V.Resolution != CR_Impossible && "Unresolvable conflict");
2891     if (V.Resolution != CR_Unresolved)
2892       continue;
2893     LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'
2894                       << LR.getValNumInfo(i)->def
2895                       << ' ' << PrintLaneMask(LaneMask) << '\n');
2896     if (SubRangeJoin)
2897       return false;
2898 
2899     ++NumLaneConflicts;
2900     assert(V.OtherVNI && "Inconsistent conflict resolution.");
2901     VNInfo *VNI = LR.getValNumInfo(i);
2902     const Val &OtherV = Other.Vals[V.OtherVNI->id];
2903 
2904     // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
2905     // join, those lanes will be tainted with a wrong value. Get the extent of
2906     // the tainted lanes.
2907     LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2908     SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent;
2909     if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2910       // Tainted lanes would extend beyond the basic block.
2911       return false;
2912 
2913     assert(!TaintExtent.empty() && "There should be at least one conflict.");
2914 
2915     // Now look at the instructions from VNI->def to TaintExtent (inclusive).
2916     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2917     MachineBasicBlock::iterator MI = MBB->begin();
2918     if (!VNI->isPHIDef()) {
2919       MI = Indexes->getInstructionFromIndex(VNI->def);
2920       // No need to check the instruction defining VNI for reads.
2921       ++MI;
2922     }
2923     assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
2924            "Interference ends on VNI->def. Should have been handled earlier");
2925     MachineInstr *LastMI =
2926       Indexes->getInstructionFromIndex(TaintExtent.front().first);
2927     assert(LastMI && "Range must end at a proper instruction");
2928     unsigned TaintNum = 0;
2929     while (true) {
2930       assert(MI != MBB->end() && "Bad LastMI");
2931       if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2932         LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
2933         return false;
2934       }
2935       // LastMI is the last instruction to use the current value.
2936       if (&*MI == LastMI) {
2937         if (++TaintNum == TaintExtent.size())
2938           break;
2939         LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
2940         assert(LastMI && "Range must end at a proper instruction");
2941         TaintedLanes = TaintExtent[TaintNum].second;
2942       }
2943       ++MI;
2944     }
2945 
2946     // The tainted lanes are unused.
2947     V.Resolution = CR_Replace;
2948     ++NumLaneResolves;
2949   }
2950   return true;
2951 }
2952 
2953 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
2954   Val &V = Vals[ValNo];
2955   if (V.Pruned || V.PrunedComputed)
2956     return V.Pruned;
2957 
2958   if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2959     return V.Pruned;
2960 
2961   // Follow copies up the dominator tree and check if any intermediate value
2962   // has been pruned.
2963   V.PrunedComputed = true;
2964   V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
2965   return V.Pruned;
2966 }
2967 
2968 void JoinVals::pruneValues(JoinVals &Other,
2969                            SmallVectorImpl<SlotIndex> &EndPoints,
2970                            bool changeInstrs) {
2971   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2972     SlotIndex Def = LR.getValNumInfo(i)->def;
2973     switch (Vals[i].Resolution) {
2974     case CR_Keep:
2975       break;
2976     case CR_Replace: {
2977       // This value takes precedence over the value in Other.LR.
2978       LIS->pruneValue(Other.LR, Def, &EndPoints);
2979       // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
2980       // instructions are only inserted to provide a live-out value for PHI
2981       // predecessors, so the instruction should simply go away once its value
2982       // has been replaced.
2983       Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2984       bool EraseImpDef = OtherV.ErasableImplicitDef &&
2985                          OtherV.Resolution == CR_Keep;
2986       if (!Def.isBlock()) {
2987         if (changeInstrs) {
2988           // Remove <def,read-undef> flags. This def is now a partial redef.
2989           // Also remove dead flags since the joined live range will
2990           // continue past this instruction.
2991           for (MachineOperand &MO :
2992                Indexes->getInstructionFromIndex(Def)->operands()) {
2993             if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
2994               if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef)
2995                 MO.setIsUndef(false);
2996               MO.setIsDead(false);
2997             }
2998           }
2999         }
3000         // This value will reach instructions below, but we need to make sure
3001         // the live range also reaches the instruction at Def.
3002         if (!EraseImpDef)
3003           EndPoints.push_back(Def);
3004       }
3005       LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Def
3006                         << ": " << Other.LR << '\n');
3007       break;
3008     }
3009     case CR_Erase:
3010     case CR_Merge:
3011       if (isPrunedValue(i, Other)) {
3012         // This value is ultimately a copy of a pruned value in LR or Other.LR.
3013         // We can no longer trust the value mapping computed by
3014         // computeAssignment(), the value that was originally copied could have
3015         // been replaced.
3016         LIS->pruneValue(LR, Def, &EndPoints);
3017         LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "
3018                           << Def << ": " << LR << '\n');
3019       }
3020       break;
3021     case CR_Unresolved:
3022     case CR_Impossible:
3023       llvm_unreachable("Unresolved conflicts");
3024     }
3025   }
3026 }
3027 
3028 /// Consider the following situation when coalescing the copy between
3029 /// %31 and %45 at 800. (The vertical lines represent live range segments.)
3030 ///
3031 ///                              Main range         Subrange 0004 (sub2)
3032 ///                              %31    %45           %31    %45
3033 ///  544    %45 = COPY %28               +                    +
3034 ///                                      | v1                 | v1
3035 ///  560B bb.1:                          +                    +
3036 ///  624        = %45.sub2               | v2                 | v2
3037 ///  800    %31 = COPY %45        +      +             +      +
3038 ///                               | v0                 | v0
3039 ///  816    %31.sub1 = ...        +                    |
3040 ///  880    %30 = COPY %31        | v1                 +
3041 ///  928    %45 = COPY %30        |      +                    +
3042 ///                               |      | v0                 | v0  <--+
3043 ///  992B   ; backedge -> bb.1    |      +                    +        |
3044 /// 1040        = %31.sub0        +                                    |
3045 ///                                                 This value must remain
3046 ///                                                 live-out!
3047 ///
3048 /// Assuming that %31 is coalesced into %45, the copy at 928 becomes
3049 /// redundant, since it copies the value from %45 back into it. The
3050 /// conflict resolution for the main range determines that %45.v0 is
3051 /// to be erased, which is ok since %31.v1 is identical to it.
3052 /// The problem happens with the subrange for sub2: it has to be live
3053 /// on exit from the block, but since 928 was actually a point of
3054 /// definition of %45.sub2, %45.sub2 was not live immediately prior
3055 /// to that definition. As a result, when 928 was erased, the value v0
3056 /// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an
3057 /// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2,
3058 /// providing an incorrect value to the use at 624.
3059 ///
3060 /// Since the main-range values %31.v1 and %45.v0 were proved to be
3061 /// identical, the corresponding values in subranges must also be the
3062 /// same. A redundant copy is removed because it's not needed, and not
3063 /// because it copied an undefined value, so any liveness that originated
3064 /// from that copy cannot disappear. When pruning a value that started
3065 /// at the removed copy, the corresponding identical value must be
3066 /// extended to replace it.
3067 void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) {
3068   // Look for values being erased.
3069   bool DidPrune = false;
3070   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3071     Val &V = Vals[i];
3072     // We should trigger in all cases in which eraseInstrs() does something.
3073     // match what eraseInstrs() is doing, print a message so
3074     if (V.Resolution != CR_Erase &&
3075         (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
3076       continue;
3077 
3078     // Check subranges at the point where the copy will be removed.
3079     SlotIndex Def = LR.getValNumInfo(i)->def;
3080     SlotIndex OtherDef;
3081     if (V.Identical)
3082       OtherDef = V.OtherVNI->def;
3083 
3084     // Print message so mismatches with eraseInstrs() can be diagnosed.
3085     LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Def
3086                       << '\n');
3087     for (LiveInterval::SubRange &S : LI.subranges()) {
3088       LiveQueryResult Q = S.Query(Def);
3089 
3090       // If a subrange starts at the copy then an undefined value has been
3091       // copied and we must remove that subrange value as well.
3092       VNInfo *ValueOut = Q.valueOutOrDead();
3093       if (ValueOut != nullptr && (Q.valueIn() == nullptr ||
3094                                   (V.Identical && V.Resolution == CR_Erase &&
3095                                    ValueOut->def == Def))) {
3096         LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
3097                           << " at " << Def << "\n");
3098         SmallVector<SlotIndex,8> EndPoints;
3099         LIS->pruneValue(S, Def, &EndPoints);
3100         DidPrune = true;
3101         // Mark value number as unused.
3102         ValueOut->markUnused();
3103 
3104         if (V.Identical && S.Query(OtherDef).valueOutOrDead()) {
3105           // If V is identical to V.OtherVNI (and S was live at OtherDef),
3106           // then we can't simply prune V from S. V needs to be replaced
3107           // with V.OtherVNI.
3108           LIS->extendToIndices(S, EndPoints);
3109         }
3110         continue;
3111       }
3112       // If a subrange ends at the copy, then a value was copied but only
3113       // partially used later. Shrink the subregister range appropriately.
3114       if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
3115         LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "
3116                           << PrintLaneMask(S.LaneMask) << " at " << Def
3117                           << "\n");
3118         ShrinkMask |= S.LaneMask;
3119       }
3120     }
3121   }
3122   if (DidPrune)
3123     LI.removeEmptySubRanges();
3124 }
3125 
3126 /// Check if any of the subranges of @p LI contain a definition at @p Def.
3127 static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) {
3128   for (LiveInterval::SubRange &SR : LI.subranges()) {
3129     if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
3130       if (VNI->def == Def)
3131         return true;
3132   }
3133   return false;
3134 }
3135 
3136 void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
3137   assert(&static_cast<LiveRange&>(LI) == &LR);
3138 
3139   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3140     if (Vals[i].Resolution != CR_Keep)
3141       continue;
3142     VNInfo *VNI = LR.getValNumInfo(i);
3143     if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
3144       continue;
3145     Vals[i].Pruned = true;
3146     ShrinkMainRange = true;
3147   }
3148 }
3149 
3150 void JoinVals::removeImplicitDefs() {
3151   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3152     Val &V = Vals[i];
3153     if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
3154       continue;
3155 
3156     VNInfo *VNI = LR.getValNumInfo(i);
3157     VNI->markUnused();
3158     LR.removeValNo(VNI);
3159   }
3160 }
3161 
3162 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
3163                            SmallVectorImpl<unsigned> &ShrinkRegs,
3164                            LiveInterval *LI) {
3165   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3166     // Get the def location before markUnused() below invalidates it.
3167     VNInfo *VNI = LR.getValNumInfo(i);
3168     SlotIndex Def = VNI->def;
3169     switch (Vals[i].Resolution) {
3170     case CR_Keep: {
3171       // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
3172       // longer. The IMPLICIT_DEF instructions are only inserted by
3173       // PHIElimination to guarantee that all PHI predecessors have a value.
3174       if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
3175         break;
3176       // Remove value number i from LR.
3177       // For intervals with subranges, removing a segment from the main range
3178       // may require extending the previous segment: for each definition of
3179       // a subregister, there will be a corresponding def in the main range.
3180       // That def may fall in the middle of a segment from another subrange.
3181       // In such cases, removing this def from the main range must be
3182       // complemented by extending the main range to account for the liveness
3183       // of the other subrange.
3184       // The new end point of the main range segment to be extended.
3185       SlotIndex NewEnd;
3186       if (LI != nullptr) {
3187         LiveRange::iterator I = LR.FindSegmentContaining(Def);
3188         assert(I != LR.end());
3189         // Do not extend beyond the end of the segment being removed.
3190         // The segment may have been pruned in preparation for joining
3191         // live ranges.
3192         NewEnd = I->end;
3193       }
3194 
3195       LR.removeValNo(VNI);
3196       // Note that this VNInfo is reused and still referenced in NewVNInfo,
3197       // make it appear like an unused value number.
3198       VNI->markUnused();
3199 
3200       if (LI != nullptr && LI->hasSubRanges()) {
3201         assert(static_cast<LiveRange*>(LI) == &LR);
3202         // Determine the end point based on the subrange information:
3203         // minimum of (earliest def of next segment,
3204         //             latest end point of containing segment)
3205         SlotIndex ED, LE;
3206         for (LiveInterval::SubRange &SR : LI->subranges()) {
3207           LiveRange::iterator I = SR.find(Def);
3208           if (I == SR.end())
3209             continue;
3210           if (I->start > Def)
3211             ED = ED.isValid() ? std::min(ED, I->start) : I->start;
3212           else
3213             LE = LE.isValid() ? std::max(LE, I->end) : I->end;
3214         }
3215         if (LE.isValid())
3216           NewEnd = std::min(NewEnd, LE);
3217         if (ED.isValid())
3218           NewEnd = std::min(NewEnd, ED);
3219 
3220         // We only want to do the extension if there was a subrange that
3221         // was live across Def.
3222         if (LE.isValid()) {
3223           LiveRange::iterator S = LR.find(Def);
3224           if (S != LR.begin())
3225             std::prev(S)->end = NewEnd;
3226         }
3227       }
3228       LLVM_DEBUG({
3229         dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';
3230         if (LI != nullptr)
3231           dbgs() << "\t\t  LHS = " << *LI << '\n';
3232       });
3233       LLVM_FALLTHROUGH;
3234     }
3235 
3236     case CR_Erase: {
3237       MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
3238       assert(MI && "No instruction to erase");
3239       if (MI->isCopy()) {
3240         Register Reg = MI->getOperand(1).getReg();
3241         if (Register::isVirtualRegister(Reg) && Reg != CP.getSrcReg() &&
3242             Reg != CP.getDstReg())
3243           ShrinkRegs.push_back(Reg);
3244       }
3245       ErasedInstrs.insert(MI);
3246       LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
3247       LIS->RemoveMachineInstrFromMaps(*MI);
3248       MI->eraseFromParent();
3249       break;
3250     }
3251     default:
3252       break;
3253     }
3254   }
3255 }
3256 
3257 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
3258                                          LaneBitmask LaneMask,
3259                                          const CoalescerPair &CP) {
3260   SmallVector<VNInfo*, 16> NewVNInfo;
3261   JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
3262                    NewVNInfo, CP, LIS, TRI, true, true);
3263   JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
3264                    NewVNInfo, CP, LIS, TRI, true, true);
3265 
3266   // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
3267   // We should be able to resolve all conflicts here as we could successfully do
3268   // it on the mainrange already. There is however a problem when multiple
3269   // ranges get mapped to the "overflow" lane mask bit which creates unexpected
3270   // interferences.
3271   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
3272     // We already determined that it is legal to merge the intervals, so this
3273     // should never fail.
3274     llvm_unreachable("*** Couldn't join subrange!\n");
3275   }
3276   if (!LHSVals.resolveConflicts(RHSVals) ||
3277       !RHSVals.resolveConflicts(LHSVals)) {
3278     // We already determined that it is legal to merge the intervals, so this
3279     // should never fail.
3280     llvm_unreachable("*** Couldn't join subrange!\n");
3281   }
3282 
3283   // The merging algorithm in LiveInterval::join() can't handle conflicting
3284   // value mappings, so we need to remove any live ranges that overlap a
3285   // CR_Replace resolution. Collect a set of end points that can be used to
3286   // restore the live range after joining.
3287   SmallVector<SlotIndex, 8> EndPoints;
3288   LHSVals.pruneValues(RHSVals, EndPoints, false);
3289   RHSVals.pruneValues(LHSVals, EndPoints, false);
3290 
3291   LHSVals.removeImplicitDefs();
3292   RHSVals.removeImplicitDefs();
3293 
3294   LRange.verify();
3295   RRange.verify();
3296 
3297   // Join RRange into LHS.
3298   LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
3299               NewVNInfo);
3300 
3301   LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask)
3302                     << ' ' << LRange << "\n");
3303   if (EndPoints.empty())
3304     return;
3305 
3306   // Recompute the parts of the live range we had to remove because of
3307   // CR_Replace conflicts.
3308   LLVM_DEBUG({
3309     dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3310     for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3311       dbgs() << EndPoints[i];
3312       if (i != n-1)
3313         dbgs() << ',';
3314     }
3315     dbgs() << ":  " << LRange << '\n';
3316   });
3317   LIS->extendToIndices(LRange, EndPoints);
3318 }
3319 
3320 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
3321                                           const LiveRange &ToMerge,
3322                                           LaneBitmask LaneMask,
3323                                           CoalescerPair &CP,
3324                                           unsigned ComposeSubRegIdx) {
3325   BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
3326   LI.refineSubRanges(
3327       Allocator, LaneMask,
3328       [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) {
3329         if (SR.empty()) {
3330           SR.assign(ToMerge, Allocator);
3331         } else {
3332           // joinSubRegRange() destroys the merged range, so we need a copy.
3333           LiveRange RangeCopy(ToMerge, Allocator);
3334           joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP);
3335         }
3336       },
3337       *LIS->getSlotIndexes(), *TRI, ComposeSubRegIdx);
3338 }
3339 
3340 bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) {
3341   if (LI.valnos.size() < LargeIntervalSizeThreshold)
3342     return false;
3343   auto &Counter = LargeLIVisitCounter[LI.reg];
3344   if (Counter < LargeIntervalFreqThreshold) {
3345     Counter++;
3346     return false;
3347   }
3348   return true;
3349 }
3350 
3351 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
3352   SmallVector<VNInfo*, 16> NewVNInfo;
3353   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
3354   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
3355   bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
3356   JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
3357                    NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3358   JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
3359                    NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3360 
3361   LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n');
3362 
3363   if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS))
3364     return false;
3365 
3366   // First compute NewVNInfo and the simple value mappings.
3367   // Detect impossible conflicts early.
3368   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
3369     return false;
3370 
3371   // Some conflicts can only be resolved after all values have been mapped.
3372   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
3373     return false;
3374 
3375   // All clear, the live ranges can be merged.
3376   if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
3377     BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
3378 
3379     // Transform lanemasks from the LHS to masks in the coalesced register and
3380     // create initial subranges if necessary.
3381     unsigned DstIdx = CP.getDstIdx();
3382     if (!LHS.hasSubRanges()) {
3383       LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
3384                                      : TRI->getSubRegIndexLaneMask(DstIdx);
3385       // LHS must support subregs or we wouldn't be in this codepath.
3386       assert(Mask.any());
3387       LHS.createSubRangeFrom(Allocator, Mask, LHS);
3388     } else if (DstIdx != 0) {
3389       // Transform LHS lanemasks to new register class if necessary.
3390       for (LiveInterval::SubRange &R : LHS.subranges()) {
3391         LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
3392         R.LaneMask = Mask;
3393       }
3394     }
3395     LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHS
3396                       << '\n');
3397 
3398     // Determine lanemasks of RHS in the coalesced register and merge subranges.
3399     unsigned SrcIdx = CP.getSrcIdx();
3400     if (!RHS.hasSubRanges()) {
3401       LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
3402                                      : TRI->getSubRegIndexLaneMask(SrcIdx);
3403       mergeSubRangeInto(LHS, RHS, Mask, CP, DstIdx);
3404     } else {
3405       // Pair up subranges and merge.
3406       for (LiveInterval::SubRange &R : RHS.subranges()) {
3407         LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
3408         mergeSubRangeInto(LHS, R, Mask, CP, DstIdx);
3409       }
3410     }
3411     LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
3412 
3413     // Pruning implicit defs from subranges may result in the main range
3414     // having stale segments.
3415     LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3416 
3417     LHSVals.pruneSubRegValues(LHS, ShrinkMask);
3418     RHSVals.pruneSubRegValues(LHS, ShrinkMask);
3419   }
3420 
3421   // The merging algorithm in LiveInterval::join() can't handle conflicting
3422   // value mappings, so we need to remove any live ranges that overlap a
3423   // CR_Replace resolution. Collect a set of end points that can be used to
3424   // restore the live range after joining.
3425   SmallVector<SlotIndex, 8> EndPoints;
3426   LHSVals.pruneValues(RHSVals, EndPoints, true);
3427   RHSVals.pruneValues(LHSVals, EndPoints, true);
3428 
3429   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
3430   // registers to require trimming.
3431   SmallVector<unsigned, 8> ShrinkRegs;
3432   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
3433   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
3434   while (!ShrinkRegs.empty())
3435     shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
3436 
3437   // Scan and mark undef any DBG_VALUEs that would refer to a different value.
3438   checkMergingChangesDbgValues(CP, LHS, LHSVals, RHS, RHSVals);
3439 
3440   // Join RHS into LHS.
3441   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
3442 
3443   // Kill flags are going to be wrong if the live ranges were overlapping.
3444   // Eventually, we should simply clear all kill flags when computing live
3445   // ranges. They are reinserted after register allocation.
3446   MRI->clearKillFlags(LHS.reg);
3447   MRI->clearKillFlags(RHS.reg);
3448 
3449   if (!EndPoints.empty()) {
3450     // Recompute the parts of the live range we had to remove because of
3451     // CR_Replace conflicts.
3452     LLVM_DEBUG({
3453       dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3454       for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3455         dbgs() << EndPoints[i];
3456         if (i != n-1)
3457           dbgs() << ',';
3458       }
3459       dbgs() << ":  " << LHS << '\n';
3460     });
3461     LIS->extendToIndices((LiveRange&)LHS, EndPoints);
3462   }
3463 
3464   return true;
3465 }
3466 
3467 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
3468   return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
3469 }
3470 
3471 void RegisterCoalescer::buildVRegToDbgValueMap(MachineFunction &MF)
3472 {
3473   const SlotIndexes &Slots = *LIS->getSlotIndexes();
3474   SmallVector<MachineInstr *, 8> ToInsert;
3475 
3476   // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
3477   // vreg => DbgValueLoc map.
3478   auto CloseNewDVRange = [this, &ToInsert](SlotIndex Slot) {
3479     for (auto *X : ToInsert)
3480       DbgVRegToValues[X->getOperand(0).getReg()].push_back({Slot, X});
3481 
3482     ToInsert.clear();
3483   };
3484 
3485   // Iterate over all instructions, collecting them into the ToInsert vector.
3486   // Once a non-debug instruction is found, record the slot index of the
3487   // collected DBG_VALUEs.
3488   for (auto &MBB : MF) {
3489     SlotIndex CurrentSlot = Slots.getMBBStartIdx(&MBB);
3490 
3491     for (auto &MI : MBB) {
3492       if (MI.isDebugValue() && MI.getOperand(0).isReg() &&
3493           MI.getOperand(0).getReg().isVirtual()) {
3494         ToInsert.push_back(&MI);
3495       } else if (!MI.isDebugInstr()) {
3496         CurrentSlot = Slots.getInstructionIndex(MI);
3497         CloseNewDVRange(CurrentSlot);
3498       }
3499     }
3500 
3501     // Close range of DBG_VALUEs at the end of blocks.
3502     CloseNewDVRange(Slots.getMBBEndIdx(&MBB));
3503   }
3504 
3505   // Sort all DBG_VALUEs we've seen by slot number.
3506   for (auto &Pair : DbgVRegToValues)
3507     llvm::sort(Pair.second);
3508 }
3509 
3510 void RegisterCoalescer::checkMergingChangesDbgValues(CoalescerPair &CP,
3511                                                      LiveRange &LHS,
3512                                                      JoinVals &LHSVals,
3513                                                      LiveRange &RHS,
3514                                                      JoinVals &RHSVals) {
3515   auto ScanForDstReg = [&](unsigned Reg) {
3516     checkMergingChangesDbgValuesImpl(Reg, RHS, LHS, LHSVals);
3517   };
3518 
3519   auto ScanForSrcReg = [&](unsigned Reg) {
3520     checkMergingChangesDbgValuesImpl(Reg, LHS, RHS, RHSVals);
3521   };
3522 
3523   // Scan for potentially unsound DBG_VALUEs: examine first the register number
3524   // Reg, and then any other vregs that may have been merged into  it.
3525   auto PerformScan = [this](unsigned Reg, std::function<void(unsigned)> Func) {
3526     Func(Reg);
3527     if (DbgMergedVRegNums.count(Reg))
3528       for (unsigned X : DbgMergedVRegNums[Reg])
3529         Func(X);
3530   };
3531 
3532   // Scan for unsound updates of both the source and destination register.
3533   PerformScan(CP.getSrcReg(), ScanForSrcReg);
3534   PerformScan(CP.getDstReg(), ScanForDstReg);
3535 }
3536 
3537 void RegisterCoalescer::checkMergingChangesDbgValuesImpl(unsigned Reg,
3538                                                          LiveRange &OtherLR,
3539                                                          LiveRange &RegLR,
3540                                                          JoinVals &RegVals) {
3541   // Are there any DBG_VALUEs to examine?
3542   auto VRegMapIt = DbgVRegToValues.find(Reg);
3543   if (VRegMapIt == DbgVRegToValues.end())
3544     return;
3545 
3546   auto &DbgValueSet = VRegMapIt->second;
3547   auto DbgValueSetIt = DbgValueSet.begin();
3548   auto SegmentIt = OtherLR.begin();
3549 
3550   bool LastUndefResult = false;
3551   SlotIndex LastUndefIdx;
3552 
3553   // If the "Other" register is live at a slot Idx, test whether Reg can
3554   // safely be merged with it, or should be marked undef.
3555   auto ShouldUndef = [&RegVals, &RegLR, &LastUndefResult,
3556                       &LastUndefIdx](SlotIndex Idx) -> bool {
3557     // Our worst-case performance typically happens with asan, causing very
3558     // many DBG_VALUEs of the same location. Cache a copy of the most recent
3559     // result for this edge-case.
3560     if (LastUndefIdx == Idx)
3561       return LastUndefResult;
3562 
3563     // If the other range was live, and Reg's was not, the register coalescer
3564     // will not have tried to resolve any conflicts. We don't know whether
3565     // the DBG_VALUE will refer to the same value number, so it must be made
3566     // undef.
3567     auto OtherIt = RegLR.find(Idx);
3568     if (OtherIt == RegLR.end())
3569       return true;
3570 
3571     // Both the registers were live: examine the conflict resolution record for
3572     // the value number Reg refers to. CR_Keep meant that this value number
3573     // "won" and the merged register definitely refers to that value. CR_Erase
3574     // means the value number was a redundant copy of the other value, which
3575     // was coalesced and Reg deleted. It's safe to refer to the other register
3576     // (which will be the source of the copy).
3577     auto Resolution = RegVals.getResolution(OtherIt->valno->id);
3578     LastUndefResult = Resolution != JoinVals::CR_Keep &&
3579                       Resolution != JoinVals::CR_Erase;
3580     LastUndefIdx = Idx;
3581     return LastUndefResult;
3582   };
3583 
3584   // Iterate over both the live-range of the "Other" register, and the set of
3585   // DBG_VALUEs for Reg at the same time. Advance whichever one has the lowest
3586   // slot index. This relies on the DbgValueSet being ordered.
3587   while (DbgValueSetIt != DbgValueSet.end() && SegmentIt != OtherLR.end()) {
3588     if (DbgValueSetIt->first < SegmentIt->end) {
3589       // "Other" is live and there is a DBG_VALUE of Reg: test if we should
3590       // set it undef.
3591       if (DbgValueSetIt->first >= SegmentIt->start &&
3592           DbgValueSetIt->second->getOperand(0).getReg() != 0 &&
3593           ShouldUndef(DbgValueSetIt->first)) {
3594         // Mark undef, erase record of this DBG_VALUE to avoid revisiting.
3595         DbgValueSetIt->second->getOperand(0).setReg(0);
3596         continue;
3597       }
3598       ++DbgValueSetIt;
3599     } else {
3600       ++SegmentIt;
3601     }
3602   }
3603 }
3604 
3605 namespace {
3606 
3607 /// Information concerning MBB coalescing priority.
3608 struct MBBPriorityInfo {
3609   MachineBasicBlock *MBB;
3610   unsigned Depth;
3611   bool IsSplit;
3612 
3613   MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
3614     : MBB(mbb), Depth(depth), IsSplit(issplit) {}
3615 };
3616 
3617 } // end anonymous namespace
3618 
3619 /// C-style comparator that sorts first based on the loop depth of the basic
3620 /// block (the unsigned), and then on the MBB number.
3621 ///
3622 /// EnableGlobalCopies assumes that the primary sort key is loop depth.
3623 static int compareMBBPriority(const MBBPriorityInfo *LHS,
3624                               const MBBPriorityInfo *RHS) {
3625   // Deeper loops first
3626   if (LHS->Depth != RHS->Depth)
3627     return LHS->Depth > RHS->Depth ? -1 : 1;
3628 
3629   // Try to unsplit critical edges next.
3630   if (LHS->IsSplit != RHS->IsSplit)
3631     return LHS->IsSplit ? -1 : 1;
3632 
3633   // Prefer blocks that are more connected in the CFG. This takes care of
3634   // the most difficult copies first while intervals are short.
3635   unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
3636   unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
3637   if (cl != cr)
3638     return cl > cr ? -1 : 1;
3639 
3640   // As a last resort, sort by block number.
3641   return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
3642 }
3643 
3644 /// \returns true if the given copy uses or defines a local live range.
3645 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
3646   if (!Copy->isCopy())
3647     return false;
3648 
3649   if (Copy->getOperand(1).isUndef())
3650     return false;
3651 
3652   Register SrcReg = Copy->getOperand(1).getReg();
3653   Register DstReg = Copy->getOperand(0).getReg();
3654   if (Register::isPhysicalRegister(SrcReg) ||
3655       Register::isPhysicalRegister(DstReg))
3656     return false;
3657 
3658   return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
3659     || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
3660 }
3661 
3662 void RegisterCoalescer::lateLiveIntervalUpdate() {
3663   for (unsigned reg : ToBeUpdated) {
3664     if (!LIS->hasInterval(reg))
3665       continue;
3666     LiveInterval &LI = LIS->getInterval(reg);
3667     shrinkToUses(&LI, &DeadDefs);
3668     if (!DeadDefs.empty())
3669       eliminateDeadDefs();
3670   }
3671   ToBeUpdated.clear();
3672 }
3673 
3674 bool RegisterCoalescer::
3675 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
3676   bool Progress = false;
3677   for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
3678     if (!CurrList[i])
3679       continue;
3680     // Skip instruction pointers that have already been erased, for example by
3681     // dead code elimination.
3682     if (ErasedInstrs.count(CurrList[i])) {
3683       CurrList[i] = nullptr;
3684       continue;
3685     }
3686     bool Again = false;
3687     bool Success = joinCopy(CurrList[i], Again);
3688     Progress |= Success;
3689     if (Success || !Again)
3690       CurrList[i] = nullptr;
3691   }
3692   return Progress;
3693 }
3694 
3695 /// Check if DstReg is a terminal node.
3696 /// I.e., it does not have any affinity other than \p Copy.
3697 static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy,
3698                           const MachineRegisterInfo *MRI) {
3699   assert(Copy.isCopyLike());
3700   // Check if the destination of this copy as any other affinity.
3701   for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
3702     if (&MI != &Copy && MI.isCopyLike())
3703       return false;
3704   return true;
3705 }
3706 
3707 bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
3708   assert(Copy.isCopyLike());
3709   if (!UseTerminalRule)
3710     return false;
3711   unsigned DstReg, DstSubReg, SrcReg, SrcSubReg;
3712   if (!isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
3713     return false;
3714   // Check if the destination of this copy has any other affinity.
3715   if (Register::isPhysicalRegister(DstReg) ||
3716       // If SrcReg is a physical register, the copy won't be coalesced.
3717       // Ignoring it may have other side effect (like missing
3718       // rematerialization). So keep it.
3719       Register::isPhysicalRegister(SrcReg) || !isTerminalReg(DstReg, Copy, MRI))
3720     return false;
3721 
3722   // DstReg is a terminal node. Check if it interferes with any other
3723   // copy involving SrcReg.
3724   const MachineBasicBlock *OrigBB = Copy.getParent();
3725   const LiveInterval &DstLI = LIS->getInterval(DstReg);
3726   for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
3727     // Technically we should check if the weight of the new copy is
3728     // interesting compared to the other one and update the weight
3729     // of the copies accordingly. However, this would only work if
3730     // we would gather all the copies first then coalesce, whereas
3731     // right now we interleave both actions.
3732     // For now, just consider the copies that are in the same block.
3733     if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
3734       continue;
3735     unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg;
3736     if (!isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
3737                 OtherSubReg))
3738       return false;
3739     if (OtherReg == SrcReg)
3740       OtherReg = OtherSrcReg;
3741     // Check if OtherReg is a non-terminal.
3742     if (Register::isPhysicalRegister(OtherReg) ||
3743         isTerminalReg(OtherReg, MI, MRI))
3744       continue;
3745     // Check that OtherReg interfere with DstReg.
3746     if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
3747       LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)
3748                         << '\n');
3749       return true;
3750     }
3751   }
3752   return false;
3753 }
3754 
3755 void
3756 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
3757   LLVM_DEBUG(dbgs() << MBB->getName() << ":\n");
3758 
3759   // Collect all copy-like instructions in MBB. Don't start coalescing anything
3760   // yet, it might invalidate the iterator.
3761   const unsigned PrevSize = WorkList.size();
3762   if (JoinGlobalCopies) {
3763     SmallVector<MachineInstr*, 2> LocalTerminals;
3764     SmallVector<MachineInstr*, 2> GlobalTerminals;
3765     // Coalesce copies bottom-up to coalesce local defs before local uses. They
3766     // are not inherently easier to resolve, but slightly preferable until we
3767     // have local live range splitting. In particular this is required by
3768     // cmp+jmp macro fusion.
3769     for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
3770          MII != E; ++MII) {
3771       if (!MII->isCopyLike())
3772         continue;
3773       bool ApplyTerminalRule = applyTerminalRule(*MII);
3774       if (isLocalCopy(&(*MII), LIS)) {
3775         if (ApplyTerminalRule)
3776           LocalTerminals.push_back(&(*MII));
3777         else
3778           LocalWorkList.push_back(&(*MII));
3779       } else {
3780         if (ApplyTerminalRule)
3781           GlobalTerminals.push_back(&(*MII));
3782         else
3783           WorkList.push_back(&(*MII));
3784       }
3785     }
3786     // Append the copies evicted by the terminal rule at the end of the list.
3787     LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
3788     WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
3789   }
3790   else {
3791     SmallVector<MachineInstr*, 2> Terminals;
3792     for (MachineInstr &MII : *MBB)
3793       if (MII.isCopyLike()) {
3794         if (applyTerminalRule(MII))
3795           Terminals.push_back(&MII);
3796         else
3797           WorkList.push_back(&MII);
3798       }
3799     // Append the copies evicted by the terminal rule at the end of the list.
3800     WorkList.append(Terminals.begin(), Terminals.end());
3801   }
3802   // Try coalescing the collected copies immediately, and remove the nulls.
3803   // This prevents the WorkList from getting too large since most copies are
3804   // joinable on the first attempt.
3805   MutableArrayRef<MachineInstr*>
3806     CurrList(WorkList.begin() + PrevSize, WorkList.end());
3807   if (copyCoalesceWorkList(CurrList))
3808     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
3809                                nullptr), WorkList.end());
3810 }
3811 
3812 void RegisterCoalescer::coalesceLocals() {
3813   copyCoalesceWorkList(LocalWorkList);
3814   for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
3815     if (LocalWorkList[j])
3816       WorkList.push_back(LocalWorkList[j]);
3817   }
3818   LocalWorkList.clear();
3819 }
3820 
3821 void RegisterCoalescer::joinAllIntervals() {
3822   LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
3823   assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
3824 
3825   std::vector<MBBPriorityInfo> MBBs;
3826   MBBs.reserve(MF->size());
3827   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
3828     MachineBasicBlock *MBB = &*I;
3829     MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
3830                                    JoinSplitEdges && isSplitEdge(MBB)));
3831   }
3832   array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
3833 
3834   // Coalesce intervals in MBB priority order.
3835   unsigned CurrDepth = std::numeric_limits<unsigned>::max();
3836   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
3837     // Try coalescing the collected local copies for deeper loops.
3838     if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
3839       coalesceLocals();
3840       CurrDepth = MBBs[i].Depth;
3841     }
3842     copyCoalesceInMBB(MBBs[i].MBB);
3843   }
3844   lateLiveIntervalUpdate();
3845   coalesceLocals();
3846 
3847   // Joining intervals can allow other intervals to be joined.  Iteratively join
3848   // until we make no progress.
3849   while (copyCoalesceWorkList(WorkList))
3850     /* empty */ ;
3851   lateLiveIntervalUpdate();
3852 }
3853 
3854 void RegisterCoalescer::releaseMemory() {
3855   ErasedInstrs.clear();
3856   WorkList.clear();
3857   DeadDefs.clear();
3858   InflateRegs.clear();
3859   LargeLIVisitCounter.clear();
3860 }
3861 
3862 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
3863   MF = &fn;
3864   MRI = &fn.getRegInfo();
3865   const TargetSubtargetInfo &STI = fn.getSubtarget();
3866   TRI = STI.getRegisterInfo();
3867   TII = STI.getInstrInfo();
3868   LIS = &getAnalysis<LiveIntervals>();
3869   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3870   Loops = &getAnalysis<MachineLoopInfo>();
3871   if (EnableGlobalCopies == cl::BOU_UNSET)
3872     JoinGlobalCopies = STI.enableJoinGlobalCopies();
3873   else
3874     JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
3875 
3876   // The MachineScheduler does not currently require JoinSplitEdges. This will
3877   // either be enabled unconditionally or replaced by a more general live range
3878   // splitting optimization.
3879   JoinSplitEdges = EnableJoinSplits;
3880 
3881   LLVM_DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
3882                     << "********** Function: " << MF->getName() << '\n');
3883 
3884   if (VerifyCoalescing)
3885     MF->verify(this, "Before register coalescing");
3886 
3887   DbgVRegToValues.clear();
3888   DbgMergedVRegNums.clear();
3889   buildVRegToDbgValueMap(fn);
3890 
3891   RegClassInfo.runOnMachineFunction(fn);
3892 
3893   // Join (coalesce) intervals if requested.
3894   if (EnableJoining)
3895     joinAllIntervals();
3896 
3897   // After deleting a lot of copies, register classes may be less constrained.
3898   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
3899   // DPR inflation.
3900   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
3901   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
3902                     InflateRegs.end());
3903   LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()
3904                     << " regs.\n");
3905   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
3906     unsigned Reg = InflateRegs[i];
3907     if (MRI->reg_nodbg_empty(Reg))
3908       continue;
3909     if (MRI->recomputeRegClass(Reg)) {
3910       LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "
3911                         << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
3912       ++NumInflated;
3913 
3914       LiveInterval &LI = LIS->getInterval(Reg);
3915       if (LI.hasSubRanges()) {
3916         // If the inflated register class does not support subregisters anymore
3917         // remove the subranges.
3918         if (!MRI->shouldTrackSubRegLiveness(Reg)) {
3919           LI.clearSubRanges();
3920         } else {
3921 #ifndef NDEBUG
3922           LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
3923           // If subranges are still supported, then the same subregs
3924           // should still be supported.
3925           for (LiveInterval::SubRange &S : LI.subranges()) {
3926             assert((S.LaneMask & ~MaxMask).none());
3927           }
3928 #endif
3929         }
3930       }
3931     }
3932   }
3933 
3934   LLVM_DEBUG(dump());
3935   if (VerifyCoalescing)
3936     MF->verify(this, "After register coalescing");
3937   return true;
3938 }
3939 
3940 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
3941    LIS->print(O, m);
3942 }
3943