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