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