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