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