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