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