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