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