Bug Summary

File:llvm/lib/CodeGen/RegisterCoalescer.cpp
Warning:line 2477, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name RegisterCoalescer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-29-190409-37574-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/RegisterCoalescer.cpp

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/RegisterCoalescer.cpp

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

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h

1//===- llvm/CodeGen/LiveInterval.h - Interval representation ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the LiveRange and LiveInterval classes. Given some
10// numbering of each the machine instructions an interval [i, j) is said to be a
11// live range for register v if there is no instruction with number j' >= j
12// such that v is live at j' and there is no instruction with number i' < i such
13// that v is live at i'. In this implementation ranges can have holes,
14// i.e. a range might look like [1,20), [50,65), [1000,1001). Each
15// individual segment is represented as an instance of LiveRange::Segment,
16// and the whole range is represented as an instance of LiveRange.
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLVM_CODEGEN_LIVEINTERVAL_H
21#define LLVM_CODEGEN_LIVEINTERVAL_H
22
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/IntEqClasses.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/CodeGen/Register.h"
29#include "llvm/CodeGen/SlotIndexes.h"
30#include "llvm/MC/LaneBitmask.h"
31#include "llvm/Support/Allocator.h"
32#include "llvm/Support/MathExtras.h"
33#include <algorithm>
34#include <cassert>
35#include <cstddef>
36#include <functional>
37#include <memory>
38#include <set>
39#include <tuple>
40#include <utility>
41
42namespace llvm {
43
44 class CoalescerPair;
45 class LiveIntervals;
46 class MachineRegisterInfo;
47 class raw_ostream;
48
49 /// VNInfo - Value Number Information.
50 /// This class holds information about a machine level values, including
51 /// definition and use points.
52 ///
53 class VNInfo {
54 public:
55 using Allocator = BumpPtrAllocator;
56
57 /// The ID number of this value.
58 unsigned id;
59
60 /// The index of the defining instruction.
61 SlotIndex def;
62
63 /// VNInfo constructor.
64 VNInfo(unsigned i, SlotIndex d) : id(i), def(d) {}
65
66 /// VNInfo constructor, copies values from orig, except for the value number.
67 VNInfo(unsigned i, const VNInfo &orig) : id(i), def(orig.def) {}
68
69 /// Copy from the parameter into this VNInfo.
70 void copyFrom(VNInfo &src) {
71 def = src.def;
72 }
73
74 /// Returns true if this value is defined by a PHI instruction (or was,
75 /// PHI instructions may have been eliminated).
76 /// PHI-defs begin at a block boundary, all other defs begin at register or
77 /// EC slots.
78 bool isPHIDef() const { return def.isBlock(); }
3
Calling 'SlotIndex::isBlock'
6
Returning from 'SlotIndex::isBlock'
7
Returning zero, which participates in a condition later
79
80 /// Returns true if this value is unused.
81 bool isUnused() const { return !def.isValid(); }
82
83 /// Mark this value as unused.
84 void markUnused() { def = SlotIndex(); }
85 };
86
87 /// Result of a LiveRange query. This class hides the implementation details
88 /// of live ranges, and it should be used as the primary interface for
89 /// examining live ranges around instructions.
90 class LiveQueryResult {
91 VNInfo *const EarlyVal;
92 VNInfo *const LateVal;
93 const SlotIndex EndPoint;
94 const bool Kill;
95
96 public:
97 LiveQueryResult(VNInfo *EarlyVal, VNInfo *LateVal, SlotIndex EndPoint,
98 bool Kill)
99 : EarlyVal(EarlyVal), LateVal(LateVal), EndPoint(EndPoint), Kill(Kill)
100 {}
101
102 /// Return the value that is live-in to the instruction. This is the value
103 /// that will be read by the instruction's use operands. Return NULL if no
104 /// value is live-in.
105 VNInfo *valueIn() const {
106 return EarlyVal;
107 }
108
109 /// Return true if the live-in value is killed by this instruction. This
110 /// means that either the live range ends at the instruction, or it changes
111 /// value.
112 bool isKill() const {
113 return Kill;
114 }
115
116 /// Return true if this instruction has a dead def.
117 bool isDeadDef() const {
118 return EndPoint.isDead();
119 }
120
121 /// Return the value leaving the instruction, if any. This can be a
122 /// live-through value, or a live def. A dead def returns NULL.
123 VNInfo *valueOut() const {
124 return isDeadDef() ? nullptr : LateVal;
125 }
126
127 /// Returns the value alive at the end of the instruction, if any. This can
128 /// be a live-through value, a live def or a dead def.
129 VNInfo *valueOutOrDead() const {
130 return LateVal;
131 }
132
133 /// Return the value defined by this instruction, if any. This includes
134 /// dead defs, it is the value created by the instruction's def operands.
135 VNInfo *valueDefined() const {
136 return EarlyVal == LateVal ? nullptr : LateVal;
137 }
138
139 /// Return the end point of the last live range segment to interact with
140 /// the instruction, if any.
141 ///
142 /// The end point is an invalid SlotIndex only if the live range doesn't
143 /// intersect the instruction at all.
144 ///
145 /// The end point may be at or past the end of the instruction's basic
146 /// block. That means the value was live out of the block.
147 SlotIndex endPoint() const {
148 return EndPoint;
149 }
150 };
151
152 /// This class represents the liveness of a register, stack slot, etc.
153 /// It manages an ordered list of Segment objects.
154 /// The Segments are organized in a static single assignment form: At places
155 /// where a new value is defined or different values reach a CFG join a new
156 /// segment with a new value number is used.
157 class LiveRange {
158 public:
159 /// This represents a simple continuous liveness interval for a value.
160 /// The start point is inclusive, the end point exclusive. These intervals
161 /// are rendered as [start,end).
162 struct Segment {
163 SlotIndex start; // Start point of the interval (inclusive)
164 SlotIndex end; // End point of the interval (exclusive)
165 VNInfo *valno = nullptr; // identifier for the value contained in this
166 // segment.
167
168 Segment() = default;
169
170 Segment(SlotIndex S, SlotIndex E, VNInfo *V)
171 : start(S), end(E), valno(V) {
172 assert(S < E && "Cannot create empty or backwards segment")((S < E && "Cannot create empty or backwards segment"
) ? static_cast<void> (0) : __assert_fail ("S < E && \"Cannot create empty or backwards segment\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 172, __PRETTY_FUNCTION__))
;
173 }
174
175 /// Return true if the index is covered by this segment.
176 bool contains(SlotIndex I) const {
177 return start <= I && I < end;
178 }
179
180 /// Return true if the given interval, [S, E), is covered by this segment.
181 bool containsInterval(SlotIndex S, SlotIndex E) const {
182 assert((S < E) && "Backwards interval?")(((S < E) && "Backwards interval?") ? static_cast<
void> (0) : __assert_fail ("(S < E) && \"Backwards interval?\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 182, __PRETTY_FUNCTION__))
;
183 return (start <= S && S < end) && (start < E && E <= end);
184 }
185
186 bool operator<(const Segment &Other) const {
187 return std::tie(start, end) < std::tie(Other.start, Other.end);
188 }
189 bool operator==(const Segment &Other) const {
190 return start == Other.start && end == Other.end;
191 }
192
193 bool operator!=(const Segment &Other) const {
194 return !(*this == Other);
195 }
196
197 void dump() const;
198 };
199
200 using Segments = SmallVector<Segment, 2>;
201 using VNInfoList = SmallVector<VNInfo *, 2>;
202
203 Segments segments; // the liveness segments
204 VNInfoList valnos; // value#'s
205
206 // The segment set is used temporarily to accelerate initial computation
207 // of live ranges of physical registers in computeRegUnitRange.
208 // After that the set is flushed to the segment vector and deleted.
209 using SegmentSet = std::set<Segment>;
210 std::unique_ptr<SegmentSet> segmentSet;
211
212 using iterator = Segments::iterator;
213 using const_iterator = Segments::const_iterator;
214
215 iterator begin() { return segments.begin(); }
216 iterator end() { return segments.end(); }
217
218 const_iterator begin() const { return segments.begin(); }
219 const_iterator end() const { return segments.end(); }
220
221 using vni_iterator = VNInfoList::iterator;
222 using const_vni_iterator = VNInfoList::const_iterator;
223
224 vni_iterator vni_begin() { return valnos.begin(); }
225 vni_iterator vni_end() { return valnos.end(); }
226
227 const_vni_iterator vni_begin() const { return valnos.begin(); }
228 const_vni_iterator vni_end() const { return valnos.end(); }
229
230 /// Constructs a new LiveRange object.
231 LiveRange(bool UseSegmentSet = false)
232 : segmentSet(UseSegmentSet ? std::make_unique<SegmentSet>()
233 : nullptr) {}
234
235 /// Constructs a new LiveRange object by copying segments and valnos from
236 /// another LiveRange.
237 LiveRange(const LiveRange &Other, BumpPtrAllocator &Allocator) {
238 assert(Other.segmentSet == nullptr &&((Other.segmentSet == nullptr && "Copying of LiveRanges with active SegmentSets is not supported"
) ? static_cast<void> (0) : __assert_fail ("Other.segmentSet == nullptr && \"Copying of LiveRanges with active SegmentSets is not supported\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 239, __PRETTY_FUNCTION__))
239 "Copying of LiveRanges with active SegmentSets is not supported")((Other.segmentSet == nullptr && "Copying of LiveRanges with active SegmentSets is not supported"
) ? static_cast<void> (0) : __assert_fail ("Other.segmentSet == nullptr && \"Copying of LiveRanges with active SegmentSets is not supported\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 239, __PRETTY_FUNCTION__))
;
240 assign(Other, Allocator);
241 }
242
243 /// Copies values numbers and live segments from \p Other into this range.
244 void assign(const LiveRange &Other, BumpPtrAllocator &Allocator) {
245 if (this == &Other)
246 return;
247
248 assert(Other.segmentSet == nullptr &&((Other.segmentSet == nullptr && "Copying of LiveRanges with active SegmentSets is not supported"
) ? static_cast<void> (0) : __assert_fail ("Other.segmentSet == nullptr && \"Copying of LiveRanges with active SegmentSets is not supported\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 249, __PRETTY_FUNCTION__))
249 "Copying of LiveRanges with active SegmentSets is not supported")((Other.segmentSet == nullptr && "Copying of LiveRanges with active SegmentSets is not supported"
) ? static_cast<void> (0) : __assert_fail ("Other.segmentSet == nullptr && \"Copying of LiveRanges with active SegmentSets is not supported\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 249, __PRETTY_FUNCTION__))
;
250 // Duplicate valnos.
251 for (const VNInfo *VNI : Other.valnos)
252 createValueCopy(VNI, Allocator);
253 // Now we can copy segments and remap their valnos.
254 for (const Segment &S : Other.segments)
255 segments.push_back(Segment(S.start, S.end, valnos[S.valno->id]));
256 }
257
258 /// advanceTo - Advance the specified iterator to point to the Segment
259 /// containing the specified position, or end() if the position is past the
260 /// end of the range. If no Segment contains this position, but the
261 /// position is in a hole, this method returns an iterator pointing to the
262 /// Segment immediately after the hole.
263 iterator advanceTo(iterator I, SlotIndex Pos) {
264 assert(I != end())((I != end()) ? static_cast<void> (0) : __assert_fail (
"I != end()", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 264, __PRETTY_FUNCTION__))
;
265 if (Pos >= endIndex())
266 return end();
267 while (I->end <= Pos) ++I;
268 return I;
269 }
270
271 const_iterator advanceTo(const_iterator I, SlotIndex Pos) const {
272 assert(I != end())((I != end()) ? static_cast<void> (0) : __assert_fail (
"I != end()", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 272, __PRETTY_FUNCTION__))
;
273 if (Pos >= endIndex())
274 return end();
275 while (I->end <= Pos) ++I;
276 return I;
277 }
278
279 /// find - Return an iterator pointing to the first segment that ends after
280 /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
281 /// when searching large ranges.
282 ///
283 /// If Pos is contained in a Segment, that segment is returned.
284 /// If Pos is in a hole, the following Segment is returned.
285 /// If Pos is beyond endIndex, end() is returned.
286 iterator find(SlotIndex Pos);
287
288 const_iterator find(SlotIndex Pos) const {
289 return const_cast<LiveRange*>(this)->find(Pos);
290 }
291
292 void clear() {
293 valnos.clear();
294 segments.clear();
295 }
296
297 size_t size() const {
298 return segments.size();
299 }
300
301 bool hasAtLeastOneValue() const { return !valnos.empty(); }
302
303 bool containsOneValue() const { return valnos.size() == 1; }
304
305 unsigned getNumValNums() const { return (unsigned)valnos.size(); }
306
307 /// getValNumInfo - Returns pointer to the specified val#.
308 ///
309 inline VNInfo *getValNumInfo(unsigned ValNo) {
310 return valnos[ValNo];
311 }
312 inline const VNInfo *getValNumInfo(unsigned ValNo) const {
313 return valnos[ValNo];
314 }
315
316 /// containsValue - Returns true if VNI belongs to this range.
317 bool containsValue(const VNInfo *VNI) const {
318 return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
319 }
320
321 /// getNextValue - Create a new value number and return it. MIIdx specifies
322 /// the instruction that defines the value number.
323 VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
324 VNInfo *VNI =
325 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
326 valnos.push_back(VNI);
327 return VNI;
328 }
329
330 /// createDeadDef - Make sure the range has a value defined at Def.
331 /// If one already exists, return it. Otherwise allocate a new value and
332 /// add liveness for a dead def.
333 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc);
334
335 /// Create a def of value @p VNI. Return @p VNI. If there already exists
336 /// a definition at VNI->def, the value defined there must be @p VNI.
337 VNInfo *createDeadDef(VNInfo *VNI);
338
339 /// Create a copy of the given value. The new value will be identical except
340 /// for the Value number.
341 VNInfo *createValueCopy(const VNInfo *orig,
342 VNInfo::Allocator &VNInfoAllocator) {
343 VNInfo *VNI =
344 new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
345 valnos.push_back(VNI);
346 return VNI;
347 }
348
349 /// RenumberValues - Renumber all values in order of appearance and remove
350 /// unused values.
351 void RenumberValues();
352
353 /// MergeValueNumberInto - This method is called when two value numbers
354 /// are found to be equivalent. This eliminates V1, replacing all
355 /// segments with the V1 value number with the V2 value number. This can
356 /// cause merging of V1/V2 values numbers and compaction of the value space.
357 VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
358
359 /// Merge all of the live segments of a specific val# in RHS into this live
360 /// range as the specified value number. The segments in RHS are allowed
361 /// to overlap with segments in the current range, it will replace the
362 /// value numbers of the overlaped live segments with the specified value
363 /// number.
364 void MergeSegmentsInAsValue(const LiveRange &RHS, VNInfo *LHSValNo);
365
366 /// MergeValueInAsValue - Merge all of the segments of a specific val#
367 /// in RHS into this live range as the specified value number.
368 /// The segments in RHS are allowed to overlap with segments in the
369 /// current range, but only if the overlapping segments have the
370 /// specified value number.
371 void MergeValueInAsValue(const LiveRange &RHS,
372 const VNInfo *RHSValNo, VNInfo *LHSValNo);
373
374 bool empty() const { return segments.empty(); }
375
376 /// beginIndex - Return the lowest numbered slot covered.
377 SlotIndex beginIndex() const {
378 assert(!empty() && "Call to beginIndex() on empty range.")((!empty() && "Call to beginIndex() on empty range.")
? static_cast<void> (0) : __assert_fail ("!empty() && \"Call to beginIndex() on empty range.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 378, __PRETTY_FUNCTION__))
;
379 return segments.front().start;
380 }
381
382 /// endNumber - return the maximum point of the range of the whole,
383 /// exclusive.
384 SlotIndex endIndex() const {
385 assert(!empty() && "Call to endIndex() on empty range.")((!empty() && "Call to endIndex() on empty range.") ?
static_cast<void> (0) : __assert_fail ("!empty() && \"Call to endIndex() on empty range.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 385, __PRETTY_FUNCTION__))
;
386 return segments.back().end;
387 }
388
389 bool expiredAt(SlotIndex index) const {
390 return index >= endIndex();
391 }
392
393 bool liveAt(SlotIndex index) const {
394 const_iterator r = find(index);
395 return r != end() && r->start <= index;
396 }
397
398 /// Return the segment that contains the specified index, or null if there
399 /// is none.
400 const Segment *getSegmentContaining(SlotIndex Idx) const {
401 const_iterator I = FindSegmentContaining(Idx);
402 return I == end() ? nullptr : &*I;
403 }
404
405 /// Return the live segment that contains the specified index, or null if
406 /// there is none.
407 Segment *getSegmentContaining(SlotIndex Idx) {
408 iterator I = FindSegmentContaining(Idx);
409 return I == end() ? nullptr : &*I;
410 }
411
412 /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
413 VNInfo *getVNInfoAt(SlotIndex Idx) const {
414 const_iterator I = FindSegmentContaining(Idx);
415 return I == end() ? nullptr : I->valno;
416 }
417
418 /// getVNInfoBefore - Return the VNInfo that is live up to but not
419 /// necessarilly including Idx, or NULL. Use this to find the reaching def
420 /// used by an instruction at this SlotIndex position.
421 VNInfo *getVNInfoBefore(SlotIndex Idx) const {
422 const_iterator I = FindSegmentContaining(Idx.getPrevSlot());
423 return I == end() ? nullptr : I->valno;
424 }
425
426 /// Return an iterator to the segment that contains the specified index, or
427 /// end() if there is none.
428 iterator FindSegmentContaining(SlotIndex Idx) {
429 iterator I = find(Idx);
430 return I != end() && I->start <= Idx ? I : end();
431 }
432
433 const_iterator FindSegmentContaining(SlotIndex Idx) const {
434 const_iterator I = find(Idx);
435 return I != end() && I->start <= Idx ? I : end();
436 }
437
438 /// overlaps - Return true if the intersection of the two live ranges is
439 /// not empty.
440 bool overlaps(const LiveRange &other) const {
441 if (other.empty())
442 return false;
443 return overlapsFrom(other, other.begin());
444 }
445
446 /// overlaps - Return true if the two ranges have overlapping segments
447 /// that are not coalescable according to CP.
448 ///
449 /// Overlapping segments where one range is defined by a coalescable
450 /// copy are allowed.
451 bool overlaps(const LiveRange &Other, const CoalescerPair &CP,
452 const SlotIndexes&) const;
453
454 /// overlaps - Return true if the live range overlaps an interval specified
455 /// by [Start, End).
456 bool overlaps(SlotIndex Start, SlotIndex End) const;
457
458 /// overlapsFrom - Return true if the intersection of the two live ranges
459 /// is not empty. The specified iterator is a hint that we can begin
460 /// scanning the Other range starting at I.
461 bool overlapsFrom(const LiveRange &Other, const_iterator StartPos) const;
462
463 /// Returns true if all segments of the @p Other live range are completely
464 /// covered by this live range.
465 /// Adjacent live ranges do not affect the covering:the liverange
466 /// [1,5](5,10] covers (3,7].
467 bool covers(const LiveRange &Other) const;
468
469 /// Add the specified Segment to this range, merging segments as
470 /// appropriate. This returns an iterator to the inserted segment (which
471 /// may have grown since it was inserted).
472 iterator addSegment(Segment S);
473
474 /// Attempt to extend a value defined after @p StartIdx to include @p Use.
475 /// Both @p StartIdx and @p Use should be in the same basic block. In case
476 /// of subranges, an extension could be prevented by an explicit "undef"
477 /// caused by a <def,read-undef> on a non-overlapping lane. The list of
478 /// location of such "undefs" should be provided in @p Undefs.
479 /// The return value is a pair: the first element is VNInfo of the value
480 /// that was extended (possibly nullptr), the second is a boolean value
481 /// indicating whether an "undef" was encountered.
482 /// If this range is live before @p Use in the basic block that starts at
483 /// @p StartIdx, and there is no intervening "undef", extend it to be live
484 /// up to @p Use, and return the pair {value, false}. If there is no
485 /// segment before @p Use and there is no "undef" between @p StartIdx and
486 /// @p Use, return {nullptr, false}. If there is an "undef" before @p Use,
487 /// return {nullptr, true}.
488 std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
489 SlotIndex StartIdx, SlotIndex Kill);
490
491 /// Simplified version of the above "extendInBlock", which assumes that
492 /// no register lanes are undefined by <def,read-undef> operands.
493 /// If this range is live before @p Use in the basic block that starts
494 /// at @p StartIdx, extend it to be live up to @p Use, and return the
495 /// value. If there is no segment before @p Use, return nullptr.
496 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
497
498 /// join - Join two live ranges (this, and other) together. This applies
499 /// mappings to the value numbers in the LHS/RHS ranges as specified. If
500 /// the ranges are not joinable, this aborts.
501 void join(LiveRange &Other,
502 const int *ValNoAssignments,
503 const int *RHSValNoAssignments,
504 SmallVectorImpl<VNInfo *> &NewVNInfo);
505
506 /// True iff this segment is a single segment that lies between the
507 /// specified boundaries, exclusively. Vregs live across a backedge are not
508 /// considered local. The boundaries are expected to lie within an extended
509 /// basic block, so vregs that are not live out should contain no holes.
510 bool isLocal(SlotIndex Start, SlotIndex End) const {
511 return beginIndex() > Start.getBaseIndex() &&
512 endIndex() < End.getBoundaryIndex();
513 }
514
515 /// Remove the specified segment from this range. Note that the segment
516 /// must be a single Segment in its entirety.
517 void removeSegment(SlotIndex Start, SlotIndex End,
518 bool RemoveDeadValNo = false);
519
520 void removeSegment(Segment S, bool RemoveDeadValNo = false) {
521 removeSegment(S.start, S.end, RemoveDeadValNo);
522 }
523
524 /// Remove segment pointed to by iterator @p I from this range. This does
525 /// not remove dead value numbers.
526 iterator removeSegment(iterator I) {
527 return segments.erase(I);
528 }
529
530 /// Query Liveness at Idx.
531 /// The sub-instruction slot of Idx doesn't matter, only the instruction
532 /// it refers to is considered.
533 LiveQueryResult Query(SlotIndex Idx) const {
534 // Find the segment that enters the instruction.
535 const_iterator I = find(Idx.getBaseIndex());
536 const_iterator E = end();
537 if (I == E)
538 return LiveQueryResult(nullptr, nullptr, SlotIndex(), false);
539
540 // Is this an instruction live-in segment?
541 // If Idx is the start index of a basic block, include live-in segments
542 // that start at Idx.getBaseIndex().
543 VNInfo *EarlyVal = nullptr;
544 VNInfo *LateVal = nullptr;
545 SlotIndex EndPoint;
546 bool Kill = false;
547 if (I->start <= Idx.getBaseIndex()) {
548 EarlyVal = I->valno;
549 EndPoint = I->end;
550 // Move to the potentially live-out segment.
551 if (SlotIndex::isSameInstr(Idx, I->end)) {
552 Kill = true;
553 if (++I == E)
554 return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
555 }
556 // Special case: A PHIDef value can have its def in the middle of a
557 // segment if the value happens to be live out of the layout
558 // predecessor.
559 // Such a value is not live-in.
560 if (EarlyVal->def == Idx.getBaseIndex())
561 EarlyVal = nullptr;
562 }
563 // I now points to the segment that may be live-through, or defined by
564 // this instr. Ignore segments starting after the current instr.
565 if (!SlotIndex::isEarlierInstr(Idx, I->start)) {
566 LateVal = I->valno;
567 EndPoint = I->end;
568 }
569 return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
570 }
571
572 /// removeValNo - Remove all the segments defined by the specified value#.
573 /// Also remove the value# from value# list.
574 void removeValNo(VNInfo *ValNo);
575
576 /// Returns true if the live range is zero length, i.e. no live segments
577 /// span instructions. It doesn't pay to spill such a range.
578 bool isZeroLength(SlotIndexes *Indexes) const {
579 for (const Segment &S : segments)
580 if (Indexes->getNextNonNullIndex(S.start).getBaseIndex() <
581 S.end.getBaseIndex())
582 return false;
583 return true;
584 }
585
586 // Returns true if any segment in the live range contains any of the
587 // provided slot indexes. Slots which occur in holes between
588 // segments will not cause the function to return true.
589 bool isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const;
590
591 bool operator<(const LiveRange& other) const {
592 const SlotIndex &thisIndex = beginIndex();
593 const SlotIndex &otherIndex = other.beginIndex();
594 return thisIndex < otherIndex;
595 }
596
597 /// Returns true if there is an explicit "undef" between @p Begin
598 /// @p End.
599 bool isUndefIn(ArrayRef<SlotIndex> Undefs, SlotIndex Begin,
600 SlotIndex End) const {
601 return std::any_of(Undefs.begin(), Undefs.end(),
602 [Begin,End] (SlotIndex Idx) -> bool {
603 return Begin <= Idx && Idx < End;
604 });
605 }
606
607 /// Flush segment set into the regular segment vector.
608 /// The method is to be called after the live range
609 /// has been created, if use of the segment set was
610 /// activated in the constructor of the live range.
611 void flushSegmentSet();
612
613 /// Stores indexes from the input index sequence R at which this LiveRange
614 /// is live to the output O iterator.
615 /// R is a range of _ascending sorted_ _random_ access iterators
616 /// to the input indexes. Indexes stored at O are ascending sorted so it
617 /// can be used directly in the subsequent search (for example for
618 /// subranges). Returns true if found at least one index.
619 template <typename Range, typename OutputIt>
620 bool findIndexesLiveAt(Range &&R, OutputIt O) const {
621 assert(llvm::is_sorted(R))((llvm::is_sorted(R)) ? static_cast<void> (0) : __assert_fail
("llvm::is_sorted(R)", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/LiveInterval.h"
, 621, __PRETTY_FUNCTION__))
;
622 auto Idx = R.begin(), EndIdx = R.end();
623 auto Seg = segments.begin(), EndSeg = segments.end();
624 bool Found = false;
625 while (Idx != EndIdx && Seg != EndSeg) {
626 // if the Seg is lower find first segment that is above Idx using binary
627 // search
628 if (Seg->end <= *Idx) {
629 Seg = std::upper_bound(
630 ++Seg, EndSeg, *Idx,
631 [=](std::remove_reference_t<decltype(*Idx)> V,
632 const std::remove_reference_t<decltype(*Seg)> &S) {
633 return V < S.end;
634 });
635 if (Seg == EndSeg)
636 break;
637 }
638 auto NotLessStart = std::lower_bound(Idx, EndIdx, Seg->start);
639 if (NotLessStart == EndIdx)
640 break;
641 auto NotLessEnd = std::lower_bound(NotLessStart, EndIdx, Seg->end);
642 if (NotLessEnd != NotLessStart) {
643 Found = true;
644 O = std::copy(NotLessStart, NotLessEnd, O);
645 }
646 Idx = NotLessEnd;
647 ++Seg;
648 }
649 return Found;
650 }
651
652 void print(raw_ostream &OS) const;
653 void dump() const;
654
655 /// Walk the range and assert if any invariants fail to hold.
656 ///
657 /// Note that this is a no-op when asserts are disabled.
658#ifdef NDEBUG
659 void verify() const {}
660#else
661 void verify() const;
662#endif
663
664 protected:
665 /// Append a segment to the list of segments.
666 void append(const LiveRange::Segment S);
667
668 private:
669 friend class LiveRangeUpdater;
670 void addSegmentToSet(Segment S);
671 void markValNoForDeletion(VNInfo *V);
672 };
673
674 inline raw_ostream &operator<<(raw_ostream &OS, const LiveRange &LR) {
675 LR.print(OS);
676 return OS;
677 }
678
679 /// LiveInterval - This class represents the liveness of a register,
680 /// or stack slot.
681 class LiveInterval : public LiveRange {
682 public:
683 using super = LiveRange;
684
685 /// A live range for subregisters. The LaneMask specifies which parts of the
686 /// super register are covered by the interval.
687 /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
688 class SubRange : public LiveRange {
689 public:
690 SubRange *Next = nullptr;
691 LaneBitmask LaneMask;
692
693 /// Constructs a new SubRange object.
694 SubRange(LaneBitmask LaneMask) : LaneMask(LaneMask) {}
695
696 /// Constructs a new SubRange object by copying liveness from @p Other.
697 SubRange(LaneBitmask LaneMask, const LiveRange &Other,
698 BumpPtrAllocator &Allocator)
699 : LiveRange(Other, Allocator), LaneMask(LaneMask) {}
700
701 void print(raw_ostream &OS) const;
702 void dump() const;
703 };
704
705 private:
706 SubRange *SubRanges = nullptr; ///< Single linked list of subregister live
707 /// ranges.
708 const Register Reg; // the register or stack slot of this interval.
709 float Weight = 0.0; // weight of this interval
710
711 public:
712 Register reg() const { return Reg; }
713 float weight() const { return Weight; }
714 void incrementWeight(float Inc) { Weight += Inc; }
715 void setWeight(float Value) { Weight = Value; }
716
717 LiveInterval(unsigned Reg, float Weight) : Reg(Reg), Weight(Weight) {}
718
719 ~LiveInterval() {
720 clearSubRanges();
721 }
722
723 template<typename T>
724 class SingleLinkedListIterator {
725 T *P;
726
727 public:
728 SingleLinkedListIterator<T>(T *P) : P(P) {}
729
730 SingleLinkedListIterator<T> &operator++() {
731 P = P->Next;
732 return *this;
733 }
734 SingleLinkedListIterator<T> operator++(int) {
735 SingleLinkedListIterator res = *this;
736 ++*this;
737 return res;
738 }
739 bool operator!=(const SingleLinkedListIterator<T> &Other) {
740 return P != Other.operator->();
741 }
742 bool operator==(const SingleLinkedListIterator<T> &Other) {
743 return P == Other.operator->();
744 }
745 T &operator*() const {
746 return *P;
747 }
748 T *operator->() const {
749 return P;
750 }
751 };
752
753 using subrange_iterator = SingleLinkedListIterator<SubRange>;
754 using const_subrange_iterator = SingleLinkedListIterator<const SubRange>;
755
756 subrange_iterator subrange_begin() {
757 return subrange_iterator(SubRanges);
758 }
759 subrange_iterator subrange_end() {
760 return subrange_iterator(nullptr);
761 }
762
763 const_subrange_iterator subrange_begin() const {
764 return const_subrange_iterator(SubRanges);
765 }
766 const_subrange_iterator subrange_end() const {
767 return const_subrange_iterator(nullptr);
768 }
769
770 iterator_range<subrange_iterator> subranges() {
771 return make_range(subrange_begin(), subrange_end());
772 }
773
774 iterator_range<const_subrange_iterator> subranges() const {
775 return make_range(subrange_begin(), subrange_end());
776 }
777
778 /// Creates a new empty subregister live range. The range is added at the
779 /// beginning of the subrange list; subrange iterators stay valid.
780 SubRange *createSubRange(BumpPtrAllocator &Allocator,
781 LaneBitmask LaneMask) {
782 SubRange *Range = new (Allocator) SubRange(LaneMask);
783 appendSubRange(Range);
784 return Range;
785 }
786
787 /// Like createSubRange() but the new range is filled with a copy of the
788 /// liveness information in @p CopyFrom.
789 SubRange *createSubRangeFrom(BumpPtrAllocator &Allocator,
790 LaneBitmask LaneMask,
791 const LiveRange &CopyFrom) {
792 SubRange *Range = new (Allocator) SubRange(LaneMask, CopyFrom, Allocator);
793 appendSubRange(Range);
794 return Range;
795 }
796
797 /// Returns true if subregister liveness information is available.
798 bool hasSubRanges() const {
799 return SubRanges != nullptr;
800 }
801
802 /// Removes all subregister liveness information.
803 void clearSubRanges();
804
805 /// Removes all subranges without any segments (subranges without segments
806 /// are not considered valid and should only exist temporarily).
807 void removeEmptySubRanges();
808
809 /// getSize - Returns the sum of sizes of all the LiveRange's.
810 ///
811 unsigned getSize() const;
812
813 /// isSpillable - Can this interval be spilled?
814 bool isSpillable() const { return Weight != huge_valf; }
815
816 /// markNotSpillable - Mark interval as not spillable
817 void markNotSpillable() { Weight = huge_valf; }
818
819 /// For a given lane mask @p LaneMask, compute indexes at which the
820 /// lane is marked undefined by subregister <def,read-undef> definitions.
821 void computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
822 LaneBitmask LaneMask,
823 const MachineRegisterInfo &MRI,
824 const SlotIndexes &Indexes) const;
825
826 /// Refines the subranges to support \p LaneMask. This may only be called
827 /// for LI.hasSubrange()==true. Subregister ranges are split or created
828 /// until \p LaneMask can be matched exactly. \p Mod is executed on the
829 /// matching subranges.
830 ///
831 /// Example:
832 /// Given an interval with subranges with lanemasks L0F00, L00F0 and
833 /// L000F, refining for mask L0018. Will split the L00F0 lane into
834 /// L00E0 and L0010 and the L000F lane into L0007 and L0008. The Mod
835 /// function will be applied to the L0010 and L0008 subranges.
836 ///
837 /// \p Indexes and \p TRI are required to clean up the VNIs that
838 /// don't define the related lane masks after they get shrunk. E.g.,
839 /// when L000F gets split into L0007 and L0008 maybe only a subset
840 /// of the VNIs that defined L000F defines L0007.
841 ///
842 /// The clean up of the VNIs need to look at the actual instructions
843 /// to decide what is or is not live at a definition point. If the
844 /// update of the subranges occurs while the IR does not reflect these
845 /// changes, \p ComposeSubRegIdx can be used to specify how the
846 /// definition are going to be rewritten.
847 /// E.g., let say we want to merge:
848 /// V1.sub1:<2 x s32> = COPY V2.sub3:<4 x s32>
849 /// We do that by choosing a class where sub1:<2 x s32> and sub3:<4 x s32>
850 /// overlap, i.e., by choosing a class where we can find "offset + 1 == 3".
851 /// Put differently we align V2's sub3 with V1's sub1:
852 /// V2: sub0 sub1 sub2 sub3
853 /// V1: <offset> sub0 sub1
854 ///
855 /// This offset will look like a composed subregidx in the the class:
856 /// V1.(composed sub2 with sub1):<4 x s32> = COPY V2.sub3:<4 x s32>
857 /// => V1.(composed sub2 with sub1):<4 x s32> = COPY V2.sub3:<4 x s32>
858 ///
859 /// Now if we didn't rewrite the uses and def of V1, all the checks for V1
860 /// need to account for this offset.
861 /// This happens during coalescing where we update the live-ranges while
862 /// still having the old IR around because updating the IR on-the-fly
863 /// would actually clobber some information on how the live-ranges that
864 /// are being updated look like.
865 void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
866 std::function<void(LiveInterval::SubRange &)> Apply,
867 const SlotIndexes &Indexes,
868 const TargetRegisterInfo &TRI,
869 unsigned ComposeSubRegIdx = 0);
870
871 bool operator<(const LiveInterval& other) const {
872 const SlotIndex &thisIndex = beginIndex();
873 const SlotIndex &otherIndex = other.beginIndex();
874 return std::tie(thisIndex, Reg) < std::tie(otherIndex, other.Reg);
875 }
876
877 void print(raw_ostream &OS) const;
878 void dump() const;
879
880 /// Walks the interval and assert if any invariants fail to hold.
881 ///
882 /// Note that this is a no-op when asserts are disabled.
883#ifdef NDEBUG
884 void verify(const MachineRegisterInfo *MRI = nullptr) const {}
885#else
886 void verify(const MachineRegisterInfo *MRI = nullptr) const;
887#endif
888
889 private:
890 /// Appends @p Range to SubRanges list.
891 void appendSubRange(SubRange *Range) {
892 Range->Next = SubRanges;
893 SubRanges = Range;
894 }
895
896 /// Free memory held by SubRange.
897 void freeSubRange(SubRange *S);
898 };
899
900 inline raw_ostream &operator<<(raw_ostream &OS,
901 const LiveInterval::SubRange &SR) {
902 SR.print(OS);
903 return OS;
904 }
905
906 inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
907 LI.print(OS);
908 return OS;
909 }
910
911 raw_ostream &operator<<(raw_ostream &OS, const LiveRange::Segment &S);
912
913 inline bool operator<(SlotIndex V, const LiveRange::Segment &S) {
914 return V < S.start;
915 }
916
917 inline bool operator<(const LiveRange::Segment &S, SlotIndex V) {
918 return S.start < V;
919 }
920
921 /// Helper class for performant LiveRange bulk updates.
922 ///
923 /// Calling LiveRange::addSegment() repeatedly can be expensive on large
924 /// live ranges because segments after the insertion point may need to be
925 /// shifted. The LiveRangeUpdater class can defer the shifting when adding
926 /// many segments in order.
927 ///
928 /// The LiveRange will be in an invalid state until flush() is called.
929 class LiveRangeUpdater {
930 LiveRange *LR;
931 SlotIndex LastStart;
932 LiveRange::iterator WriteI;
933 LiveRange::iterator ReadI;
934 SmallVector<LiveRange::Segment, 16> Spills;
935 void mergeSpills();
936
937 public:
938 /// Create a LiveRangeUpdater for adding segments to LR.
939 /// LR will temporarily be in an invalid state until flush() is called.
940 LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
941
942 ~LiveRangeUpdater() { flush(); }
943
944 /// Add a segment to LR and coalesce when possible, just like
945 /// LR.addSegment(). Segments should be added in increasing start order for
946 /// best performance.
947 void add(LiveRange::Segment);
948
949 void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
950 add(LiveRange::Segment(Start, End, VNI));
951 }
952
953 /// Return true if the LR is currently in an invalid state, and flush()
954 /// needs to be called.
955 bool isDirty() const { return LastStart.isValid(); }
956
957 /// Flush the updater state to LR so it is valid and contains all added
958 /// segments.
959 void flush();
960
961 /// Select a different destination live range.
962 void setDest(LiveRange *lr) {
963 if (LR != lr && isDirty())
964 flush();
965 LR = lr;
966 }
967
968 /// Get the current destination live range.
969 LiveRange *getDest() const { return LR; }
970
971 void dump() const;
972 void print(raw_ostream&) const;
973 };
974
975 inline raw_ostream &operator<<(raw_ostream &OS, const LiveRangeUpdater &X) {
976 X.print(OS);
977 return OS;
978 }
979
980 /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
981 /// LiveInterval into equivalence clases of connected components. A
982 /// LiveInterval that has multiple connected components can be broken into
983 /// multiple LiveIntervals.
984 ///
985 /// Given a LiveInterval that may have multiple connected components, run:
986 ///
987 /// unsigned numComps = ConEQ.Classify(LI);
988 /// if (numComps > 1) {
989 /// // allocate numComps-1 new LiveIntervals into LIS[1..]
990 /// ConEQ.Distribute(LIS);
991 /// }
992
993 class ConnectedVNInfoEqClasses {
994 LiveIntervals &LIS;
995 IntEqClasses EqClass;
996
997 public:
998 explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
999
1000 /// Classify the values in \p LR into connected components.
1001 /// Returns the number of connected components.
1002 unsigned Classify(const LiveRange &LR);
1003
1004 /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
1005 /// the equivalence class assigned the VNI.
1006 unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
1007
1008 /// Distribute values in \p LI into a separate LiveIntervals
1009 /// for each connected component. LIV must have an empty LiveInterval for
1010 /// each additional connected component. The first connected component is
1011 /// left in \p LI.
1012 void Distribute(LiveInterval &LI, LiveInterval *LIV[],
1013 MachineRegisterInfo &MRI);
1014 };
1015
1016} // end namespace llvm
1017
1018#endif // LLVM_CODEGEN_LIVEINTERVAL_H

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h

1//===- llvm/CodeGen/SlotIndexes.h - Slot indexes representation -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements SlotIndex and related classes. The purpose of SlotIndex
10// is to describe a position at which a register can become live, or cease to
11// be live.
12//
13// SlotIndex is mostly a proxy for entries of the SlotIndexList, a class which
14// is held is LiveIntervals and provides the real numbering. This allows
15// LiveIntervals to perform largely transparent renumbering.
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_CODEGEN_SLOTINDEXES_H
19#define LLVM_CODEGEN_SLOTINDEXES_H
20
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/IntervalMap.h"
23#include "llvm/ADT/PointerIntPair.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/ilist.h"
26#include "llvm/CodeGen/MachineBasicBlock.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/CodeGen/MachineInstrBundle.h"
31#include "llvm/Pass.h"
32#include "llvm/Support/Allocator.h"
33#include <algorithm>
34#include <cassert>
35#include <iterator>
36#include <utility>
37
38namespace llvm {
39
40class raw_ostream;
41
42 /// This class represents an entry in the slot index list held in the
43 /// SlotIndexes pass. It should not be used directly. See the
44 /// SlotIndex & SlotIndexes classes for the public interface to this
45 /// information.
46 class IndexListEntry : public ilist_node<IndexListEntry> {
47 MachineInstr *mi;
48 unsigned index;
49
50 public:
51 IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {}
52
53 MachineInstr* getInstr() const { return mi; }
54 void setInstr(MachineInstr *mi) {
55 this->mi = mi;
56 }
57
58 unsigned getIndex() const { return index; }
59 void setIndex(unsigned index) {
60 this->index = index;
61 }
62
63#ifdef EXPENSIVE_CHECKS
64 // When EXPENSIVE_CHECKS is defined, "erased" index list entries will
65 // actually be moved to a "graveyard" list, and have their pointers
66 // poisoned, so that dangling SlotIndex access can be reliably detected.
67 void setPoison() {
68 intptr_t tmp = reinterpret_cast<intptr_t>(mi);
69 assert(((tmp & 0x1) == 0x0) && "Pointer already poisoned?")((((tmp & 0x1) == 0x0) && "Pointer already poisoned?"
) ? static_cast<void> (0) : __assert_fail ("((tmp & 0x1) == 0x0) && \"Pointer already poisoned?\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 69, __PRETTY_FUNCTION__))
;
70 tmp |= 0x1;
71 mi = reinterpret_cast<MachineInstr*>(tmp);
72 }
73
74 bool isPoisoned() const { return (reinterpret_cast<intptr_t>(mi) & 0x1) == 0x1; }
75#endif // EXPENSIVE_CHECKS
76 };
77
78 template <>
79 struct ilist_alloc_traits<IndexListEntry>
80 : public ilist_noalloc_traits<IndexListEntry> {};
81
82 /// SlotIndex - An opaque wrapper around machine indexes.
83 class SlotIndex {
84 friend class SlotIndexes;
85
86 enum Slot {
87 /// Basic block boundary. Used for live ranges entering and leaving a
88 /// block without being live in the layout neighbor. Also used as the
89 /// def slot of PHI-defs.
90 Slot_Block,
91
92 /// Early-clobber register use/def slot. A live range defined at
93 /// Slot_EarlyClobber interferes with normal live ranges killed at
94 /// Slot_Register. Also used as the kill slot for live ranges tied to an
95 /// early-clobber def.
96 Slot_EarlyClobber,
97
98 /// Normal register use/def slot. Normal instructions kill and define
99 /// register live ranges at this slot.
100 Slot_Register,
101
102 /// Dead def kill point. Kill slot for a live range that is defined by
103 /// the same instruction (Slot_Register or Slot_EarlyClobber), but isn't
104 /// used anywhere.
105 Slot_Dead,
106
107 Slot_Count
108 };
109
110 PointerIntPair<IndexListEntry*, 2, unsigned> lie;
111
112 SlotIndex(IndexListEntry *entry, unsigned slot)
113 : lie(entry, slot) {}
114
115 IndexListEntry* listEntry() const {
116 assert(isValid() && "Attempt to compare reserved index.")((isValid() && "Attempt to compare reserved index.") ?
static_cast<void> (0) : __assert_fail ("isValid() && \"Attempt to compare reserved index.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 116, __PRETTY_FUNCTION__))
;
117#ifdef EXPENSIVE_CHECKS
118 assert(!lie.getPointer()->isPoisoned() &&((!lie.getPointer()->isPoisoned() && "Attempt to access deleted list-entry."
) ? static_cast<void> (0) : __assert_fail ("!lie.getPointer()->isPoisoned() && \"Attempt to access deleted list-entry.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 119, __PRETTY_FUNCTION__))
119 "Attempt to access deleted list-entry.")((!lie.getPointer()->isPoisoned() && "Attempt to access deleted list-entry."
) ? static_cast<void> (0) : __assert_fail ("!lie.getPointer()->isPoisoned() && \"Attempt to access deleted list-entry.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 119, __PRETTY_FUNCTION__))
;
120#endif // EXPENSIVE_CHECKS
121 return lie.getPointer();
122 }
123
124 unsigned getIndex() const {
125 return listEntry()->getIndex() | getSlot();
126 }
127
128 /// Returns the slot for this SlotIndex.
129 Slot getSlot() const {
130 return static_cast<Slot>(lie.getInt());
131 }
132
133 public:
134 enum {
135 /// The default distance between instructions as returned by distance().
136 /// This may vary as instructions are inserted and removed.
137 InstrDist = 4 * Slot_Count
138 };
139
140 /// Construct an invalid index.
141 SlotIndex() = default;
142
143 // Construct a new slot index from the given one, and set the slot.
144 SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
145 assert(lie.getPointer() != nullptr &&((lie.getPointer() != nullptr && "Attempt to construct index with 0 pointer."
) ? static_cast<void> (0) : __assert_fail ("lie.getPointer() != nullptr && \"Attempt to construct index with 0 pointer.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 146, __PRETTY_FUNCTION__))
146 "Attempt to construct index with 0 pointer.")((lie.getPointer() != nullptr && "Attempt to construct index with 0 pointer."
) ? static_cast<void> (0) : __assert_fail ("lie.getPointer() != nullptr && \"Attempt to construct index with 0 pointer.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 146, __PRETTY_FUNCTION__))
;
147 }
148
149 /// Returns true if this is a valid index. Invalid indices do
150 /// not point into an index table, and cannot be compared.
151 bool isValid() const {
152 return lie.getPointer();
153 }
154
155 /// Return true for a valid index.
156 explicit operator bool() const { return isValid(); }
157
158 /// Print this index to the given raw_ostream.
159 void print(raw_ostream &os) const;
160
161 /// Dump this index to stderr.
162 void dump() const;
163
164 /// Compare two SlotIndex objects for equality.
165 bool operator==(SlotIndex other) const {
166 return lie == other.lie;
167 }
168 /// Compare two SlotIndex objects for inequality.
169 bool operator!=(SlotIndex other) const {
170 return lie != other.lie;
171 }
172
173 /// Compare two SlotIndex objects. Return true if the first index
174 /// is strictly lower than the second.
175 bool operator<(SlotIndex other) const {
176 return getIndex() < other.getIndex();
177 }
178 /// Compare two SlotIndex objects. Return true if the first index
179 /// is lower than, or equal to, the second.
180 bool operator<=(SlotIndex other) const {
181 return getIndex() <= other.getIndex();
182 }
183
184 /// Compare two SlotIndex objects. Return true if the first index
185 /// is greater than the second.
186 bool operator>(SlotIndex other) const {
187 return getIndex() > other.getIndex();
188 }
189
190 /// Compare two SlotIndex objects. Return true if the first index
191 /// is greater than, or equal to, the second.
192 bool operator>=(SlotIndex other) const {
193 return getIndex() >= other.getIndex();
194 }
195
196 /// isSameInstr - Return true if A and B refer to the same instruction.
197 static bool isSameInstr(SlotIndex A, SlotIndex B) {
198 return A.lie.getPointer() == B.lie.getPointer();
199 }
200
201 /// isEarlierInstr - Return true if A refers to an instruction earlier than
202 /// B. This is equivalent to A < B && !isSameInstr(A, B).
203 static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
204 return A.listEntry()->getIndex() < B.listEntry()->getIndex();
205 }
206
207 /// Return true if A refers to the same instruction as B or an earlier one.
208 /// This is equivalent to !isEarlierInstr(B, A).
209 static bool isEarlierEqualInstr(SlotIndex A, SlotIndex B) {
210 return !isEarlierInstr(B, A);
211 }
212
213 /// Return the distance from this index to the given one.
214 int distance(SlotIndex other) const {
215 return other.getIndex() - getIndex();
216 }
217
218 /// Return the scaled distance from this index to the given one, where all
219 /// slots on the same instruction have zero distance.
220 int getInstrDistance(SlotIndex other) const {
221 return (other.listEntry()->getIndex() - listEntry()->getIndex())
222 / Slot_Count;
223 }
224
225 /// isBlock - Returns true if this is a block boundary slot.
226 bool isBlock() const { return getSlot() == Slot_Block; }
4
Assuming the condition is false
5
Returning zero, which participates in a condition later
227
228 /// isEarlyClobber - Returns true if this is an early-clobber slot.
229 bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
230
231 /// isRegister - Returns true if this is a normal register use/def slot.
232 /// Note that early-clobber slots may also be used for uses and defs.
233 bool isRegister() const { return getSlot() == Slot_Register; }
234
235 /// isDead - Returns true if this is a dead def kill slot.
236 bool isDead() const { return getSlot() == Slot_Dead; }
237
238 /// Returns the base index for associated with this index. The base index
239 /// is the one associated with the Slot_Block slot for the instruction
240 /// pointed to by this index.
241 SlotIndex getBaseIndex() const {
242 return SlotIndex(listEntry(), Slot_Block);
243 }
244
245 /// Returns the boundary index for associated with this index. The boundary
246 /// index is the one associated with the Slot_Block slot for the instruction
247 /// pointed to by this index.
248 SlotIndex getBoundaryIndex() const {
249 return SlotIndex(listEntry(), Slot_Dead);
250 }
251
252 /// Returns the register use/def slot in the current instruction for a
253 /// normal or early-clobber def.
254 SlotIndex getRegSlot(bool EC = false) const {
255 return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
256 }
257
258 /// Returns the dead def kill slot for the current instruction.
259 SlotIndex getDeadSlot() const {
260 return SlotIndex(listEntry(), Slot_Dead);
261 }
262
263 /// Returns the next slot in the index list. This could be either the
264 /// next slot for the instruction pointed to by this index or, if this
265 /// index is a STORE, the first slot for the next instruction.
266 /// WARNING: This method is considerably more expensive than the methods
267 /// that return specific slots (getUseIndex(), etc). If you can - please
268 /// use one of those methods.
269 SlotIndex getNextSlot() const {
270 Slot s = getSlot();
271 if (s == Slot_Dead) {
272 return SlotIndex(&*++listEntry()->getIterator(), Slot_Block);
273 }
274 return SlotIndex(listEntry(), s + 1);
275 }
276
277 /// Returns the next index. This is the index corresponding to the this
278 /// index's slot, but for the next instruction.
279 SlotIndex getNextIndex() const {
280 return SlotIndex(&*++listEntry()->getIterator(), getSlot());
281 }
282
283 /// Returns the previous slot in the index list. This could be either the
284 /// previous slot for the instruction pointed to by this index or, if this
285 /// index is a Slot_Block, the last slot for the previous instruction.
286 /// WARNING: This method is considerably more expensive than the methods
287 /// that return specific slots (getUseIndex(), etc). If you can - please
288 /// use one of those methods.
289 SlotIndex getPrevSlot() const {
290 Slot s = getSlot();
291 if (s == Slot_Block) {
292 return SlotIndex(&*--listEntry()->getIterator(), Slot_Dead);
293 }
294 return SlotIndex(listEntry(), s - 1);
295 }
296
297 /// Returns the previous index. This is the index corresponding to this
298 /// index's slot, but for the previous instruction.
299 SlotIndex getPrevIndex() const {
300 return SlotIndex(&*--listEntry()->getIterator(), getSlot());
301 }
302 };
303
304 inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
305 li.print(os);
306 return os;
307 }
308
309 using IdxMBBPair = std::pair<SlotIndex, MachineBasicBlock *>;
310
311 /// SlotIndexes pass.
312 ///
313 /// This pass assigns indexes to each instruction.
314 class SlotIndexes : public MachineFunctionPass {
315 private:
316 // IndexListEntry allocator.
317 BumpPtrAllocator ileAllocator;
318
319 using IndexList = ilist<IndexListEntry>;
320 IndexList indexList;
321
322 MachineFunction *mf;
323
324 using Mi2IndexMap = DenseMap<const MachineInstr *, SlotIndex>;
325 Mi2IndexMap mi2iMap;
326
327 /// MBBRanges - Map MBB number to (start, stop) indexes.
328 SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
329
330 /// Idx2MBBMap - Sorted list of pairs of index of first instruction
331 /// and MBB id.
332 SmallVector<IdxMBBPair, 8> idx2MBBMap;
333
334 IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
335 IndexListEntry *entry =
336 static_cast<IndexListEntry *>(ileAllocator.Allocate(
337 sizeof(IndexListEntry), alignof(IndexListEntry)));
338
339 new (entry) IndexListEntry(mi, index);
340
341 return entry;
342 }
343
344 /// Renumber locally after inserting curItr.
345 void renumberIndexes(IndexList::iterator curItr);
346
347 public:
348 static char ID;
349
350 SlotIndexes();
351
352 ~SlotIndexes() override;
353
354 void getAnalysisUsage(AnalysisUsage &au) const override;
355 void releaseMemory() override;
356
357 bool runOnMachineFunction(MachineFunction &fn) override;
358
359 /// Dump the indexes.
360 void dump() const;
361
362 /// Repair indexes after adding and removing instructions.
363 void repairIndexesInRange(MachineBasicBlock *MBB,
364 MachineBasicBlock::iterator Begin,
365 MachineBasicBlock::iterator End);
366
367 /// Returns the zero index for this analysis.
368 SlotIndex getZeroIndex() {
369 assert(indexList.front().getIndex() == 0 && "First index is not 0?")((indexList.front().getIndex() == 0 && "First index is not 0?"
) ? static_cast<void> (0) : __assert_fail ("indexList.front().getIndex() == 0 && \"First index is not 0?\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 369, __PRETTY_FUNCTION__))
;
370 return SlotIndex(&indexList.front(), 0);
371 }
372
373 /// Returns the base index of the last slot in this analysis.
374 SlotIndex getLastIndex() {
375 return SlotIndex(&indexList.back(), 0);
376 }
377
378 /// Returns true if the given machine instr is mapped to an index,
379 /// otherwise returns false.
380 bool hasIndex(const MachineInstr &instr) const {
381 return mi2iMap.count(&instr);
382 }
383
384 /// Returns the base index for the given instruction.
385 SlotIndex getInstructionIndex(const MachineInstr &MI,
386 bool IgnoreBundle = false) const {
387 // Instructions inside a bundle have the same number as the bundle itself.
388 auto BundleStart = getBundleStart(MI.getIterator());
389 auto BundleEnd = getBundleEnd(MI.getIterator());
390 // Use the first non-debug instruction in the bundle to get SlotIndex.
391 const MachineInstr &BundleNonDebug =
392 IgnoreBundle ? MI
393 : *skipDebugInstructionsForward(BundleStart, BundleEnd);
394 assert(!BundleNonDebug.isDebugInstr() &&((!BundleNonDebug.isDebugInstr() && "Could not use a debug instruction to query mi2iMap."
) ? static_cast<void> (0) : __assert_fail ("!BundleNonDebug.isDebugInstr() && \"Could not use a debug instruction to query mi2iMap.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 395, __PRETTY_FUNCTION__))
395 "Could not use a debug instruction to query mi2iMap.")((!BundleNonDebug.isDebugInstr() && "Could not use a debug instruction to query mi2iMap."
) ? static_cast<void> (0) : __assert_fail ("!BundleNonDebug.isDebugInstr() && \"Could not use a debug instruction to query mi2iMap.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 395, __PRETTY_FUNCTION__))
;
396 Mi2IndexMap::const_iterator itr = mi2iMap.find(&BundleNonDebug);
397 assert(itr != mi2iMap.end() && "Instruction not found in maps.")((itr != mi2iMap.end() && "Instruction not found in maps."
) ? static_cast<void> (0) : __assert_fail ("itr != mi2iMap.end() && \"Instruction not found in maps.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 397, __PRETTY_FUNCTION__))
;
398 return itr->second;
399 }
400
401 /// Returns the instruction for the given index, or null if the given
402 /// index has no instruction associated with it.
403 MachineInstr* getInstructionFromIndex(SlotIndex index) const {
404 return index.isValid() ? index.listEntry()->getInstr() : nullptr;
405 }
406
407 /// Returns the next non-null index, if one exists.
408 /// Otherwise returns getLastIndex().
409 SlotIndex getNextNonNullIndex(SlotIndex Index) {
410 IndexList::iterator I = Index.listEntry()->getIterator();
411 IndexList::iterator E = indexList.end();
412 while (++I != E)
413 if (I->getInstr())
414 return SlotIndex(&*I, Index.getSlot());
415 // We reached the end of the function.
416 return getLastIndex();
417 }
418
419 /// getIndexBefore - Returns the index of the last indexed instruction
420 /// before MI, or the start index of its basic block.
421 /// MI is not required to have an index.
422 SlotIndex getIndexBefore(const MachineInstr &MI) const {
423 const MachineBasicBlock *MBB = MI.getParent();
424 assert(MBB && "MI must be inserted in a basic block")((MBB && "MI must be inserted in a basic block") ? static_cast
<void> (0) : __assert_fail ("MBB && \"MI must be inserted in a basic block\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 424, __PRETTY_FUNCTION__))
;
425 MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
426 while (true) {
427 if (I == B)
428 return getMBBStartIdx(MBB);
429 --I;
430 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(&*I);
431 if (MapItr != mi2iMap.end())
432 return MapItr->second;
433 }
434 }
435
436 /// getIndexAfter - Returns the index of the first indexed instruction
437 /// after MI, or the end index of its basic block.
438 /// MI is not required to have an index.
439 SlotIndex getIndexAfter(const MachineInstr &MI) const {
440 const MachineBasicBlock *MBB = MI.getParent();
441 assert(MBB && "MI must be inserted in a basic block")((MBB && "MI must be inserted in a basic block") ? static_cast
<void> (0) : __assert_fail ("MBB && \"MI must be inserted in a basic block\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 441, __PRETTY_FUNCTION__))
;
442 MachineBasicBlock::const_iterator I = MI, E = MBB->end();
443 while (true) {
444 ++I;
445 if (I == E)
446 return getMBBEndIdx(MBB);
447 Mi2IndexMap::const_iterator MapItr = mi2iMap.find(&*I);
448 if (MapItr != mi2iMap.end())
449 return MapItr->second;
450 }
451 }
452
453 /// Return the (start,end) range of the given basic block number.
454 const std::pair<SlotIndex, SlotIndex> &
455 getMBBRange(unsigned Num) const {
456 return MBBRanges[Num];
457 }
458
459 /// Return the (start,end) range of the given basic block.
460 const std::pair<SlotIndex, SlotIndex> &
461 getMBBRange(const MachineBasicBlock *MBB) const {
462 return getMBBRange(MBB->getNumber());
463 }
464
465 /// Returns the first index in the given basic block number.
466 SlotIndex getMBBStartIdx(unsigned Num) const {
467 return getMBBRange(Num).first;
468 }
469
470 /// Returns the first index in the given basic block.
471 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
472 return getMBBRange(mbb).first;
473 }
474
475 /// Returns the last index in the given basic block number.
476 SlotIndex getMBBEndIdx(unsigned Num) const {
477 return getMBBRange(Num).second;
478 }
479
480 /// Returns the last index in the given basic block.
481 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
482 return getMBBRange(mbb).second;
483 }
484
485 /// Iterator over the idx2MBBMap (sorted pairs of slot index of basic block
486 /// begin and basic block)
487 using MBBIndexIterator = SmallVectorImpl<IdxMBBPair>::const_iterator;
488
489 /// Move iterator to the next IdxMBBPair where the SlotIndex is greater or
490 /// equal to \p To.
491 MBBIndexIterator advanceMBBIndex(MBBIndexIterator I, SlotIndex To) const {
492 return std::partition_point(
493 I, idx2MBBMap.end(),
494 [=](const IdxMBBPair &IM) { return IM.first < To; });
495 }
496
497 /// Get an iterator pointing to the IdxMBBPair with the biggest SlotIndex
498 /// that is greater or equal to \p Idx.
499 MBBIndexIterator findMBBIndex(SlotIndex Idx) const {
500 return advanceMBBIndex(idx2MBBMap.begin(), Idx);
501 }
502
503 /// Returns an iterator for the begin of the idx2MBBMap.
504 MBBIndexIterator MBBIndexBegin() const {
505 return idx2MBBMap.begin();
506 }
507
508 /// Return an iterator for the end of the idx2MBBMap.
509 MBBIndexIterator MBBIndexEnd() const {
510 return idx2MBBMap.end();
511 }
512
513 /// Returns the basic block which the given index falls in.
514 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
515 if (MachineInstr *MI = getInstructionFromIndex(index))
516 return MI->getParent();
517
518 MBBIndexIterator I = findMBBIndex(index);
519 // Take the pair containing the index
520 MBBIndexIterator J =
521 ((I != MBBIndexEnd() && I->first > index) ||
522 (I == MBBIndexEnd() && !idx2MBBMap.empty())) ? std::prev(I) : I;
523
524 assert(J != MBBIndexEnd() && J->first <= index &&((J != MBBIndexEnd() && J->first <= index &&
index < getMBBEndIdx(J->second) && "index does not correspond to an MBB"
) ? static_cast<void> (0) : __assert_fail ("J != MBBIndexEnd() && J->first <= index && index < getMBBEndIdx(J->second) && \"index does not correspond to an MBB\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 526, __PRETTY_FUNCTION__))
525 index < getMBBEndIdx(J->second) &&((J != MBBIndexEnd() && J->first <= index &&
index < getMBBEndIdx(J->second) && "index does not correspond to an MBB"
) ? static_cast<void> (0) : __assert_fail ("J != MBBIndexEnd() && J->first <= index && index < getMBBEndIdx(J->second) && \"index does not correspond to an MBB\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SlotIndexes.h"
, 526, __PRETTY_FUNCTION__))
526