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