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