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