Bug Summary

File:llvm/lib/CodeGen/PeepholeOptimizer.cpp
Warning:line 543, column 30
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name PeepholeOptimizer.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 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp

1//===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
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// Perform peephole optimizations on the machine code:
10//
11// - Optimize Extensions
12//
13// Optimization of sign / zero extension instructions. It may be extended to
14// handle other instructions with similar properties.
15//
16// On some targets, some instructions, e.g. X86 sign / zero extension, may
17// leave the source value in the lower part of the result. This optimization
18// will replace some uses of the pre-extension value with uses of the
19// sub-register of the results.
20//
21// - Optimize Comparisons
22//
23// Optimization of comparison instructions. For instance, in this code:
24//
25// sub r1, 1
26// cmp r1, 0
27// bz L1
28//
29// If the "sub" instruction all ready sets (or could be modified to set) the
30// same flag that the "cmp" instruction sets and that "bz" uses, then we can
31// eliminate the "cmp" instruction.
32//
33// Another instance, in this code:
34//
35// sub r1, r3 | sub r1, imm
36// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
37// bge L1
38//
39// If the branch instruction can use flag from "sub", then we can replace
40// "sub" with "subs" and eliminate the "cmp" instruction.
41//
42// - Optimize Loads:
43//
44// Loads that can be folded into a later instruction. A load is foldable
45// if it loads to virtual registers and the virtual register defined has
46// a single use.
47//
48// - Optimize Copies and Bitcast (more generally, target specific copies):
49//
50// Rewrite copies and bitcasts to avoid cross register bank copies
51// when possible.
52// E.g., Consider the following example, where capital and lower
53// letters denote different register file:
54// b = copy A <-- cross-bank copy
55// C = copy b <-- cross-bank copy
56// =>
57// b = copy A <-- cross-bank copy
58// C = copy A <-- same-bank copy
59//
60// E.g., for bitcast:
61// b = bitcast A <-- cross-bank copy
62// C = bitcast b <-- cross-bank copy
63// =>
64// b = bitcast A <-- cross-bank copy
65// C = copy A <-- same-bank copy
66//===----------------------------------------------------------------------===//
67
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/Optional.h"
70#include "llvm/ADT/SmallPtrSet.h"
71#include "llvm/ADT/SmallSet.h"
72#include "llvm/ADT/SmallVector.h"
73#include "llvm/ADT/Statistic.h"
74#include "llvm/CodeGen/MachineBasicBlock.h"
75#include "llvm/CodeGen/MachineDominators.h"
76#include "llvm/CodeGen/MachineFunction.h"
77#include "llvm/CodeGen/MachineFunctionPass.h"
78#include "llvm/CodeGen/MachineInstr.h"
79#include "llvm/CodeGen/MachineInstrBuilder.h"
80#include "llvm/CodeGen/MachineLoopInfo.h"
81#include "llvm/CodeGen/MachineOperand.h"
82#include "llvm/CodeGen/MachineRegisterInfo.h"
83#include "llvm/CodeGen/TargetInstrInfo.h"
84#include "llvm/CodeGen/TargetOpcodes.h"
85#include "llvm/CodeGen/TargetRegisterInfo.h"
86#include "llvm/CodeGen/TargetSubtargetInfo.h"
87#include "llvm/InitializePasses.h"
88#include "llvm/MC/LaneBitmask.h"
89#include "llvm/MC/MCInstrDesc.h"
90#include "llvm/Pass.h"
91#include "llvm/Support/CommandLine.h"
92#include "llvm/Support/Debug.h"
93#include "llvm/Support/ErrorHandling.h"
94#include "llvm/Support/raw_ostream.h"
95#include <cassert>
96#include <cstdint>
97#include <memory>
98#include <utility>
99
100using namespace llvm;
101using RegSubRegPair = TargetInstrInfo::RegSubRegPair;
102using RegSubRegPairAndIdx = TargetInstrInfo::RegSubRegPairAndIdx;
103
104#define DEBUG_TYPE"peephole-opt" "peephole-opt"
105
106// Optimize Extensions
107static cl::opt<bool>
108Aggressive("aggressive-ext-opt", cl::Hidden,
109 cl::desc("Aggressive extension optimization"));
110
111static cl::opt<bool>
112DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
113 cl::desc("Disable the peephole optimizer"));
114
115/// Specifiy whether or not the value tracking looks through
116/// complex instructions. When this is true, the value tracker
117/// bails on everything that is not a copy or a bitcast.
118static cl::opt<bool>
119DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
120 cl::desc("Disable advanced copy optimization"));
121
122static cl::opt<bool> DisableNAPhysCopyOpt(
123 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
124 cl::desc("Disable non-allocatable physical register copy optimization"));
125
126// Limit the number of PHI instructions to process
127// in PeepholeOptimizer::getNextSource.
128static cl::opt<unsigned> RewritePHILimit(
129 "rewrite-phi-limit", cl::Hidden, cl::init(10),
130 cl::desc("Limit the length of PHI chains to lookup"));
131
132// Limit the length of recurrence chain when evaluating the benefit of
133// commuting operands.
134static cl::opt<unsigned> MaxRecurrenceChain(
135 "recurrence-chain-limit", cl::Hidden, cl::init(3),
136 cl::desc("Maximum length of recurrence chain when evaluating the benefit "
137 "of commuting operands"));
138
139
140STATISTIC(NumReuse, "Number of extension results reused")static llvm::Statistic NumReuse = {"peephole-opt", "NumReuse"
, "Number of extension results reused"}
;
141STATISTIC(NumCmps, "Number of compares eliminated")static llvm::Statistic NumCmps = {"peephole-opt", "NumCmps", "Number of compares eliminated"
}
;
142STATISTIC(NumImmFold, "Number of move immediate folded")static llvm::Statistic NumImmFold = {"peephole-opt", "NumImmFold"
, "Number of move immediate folded"}
;
143STATISTIC(NumLoadFold, "Number of loads folded")static llvm::Statistic NumLoadFold = {"peephole-opt", "NumLoadFold"
, "Number of loads folded"}
;
144STATISTIC(NumSelects, "Number of selects optimized")static llvm::Statistic NumSelects = {"peephole-opt", "NumSelects"
, "Number of selects optimized"}
;
145STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized")static llvm::Statistic NumUncoalescableCopies = {"peephole-opt"
, "NumUncoalescableCopies", "Number of uncoalescable copies optimized"
}
;
146STATISTIC(NumRewrittenCopies, "Number of copies rewritten")static llvm::Statistic NumRewrittenCopies = {"peephole-opt", "NumRewrittenCopies"
, "Number of copies rewritten"}
;
147STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed")static llvm::Statistic NumNAPhysCopies = {"peephole-opt", "NumNAPhysCopies"
, "Number of non-allocatable physical copies removed"}
;
148
149namespace {
150
151 class ValueTrackerResult;
152 class RecurrenceInstr;
153
154 class PeepholeOptimizer : public MachineFunctionPass {
155 const TargetInstrInfo *TII;
156 const TargetRegisterInfo *TRI;
157 MachineRegisterInfo *MRI;
158 MachineDominatorTree *DT; // Machine dominator tree
159 MachineLoopInfo *MLI;
160
161 public:
162 static char ID; // Pass identification
163
164 PeepholeOptimizer() : MachineFunctionPass(ID) {
165 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
166 }
167
168 bool runOnMachineFunction(MachineFunction &MF) override;
169
170 void getAnalysisUsage(AnalysisUsage &AU) const override {
171 AU.setPreservesCFG();
172 MachineFunctionPass::getAnalysisUsage(AU);
173 AU.addRequired<MachineLoopInfo>();
174 AU.addPreserved<MachineLoopInfo>();
175 if (Aggressive) {
176 AU.addRequired<MachineDominatorTree>();
177 AU.addPreserved<MachineDominatorTree>();
178 }
179 }
180
181 /// Track Def -> Use info used for rewriting copies.
182 using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
183
184 /// Sequence of instructions that formulate recurrence cycle.
185 using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
186
187 private:
188 bool optimizeCmpInstr(MachineInstr &MI);
189 bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
190 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
191 bool optimizeSelect(MachineInstr &MI,
192 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
193 bool optimizeCondBranch(MachineInstr &MI);
194 bool optimizeCoalescableCopy(MachineInstr &MI);
195 bool optimizeUncoalescableCopy(MachineInstr &MI,
196 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
197 bool optimizeRecurrence(MachineInstr &PHI);
198 bool findNextSource(RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
199 bool isMoveImmediate(MachineInstr &MI,
200 SmallSet<unsigned, 4> &ImmDefRegs,
201 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
202 bool foldImmediate(MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
203 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
204
205 /// Finds recurrence cycles, but only ones that formulated around
206 /// a def operand and a use operand that are tied. If there is a use
207 /// operand commutable with the tied use operand, find recurrence cycle
208 /// along that operand as well.
209 bool findTargetRecurrence(unsigned Reg,
210 const SmallSet<unsigned, 2> &TargetReg,
211 RecurrenceCycle &RC);
212
213 /// If copy instruction \p MI is a virtual register copy, track it in
214 /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
215 /// previously seen as a copy, replace the uses of this copy with the
216 /// previously seen copy's destination register.
217 bool foldRedundantCopy(MachineInstr &MI,
218 SmallSet<unsigned, 4> &CopySrcRegs,
219 DenseMap<unsigned, MachineInstr *> &CopyMIs);
220
221 /// Is the register \p Reg a non-allocatable physical register?
222 bool isNAPhysCopy(unsigned Reg);
223
224 /// If copy instruction \p MI is a non-allocatable virtual<->physical
225 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
226 /// non-allocatable physical register was previously copied to a virtual
227 /// registered and hasn't been clobbered, the virt->phys copy can be
228 /// deleted.
229 bool foldRedundantNAPhysCopy(MachineInstr &MI,
230 DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
231
232 bool isLoadFoldable(MachineInstr &MI,
233 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
234
235 /// Check whether \p MI is understood by the register coalescer
236 /// but may require some rewriting.
237 bool isCoalescableCopy(const MachineInstr &MI) {
238 // SubregToRegs are not interesting, because they are already register
239 // coalescer friendly.
240 return MI.isCopy() || (!DisableAdvCopyOpt &&
241 (MI.isRegSequence() || MI.isInsertSubreg() ||
242 MI.isExtractSubreg()));
243 }
244
245 /// Check whether \p MI is a copy like instruction that is
246 /// not recognized by the register coalescer.
247 bool isUncoalescableCopy(const MachineInstr &MI) {
248 return MI.isBitcast() ||
249 (!DisableAdvCopyOpt &&
250 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
251 MI.isExtractSubregLike()));
252 }
253
254 MachineInstr &rewriteSource(MachineInstr &CopyLike,
255 RegSubRegPair Def, RewriteMapTy &RewriteMap);
256 };
257
258 /// Helper class to hold instructions that are inside recurrence cycles.
259 /// The recurrence cycle is formulated around 1) a def operand and its
260 /// tied use operand, or 2) a def operand and a use operand that is commutable
261 /// with another use operand which is tied to the def operand. In the latter
262 /// case, index of the tied use operand and the commutable use operand are
263 /// maintained with CommutePair.
264 class RecurrenceInstr {
265 public:
266 using IndexPair = std::pair<unsigned, unsigned>;
267
268 RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
269 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
270 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
271
272 MachineInstr *getMI() const { return MI; }
273 Optional<IndexPair> getCommutePair() const { return CommutePair; }
274
275 private:
276 MachineInstr *MI;
277 Optional<IndexPair> CommutePair;
278 };
279
280 /// Helper class to hold a reply for ValueTracker queries.
281 /// Contains the returned sources for a given search and the instructions
282 /// where the sources were tracked from.
283 class ValueTrackerResult {
284 private:
285 /// Track all sources found by one ValueTracker query.
286 SmallVector<RegSubRegPair, 2> RegSrcs;
287
288 /// Instruction using the sources in 'RegSrcs'.
289 const MachineInstr *Inst = nullptr;
290
291 public:
292 ValueTrackerResult() = default;
293
294 ValueTrackerResult(unsigned Reg, unsigned SubReg) {
295 addSource(Reg, SubReg);
296 }
297
298 bool isValid() const { return getNumSources() > 0; }
299
300 void setInst(const MachineInstr *I) { Inst = I; }
301 const MachineInstr *getInst() const { return Inst; }
302
303 void clear() {
304 RegSrcs.clear();
305 Inst = nullptr;
306 }
307
308 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
309 RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
310 }
311
312 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
313 assert(Idx < getNumSources() && "Reg pair source out of index")((Idx < getNumSources() && "Reg pair source out of index"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSources() && \"Reg pair source out of index\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 313, __PRETTY_FUNCTION__))
;
314 RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
315 }
316
317 int getNumSources() const { return RegSrcs.size(); }
318
319 RegSubRegPair getSrc(int Idx) const {
320 return RegSrcs[Idx];
321 }
322
323 unsigned getSrcReg(int Idx) const {
324 assert(Idx < getNumSources() && "Reg source out of index")((Idx < getNumSources() && "Reg source out of index"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSources() && \"Reg source out of index\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 324, __PRETTY_FUNCTION__))
;
325 return RegSrcs[Idx].Reg;
326 }
327
328 unsigned getSrcSubReg(int Idx) const {
329 assert(Idx < getNumSources() && "SubReg source out of index")((Idx < getNumSources() && "SubReg source out of index"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSources() && \"SubReg source out of index\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 329, __PRETTY_FUNCTION__))
;
330 return RegSrcs[Idx].SubReg;
331 }
332
333 bool operator==(const ValueTrackerResult &Other) {
334 if (Other.getInst() != getInst())
335 return false;
336
337 if (Other.getNumSources() != getNumSources())
338 return false;
339
340 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
341 if (Other.getSrcReg(i) != getSrcReg(i) ||
342 Other.getSrcSubReg(i) != getSrcSubReg(i))
343 return false;
344 return true;
345 }
346 };
347
348 /// Helper class to track the possible sources of a value defined by
349 /// a (chain of) copy related instructions.
350 /// Given a definition (instruction and definition index), this class
351 /// follows the use-def chain to find successive suitable sources.
352 /// The given source can be used to rewrite the definition into
353 /// def = COPY src.
354 ///
355 /// For instance, let us consider the following snippet:
356 /// v0 =
357 /// v2 = INSERT_SUBREG v1, v0, sub0
358 /// def = COPY v2.sub0
359 ///
360 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
361 /// suitable sources:
362 /// v2.sub0 and v0.
363 /// Then, def can be rewritten into def = COPY v0.
364 class ValueTracker {
365 private:
366 /// The current point into the use-def chain.
367 const MachineInstr *Def = nullptr;
368
369 /// The index of the definition in Def.
370 unsigned DefIdx = 0;
371
372 /// The sub register index of the definition.
373 unsigned DefSubReg;
374
375 /// The register where the value can be found.
376 unsigned Reg;
377
378 /// MachineRegisterInfo used to perform tracking.
379 const MachineRegisterInfo &MRI;
380
381 /// Optional TargetInstrInfo used to perform some complex tracking.
382 const TargetInstrInfo *TII;
383
384 /// Dispatcher to the right underlying implementation of getNextSource.
385 ValueTrackerResult getNextSourceImpl();
386
387 /// Specialized version of getNextSource for Copy instructions.
388 ValueTrackerResult getNextSourceFromCopy();
389
390 /// Specialized version of getNextSource for Bitcast instructions.
391 ValueTrackerResult getNextSourceFromBitcast();
392
393 /// Specialized version of getNextSource for RegSequence instructions.
394 ValueTrackerResult getNextSourceFromRegSequence();
395
396 /// Specialized version of getNextSource for InsertSubreg instructions.
397 ValueTrackerResult getNextSourceFromInsertSubreg();
398
399 /// Specialized version of getNextSource for ExtractSubreg instructions.
400 ValueTrackerResult getNextSourceFromExtractSubreg();
401
402 /// Specialized version of getNextSource for SubregToReg instructions.
403 ValueTrackerResult getNextSourceFromSubregToReg();
404
405 /// Specialized version of getNextSource for PHI instructions.
406 ValueTrackerResult getNextSourceFromPHI();
407
408 public:
409 /// Create a ValueTracker instance for the value defined by \p Reg.
410 /// \p DefSubReg represents the sub register index the value tracker will
411 /// track. It does not need to match the sub register index used in the
412 /// definition of \p Reg.
413 /// If \p Reg is a physical register, a value tracker constructed with
414 /// this constructor will not find any alternative source.
415 /// Indeed, when \p Reg is a physical register that constructor does not
416 /// know which definition of \p Reg it should track.
417 /// Use the next constructor to track a physical register.
418 ValueTracker(unsigned Reg, unsigned DefSubReg,
419 const MachineRegisterInfo &MRI,
420 const TargetInstrInfo *TII = nullptr)
421 : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
422 if (!Register::isPhysicalRegister(Reg)) {
423 Def = MRI.getVRegDef(Reg);
424 DefIdx = MRI.def_begin(Reg).getOperandNo();
425 }
426 }
427
428 /// Following the use-def chain, get the next available source
429 /// for the tracked value.
430 /// \return A ValueTrackerResult containing a set of registers
431 /// and sub registers with tracked values. A ValueTrackerResult with
432 /// an empty set of registers means no source was found.
433 ValueTrackerResult getNextSource();
434 };
435
436} // end anonymous namespace
437
438char PeepholeOptimizer::ID = 0;
439
440char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
441
442INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,static void *initializePeepholeOptimizerPassOnce(PassRegistry
&Registry) {
443 "Peephole Optimizations", false, false)static void *initializePeepholeOptimizerPassOnce(PassRegistry
&Registry) {
444INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)initializeMachineDominatorTreePass(Registry);
445INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)initializeMachineLoopInfoPass(Registry);
446INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,PassInfo *PI = new PassInfo( "Peephole Optimizations", "peephole-opt"
, &PeepholeOptimizer::ID, PassInfo::NormalCtor_t(callDefaultCtor
<PeepholeOptimizer>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializePeepholeOptimizerPassFlag
; void llvm::initializePeepholeOptimizerPass(PassRegistry &
Registry) { llvm::call_once(InitializePeepholeOptimizerPassFlag
, initializePeepholeOptimizerPassOnce, std::ref(Registry)); }
447 "Peephole Optimizations", false, false)PassInfo *PI = new PassInfo( "Peephole Optimizations", "peephole-opt"
, &PeepholeOptimizer::ID, PassInfo::NormalCtor_t(callDefaultCtor
<PeepholeOptimizer>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializePeepholeOptimizerPassFlag
; void llvm::initializePeepholeOptimizerPass(PassRegistry &
Registry) { llvm::call_once(InitializePeepholeOptimizerPassFlag
, initializePeepholeOptimizerPassOnce, std::ref(Registry)); }
448
449/// If instruction is a copy-like instruction, i.e. it reads a single register
450/// and writes a single register and it does not modify the source, and if the
451/// source value is preserved as a sub-register of the result, then replace all
452/// reachable uses of the source with the subreg of the result.
453///
454/// Do not generate an EXTRACT that is used only in a debug use, as this changes
455/// the code. Since this code does not currently share EXTRACTs, just ignore all
456/// debug uses.
457bool PeepholeOptimizer::
458optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
459 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
460 unsigned SrcReg, DstReg, SubIdx;
461 if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
24
Assuming the condition is false
25
Taking false branch
462 return false;
463
464 if (Register::isPhysicalRegister(DstReg) ||
26
Calling 'Register::isPhysicalRegister'
33
Returning from 'Register::isPhysicalRegister'
42
Taking false branch
465 Register::isPhysicalRegister(SrcReg))
34
Calling 'Register::isPhysicalRegister'
41
Returning from 'Register::isPhysicalRegister'
466 return false;
467
468 if (MRI->hasOneNonDBGUse(SrcReg))
43
Assuming the condition is false
44
Taking false branch
469 // No other uses.
470 return false;
471
472 // Ensure DstReg can get a register class that actually supports
473 // sub-registers. Don't change the class until we commit.
474 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
475 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
476 if (!DstRC)
45
Assuming 'DstRC' is non-null
46
Taking false branch
477 return false;
478
479 // The ext instr may be operating on a sub-register of SrcReg as well.
480 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
481 // register.
482 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
483 // SrcReg:SubIdx should be replaced.
484 bool UseSrcSubIdx =
485 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
47
Assuming the condition is false
486
487 // The source has other uses. See if we can replace the other uses with use of
488 // the result of the extension.
489 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
490 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
491 ReachedBBs.insert(UI.getParent());
492
493 // Uses that are in the same BB of uses of the result of the instruction.
494 SmallVector<MachineOperand*, 8> Uses;
495
496 // Uses that the result of the instruction can reach.
497 SmallVector<MachineOperand*, 8> ExtendedUses;
498
499 bool ExtendLife = true;
500 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
501 MachineInstr *UseMI = UseMO.getParent();
502 if (UseMI == &MI)
48
Assuming the condition is false
49
Taking false branch
503 continue;
504
505 if (UseMI->isPHI()) {
50
Calling 'MachineInstr::isPHI'
54
Returning from 'MachineInstr::isPHI'
55
Taking false branch
506 ExtendLife = false;
507 continue;
508 }
509
510 // Only accept uses of SrcReg:SubIdx.
511 if (UseSrcSubIdx
55.1
'UseSrcSubIdx' is false
55.1
'UseSrcSubIdx' is false
55.1
'UseSrcSubIdx' is false
55.1
'UseSrcSubIdx' is false
&& UseMO.getSubReg() != SubIdx)
512 continue;
513
514 // It's an error to translate this:
515 //
516 // %reg1025 = <sext> %reg1024
517 // ...
518 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
519 //
520 // into this:
521 //
522 // %reg1025 = <sext> %reg1024
523 // ...
524 // %reg1027 = COPY %reg1025:4
525 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
526 //
527 // The problem here is that SUBREG_TO_REG is there to assert that an
528 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
529 // the COPY here, it will give us the value after the <sext>, not the
530 // original value of %reg1024 before <sext>.
531 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
56
Assuming the condition is false
57
Taking false branch
532 continue;
533
534 MachineBasicBlock *UseMBB = UseMI->getParent();
535 if (UseMBB == &MBB) {
58
Assuming the condition is false
59
Taking false branch
536 // Local uses that come after the extension.
537 if (!LocalMIs.count(UseMI))
538 Uses.push_back(&UseMO);
539 } else if (ReachedBBs.count(UseMBB)) {
60
Assuming the condition is false
61
Taking false branch
540 // Non-local uses where the result of the extension is used. Always
541 // replace these unless it's a PHI.
542 Uses.push_back(&UseMO);
543 } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
62
Assuming the condition is true
63
Called C++ object pointer is null
544 // We may want to extend the live range of the extension result in order
545 // to replace these uses.
546 ExtendedUses.push_back(&UseMO);
547 } else {
548 // Both will be live out of the def MBB anyway. Don't extend live range of
549 // the extension result.
550 ExtendLife = false;
551 break;
552 }
553 }
554
555 if (ExtendLife && !ExtendedUses.empty())
556 // Extend the liveness of the extension result.
557 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
558
559 // Now replace all uses.
560 bool Changed = false;
561 if (!Uses.empty()) {
562 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
563
564 // Look for PHI uses of the extended result, we don't want to extend the
565 // liveness of a PHI input. It breaks all kinds of assumptions down
566 // stream. A PHI use is expected to be the kill of its source values.
567 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
568 if (UI.isPHI())
569 PHIBBs.insert(UI.getParent());
570
571 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
572 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
573 MachineOperand *UseMO = Uses[i];
574 MachineInstr *UseMI = UseMO->getParent();
575 MachineBasicBlock *UseMBB = UseMI->getParent();
576 if (PHIBBs.count(UseMBB))
577 continue;
578
579 // About to add uses of DstReg, clear DstReg's kill flags.
580 if (!Changed) {
581 MRI->clearKillFlags(DstReg);
582 MRI->constrainRegClass(DstReg, DstRC);
583 }
584
585 Register NewVR = MRI->createVirtualRegister(RC);
586 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
587 TII->get(TargetOpcode::COPY), NewVR)
588 .addReg(DstReg, 0, SubIdx);
589 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
590 if (UseSrcSubIdx) {
591 Copy->getOperand(0).setSubReg(SubIdx);
592 Copy->getOperand(0).setIsUndef();
593 }
594 UseMO->setReg(NewVR);
595 ++NumReuse;
596 Changed = true;
597 }
598 }
599
600 return Changed;
601}
602
603/// If the instruction is a compare and the previous instruction it's comparing
604/// against already sets (or could be modified to set) the same flag as the
605/// compare, then we can remove the comparison and use the flag from the
606/// previous instruction.
607bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr &MI) {
608 // If this instruction is a comparison against zero and isn't comparing a
609 // physical register, we can try to optimize it.
610 unsigned SrcReg, SrcReg2;
611 int CmpMask, CmpValue;
612 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
613 Register::isPhysicalRegister(SrcReg) ||
614 (SrcReg2 != 0 && Register::isPhysicalRegister(SrcReg2)))
615 return false;
616
617 // Attempt to optimize the comparison instruction.
618 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
619 ++NumCmps;
620 return true;
621 }
622
623 return false;
624}
625
626/// Optimize a select instruction.
627bool PeepholeOptimizer::optimizeSelect(MachineInstr &MI,
628 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
629 unsigned TrueOp = 0;
630 unsigned FalseOp = 0;
631 bool Optimizable = false;
632 SmallVector<MachineOperand, 4> Cond;
633 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
634 return false;
635 if (!Optimizable)
636 return false;
637 if (!TII->optimizeSelect(MI, LocalMIs))
638 return false;
639 MI.eraseFromParent();
640 ++NumSelects;
641 return true;
642}
643
644/// Check if a simpler conditional branch can be generated.
645bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
646 return TII->optimizeCondBranch(MI);
647}
648
649/// Try to find the next source that share the same register file
650/// for the value defined by \p Reg and \p SubReg.
651/// When true is returned, the \p RewriteMap can be used by the client to
652/// retrieve all Def -> Use along the way up to the next source. Any found
653/// Use that is not itself a key for another entry, is the next source to
654/// use. During the search for the next source, multiple sources can be found
655/// given multiple incoming sources of a PHI instruction. In this case, we
656/// look in each PHI source for the next source; all found next sources must
657/// share the same register file as \p Reg and \p SubReg. The client should
658/// then be capable to rewrite all intermediate PHIs to get the next source.
659/// \return False if no alternative sources are available. True otherwise.
660bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg,
661 RewriteMapTy &RewriteMap) {
662 // Do not try to find a new source for a physical register.
663 // So far we do not have any motivating example for doing that.
664 // Thus, instead of maintaining untested code, we will revisit that if
665 // that changes at some point.
666 unsigned Reg = RegSubReg.Reg;
667 if (Register::isPhysicalRegister(Reg))
668 return false;
669 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
670
671 SmallVector<RegSubRegPair, 4> SrcToLook;
672 RegSubRegPair CurSrcPair = RegSubReg;
673 SrcToLook.push_back(CurSrcPair);
674
675 unsigned PHICount = 0;
676 do {
677 CurSrcPair = SrcToLook.pop_back_val();
678 // As explained above, do not handle physical registers
679 if (Register::isPhysicalRegister(CurSrcPair.Reg))
680 return false;
681
682 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
683
684 // Follow the chain of copies until we find a more suitable source, a phi
685 // or have to abort.
686 while (true) {
687 ValueTrackerResult Res = ValTracker.getNextSource();
688 // Abort at the end of a chain (without finding a suitable source).
689 if (!Res.isValid())
690 return false;
691
692 // Insert the Def -> Use entry for the recently found source.
693 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
694 if (CurSrcRes.isValid()) {
695 assert(CurSrcRes == Res && "ValueTrackerResult found must match")((CurSrcRes == Res && "ValueTrackerResult found must match"
) ? static_cast<void> (0) : __assert_fail ("CurSrcRes == Res && \"ValueTrackerResult found must match\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 695, __PRETTY_FUNCTION__))
;
696 // An existent entry with multiple sources is a PHI cycle we must avoid.
697 // Otherwise it's an entry with a valid next source we already found.
698 if (CurSrcRes.getNumSources() > 1) {
699 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "findNextSource: found PHI cycle, aborting...\n"
; } } while (false)
700 << "findNextSource: found PHI cycle, aborting...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "findNextSource: found PHI cycle, aborting...\n"
; } } while (false)
;
701 return false;
702 }
703 break;
704 }
705 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
706
707 // ValueTrackerResult usually have one source unless it's the result from
708 // a PHI instruction. Add the found PHI edges to be looked up further.
709 unsigned NumSrcs = Res.getNumSources();
710 if (NumSrcs > 1) {
711 PHICount++;
712 if (PHICount >= RewritePHILimit) {
713 LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "findNextSource: PHI limit reached\n"
; } } while (false)
;
714 return false;
715 }
716
717 for (unsigned i = 0; i < NumSrcs; ++i)
718 SrcToLook.push_back(Res.getSrc(i));
719 break;
720 }
721
722 CurSrcPair = Res.getSrc(0);
723 // Do not extend the live-ranges of physical registers as they add
724 // constraints to the register allocator. Moreover, if we want to extend
725 // the live-range of a physical register, unlike SSA virtual register,
726 // we will have to check that they aren't redefine before the related use.
727 if (Register::isPhysicalRegister(CurSrcPair.Reg))
728 return false;
729
730 // Keep following the chain if the value isn't any better yet.
731 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
732 if (!TRI->shouldRewriteCopySrc(DefRC, RegSubReg.SubReg, SrcRC,
733 CurSrcPair.SubReg))
734 continue;
735
736 // We currently cannot deal with subreg operands on PHI instructions
737 // (see insertPHI()).
738 if (PHICount > 0 && CurSrcPair.SubReg != 0)
739 continue;
740
741 // We found a suitable source, and are done with this chain.
742 break;
743 }
744 } while (!SrcToLook.empty());
745
746 // If we did not find a more suitable source, there is nothing to optimize.
747 return CurSrcPair.Reg != Reg;
748}
749
750/// Insert a PHI instruction with incoming edges \p SrcRegs that are
751/// guaranteed to have the same register class. This is necessary whenever we
752/// successfully traverse a PHI instruction and find suitable sources coming
753/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
754/// suitable to be used in a new COPY instruction.
755static MachineInstr &
756insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
757 const SmallVectorImpl<RegSubRegPair> &SrcRegs,
758 MachineInstr &OrigPHI) {
759 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?")((!SrcRegs.empty() && "No sources to create a PHI instruction?"
) ? static_cast<void> (0) : __assert_fail ("!SrcRegs.empty() && \"No sources to create a PHI instruction?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 759, __PRETTY_FUNCTION__))
;
760
761 const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
762 // NewRC is only correct if no subregisters are involved. findNextSource()
763 // should have rejected those cases already.
764 assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand")((SrcRegs[0].SubReg == 0 && "should not have subreg operand"
) ? static_cast<void> (0) : __assert_fail ("SrcRegs[0].SubReg == 0 && \"should not have subreg operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 764, __PRETTY_FUNCTION__))
;
765 Register NewVR = MRI.createVirtualRegister(NewRC);
766 MachineBasicBlock *MBB = OrigPHI.getParent();
767 MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
768 TII.get(TargetOpcode::PHI), NewVR);
769
770 unsigned MBBOpIdx = 2;
771 for (const RegSubRegPair &RegPair : SrcRegs) {
772 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
773 MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
774 // Since we're extended the lifetime of RegPair.Reg, clear the
775 // kill flags to account for that and make RegPair.Reg reaches
776 // the new PHI.
777 MRI.clearKillFlags(RegPair.Reg);
778 MBBOpIdx += 2;
779 }
780
781 return *MIB;
782}
783
784namespace {
785
786/// Interface to query instructions amenable to copy rewriting.
787class Rewriter {
788protected:
789 MachineInstr &CopyLike;
790 unsigned CurrentSrcIdx = 0; ///< The index of the source being rewritten.
791public:
792 Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
793 virtual ~Rewriter() {}
794
795 /// Get the next rewritable source (SrcReg, SrcSubReg) and
796 /// the related value that it affects (DstReg, DstSubReg).
797 /// A source is considered rewritable if its register class and the
798 /// register class of the related DstReg may not be register
799 /// coalescer friendly. In other words, given a copy-like instruction
800 /// not all the arguments may be returned at rewritable source, since
801 /// some arguments are none to be register coalescer friendly.
802 ///
803 /// Each call of this method moves the current source to the next
804 /// rewritable source.
805 /// For instance, let CopyLike be the instruction to rewrite.
806 /// CopyLike has one definition and one source:
807 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
808 ///
809 /// The first call will give the first rewritable source, i.e.,
810 /// the only source this instruction has:
811 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
812 /// This source defines the whole definition, i.e.,
813 /// (DstReg, DstSubReg) = (dst, dstSubIdx).
814 ///
815 /// The second and subsequent calls will return false, as there is only one
816 /// rewritable source.
817 ///
818 /// \return True if a rewritable source has been found, false otherwise.
819 /// The output arguments are valid if and only if true is returned.
820 virtual bool getNextRewritableSource(RegSubRegPair &Src,
821 RegSubRegPair &Dst) = 0;
822
823 /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
824 /// \return True if the rewriting was possible, false otherwise.
825 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) = 0;
826};
827
828/// Rewriter for COPY instructions.
829class CopyRewriter : public Rewriter {
830public:
831 CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
832 assert(MI.isCopy() && "Expected copy instruction")((MI.isCopy() && "Expected copy instruction") ? static_cast
<void> (0) : __assert_fail ("MI.isCopy() && \"Expected copy instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 832, __PRETTY_FUNCTION__))
;
833 }
834 virtual ~CopyRewriter() = default;
835
836 bool getNextRewritableSource(RegSubRegPair &Src,
837 RegSubRegPair &Dst) override {
838 // CurrentSrcIdx > 0 means this function has already been called.
839 if (CurrentSrcIdx > 0)
840 return false;
841 // This is the first call to getNextRewritableSource.
842 // Move the CurrentSrcIdx to remember that we made that call.
843 CurrentSrcIdx = 1;
844 // The rewritable source is the argument.
845 const MachineOperand &MOSrc = CopyLike.getOperand(1);
846 Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
847 // What we track are the alternative sources of the definition.
848 const MachineOperand &MODef = CopyLike.getOperand(0);
849 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
850 return true;
851 }
852
853 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
854 if (CurrentSrcIdx != 1)
855 return false;
856 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
857 MOSrc.setReg(NewReg);
858 MOSrc.setSubReg(NewSubReg);
859 return true;
860 }
861};
862
863/// Helper class to rewrite uncoalescable copy like instructions
864/// into new COPY (coalescable friendly) instructions.
865class UncoalescableRewriter : public Rewriter {
866 unsigned NumDefs; ///< Number of defs in the bitcast.
867
868public:
869 UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
870 NumDefs = MI.getDesc().getNumDefs();
871 }
872
873 /// \see See Rewriter::getNextRewritableSource()
874 /// All such sources need to be considered rewritable in order to
875 /// rewrite a uncoalescable copy-like instruction. This method return
876 /// each definition that must be checked if rewritable.
877 bool getNextRewritableSource(RegSubRegPair &Src,
878 RegSubRegPair &Dst) override {
879 // Find the next non-dead definition and continue from there.
880 if (CurrentSrcIdx == NumDefs)
881 return false;
882
883 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
884 ++CurrentSrcIdx;
885 if (CurrentSrcIdx == NumDefs)
886 return false;
887 }
888
889 // What we track are the alternative sources of the definition.
890 Src = RegSubRegPair(0, 0);
891 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
892 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
893
894 CurrentSrcIdx++;
895 return true;
896 }
897
898 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
899 return false;
900 }
901};
902
903/// Specialized rewriter for INSERT_SUBREG instruction.
904class InsertSubregRewriter : public Rewriter {
905public:
906 InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
907 assert(MI.isInsertSubreg() && "Invalid instruction")((MI.isInsertSubreg() && "Invalid instruction") ? static_cast
<void> (0) : __assert_fail ("MI.isInsertSubreg() && \"Invalid instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 907, __PRETTY_FUNCTION__))
;
908 }
909
910 /// \see See Rewriter::getNextRewritableSource()
911 /// Here CopyLike has the following form:
912 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
913 /// Src1 has the same register class has dst, hence, there is
914 /// nothing to rewrite.
915 /// Src2.src2SubIdx, may not be register coalescer friendly.
916 /// Therefore, the first call to this method returns:
917 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
918 /// (DstReg, DstSubReg) = (dst, subIdx).
919 ///
920 /// Subsequence calls will return false.
921 bool getNextRewritableSource(RegSubRegPair &Src,
922 RegSubRegPair &Dst) override {
923 // If we already get the only source we can rewrite, return false.
924 if (CurrentSrcIdx == 2)
925 return false;
926 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
927 CurrentSrcIdx = 2;
928 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
929 Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
930 const MachineOperand &MODef = CopyLike.getOperand(0);
931
932 // We want to track something that is compatible with the
933 // partial definition.
934 if (MODef.getSubReg())
935 // Bail if we have to compose sub-register indices.
936 return false;
937 Dst = RegSubRegPair(MODef.getReg(),
938 (unsigned)CopyLike.getOperand(3).getImm());
939 return true;
940 }
941
942 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
943 if (CurrentSrcIdx != 2)
944 return false;
945 // We are rewriting the inserted reg.
946 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
947 MO.setReg(NewReg);
948 MO.setSubReg(NewSubReg);
949 return true;
950 }
951};
952
953/// Specialized rewriter for EXTRACT_SUBREG instruction.
954class ExtractSubregRewriter : public Rewriter {
955 const TargetInstrInfo &TII;
956
957public:
958 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
959 : Rewriter(MI), TII(TII) {
960 assert(MI.isExtractSubreg() && "Invalid instruction")((MI.isExtractSubreg() && "Invalid instruction") ? static_cast
<void> (0) : __assert_fail ("MI.isExtractSubreg() && \"Invalid instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 960, __PRETTY_FUNCTION__))
;
961 }
962
963 /// \see Rewriter::getNextRewritableSource()
964 /// Here CopyLike has the following form:
965 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
966 /// There is only one rewritable source: Src.subIdx,
967 /// which defines dst.dstSubIdx.
968 bool getNextRewritableSource(RegSubRegPair &Src,
969 RegSubRegPair &Dst) override {
970 // If we already get the only source we can rewrite, return false.
971 if (CurrentSrcIdx == 1)
972 return false;
973 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
974 CurrentSrcIdx = 1;
975 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
976 // If we have to compose sub-register indices, bail out.
977 if (MOExtractedReg.getSubReg())
978 return false;
979
980 Src = RegSubRegPair(MOExtractedReg.getReg(),
981 CopyLike.getOperand(2).getImm());
982
983 // We want to track something that is compatible with the definition.
984 const MachineOperand &MODef = CopyLike.getOperand(0);
985 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
986 return true;
987 }
988
989 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
990 // The only source we can rewrite is the input register.
991 if (CurrentSrcIdx != 1)
992 return false;
993
994 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
995
996 // If we find a source that does not require to extract something,
997 // rewrite the operation with a copy.
998 if (!NewSubReg) {
999 // Move the current index to an invalid position.
1000 // We do not want another call to this method to be able
1001 // to do any change.
1002 CurrentSrcIdx = -1;
1003 // Rewrite the operation as a COPY.
1004 // Get rid of the sub-register index.
1005 CopyLike.RemoveOperand(2);
1006 // Morph the operation into a COPY.
1007 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1008 return true;
1009 }
1010 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1011 return true;
1012 }
1013};
1014
1015/// Specialized rewriter for REG_SEQUENCE instruction.
1016class RegSequenceRewriter : public Rewriter {
1017public:
1018 RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
1019 assert(MI.isRegSequence() && "Invalid instruction")((MI.isRegSequence() && "Invalid instruction") ? static_cast
<void> (0) : __assert_fail ("MI.isRegSequence() && \"Invalid instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1019, __PRETTY_FUNCTION__))
;
1020 }
1021
1022 /// \see Rewriter::getNextRewritableSource()
1023 /// Here CopyLike has the following form:
1024 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1025 /// Each call will return a different source, walking all the available
1026 /// source.
1027 ///
1028 /// The first call returns:
1029 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1030 /// (DstReg, DstSubReg) = (dst, subIdx1).
1031 ///
1032 /// The second call returns:
1033 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1034 /// (DstReg, DstSubReg) = (dst, subIdx2).
1035 ///
1036 /// And so on, until all the sources have been traversed, then
1037 /// it returns false.
1038 bool getNextRewritableSource(RegSubRegPair &Src,
1039 RegSubRegPair &Dst) override {
1040 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1041
1042 // If this is the first call, move to the first argument.
1043 if (CurrentSrcIdx == 0) {
1044 CurrentSrcIdx = 1;
1045 } else {
1046 // Otherwise, move to the next argument and check that it is valid.
1047 CurrentSrcIdx += 2;
1048 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1049 return false;
1050 }
1051 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1052 Src.Reg = MOInsertedReg.getReg();
1053 // If we have to compose sub-register indices, bail out.
1054 if ((Src.SubReg = MOInsertedReg.getSubReg()))
1055 return false;
1056
1057 // We want to track something that is compatible with the related
1058 // partial definition.
1059 Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1060
1061 const MachineOperand &MODef = CopyLike.getOperand(0);
1062 Dst.Reg = MODef.getReg();
1063 // If we have to compose sub-registers, bail.
1064 return MODef.getSubReg() == 0;
1065 }
1066
1067 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1068 // We cannot rewrite out of bound operands.
1069 // Moreover, rewritable sources are at odd positions.
1070 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1071 return false;
1072
1073 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1074 MO.setReg(NewReg);
1075 MO.setSubReg(NewSubReg);
1076 return true;
1077 }
1078};
1079
1080} // end anonymous namespace
1081
1082/// Get the appropriated Rewriter for \p MI.
1083/// \return A pointer to a dynamically allocated Rewriter or nullptr if no
1084/// rewriter works for \p MI.
1085static Rewriter *getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII) {
1086 // Handle uncoalescable copy-like instructions.
1087 if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1088 MI.isExtractSubregLike())
1089 return new UncoalescableRewriter(MI);
1090
1091 switch (MI.getOpcode()) {
1092 default:
1093 return nullptr;
1094 case TargetOpcode::COPY:
1095 return new CopyRewriter(MI);
1096 case TargetOpcode::INSERT_SUBREG:
1097 return new InsertSubregRewriter(MI);
1098 case TargetOpcode::EXTRACT_SUBREG:
1099 return new ExtractSubregRewriter(MI, TII);
1100 case TargetOpcode::REG_SEQUENCE:
1101 return new RegSequenceRewriter(MI);
1102 }
1103}
1104
1105/// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
1106/// the new source to use for rewrite. If \p HandleMultipleSources is true and
1107/// multiple sources for a given \p Def are found along the way, we found a
1108/// PHI instructions that needs to be rewritten.
1109/// TODO: HandleMultipleSources should be removed once we test PHI handling
1110/// with coalescable copies.
1111static RegSubRegPair
1112getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
1113 RegSubRegPair Def,
1114 const PeepholeOptimizer::RewriteMapTy &RewriteMap,
1115 bool HandleMultipleSources = true) {
1116 RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
1117 while (true) {
1118 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
1119 // If there are no entries on the map, LookupSrc is the new source.
1120 if (!Res.isValid())
1121 return LookupSrc;
1122
1123 // There's only one source for this definition, keep searching...
1124 unsigned NumSrcs = Res.getNumSources();
1125 if (NumSrcs == 1) {
1126 LookupSrc.Reg = Res.getSrcReg(0);
1127 LookupSrc.SubReg = Res.getSrcSubReg(0);
1128 continue;
1129 }
1130
1131 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
1132 if (!HandleMultipleSources)
1133 break;
1134
1135 // Multiple sources, recurse into each source to find a new source
1136 // for it. Then, rewrite the PHI accordingly to its new edges.
1137 SmallVector<RegSubRegPair, 4> NewPHISrcs;
1138 for (unsigned i = 0; i < NumSrcs; ++i) {
1139 RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
1140 NewPHISrcs.push_back(
1141 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
1142 }
1143
1144 // Build the new PHI node and return its def register as the new source.
1145 MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
1146 MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
1147 LLVM_DEBUG(dbgs() << "-- getNewSource\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "-- getNewSource\n"; } } while
(false)
;
1148 LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << " Replacing: " <<
OrigPHI; } } while (false)
;
1149 LLVM_DEBUG(dbgs() << " With: " << NewPHI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << " With: " <<
NewPHI; } } while (false)
;
1150 const MachineOperand &MODef = NewPHI.getOperand(0);
1151 return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
1152 }
1153
1154 return RegSubRegPair(0, 0);
1155}
1156
1157/// Optimize generic copy instructions to avoid cross register bank copy.
1158/// The optimization looks through a chain of copies and tries to find a source
1159/// that has a compatible register class.
1160/// Two register classes are considered to be compatible if they share the same
1161/// register bank.
1162/// New copies issued by this optimization are register allocator
1163/// friendly. This optimization does not remove any copy as it may
1164/// overconstrain the register allocator, but replaces some operands
1165/// when possible.
1166/// \pre isCoalescableCopy(*MI) is true.
1167/// \return True, when \p MI has been rewritten. False otherwise.
1168bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
1169 assert(isCoalescableCopy(MI) && "Invalid argument")((isCoalescableCopy(MI) && "Invalid argument") ? static_cast
<void> (0) : __assert_fail ("isCoalescableCopy(MI) && \"Invalid argument\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1169, __PRETTY_FUNCTION__))
;
1170 assert(MI.getDesc().getNumDefs() == 1 &&((MI.getDesc().getNumDefs() == 1 && "Coalescer can understand multiple defs?!"
) ? static_cast<void> (0) : __assert_fail ("MI.getDesc().getNumDefs() == 1 && \"Coalescer can understand multiple defs?!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1171, __PRETTY_FUNCTION__))
1171 "Coalescer can understand multiple defs?!")((MI.getDesc().getNumDefs() == 1 && "Coalescer can understand multiple defs?!"
) ? static_cast<void> (0) : __assert_fail ("MI.getDesc().getNumDefs() == 1 && \"Coalescer can understand multiple defs?!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1171, __PRETTY_FUNCTION__))
;
1172 const MachineOperand &MODef = MI.getOperand(0);
1173 // Do not rewrite physical definitions.
1174 if (Register::isPhysicalRegister(MODef.getReg()))
1175 return false;
1176
1177 bool Changed = false;
1178 // Get the right rewriter for the current copy.
1179 std::unique_ptr<Rewriter> CpyRewriter(getCopyRewriter(MI, *TII));
1180 // If none exists, bail out.
1181 if (!CpyRewriter)
1182 return false;
1183 // Rewrite each rewritable source.
1184 RegSubRegPair Src;
1185 RegSubRegPair TrackPair;
1186 while (CpyRewriter->getNextRewritableSource(Src, TrackPair)) {
1187 // Keep track of PHI nodes and its incoming edges when looking for sources.
1188 RewriteMapTy RewriteMap;
1189 // Try to find a more suitable source. If we failed to do so, or get the
1190 // actual source, move to the next source.
1191 if (!findNextSource(TrackPair, RewriteMap))
1192 continue;
1193
1194 // Get the new source to rewrite. TODO: Only enable handling of multiple
1195 // sources (PHIs) once we have a motivating example and testcases for it.
1196 RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
1197 /*HandleMultipleSources=*/false);
1198 if (Src.Reg == NewSrc.Reg || NewSrc.Reg == 0)
1199 continue;
1200
1201 // Rewrite source.
1202 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1203 // We may have extended the live-range of NewSrc, account for that.
1204 MRI->clearKillFlags(NewSrc.Reg);
1205 Changed = true;
1206 }
1207 }
1208 // TODO: We could have a clean-up method to tidy the instruction.
1209 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1210 // => v0 = COPY v1
1211 // Currently we haven't seen motivating example for that and we
1212 // want to avoid untested code.
1213 NumRewrittenCopies += Changed;
1214 return Changed;
1215}
1216
1217/// Rewrite the source found through \p Def, by using the \p RewriteMap
1218/// and create a new COPY instruction. More info about RewriteMap in
1219/// PeepholeOptimizer::findNextSource. Right now this is only used to handle
1220/// Uncoalescable copies, since they are copy like instructions that aren't
1221/// recognized by the register allocator.
1222MachineInstr &
1223PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
1224 RegSubRegPair Def, RewriteMapTy &RewriteMap) {
1225 assert(!Register::isPhysicalRegister(Def.Reg) &&((!Register::isPhysicalRegister(Def.Reg) && "We do not rewrite physical registers"
) ? static_cast<void> (0) : __assert_fail ("!Register::isPhysicalRegister(Def.Reg) && \"We do not rewrite physical registers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1226, __PRETTY_FUNCTION__))
1226 "We do not rewrite physical registers")((!Register::isPhysicalRegister(Def.Reg) && "We do not rewrite physical registers"
) ? static_cast<void> (0) : __assert_fail ("!Register::isPhysicalRegister(Def.Reg) && \"We do not rewrite physical registers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1226, __PRETTY_FUNCTION__))
;
1227
1228 // Find the new source to use in the COPY rewrite.
1229 RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
1230
1231 // Insert the COPY.
1232 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
1233 Register NewVReg = MRI->createVirtualRegister(DefRC);
1234
1235 MachineInstr *NewCopy =
1236 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1237 TII->get(TargetOpcode::COPY), NewVReg)
1238 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
1239
1240 if (Def.SubReg) {
1241 NewCopy->getOperand(0).setSubReg(Def.SubReg);
1242 NewCopy->getOperand(0).setIsUndef();
1243 }
1244
1245 LLVM_DEBUG(dbgs() << "-- RewriteSource\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "-- RewriteSource\n"; } }
while (false)
;
1246 LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << " Replacing: " <<
CopyLike; } } while (false)
;
1247 LLVM_DEBUG(dbgs() << " With: " << *NewCopy)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << " With: " <<
*NewCopy; } } while (false)
;
1248 MRI->replaceRegWith(Def.Reg, NewVReg);
1249 MRI->clearKillFlags(NewVReg);
1250
1251 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1252 // account for that.
1253 MRI->clearKillFlags(NewSrc.Reg);
1254
1255 return *NewCopy;
1256}
1257
1258/// Optimize copy-like instructions to create
1259/// register coalescer friendly instruction.
1260/// The optimization tries to kill-off the \p MI by looking
1261/// through a chain of copies to find a source that has a compatible
1262/// register class.
1263/// If such a source is found, it replace \p MI by a generic COPY
1264/// operation.
1265/// \pre isUncoalescableCopy(*MI) is true.
1266/// \return True, when \p MI has been optimized. In that case, \p MI has
1267/// been removed from its parent.
1268/// All COPY instructions created, are inserted in \p LocalMIs.
1269bool PeepholeOptimizer::optimizeUncoalescableCopy(
1270 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1271 assert(isUncoalescableCopy(MI) && "Invalid argument")((isUncoalescableCopy(MI) && "Invalid argument") ? static_cast
<void> (0) : __assert_fail ("isUncoalescableCopy(MI) && \"Invalid argument\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1271, __PRETTY_FUNCTION__))
;
1272 UncoalescableRewriter CpyRewriter(MI);
1273
1274 // Rewrite each rewritable source by generating new COPYs. This works
1275 // differently from optimizeCoalescableCopy since it first makes sure that all
1276 // definitions can be rewritten.
1277 RewriteMapTy RewriteMap;
1278 RegSubRegPair Src;
1279 RegSubRegPair Def;
1280 SmallVector<RegSubRegPair, 4> RewritePairs;
1281 while (CpyRewriter.getNextRewritableSource(Src, Def)) {
1282 // If a physical register is here, this is probably for a good reason.
1283 // Do not rewrite that.
1284 if (Register::isPhysicalRegister(Def.Reg))
1285 return false;
1286
1287 // If we do not know how to rewrite this definition, there is no point
1288 // in trying to kill this instruction.
1289 if (!findNextSource(Def, RewriteMap))
1290 return false;
1291
1292 RewritePairs.push_back(Def);
1293 }
1294
1295 // The change is possible for all defs, do it.
1296 for (const RegSubRegPair &Def : RewritePairs) {
1297 // Rewrite the "copy" in a way the register coalescer understands.
1298 MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
1299 LocalMIs.insert(&NewCopy);
1300 }
1301
1302 // MI is now dead.
1303 MI.eraseFromParent();
1304 ++NumUncoalescableCopies;
1305 return true;
1306}
1307
1308/// Check whether MI is a candidate for folding into a later instruction.
1309/// We only fold loads to virtual registers and the virtual register defined
1310/// has a single user.
1311bool PeepholeOptimizer::isLoadFoldable(
1312 MachineInstr &MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1313 if (!MI.canFoldAsLoad() || !MI.mayLoad())
1314 return false;
1315 const MCInstrDesc &MCID = MI.getDesc();
1316 if (MCID.getNumDefs() != 1)
1317 return false;
1318
1319 Register Reg = MI.getOperand(0).getReg();
1320 // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
1321 // loads. It should be checked when processing uses of the load, since
1322 // uses can be removed during peephole.
1323 if (!MI.getOperand(0).getSubReg() && Register::isVirtualRegister(Reg) &&
1324 MRI->hasOneNonDBGUser(Reg)) {
1325 FoldAsLoadDefCandidates.insert(Reg);
1326 return true;
1327 }
1328 return false;
1329}
1330
1331bool PeepholeOptimizer::isMoveImmediate(
1332 MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
1333 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
1334 const MCInstrDesc &MCID = MI.getDesc();
1335 if (!MI.isMoveImmediate())
1336 return false;
1337 if (MCID.getNumDefs() != 1)
1338 return false;
1339 Register Reg = MI.getOperand(0).getReg();
1340 if (Register::isVirtualRegister(Reg)) {
1341 ImmDefMIs.insert(std::make_pair(Reg, &MI));
1342 ImmDefRegs.insert(Reg);
1343 return true;
1344 }
1345
1346 return false;
1347}
1348
1349/// Try folding register operands that are defined by move immediate
1350/// instructions, i.e. a trivial constant folding optimization, if
1351/// and only if the def and use are in the same BB.
1352bool PeepholeOptimizer::foldImmediate(MachineInstr &MI,
1353 SmallSet<unsigned, 4> &ImmDefRegs,
1354 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
1355 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1356 MachineOperand &MO = MI.getOperand(i);
1357 if (!MO.isReg() || MO.isDef())
1358 continue;
1359 // Ignore dead implicit defs.
1360 if (MO.isImplicit() && MO.isDead())
1361 continue;
1362 Register Reg = MO.getReg();
1363 if (!Register::isVirtualRegister(Reg))
1364 continue;
1365 if (ImmDefRegs.count(Reg) == 0)
1366 continue;
1367 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1368 assert(II != ImmDefMIs.end() && "couldn't find immediate definition")((II != ImmDefMIs.end() && "couldn't find immediate definition"
) ? static_cast<void> (0) : __assert_fail ("II != ImmDefMIs.end() && \"couldn't find immediate definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1368, __PRETTY_FUNCTION__))
;
1369 if (TII->FoldImmediate(MI, *II->second, Reg, MRI)) {
1370 ++NumImmFold;
1371 return true;
1372 }
1373 }
1374 return false;
1375}
1376
1377// FIXME: This is very simple and misses some cases which should be handled when
1378// motivating examples are found.
1379//
1380// The copy rewriting logic should look at uses as well as defs and be able to
1381// eliminate copies across blocks.
1382//
1383// Later copies that are subregister extracts will also not be eliminated since
1384// only the first copy is considered.
1385//
1386// e.g.
1387// %1 = COPY %0
1388// %2 = COPY %0:sub1
1389//
1390// Should replace %2 uses with %1:sub1
1391bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI,
1392 SmallSet<unsigned, 4> &CopySrcRegs,
1393 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1394 assert(MI.isCopy() && "expected a COPY machine instruction")((MI.isCopy() && "expected a COPY machine instruction"
) ? static_cast<void> (0) : __assert_fail ("MI.isCopy() && \"expected a COPY machine instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1394, __PRETTY_FUNCTION__))
;
1395
1396 Register SrcReg = MI.getOperand(1).getReg();
1397 if (!Register::isVirtualRegister(SrcReg))
1398 return false;
1399
1400 Register DstReg = MI.getOperand(0).getReg();
1401 if (!Register::isVirtualRegister(DstReg))
1402 return false;
1403
1404 if (CopySrcRegs.insert(SrcReg).second) {
1405 // First copy of this reg seen.
1406 CopyMIs.insert(std::make_pair(SrcReg, &MI));
1407 return false;
1408 }
1409
1410 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1411
1412 unsigned SrcSubReg = MI.getOperand(1).getSubReg();
1413 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1414
1415 // Can't replace different subregister extracts.
1416 if (SrcSubReg != PrevSrcSubReg)
1417 return false;
1418
1419 Register PrevDstReg = PrevCopy->getOperand(0).getReg();
1420
1421 // Only replace if the copy register class is the same.
1422 //
1423 // TODO: If we have multiple copies to different register classes, we may want
1424 // to track multiple copies of the same source register.
1425 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1426 return false;
1427
1428 MRI->replaceRegWith(DstReg, PrevDstReg);
1429
1430 // Lifetime of the previous copy has been extended.
1431 MRI->clearKillFlags(PrevDstReg);
1432 return true;
1433}
1434
1435bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1436 return Register::isPhysicalRegister(Reg) && !MRI->isAllocatable(Reg);
1437}
1438
1439bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1440 MachineInstr &MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1441 assert(MI.isCopy() && "expected a COPY machine instruction")((MI.isCopy() && "expected a COPY machine instruction"
) ? static_cast<void> (0) : __assert_fail ("MI.isCopy() && \"expected a COPY machine instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1441, __PRETTY_FUNCTION__))
;
1442
1443 if (DisableNAPhysCopyOpt)
1444 return false;
1445
1446 Register DstReg = MI.getOperand(0).getReg();
1447 Register SrcReg = MI.getOperand(1).getReg();
1448 if (isNAPhysCopy(SrcReg) && Register::isVirtualRegister(DstReg)) {
1449 // %vreg = COPY %physreg
1450 // Avoid using a datastructure which can track multiple live non-allocatable
1451 // phys->virt copies since LLVM doesn't seem to do this.
1452 NAPhysToVirtMIs.insert({SrcReg, &MI});
1453 return false;
1454 }
1455
1456 if (!(Register::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1457 return false;
1458
1459 // %physreg = COPY %vreg
1460 auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1461 if (PrevCopy == NAPhysToVirtMIs.end()) {
1462 // We can't remove the copy: there was an intervening clobber of the
1463 // non-allocatable physical register after the copy to virtual.
1464 LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
<< MI; } } while (false)
1465 << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
<< MI; } } while (false)
;
1466 return false;
1467 }
1468
1469 Register PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1470 if (PrevDstReg == SrcReg) {
1471 // Remove the virt->phys copy: we saw the virtual register definition, and
1472 // the non-allocatable physical register's state hasn't changed since then.
1473 LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: erasing " <<
MI; } } while (false)
;
1474 ++NumNAPhysCopies;
1475 return true;
1476 }
1477
1478 // Potential missed optimization opportunity: we saw a different virtual
1479 // register get a copy of the non-allocatable physical register, and we only
1480 // track one such copy. Avoid getting confused by this new non-allocatable
1481 // physical register definition, and remove it from the tracked copies.
1482 LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: missed opportunity "
<< MI; } } while (false)
;
1483 NAPhysToVirtMIs.erase(PrevCopy);
1484 return false;
1485}
1486
1487/// \bried Returns true if \p MO is a virtual register operand.
1488static bool isVirtualRegisterOperand(MachineOperand &MO) {
1489 if (!MO.isReg())
1490 return false;
1491 return Register::isVirtualRegister(MO.getReg());
1492}
1493
1494bool PeepholeOptimizer::findTargetRecurrence(
1495 unsigned Reg, const SmallSet<unsigned, 2> &TargetRegs,
1496 RecurrenceCycle &RC) {
1497 // Recurrence found if Reg is in TargetRegs.
1498 if (TargetRegs.count(Reg))
1499 return true;
1500
1501 // TODO: Curerntly, we only allow the last instruction of the recurrence
1502 // cycle (the instruction that feeds the PHI instruction) to have more than
1503 // one uses to guarantee that commuting operands does not tie registers
1504 // with overlapping live range. Once we have actual live range info of
1505 // each register, this constraint can be relaxed.
1506 if (!MRI->hasOneNonDBGUse(Reg))
1507 return false;
1508
1509 // Give up if the reccurrence chain length is longer than the limit.
1510 if (RC.size() >= MaxRecurrenceChain)
1511 return false;
1512
1513 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
1514 unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
1515
1516 // Only interested in recurrences whose instructions have only one def, which
1517 // is a virtual register.
1518 if (MI.getDesc().getNumDefs() != 1)
1519 return false;
1520
1521 MachineOperand &DefOp = MI.getOperand(0);
1522 if (!isVirtualRegisterOperand(DefOp))
1523 return false;
1524
1525 // Check if def operand of MI is tied to any use operand. We are only
1526 // interested in the case that all the instructions in the recurrence chain
1527 // have there def operand tied with one of the use operand.
1528 unsigned TiedUseIdx;
1529 if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
1530 return false;
1531
1532 if (Idx == TiedUseIdx) {
1533 RC.push_back(RecurrenceInstr(&MI));
1534 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1535 } else {
1536 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1537 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1538 if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
1539 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1540 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1541 }
1542 }
1543
1544 return false;
1545}
1546
1547/// Phi instructions will eventually be lowered to copy instructions.
1548/// If phi is in a loop header, a recurrence may formulated around the source
1549/// and destination of the phi. For such case commuting operands of the
1550/// instructions in the recurrence may enable coalescing of the copy instruction
1551/// generated from the phi. For example, if there is a recurrence of
1552///
1553/// LoopHeader:
1554/// %1 = phi(%0, %100)
1555/// LoopLatch:
1556/// %0<def, tied1> = ADD %2<def, tied0>, %1
1557///
1558/// , the fact that %0 and %2 are in the same tied operands set makes
1559/// the coalescing of copy instruction generated from the phi in
1560/// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
1561/// %2 have overlapping live range. This introduces additional move
1562/// instruction to the final assembly. However, if we commute %2 and
1563/// %1 of ADD instruction, the redundant move instruction can be
1564/// avoided.
1565bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1566 SmallSet<unsigned, 2> TargetRegs;
1567 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1568 MachineOperand &MO = PHI.getOperand(Idx);
1569 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction")((isVirtualRegisterOperand(MO) && "Invalid PHI instruction"
) ? static_cast<void> (0) : __assert_fail ("isVirtualRegisterOperand(MO) && \"Invalid PHI instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1569, __PRETTY_FUNCTION__))
;
1570 TargetRegs.insert(MO.getReg());
1571 }
1572
1573 bool Changed = false;
1574 RecurrenceCycle RC;
1575 if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
1576 // Commutes operands of instructions in RC if necessary so that the copy to
1577 // be generated from PHI can be coalesced.
1578 LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "Optimize recurrence chain from "
<< PHI; } } while (false)
;
1579 for (auto &RI : RC) {
1580 LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "\tInst: " << *(RI.
getMI()); } } while (false)
;
1581 auto CP = RI.getCommutePair();
1582 if (CP) {
1583 Changed = true;
1584 TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
1585 (*CP).second);
1586 LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "\t\tCommuted: " <<
*(RI.getMI()); } } while (false)
;
1587 }
1588 }
1589 }
1590
1591 return Changed;
1592}
1593
1594bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1595 if (skipFunction(MF.getFunction()))
1
Assuming the condition is false
2
Taking false branch
1596 return false;
1597
1598 LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "********** PEEPHOLE OPTIMIZER **********\n"
; } } while (false)
;
3
Assuming 'DebugFlag' is false
4
Loop condition is false. Exiting loop
1599 LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "********** Function: " <<
MF.getName() << '\n'; } } while (false)
;
5
Loop condition is false. Exiting loop
1600
1601 if (DisablePeephole)
6
Assuming the condition is false
7
Taking false branch
1602 return false;
1603
1604 TII = MF.getSubtarget().getInstrInfo();
1605 TRI = MF.getSubtarget().getRegisterInfo();
1606 MRI = &MF.getRegInfo();
1607 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
8
Assuming the condition is false
9
'?' condition is false
10
Null pointer value stored to field 'DT'
1608 MLI = &getAnalysis<MachineLoopInfo>();
1609
1610 bool Changed = false;
1611
1612 for (MachineBasicBlock &MBB : MF) {
1613 bool SeenMoveImm = false;
1614
1615 // During this forward scan, at some point it needs to answer the question
1616 // "given a pointer to an MI in the current BB, is it located before or
1617 // after the current instruction".
1618 // To perform this, the following set keeps track of the MIs already seen
1619 // during the scan, if a MI is not in the set, it is assumed to be located
1620 // after. Newly created MIs have to be inserted in the set as well.
1621 SmallPtrSet<MachineInstr*, 16> LocalMIs;
1622 SmallSet<unsigned, 4> ImmDefRegs;
1623 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1624 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1625
1626 // Track when a non-allocatable physical register is copied to a virtual
1627 // register so that useless moves can be removed.
1628 //
1629 // %physreg is the map index; MI is the last valid `%vreg = COPY %physreg`
1630 // without any intervening re-definition of %physreg.
1631 DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1632
1633 // Set of virtual registers that are copied from.
1634 SmallSet<unsigned, 4> CopySrcRegs;
1635 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1636
1637 bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1638
1639 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
11
Loop condition is true. Entering loop body
1640 MII != MIE; ) {
1641 MachineInstr *MI = &*MII;
1642 // We may be erasing MI below, increment MII now.
1643 ++MII;
1644 LocalMIs.insert(MI);
1645
1646 // Skip debug instructions. They should not affect this peephole optimization.
1647 if (MI->isDebugInstr())
12
Taking false branch
1648 continue;
1649
1650 if (MI->isPosition())
13
Taking false branch
1651 continue;
1652
1653 if (IsLoopHeader && MI->isPHI()) {
14
Assuming 'IsLoopHeader' is false
1654 if (optimizeRecurrence(*MI)) {
1655 Changed = true;
1656 continue;
1657 }
1658 }
1659
1660 if (!MI->isCopy()) {
15
Taking true branch
1661 for (const MachineOperand &MO : MI->operands()) {
16
Assuming '__begin4' is equal to '__end4'
1662 // Visit all operands: definitions can be implicit or explicit.
1663 if (MO.isReg()) {
1664 Register Reg = MO.getReg();
1665 if (MO.isDef() && isNAPhysCopy(Reg)) {
1666 const auto &Def = NAPhysToVirtMIs.find(Reg);
1667 if (Def != NAPhysToVirtMIs.end()) {
1668 // A new definition of the non-allocatable physical register
1669 // invalidates previous copies.
1670 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: invalidating because of "
<< *MI; } } while (false)
1671 << "NAPhysCopy: invalidating because of " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: invalidating because of "
<< *MI; } } while (false)
;
1672 NAPhysToVirtMIs.erase(Def);
1673 }
1674 }
1675 } else if (MO.isRegMask()) {
1676 const uint32_t *RegMask = MO.getRegMask();
1677 for (auto &RegMI : NAPhysToVirtMIs) {
1678 unsigned Def = RegMI.first;
1679 if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
1680 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: invalidating because of "
<< *MI; } } while (false)
1681 << "NAPhysCopy: invalidating because of " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: invalidating because of "
<< *MI; } } while (false)
;
1682 NAPhysToVirtMIs.erase(Def);
1683 }
1684 }
1685 }
1686 }
1687 }
1688
1689 if (MI->isImplicitDef() || MI->isKill())
17
Taking false branch
1690 continue;
1691
1692 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
18
Assuming the condition is false
19
Taking false branch
1693 // Blow away all non-allocatable physical registers knowledge since we
1694 // don't know what's correct anymore.
1695 //
1696 // FIXME: handle explicit asm clobbers.
1697 LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: blowing away all info due to "
<< *MI; } } while (false)
1698 << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "NAPhysCopy: blowing away all info due to "
<< *MI; } } while (false)
;
1699 NAPhysToVirtMIs.clear();
1700 }
1701
1702 if ((isUncoalescableCopy(*MI) &&
1703 optimizeUncoalescableCopy(*MI, LocalMIs)) ||
1704 (MI->isCompare() && optimizeCmpInstr(*MI)) ||
20
Assuming the condition is false
1705 (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
21
Assuming the condition is false
1706 // MI is deleted.
1707 LocalMIs.erase(MI);
1708 Changed = true;
1709 continue;
1710 }
1711
1712 if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
1713 Changed = true;
1714 continue;
1715 }
1716
1717 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
1718 // MI is just rewritten.
1719 Changed = true;
1720 continue;
1721 }
1722
1723 if (MI->isCopy() &&
1724 (foldRedundantCopy(*MI, CopySrcRegs, CopySrcMIs) ||
1725 foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
1726 LocalMIs.erase(MI);
1727 MI->eraseFromParent();
1728 Changed = true;
1729 continue;
1730 }
1731
1732 if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
22
Taking false branch
1733 SeenMoveImm = true;
1734 } else {
1735 Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
23
Calling 'PeepholeOptimizer::optimizeExtInstr'
1736 // optimizeExtInstr might have created new instructions after MI
1737 // and before the already incremented MII. Adjust MII so that the
1738 // next iteration sees the new instructions.
1739 MII = MI;
1740 ++MII;
1741 if (SeenMoveImm)
1742 Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs);
1743 }
1744
1745 // Check whether MI is a load candidate for folding into a later
1746 // instruction. If MI is not a candidate, check whether we can fold an
1747 // earlier load into MI.
1748 if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
1749 !FoldAsLoadDefCandidates.empty()) {
1750
1751 // We visit each operand even after successfully folding a previous
1752 // one. This allows us to fold multiple loads into a single
1753 // instruction. We do assume that optimizeLoadInstr doesn't insert
1754 // foldable uses earlier in the argument list. Since we don't restart
1755 // iteration, we'd miss such cases.
1756 const MCInstrDesc &MIDesc = MI->getDesc();
1757 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
1758 ++i) {
1759 const MachineOperand &MOp = MI->getOperand(i);
1760 if (!MOp.isReg())
1761 continue;
1762 unsigned FoldAsLoadDefReg = MOp.getReg();
1763 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1764 // We need to fold load after optimizeCmpInstr, since
1765 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1766 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1767 // we need it for markUsesInDebugValueAsUndef().
1768 unsigned FoldedReg = FoldAsLoadDefReg;
1769 MachineInstr *DefMI = nullptr;
1770 if (MachineInstr *FoldMI =
1771 TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
1772 // Update LocalMIs since we replaced MI with FoldMI and deleted
1773 // DefMI.
1774 LLVM_DEBUG(dbgs() << "Replacing: " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "Replacing: " << *MI
; } } while (false)
;
1775 LLVM_DEBUG(dbgs() << " With: " << *FoldMI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << " With: " << *FoldMI
; } } while (false)
;
1776 LocalMIs.erase(MI);
1777 LocalMIs.erase(DefMI);
1778 LocalMIs.insert(FoldMI);
1779 // Update the call site info.
1780 if (MI->shouldUpdateCallSiteInfo())
1781 MI->getMF()->moveCallSiteInfo(MI, FoldMI);
1782 MI->eraseFromParent();
1783 DefMI->eraseFromParent();
1784 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1785 FoldAsLoadDefCandidates.erase(FoldedReg);
1786 ++NumLoadFold;
1787
1788 // MI is replaced with FoldMI so we can continue trying to fold
1789 Changed = true;
1790 MI = FoldMI;
1791 }
1792 }
1793 }
1794 }
1795
1796 // If we run into an instruction we can't fold across, discard
1797 // the load candidates. Note: We might be able to fold *into* this
1798 // instruction, so this needs to be after the folding logic.
1799 if (MI->isLoadFoldBarrier()) {
1800 LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("peephole-opt")) { dbgs() << "Encountered load fold barrier on "
<< *MI; } } while (false)
;
1801 FoldAsLoadDefCandidates.clear();
1802 }
1803 }
1804 }
1805
1806 return Changed;
1807}
1808
1809ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1810 assert(Def->isCopy() && "Invalid definition")((Def->isCopy() && "Invalid definition") ? static_cast
<void> (0) : __assert_fail ("Def->isCopy() && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1810, __PRETTY_FUNCTION__))
;
1811 // Copy instruction are supposed to be: Def = Src.
1812 // If someone breaks this assumption, bad things will happen everywhere.
1813 // There may be implicit uses preventing the copy to be moved across
1814 // some target specific register definitions
1815 assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 &&((Def->getNumOperands() - Def->getNumImplicitOperands()
== 2 && "Invalid number of operands") ? static_cast<
void> (0) : __assert_fail ("Def->getNumOperands() - Def->getNumImplicitOperands() == 2 && \"Invalid number of operands\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1816, __PRETTY_FUNCTION__))
1816 "Invalid number of operands")((Def->getNumOperands() - Def->getNumImplicitOperands()
== 2 && "Invalid number of operands") ? static_cast<
void> (0) : __assert_fail ("Def->getNumOperands() - Def->getNumImplicitOperands() == 2 && \"Invalid number of operands\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1816, __PRETTY_FUNCTION__))
;
1817 assert(!Def->hasImplicitDef() && "Only implicit uses are allowed")((!Def->hasImplicitDef() && "Only implicit uses are allowed"
) ? static_cast<void> (0) : __assert_fail ("!Def->hasImplicitDef() && \"Only implicit uses are allowed\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1817, __PRETTY_FUNCTION__))
;
1818
1819 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1820 // If we look for a different subreg, it means we want a subreg of src.
1821 // Bails as we do not support composing subregs yet.
1822 return ValueTrackerResult();
1823 // Otherwise, we want the whole source.
1824 const MachineOperand &Src = Def->getOperand(1);
1825 if (Src.isUndef())
1826 return ValueTrackerResult();
1827 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1828}
1829
1830ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1831 assert(Def->isBitcast() && "Invalid definition")((Def->isBitcast() && "Invalid definition") ? static_cast
<void> (0) : __assert_fail ("Def->isBitcast() && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1831, __PRETTY_FUNCTION__))
;
1832
1833 // Bail if there are effects that a plain copy will not expose.
1834 if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects())
1835 return ValueTrackerResult();
1836
1837 // Bitcasts with more than one def are not supported.
1838 if (Def->getDesc().getNumDefs() != 1)
1839 return ValueTrackerResult();
1840 const MachineOperand DefOp = Def->getOperand(DefIdx);
1841 if (DefOp.getSubReg() != DefSubReg)
1842 // If we look for a different subreg, it means we want a subreg of the src.
1843 // Bails as we do not support composing subregs yet.
1844 return ValueTrackerResult();
1845
1846 unsigned SrcIdx = Def->getNumOperands();
1847 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1848 ++OpIdx) {
1849 const MachineOperand &MO = Def->getOperand(OpIdx);
1850 if (!MO.isReg() || !MO.getReg())
1851 continue;
1852 // Ignore dead implicit defs.
1853 if (MO.isImplicit() && MO.isDead())
1854 continue;
1855 assert(!MO.isDef() && "We should have skipped all the definitions by now")((!MO.isDef() && "We should have skipped all the definitions by now"
) ? static_cast<void> (0) : __assert_fail ("!MO.isDef() && \"We should have skipped all the definitions by now\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1855, __PRETTY_FUNCTION__))
;
1856 if (SrcIdx != EndOpIdx)
1857 // Multiple sources?
1858 return ValueTrackerResult();
1859 SrcIdx = OpIdx;
1860 }
1861
1862 // In some rare case, Def has no input, SrcIdx is out of bound,
1863 // getOperand(SrcIdx) will fail below.
1864 if (SrcIdx >= Def->getNumOperands())
1865 return ValueTrackerResult();
1866
1867 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
1868 // will break the assumed guarantees for the upper bits.
1869 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
1870 if (UseMI.isSubregToReg())
1871 return ValueTrackerResult();
1872 }
1873
1874 const MachineOperand &Src = Def->getOperand(SrcIdx);
1875 if (Src.isUndef())
1876 return ValueTrackerResult();
1877 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1878}
1879
1880ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1881 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&(((Def->isRegSequence() || Def->isRegSequenceLike()) &&
"Invalid definition") ? static_cast<void> (0) : __assert_fail
("(Def->isRegSequence() || Def->isRegSequenceLike()) && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1882, __PRETTY_FUNCTION__))
1882 "Invalid definition")(((Def->isRegSequence() || Def->isRegSequenceLike()) &&
"Invalid definition") ? static_cast<void> (0) : __assert_fail
("(Def->isRegSequence() || Def->isRegSequenceLike()) && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1882, __PRETTY_FUNCTION__))
;
1883
1884 if (Def->getOperand(DefIdx).getSubReg())
1885 // If we are composing subregs, bail out.
1886 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1887 // This should almost never happen as the SSA property is tracked at
1888 // the register level (as opposed to the subreg level).
1889 // I.e.,
1890 // Def.sub0 =
1891 // Def.sub1 =
1892 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1893 // Def. Thus, it must not be generated.
1894 // However, some code could theoretically generates a single
1895 // Def.sub0 (i.e, not defining the other subregs) and we would
1896 // have this case.
1897 // If we can ascertain (or force) that this never happens, we could
1898 // turn that into an assertion.
1899 return ValueTrackerResult();
1900
1901 if (!TII)
1902 // We could handle the REG_SEQUENCE here, but we do not want to
1903 // duplicate the code from the generic TII.
1904 return ValueTrackerResult();
1905
1906 SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1907 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1908 return ValueTrackerResult();
1909
1910 // We are looking at:
1911 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1912 // Check if one of the operand defines the subreg we are interested in.
1913 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
1914 if (RegSeqInput.SubIdx == DefSubReg)
1915 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1916 }
1917
1918 // If the subreg we are tracking is super-defined by another subreg,
1919 // we could follow this value. However, this would require to compose
1920 // the subreg and we do not do that for now.
1921 return ValueTrackerResult();
1922}
1923
1924ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1925 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&(((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
"Invalid definition") ? static_cast<void> (0) : __assert_fail
("(Def->isInsertSubreg() || Def->isInsertSubregLike()) && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1926, __PRETTY_FUNCTION__))
1926 "Invalid definition")(((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
"Invalid definition") ? static_cast<void> (0) : __assert_fail
("(Def->isInsertSubreg() || Def->isInsertSubregLike()) && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1926, __PRETTY_FUNCTION__))
;
1927
1928 if (Def->getOperand(DefIdx).getSubReg())
1929 // If we are composing subreg, bail out.
1930 // Same remark as getNextSourceFromRegSequence.
1931 // I.e., this may be turned into an assert.
1932 return ValueTrackerResult();
1933
1934 if (!TII)
1935 // We could handle the REG_SEQUENCE here, but we do not want to
1936 // duplicate the code from the generic TII.
1937 return ValueTrackerResult();
1938
1939 RegSubRegPair BaseReg;
1940 RegSubRegPairAndIdx InsertedReg;
1941 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1942 return ValueTrackerResult();
1943
1944 // We are looking at:
1945 // Def = INSERT_SUBREG v0, v1, sub1
1946 // There are two cases:
1947 // 1. DefSubReg == sub1, get v1.
1948 // 2. DefSubReg != sub1, the value may be available through v0.
1949
1950 // #1 Check if the inserted register matches the required sub index.
1951 if (InsertedReg.SubIdx == DefSubReg) {
1952 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1953 }
1954 // #2 Otherwise, if the sub register we are looking for is not partial
1955 // defined by the inserted element, we can look through the main
1956 // register (v0).
1957 const MachineOperand &MODef = Def->getOperand(DefIdx);
1958 // If the result register (Def) and the base register (v0) do not
1959 // have the same register class or if we have to compose
1960 // subregisters, bail out.
1961 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1962 BaseReg.SubReg)
1963 return ValueTrackerResult();
1964
1965 // Get the TRI and check if the inserted sub-register overlaps with the
1966 // sub-register we are tracking.
1967 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1968 if (!TRI ||
1969 !(TRI->getSubRegIndexLaneMask(DefSubReg) &
1970 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
1971 return ValueTrackerResult();
1972 // At this point, the value is available in v0 via the same subreg
1973 // we used for Def.
1974 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
1975}
1976
1977ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
1978 assert((Def->isExtractSubreg() ||(((Def->isExtractSubreg() || Def->isExtractSubregLike()
) && "Invalid definition") ? static_cast<void> (
0) : __assert_fail ("(Def->isExtractSubreg() || Def->isExtractSubregLike()) && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1979, __PRETTY_FUNCTION__))
1979 Def->isExtractSubregLike()) && "Invalid definition")(((Def->isExtractSubreg() || Def->isExtractSubregLike()
) && "Invalid definition") ? static_cast<void> (
0) : __assert_fail ("(Def->isExtractSubreg() || Def->isExtractSubregLike()) && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 1979, __PRETTY_FUNCTION__))
;
1980 // We are looking at:
1981 // Def = EXTRACT_SUBREG v0, sub0
1982
1983 // Bail if we have to compose sub registers.
1984 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1985 if (DefSubReg)
1986 return ValueTrackerResult();
1987
1988 if (!TII)
1989 // We could handle the EXTRACT_SUBREG here, but we do not want to
1990 // duplicate the code from the generic TII.
1991 return ValueTrackerResult();
1992
1993 RegSubRegPairAndIdx ExtractSubregInputReg;
1994 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1995 return ValueTrackerResult();
1996
1997 // Bail if we have to compose sub registers.
1998 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
1999 if (ExtractSubregInputReg.SubReg)
2000 return ValueTrackerResult();
2001 // Otherwise, the value is available in the v0.sub0.
2002 return ValueTrackerResult(ExtractSubregInputReg.Reg,
2003 ExtractSubregInputReg.SubIdx);
2004}
2005
2006ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
2007 assert(Def->isSubregToReg() && "Invalid definition")((Def->isSubregToReg() && "Invalid definition") ? static_cast
<void> (0) : __assert_fail ("Def->isSubregToReg() && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2007, __PRETTY_FUNCTION__))
;
2008 // We are looking at:
2009 // Def = SUBREG_TO_REG Imm, v0, sub0
2010
2011 // Bail if we have to compose sub registers.
2012 // If DefSubReg != sub0, we would have to check that all the bits
2013 // we track are included in sub0 and if yes, we would have to
2014 // determine the right subreg in v0.
2015 if (DefSubReg != Def->getOperand(3).getImm())
2016 return ValueTrackerResult();
2017 // Bail if we have to compose sub registers.
2018 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2019 if (Def->getOperand(2).getSubReg())
2020 return ValueTrackerResult();
2021
2022 return ValueTrackerResult(Def->getOperand(2).getReg(),
2023 Def->getOperand(3).getImm());
2024}
2025
2026/// Explore each PHI incoming operand and return its sources.
2027ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2028 assert(Def->isPHI() && "Invalid definition")((Def->isPHI() && "Invalid definition") ? static_cast
<void> (0) : __assert_fail ("Def->isPHI() && \"Invalid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2028, __PRETTY_FUNCTION__))
;
2029 ValueTrackerResult Res;
2030
2031 // If we look for a different subreg, bail as we do not support composing
2032 // subregs yet.
2033 if (Def->getOperand(0).getSubReg() != DefSubReg)
2034 return ValueTrackerResult();
2035
2036 // Return all register sources for PHI instructions.
2037 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2038 const MachineOperand &MO = Def->getOperand(i);
2039 assert(MO.isReg() && "Invalid PHI instruction")((MO.isReg() && "Invalid PHI instruction") ? static_cast
<void> (0) : __assert_fail ("MO.isReg() && \"Invalid PHI instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2039, __PRETTY_FUNCTION__))
;
2040 // We have no code to deal with undef operands. They shouldn't happen in
2041 // normal programs anyway.
2042 if (MO.isUndef())
2043 return ValueTrackerResult();
2044 Res.addSource(MO.getReg(), MO.getSubReg());
2045 }
2046
2047 return Res;
2048}
2049
2050ValueTrackerResult ValueTracker::getNextSourceImpl() {
2051 assert(Def && "This method needs a valid definition")((Def && "This method needs a valid definition") ? static_cast
<void> (0) : __assert_fail ("Def && \"This method needs a valid definition\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2051, __PRETTY_FUNCTION__))
;
2052
2053 assert(((Def->getOperand(DefIdx).isDef() &&((((Def->getOperand(DefIdx).isDef() && (DefIdx <
Def->getDesc().getNumDefs() || Def->getDesc().isVariadic
())) || Def->getOperand(DefIdx).isImplicit()) && "Invalid DefIdx"
) ? static_cast<void> (0) : __assert_fail ("((Def->getOperand(DefIdx).isDef() && (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic())) || Def->getOperand(DefIdx).isImplicit()) && \"Invalid DefIdx\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2057, __PRETTY_FUNCTION__))
2054 (DefIdx < Def->getDesc().getNumDefs() ||((((Def->getOperand(DefIdx).isDef() && (DefIdx <
Def->getDesc().getNumDefs() || Def->getDesc().isVariadic
())) || Def->getOperand(DefIdx).isImplicit()) && "Invalid DefIdx"
) ? static_cast<void> (0) : __assert_fail ("((Def->getOperand(DefIdx).isDef() && (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic())) || Def->getOperand(DefIdx).isImplicit()) && \"Invalid DefIdx\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2057, __PRETTY_FUNCTION__))
2055 Def->getDesc().isVariadic())) ||((((Def->getOperand(DefIdx).isDef() && (DefIdx <
Def->getDesc().getNumDefs() || Def->getDesc().isVariadic
())) || Def->getOperand(DefIdx).isImplicit()) && "Invalid DefIdx"
) ? static_cast<void> (0) : __assert_fail ("((Def->getOperand(DefIdx).isDef() && (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic())) || Def->getOperand(DefIdx).isImplicit()) && \"Invalid DefIdx\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2057, __PRETTY_FUNCTION__))
2056 Def->getOperand(DefIdx).isImplicit()) &&((((Def->getOperand(DefIdx).isDef() && (DefIdx <
Def->getDesc().getNumDefs() || Def->getDesc().isVariadic
())) || Def->getOperand(DefIdx).isImplicit()) && "Invalid DefIdx"
) ? static_cast<void> (0) : __assert_fail ("((Def->getOperand(DefIdx).isDef() && (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic())) || Def->getOperand(DefIdx).isImplicit()) && \"Invalid DefIdx\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2057, __PRETTY_FUNCTION__))
2057 "Invalid DefIdx")((((Def->getOperand(DefIdx).isDef() && (DefIdx <
Def->getDesc().getNumDefs() || Def->getDesc().isVariadic
())) || Def->getOperand(DefIdx).isImplicit()) && "Invalid DefIdx"
) ? static_cast<void> (0) : __assert_fail ("((Def->getOperand(DefIdx).isDef() && (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic())) || Def->getOperand(DefIdx).isImplicit()) && \"Invalid DefIdx\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/PeepholeOptimizer.cpp"
, 2057, __PRETTY_FUNCTION__))
;
2058 if (Def->isCopy())
2059 return getNextSourceFromCopy();
2060 if (Def->isBitcast())
2061 return getNextSourceFromBitcast();
2062 // All the remaining cases involve "complex" instructions.
2063 // Bail if we did not ask for the advanced tracking.
2064 if (DisableAdvCopyOpt)
2065 return ValueTrackerResult();
2066 if (Def->isRegSequence() || Def->isRegSequenceLike())
2067 return getNextSourceFromRegSequence();
2068 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
2069 return getNextSourceFromInsertSubreg();
2070 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
2071 return getNextSourceFromExtractSubreg();
2072 if (Def->isSubregToReg())
2073 return getNextSourceFromSubregToReg();
2074 if (Def->isPHI())
2075 return getNextSourceFromPHI();
2076 return ValueTrackerResult();
2077}
2078
2079ValueTrackerResult ValueTracker::getNextSource() {
2080 // If we reach a point where we cannot move up in the use-def chain,
2081 // there is nothing we can get.
2082 if (!Def)
2083 return ValueTrackerResult();
2084
2085 ValueTrackerResult Res = getNextSourceImpl();
2086 if (Res.isValid()) {
2087 // Update definition, definition index, and subregister for the
2088 // next call of getNextSource.
2089 // Update the current register.
2090 bool OneRegSrc = Res.getNumSources() == 1;
2091 if (OneRegSrc)
2092 Reg = Res.getSrcReg(0);
2093 // Update the result before moving up in the use-def chain
2094 // with the instruction containing the last found sources.
2095 Res.setInst(Def);
2096
2097 // If we can still move up in the use-def chain, move to the next
2098 // definition.
2099 if (!Register::isPhysicalRegister(Reg) && OneRegSrc) {
2100 MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg);
2101 if (DI != MRI.def_end()) {
2102 Def = DI->getParent();
2103 DefIdx = DI.getOperandNo();
2104 DefSubReg = Res.getSrcSubReg(0);
2105 } else {
2106 Def = nullptr;
2107 }
2108 return Res;
2109 }
2110 }
2111 // If we end up here, this means we will not be able to find another source
2112 // for the next iteration. Make sure any new call to getNextSource bails out
2113 // early by cutting the use-def chain.
2114 Def = nullptr;
2115 return Res;
2116}

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/Register.h

1//===-- llvm/CodeGen/Register.h ---------------------------------*- 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#ifndef LLVM_CODEGEN_REGISTER_H
10#define LLVM_CODEGEN_REGISTER_H
11
12#include "llvm/MC/MCRegister.h"
13#include <cassert>
14
15namespace llvm {
16
17/// Wrapper class representing virtual and physical registers. Should be passed
18/// by value.
19class Register {
20 unsigned Reg;
21
22public:
23 Register(unsigned Val = 0): Reg(Val) {}
24 Register(MCRegister Val): Reg(Val) {}
25
26 // Register numbers can represent physical registers, virtual registers, and
27 // sometimes stack slots. The unsigned values are divided into these ranges:
28 //
29 // 0 Not a register, can be used as a sentinel.
30 // [1;2^30) Physical registers assigned by TableGen.
31 // [2^30;2^31) Stack slots. (Rarely used.)
32 // [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
33 //
34 // Further sentinels can be allocated from the small negative integers.
35 // DenseMapInfo<unsigned> uses -1u and -2u.
36
37 /// isStackSlot - Sometimes it is useful the be able to store a non-negative
38 /// frame index in a variable that normally holds a register. isStackSlot()
39 /// returns true if Reg is in the range used for stack slots.
40 ///
41 /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
42 /// slots, so if a variable may contains a stack slot, always check
43 /// isStackSlot() first.
44 ///
45 static bool isStackSlot(unsigned Reg) {
46 return MCRegister::isStackSlot(Reg);
47 }
48
49 /// Compute the frame index from a register value representing a stack slot.
50 static int stackSlot2Index(unsigned Reg) {
51 assert(isStackSlot(Reg) && "Not a stack slot")((isStackSlot(Reg) && "Not a stack slot") ? static_cast
<void> (0) : __assert_fail ("isStackSlot(Reg) && \"Not a stack slot\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/Register.h"
, 51, __PRETTY_FUNCTION__))
;
52 return int(Reg - (1u << 30));
53 }
54
55 /// Convert a non-negative frame index to a stack slot register value.
56 static unsigned index2StackSlot(int FI) {
57 assert(FI >= 0 && "Cannot hold a negative frame index.")((FI >= 0 && "Cannot hold a negative frame index."
) ? static_cast<void> (0) : __assert_fail ("FI >= 0 && \"Cannot hold a negative frame index.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/Register.h"
, 57, __PRETTY_FUNCTION__))
;
58 return FI + (1u << 30);
59 }
60
61 /// Return true if the specified register number is in
62 /// the physical register namespace.
63 static bool isPhysicalRegister(unsigned Reg) {
64 return MCRegister::isPhysicalRegister(Reg);
27
Calling 'MCRegister::isPhysicalRegister'
31
Returning from 'MCRegister::isPhysicalRegister'
32
Returning zero, which participates in a condition later
35
Calling 'MCRegister::isPhysicalRegister'
39
Returning from 'MCRegister::isPhysicalRegister'
40
Returning zero, which participates in a condition later
65 }
66
67 /// Return true if the specified register number is in
68 /// the virtual register namespace.
69 static bool isVirtualRegister(unsigned Reg) {
70 assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.")((!isStackSlot(Reg) && "Not a register! Check isStackSlot() first."
) ? static_cast<void> (0) : __assert_fail ("!isStackSlot(Reg) && \"Not a register! Check isStackSlot() first.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/Register.h"
, 70, __PRETTY_FUNCTION__))
;
71 return int(Reg) < 0;
72 }
73
74 /// Convert a virtual register number to a 0-based index.
75 /// The first virtual register in a function will get the index 0.
76 static unsigned virtReg2Index(unsigned Reg) {
77 assert(isVirtualRegister(Reg) && "Not a virtual register")((isVirtualRegister(Reg) && "Not a virtual register")
? static_cast<void> (0) : __assert_fail ("isVirtualRegister(Reg) && \"Not a virtual register\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/Register.h"
, 77, __PRETTY_FUNCTION__))
;
78 return Reg & ~(1u << 31);
79 }
80
81 /// Convert a 0-based index to a virtual register number.
82 /// This is the inverse operation of VirtReg2IndexFunctor below.
83 static unsigned index2VirtReg(unsigned Index) {
84 return Index | (1u << 31);
85 }
86
87 /// Return true if the specified register number is in the virtual register
88 /// namespace.
89 bool isVirtual() const {
90 return isVirtualRegister(Reg);
91 }
92
93 /// Return true if the specified register number is in the physical register
94 /// namespace.
95 bool isPhysical() const {
96 return isPhysicalRegister(Reg);
97 }
98
99 /// Convert a virtual register number to a 0-based index. The first virtual
100 /// register in a function will get the index 0.
101 unsigned virtRegIndex() const {
102 return virtReg2Index(Reg);
103 }
104
105 operator unsigned() const {
106 return Reg;
107 }
108
109 unsigned id() const { return Reg; }
110
111 operator MCRegister() const {
112 return MCRegister(Reg);
113 }
114
115 bool isValid() const {
116 return Reg != 0;
117 }
118
119 /// Comparisons between register objects
120 bool operator==(const Register &Other) const { return Reg == Other.Reg; }
121 bool operator!=(const Register &Other) const { return Reg != Other.Reg; }
122 bool operator==(const MCRegister &Other) const { return Reg == Other.id(); }
123 bool operator!=(const MCRegister &Other) const { return Reg != Other.id(); }
124
125 /// Comparisons against register constants. E.g.
126 /// * R == AArch64::WZR
127 /// * R == 0
128 /// * R == VirtRegMap::NO_PHYS_REG
129 bool operator==(unsigned Other) const { return Reg == Other; }
130 bool operator!=(unsigned Other) const { return Reg != Other; }
131 bool operator==(int Other) const { return Reg == unsigned(Other); }
132 bool operator!=(int Other) const { return Reg != unsigned(Other); }
133 // MSVC requires that we explicitly declare these two as well.
134 bool operator==(MCPhysReg Other) const { return Reg == unsigned(Other); }
135 bool operator!=(MCPhysReg Other) const { return Reg != unsigned(Other); }
136};
137
138// Provide DenseMapInfo for Register
139template<> struct DenseMapInfo<Register> {
140 static inline unsigned getEmptyKey() {
141 return DenseMapInfo<unsigned>::getEmptyKey();
142 }
143 static inline unsigned getTombstoneKey() {
144 return DenseMapInfo<unsigned>::getTombstoneKey();
145 }
146 static unsigned getHashValue(const Register &Val) {
147 return DenseMapInfo<unsigned>::getHashValue(Val.id());
148 }
149 static bool isEqual(const Register &LHS, const Register &RHS) {
150 return DenseMapInfo<unsigned>::isEqual(LHS.id(), RHS.id());
151 }
152};
153
154}
155
156#endif // ifndef LLVM_CODEGEN_REGISTER_H

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/MC/MCRegister.h

1//===-- llvm/MC/Register.h --------------------------------------*- 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#ifndef LLVM_MC_REGISTER_H
10#define LLVM_MC_REGISTER_H
11
12#include "llvm/ADT/DenseMapInfo.h"
13#include <cassert>
14
15namespace llvm {
16
17/// An unsigned integer type large enough to represent all physical registers,
18/// but not necessarily virtual registers.
19using MCPhysReg = uint16_t;
20
21/// Wrapper class representing physical registers. Should be passed by value.
22class MCRegister {
23 unsigned Reg;
24
25public:
26 MCRegister(unsigned Val = 0): Reg(Val) {}
27
28 // Register numbers can represent physical registers, virtual registers, and
29 // sometimes stack slots. The unsigned values are divided into these ranges:
30 //
31 // 0 Not a register, can be used as a sentinel.
32 // [1;2^30) Physical registers assigned by TableGen.
33 // [2^30;2^31) Stack slots. (Rarely used.)
34 // [2^31;2^32) Virtual registers assigned by MachineRegisterInfo.
35 //
36 // Further sentinels can be allocated from the small negative integers.
37 // DenseMapInfo<unsigned> uses -1u and -2u.
38
39 /// This is the portion of the positive number space that is not a physical
40 /// register. StackSlot values do not exist in the MC layer, see
41 /// Register::isStackSlot() for the more information on them.
42 ///
43 /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
44 /// slots, so if a variable may contains a stack slot, always check
45 /// isStackSlot() first.
46 static bool isStackSlot(unsigned Reg) {
47 return int(Reg) >= (1 << 30);
48 }
49
50 /// Return true if the specified register number is in
51 /// the physical register namespace.
52 static bool isPhysicalRegister(unsigned Reg) {
53 assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.")((!isStackSlot(Reg) && "Not a register! Check isStackSlot() first."
) ? static_cast<void> (0) : __assert_fail ("!isStackSlot(Reg) && \"Not a register! Check isStackSlot() first.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/MC/MCRegister.h"
, 53, __PRETTY_FUNCTION__))
;
28
'?' condition is true
36
'?' condition is true
54 return int(Reg) > 0;
29
Assuming 'Reg' is <= 0
30
Returning zero, which participates in a condition later
37
Assuming 'Reg' is <= 0
38
Returning zero, which participates in a condition later
55 }
56
57 /// Return true if the specified register number is in the physical register
58 /// namespace.
59 bool isPhysical() const {
60 return isPhysicalRegister(Reg);
61 }
62
63 operator unsigned() const {
64 return Reg;
65 }
66
67 unsigned id() const {
68 return Reg;
69 }
70
71 bool isValid() const {
72 return Reg != 0;
73 }
74
75 /// Comparisons between register objects
76 bool operator==(const MCRegister &Other) const { return Reg == Other.Reg; }
77 bool operator!=(const MCRegister &Other) const { return Reg != Other.Reg; }
78
79 /// Comparisons against register constants. E.g.
80 /// * R == AArch64::WZR
81 /// * R == 0
82 /// * R == VirtRegMap::NO_PHYS_REG
83 bool operator==(unsigned Other) const { return Reg == Other; }
84 bool operator!=(unsigned Other) const { return Reg != Other; }
85 bool operator==(int Other) const { return Reg == unsigned(Other); }
86 bool operator!=(int Other) const { return Reg != unsigned(Other); }
87 // MSVC requires that we explicitly declare these two as well.
88 bool operator==(MCPhysReg Other) const { return Reg == unsigned(Other); }
89 bool operator!=(MCPhysReg Other) const { return Reg != unsigned(Other); }
90};
91
92// Provide DenseMapInfo for MCRegister
93template<> struct DenseMapInfo<MCRegister> {
94 static inline unsigned getEmptyKey() {
95 return DenseMapInfo<unsigned>::getEmptyKey();
96 }
97 static inline unsigned getTombstoneKey() {
98 return DenseMapInfo<unsigned>::getTombstoneKey();
99 }
100 static unsigned getHashValue(const MCRegister &Val) {
101 return DenseMapInfo<unsigned>::getHashValue(Val.id());
102 }
103 static bool isEqual(const MCRegister &LHS, const MCRegister &RHS) {
104 return DenseMapInfo<unsigned>::isEqual(LHS.id(), RHS.id());
105 }
106};
107
108}
109
110#endif // ifndef LLVM_MC_REGISTER_H

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/MachineInstr.h

1//===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- 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 contains the declaration of the MachineInstr class, which is the
10// basic representation for all target dependent machine instructions used by
11// the back end.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CODEGEN_MACHINEINSTR_H
16#define LLVM_CODEGEN_MACHINEINSTR_H
17
18#include "llvm/ADT/DenseMapInfo.h"
19#include "llvm/ADT/PointerSumType.h"
20#include "llvm/ADT/ilist.h"
21#include "llvm/ADT/ilist_node.h"
22#include "llvm/ADT/iterator_range.h"
23#include "llvm/CodeGen/MachineMemOperand.h"
24#include "llvm/CodeGen/MachineOperand.h"
25#include "llvm/CodeGen/TargetOpcodes.h"
26#include "llvm/IR/DebugLoc.h"
27#include "llvm/IR/InlineAsm.h"
28#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCSymbol.h"
30#include "llvm/Support/ArrayRecycler.h"
31#include "llvm/Support/TrailingObjects.h"
32#include <algorithm>
33#include <cassert>
34#include <cstdint>
35#include <utility>
36
37namespace llvm {
38
39class AAResults;
40template <typename T> class ArrayRef;
41class DIExpression;
42class DILocalVariable;
43class MachineBasicBlock;
44class MachineFunction;
45class MachineMemOperand;
46class MachineRegisterInfo;
47class ModuleSlotTracker;
48class raw_ostream;
49template <typename T> class SmallVectorImpl;
50class SmallBitVector;
51class StringRef;
52class TargetInstrInfo;
53class TargetRegisterClass;
54class TargetRegisterInfo;
55
56//===----------------------------------------------------------------------===//
57/// Representation of each machine instruction.
58///
59/// This class isn't a POD type, but it must have a trivial destructor. When a
60/// MachineFunction is deleted, all the contained MachineInstrs are deallocated
61/// without having their destructor called.
62///
63class MachineInstr
64 : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
65 ilist_sentinel_tracking<true>> {
66public:
67 using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator;
68
69 /// Flags to specify different kinds of comments to output in
70 /// assembly code. These flags carry semantic information not
71 /// otherwise easily derivable from the IR text.
72 ///
73 enum CommentFlag {
74 ReloadReuse = 0x1, // higher bits are reserved for target dep comments.
75 NoSchedComment = 0x2,
76 TAsmComments = 0x4 // Target Asm comments should start from this value.
77 };
78
79 enum MIFlag {
80 NoFlags = 0,
81 FrameSetup = 1 << 0, // Instruction is used as a part of
82 // function frame setup code.
83 FrameDestroy = 1 << 1, // Instruction is used as a part of
84 // function frame destruction code.
85 BundledPred = 1 << 2, // Instruction has bundled predecessors.
86 BundledSucc = 1 << 3, // Instruction has bundled successors.
87 FmNoNans = 1 << 4, // Instruction does not support Fast
88 // math nan values.
89 FmNoInfs = 1 << 5, // Instruction does not support Fast
90 // math infinity values.
91 FmNsz = 1 << 6, // Instruction is not required to retain
92 // signed zero values.
93 FmArcp = 1 << 7, // Instruction supports Fast math
94 // reciprocal approximations.
95 FmContract = 1 << 8, // Instruction supports Fast math
96 // contraction operations like fma.
97 FmAfn = 1 << 9, // Instruction may map to Fast math
98 // instrinsic approximation.
99 FmReassoc = 1 << 10, // Instruction supports Fast math
100 // reassociation of operand order.
101 NoUWrap = 1 << 11, // Instruction supports binary operator
102 // no unsigned wrap.
103 NoSWrap = 1 << 12, // Instruction supports binary operator
104 // no signed wrap.
105 IsExact = 1 << 13, // Instruction supports division is
106 // known to be exact.
107 NoFPExcept = 1 << 14, // Instruction does not raise
108 // floatint-point exceptions.
109 };
110
111private:
112 const MCInstrDesc *MCID; // Instruction descriptor.
113 MachineBasicBlock *Parent = nullptr; // Pointer to the owning basic block.
114
115 // Operands are allocated by an ArrayRecycler.
116 MachineOperand *Operands = nullptr; // Pointer to the first operand.
117 unsigned NumOperands = 0; // Number of operands on instruction.
118 using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
119 OperandCapacity CapOperands; // Capacity of the Operands array.
120
121 uint16_t Flags = 0; // Various bits of additional
122 // information about machine
123 // instruction.
124
125 uint8_t AsmPrinterFlags = 0; // Various bits of information used by
126 // the AsmPrinter to emit helpful
127 // comments. This is *not* semantic
128 // information. Do not use this for
129 // anything other than to convey comment
130 // information to AsmPrinter.
131
132 /// Internal implementation detail class that provides out-of-line storage for
133 /// extra info used by the machine instruction when this info cannot be stored
134 /// in-line within the instruction itself.
135 ///
136 /// This has to be defined eagerly due to the implementation constraints of
137 /// `PointerSumType` where it is used.
138 class ExtraInfo final
139 : TrailingObjects<ExtraInfo, MachineMemOperand *, MCSymbol *, MDNode *> {
140 public:
141 static ExtraInfo *create(BumpPtrAllocator &Allocator,
142 ArrayRef<MachineMemOperand *> MMOs,
143 MCSymbol *PreInstrSymbol = nullptr,
144 MCSymbol *PostInstrSymbol = nullptr,
145 MDNode *HeapAllocMarker = nullptr) {
146 bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
147 bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
148 bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
149 auto *Result = new (Allocator.Allocate(
150 totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *>(
151 MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol,
152 HasHeapAllocMarker),
153 alignof(ExtraInfo)))
154 ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol,
155 HasHeapAllocMarker);
156
157 // Copy the actual data into the trailing objects.
158 std::copy(MMOs.begin(), MMOs.end(),
159 Result->getTrailingObjects<MachineMemOperand *>());
160
161 if (HasPreInstrSymbol)
162 Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol;
163 if (HasPostInstrSymbol)
164 Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] =
165 PostInstrSymbol;
166 if (HasHeapAllocMarker)
167 Result->getTrailingObjects<MDNode *>()[0] = HeapAllocMarker;
168
169 return Result;
170 }
171
172 ArrayRef<MachineMemOperand *> getMMOs() const {
173 return makeArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs);
174 }
175
176 MCSymbol *getPreInstrSymbol() const {
177 return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr;
178 }
179
180 MCSymbol *getPostInstrSymbol() const {
181 return HasPostInstrSymbol
182 ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol]
183 : nullptr;
184 }
185
186 MDNode *getHeapAllocMarker() const {
187 return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr;
188 }
189
190 private:
191 friend TrailingObjects;
192
193 // Description of the extra info, used to interpret the actual optional
194 // data appended.
195 //
196 // Note that this is not terribly space optimized. This leaves a great deal
197 // of flexibility to fit more in here later.
198 const int NumMMOs;
199 const bool HasPreInstrSymbol;
200 const bool HasPostInstrSymbol;
201 const bool HasHeapAllocMarker;
202
203 // Implement the `TrailingObjects` internal API.
204 size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const {
205 return NumMMOs;
206 }
207 size_t numTrailingObjects(OverloadToken<MCSymbol *>) const {
208 return HasPreInstrSymbol + HasPostInstrSymbol;
209 }
210 size_t numTrailingObjects(OverloadToken<MDNode *>) const {
211 return HasHeapAllocMarker;
212 }
213
214 // Just a boring constructor to allow us to initialize the sizes. Always use
215 // the `create` routine above.
216 ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol,
217 bool HasHeapAllocMarker)
218 : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol),
219 HasPostInstrSymbol(HasPostInstrSymbol),
220 HasHeapAllocMarker(HasHeapAllocMarker) {}
221 };
222
223 /// Enumeration of the kinds of inline extra info available. It is important
224 /// that the `MachineMemOperand` inline kind has a tag value of zero to make
225 /// it accessible as an `ArrayRef`.
226 enum ExtraInfoInlineKinds {
227 EIIK_MMO = 0,
228 EIIK_PreInstrSymbol,
229 EIIK_PostInstrSymbol,
230 EIIK_OutOfLine
231 };
232
233 // We store extra information about the instruction here. The common case is
234 // expected to be nothing or a single pointer (typically a MMO or a symbol).
235 // We work to optimize this common case by storing it inline here rather than
236 // requiring a separate allocation, but we fall back to an allocation when
237 // multiple pointers are needed.
238 PointerSumType<ExtraInfoInlineKinds,
239 PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>,
240 PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>,
241 PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>,
242 PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>>
243 Info;
244
245 DebugLoc debugLoc; // Source line information.
246
247 // Intrusive list support
248 friend struct ilist_traits<MachineInstr>;
249 friend struct ilist_callback_traits<MachineBasicBlock>;
250 void setParent(MachineBasicBlock *P) { Parent = P; }
251
252 /// This constructor creates a copy of the given
253 /// MachineInstr in the given MachineFunction.
254 MachineInstr(MachineFunction &, const MachineInstr &);
255
256 /// This constructor create a MachineInstr and add the implicit operands.
257 /// It reserves space for number of operands specified by
258 /// MCInstrDesc. An explicit DebugLoc is supplied.
259 MachineInstr(MachineFunction &, const MCInstrDesc &tid, DebugLoc dl,
260 bool NoImp = false);
261
262 // MachineInstrs are pool-allocated and owned by MachineFunction.
263 friend class MachineFunction;
264
265 void
266 dumprImpl(const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
267 SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const;
268
269public:
270 MachineInstr(const MachineInstr &) = delete;
271 MachineInstr &operator=(const MachineInstr &) = delete;
272 // Use MachineFunction::DeleteMachineInstr() instead.
273 ~MachineInstr() = delete;
274
275 const MachineBasicBlock* getParent() const { return Parent; }
276 MachineBasicBlock* getParent() { return Parent; }
277
278 /// Return the function that contains the basic block that this instruction
279 /// belongs to.
280 ///
281 /// Note: this is undefined behaviour if the instruction does not have a
282 /// parent.
283 const MachineFunction *getMF() const;
284 MachineFunction *getMF() {
285 return const_cast<MachineFunction *>(
286 static_cast<const MachineInstr *>(this)->getMF());
287 }
288
289 /// Return the asm printer flags bitvector.
290 uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
291
292 /// Clear the AsmPrinter bitvector.
293 void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
294
295 /// Return whether an AsmPrinter flag is set.
296 bool getAsmPrinterFlag(CommentFlag Flag) const {
297 return AsmPrinterFlags & Flag;
298 }
299
300 /// Set a flag for the AsmPrinter.
301 void setAsmPrinterFlag(uint8_t Flag) {
302 AsmPrinterFlags |= Flag;
303 }
304
305 /// Clear specific AsmPrinter flags.
306 void clearAsmPrinterFlag(CommentFlag Flag) {
307 AsmPrinterFlags &= ~Flag;
308 }
309
310 /// Return the MI flags bitvector.
311 uint16_t getFlags() const {
312 return Flags;
313 }
314
315 /// Return whether an MI flag is set.
316 bool getFlag(MIFlag Flag) const {
317 return Flags & Flag;
318 }
319
320 /// Set a MI flag.
321 void setFlag(MIFlag Flag) {
322 Flags |= (uint16_t)Flag;
323 }
324
325 void setFlags(unsigned flags) {
326 // Filter out the automatically maintained flags.
327 unsigned Mask = BundledPred | BundledSucc;
328 Flags = (Flags & Mask) | (flags & ~Mask);
329 }
330
331 /// clearFlag - Clear a MI flag.
332 void clearFlag(MIFlag Flag) {
333 Flags &= ~((uint16_t)Flag);
334 }
335
336 /// Return true if MI is in a bundle (but not the first MI in a bundle).
337 ///
338 /// A bundle looks like this before it's finalized:
339 /// ----------------
340 /// | MI |
341 /// ----------------
342 /// |
343 /// ----------------
344 /// | MI * |
345 /// ----------------
346 /// |
347 /// ----------------
348 /// | MI * |
349 /// ----------------
350 /// In this case, the first MI starts a bundle but is not inside a bundle, the
351 /// next 2 MIs are considered "inside" the bundle.
352 ///
353 /// After a bundle is finalized, it looks like this:
354 /// ----------------
355 /// | Bundle |
356 /// ----------------
357 /// |
358 /// ----------------
359 /// | MI * |
360 /// ----------------
361 /// |
362 /// ----------------
363 /// | MI * |
364 /// ----------------
365 /// |
366 /// ----------------
367 /// | MI * |
368 /// ----------------
369 /// The first instruction has the special opcode "BUNDLE". It's not "inside"
370 /// a bundle, but the next three MIs are.
371 bool isInsideBundle() const {
372 return getFlag(BundledPred);
373 }
374
375 /// Return true if this instruction part of a bundle. This is true
376 /// if either itself or its following instruction is marked "InsideBundle".
377 bool isBundled() const {
378 return isBundledWithPred() || isBundledWithSucc();
379 }
380
381 /// Return true if this instruction is part of a bundle, and it is not the
382 /// first instruction in the bundle.
383 bool isBundledWithPred() const { return getFlag(BundledPred); }
384
385 /// Return true if this instruction is part of a bundle, and it is not the
386 /// last instruction in the bundle.
387 bool isBundledWithSucc() const { return getFlag(BundledSucc); }
388
389 /// Bundle this instruction with its predecessor. This can be an unbundled
390 /// instruction, or it can be the first instruction in a bundle.
391 void bundleWithPred();
392
393 /// Bundle this instruction with its successor. This can be an unbundled
394 /// instruction, or it can be the last instruction in a bundle.
395 void bundleWithSucc();
396
397 /// Break bundle above this instruction.
398 void unbundleFromPred();
399
400 /// Break bundle below this instruction.
401 void unbundleFromSucc();
402
403 /// Returns the debug location id of this MachineInstr.
404 const DebugLoc &getDebugLoc() const { return debugLoc; }
405
406 /// Return the debug variable referenced by
407 /// this DBG_VALUE instruction.
408 const DILocalVariable *getDebugVariable() const;
409
410 /// Return the complex address expression referenced by
411 /// this DBG_VALUE instruction.
412 const DIExpression *getDebugExpression() const;
413
414 /// Return the debug label referenced by
415 /// this DBG_LABEL instruction.
416 const DILabel *getDebugLabel() const;
417
418 /// Emit an error referring to the source location of this instruction.
419 /// This should only be used for inline assembly that is somehow
420 /// impossible to compile. Other errors should have been handled much
421 /// earlier.
422 ///
423 /// If this method returns, the caller should try to recover from the error.
424 void emitError(StringRef Msg) const;
425
426 /// Returns the target instruction descriptor of this MachineInstr.
427 const MCInstrDesc &getDesc() const { return *MCID; }
428
429 /// Returns the opcode of this MachineInstr.
430 unsigned getOpcode() const { return MCID->Opcode; }
431
432 /// Retuns the total number of operands.
433 unsigned getNumOperands() const { return NumOperands; }
434
435 const MachineOperand& getOperand(unsigned i) const {
436 assert(i < getNumOperands() && "getOperand() out of range!")((i < getNumOperands() && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumOperands() && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/MachineInstr.h"
, 436, __PRETTY_FUNCTION__))
;
437 return Operands[i];
438 }
439 MachineOperand& getOperand(unsigned i) {
440 assert(i < getNumOperands() && "getOperand() out of range!")((i < getNumOperands() && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumOperands() && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/MachineInstr.h"
, 440, __PRETTY_FUNCTION__))
;
441 return Operands[i];
442 }
443
444 /// Returns the total number of definitions.
445 unsigned getNumDefs() const {
446 return getNumExplicitDefs() + MCID->getNumImplicitDefs();
447 }
448
449 /// Returns true if the instruction has implicit definition.
450 bool hasImplicitDef() const {
451 for (unsigned I = getNumExplicitOperands(), E = getNumOperands();
452 I != E; ++I) {
453 const MachineOperand &MO = getOperand(I);
454 if (MO.isDef() && MO.isImplicit())
455 return true;
456 }
457 return false;
458 }
459
460 /// Returns the implicit operands number.
461 unsigned getNumImplicitOperands() const {
462 return getNumOperands() - getNumExplicitOperands();
463 }
464
465 /// Return true if operand \p OpIdx is a subregister index.
466 bool isOperandSubregIdx(unsigned OpIdx) const {
467 assert(getOperand(OpIdx).getType() == MachineOperand::MO_Immediate &&((getOperand(OpIdx).getType() == MachineOperand::MO_Immediate
&& "Expected MO_Immediate operand type.") ? static_cast
<void> (0) : __assert_fail ("getOperand(OpIdx).getType() == MachineOperand::MO_Immediate && \"Expected MO_Immediate operand type.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/MachineInstr.h"
, 468, __PRETTY_FUNCTION__))
468 "Expected MO_Immediate operand type.")((getOperand(OpIdx).getType() == MachineOperand::MO_Immediate
&& "Expected MO_Immediate operand type.") ? static_cast
<void> (0) : __assert_fail ("getOperand(OpIdx).getType() == MachineOperand::MO_Immediate && \"Expected MO_Immediate operand type.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/MachineInstr.h"
, 468, __PRETTY_FUNCTION__))
;
469 if (isExtractSubreg() && OpIdx == 2)
470 return true;
471 if (isInsertSubreg() && OpIdx == 3)
472 return true;
473 if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
474 return true;
475 if (isSubregToReg() && OpIdx == 3)
476 return true;
477 return false;
478 }
479
480 /// Returns the number of non-implicit operands.
481 unsigned getNumExplicitOperands() const;
482
483 /// Returns the number of non-implicit definitions.
484 unsigned getNumExplicitDefs() const;
485
486 /// iterator/begin/end - Iterate over all operands of a machine instruction.
487 using mop_iterator = MachineOperand *;
488 using const_mop_iterator = const MachineOperand *;
489
490 mop_iterator operands_begin() { return Operands; }
491 mop_iterator operands_end() { return Operands + NumOperands; }
492
493 const_mop_iterator operands_begin() const { return Operands; }
494 const_mop_iterator operands_end() const { return Operands + NumOperands; }
495
496 iterator_range<mop_iterator> operands() {
497 return make_range(operands_begin(), operands_end());
498 }
499 iterator_range<const_mop_iterator> operands() const {
500 return make_range(operands_begin(), operands_end());
501 }
502 iterator_range<mop_iterator> explicit_operands() {
503 return make_range(operands_begin(),
504 operands_begin() + getNumExplicitOperands());
505 }
506 iterator_range<const_mop_iterator> explicit_operands() const {
507 return make_range(operands_begin(),
508 operands_begin() + getNumExplicitOperands());
509 }
510 iterator_range<mop_iterator> implicit_operands() {
511 return make_range(explicit_operands().end(), operands_end());
512 }
513 iterator_range<const_mop_iterator> implicit_operands() const {
514 return make_range(explicit_operands().end(), operands_end());
515 }
516 /// Returns a range over all explicit operands that are register definitions.
517 /// Implicit definition are not included!
518 iterator_range<mop_iterator> defs() {
519 return make_range(operands_begin(),
520 operands_begin() + getNumExplicitDefs());
521 }
522 /// \copydoc defs()
523 iterator_range<const_mop_iterator> defs() const {
524 return make_range(operands_begin(),
525 operands_begin() + getNumExplicitDefs());
526 }
527 /// Returns a range that includes all operands that are register uses.
528 /// This may include unrelated operands which are not register uses.
529 iterator_range<mop_iterator> uses() {
530 return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
531 }
532 /// \copydoc uses()
533 iterator_range<const_mop_iterator> uses() const {
534 return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
535 }
536 iterator_range<mop_iterator> explicit_uses() {
537 return make_range(operands_begin() + getNumExplicitDefs(),
538 operands_begin() + getNumExplicitOperands());
539 }
540 iterator_range<const_mop_iterator> explicit_uses() const {
541 return make_range(operands_begin() + getNumExplicitDefs(),
542 operands_begin() + getNumExplicitOperands());
543 }
544
545 /// Returns the number of the operand iterator \p I points to.
546 unsigned getOperandNo(const_mop_iterator I) const {
547 return I - operands_begin();
548 }
549
550 /// Access to memory operands of the instruction. If there are none, that does
551 /// not imply anything about whether the function accesses memory. Instead,
552 /// the caller must behave conservatively.
553 ArrayRef<MachineMemOperand *> memoperands() const {
554 if (!Info)
555 return {};
556
557 if (Info.is<EIIK_MMO>())
558 return makeArrayRef(Info.getAddrOfZeroTagPointer(), 1);
559
560 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
561 return EI->getMMOs();
562
563 return {};
564 }
565
566 /// Access to memory operands of the instruction.
567 ///
568 /// If `memoperands_begin() == memoperands_end()`, that does not imply
569 /// anything about whether the function accesses memory. Instead, the caller
570 /// must behave conservatively.
571 mmo_iterator memoperands_begin() const { return memoperands().begin(); }
572
573 /// Access to memory operands of the instruction.
574 ///
575 /// If `memoperands_begin() == memoperands_end()`, that does not imply
576 /// anything about whether the function accesses memory. Instead, the caller
577 /// must behave conservatively.
578 mmo_iterator memoperands_end() const { return memoperands().end(); }
579
580 /// Return true if we don't have any memory operands which described the
581 /// memory access done by this instruction. If this is true, calling code
582 /// must be conservative.
583 bool memoperands_empty() const { return memoperands().empty(); }
584
585 /// Return true if this instruction has exactly one MachineMemOperand.
586 bool hasOneMemOperand() const { return memoperands().size() == 1; }
587
588 /// Return the number of memory operands.
589 unsigned getNumMemOperands() const { return memoperands().size(); }
590
591 /// Helper to extract a pre-instruction symbol if one has been added.
592 MCSymbol *getPreInstrSymbol() const {
593 if (!Info)
594 return nullptr;
595 if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
596 return S;
597 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
598 return EI->getPreInstrSymbol();
599
600 return nullptr;
601 }
602
603 /// Helper to extract a post-instruction symbol if one has been added.
604 MCSymbol *getPostInstrSymbol() const {
605 if (!Info)
606 return nullptr;
607 if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
608 return S;
609 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
610 return EI->getPostInstrSymbol();
611
612 return nullptr;
613 }
614
615 /// Helper to extract a heap alloc marker if one has been added.
616 MDNode *getHeapAllocMarker() const {
617 if (!Info)
618 return nullptr;
619 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
620 return EI->getHeapAllocMarker();
621
622 return nullptr;
623 }
624
625 /// API for querying MachineInstr properties. They are the same as MCInstrDesc
626 /// queries but they are bundle aware.
627
628 enum QueryType {
629 IgnoreBundle, // Ignore bundles
630 AnyInBundle, // Return true if any instruction in bundle has property
631 AllInBundle // Return true if all instructions in bundle have property
632 };
633
634 /// Return true if the instruction (or in the case of a bundle,
635 /// the instructions inside the bundle) has the specified property.
636 /// The first argument is the property being queried.
637 /// The second argument indicates whether the query should look inside
638 /// instruction bundles.
639 bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
640 assert(MCFlag < 64 &&((MCFlag < 64 && "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle."
) ? static_cast<void> (0) : __assert_fail ("MCFlag < 64 && \"MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/MachineInstr.h"
, 641, __PRETTY_FUNCTION__))
641 "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.")((MCFlag < 64 && "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle."
) ? static_cast<void> (0) : __assert_fail ("MCFlag < 64 && \"MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/MachineInstr.h"
, 641, __PRETTY_FUNCTION__))
;
642 // Inline the fast path for unbundled or bundle-internal instructions.
643 if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
644 return getDesc().getFlags() & (1ULL << MCFlag);
645
646 // If this is the first instruction in a bundle, take the slow path.
647 return hasPropertyInBundle(1ULL << MCFlag, Type);
648 }
649
650 /// Return true if this is an instruction that should go through the usual
651 /// legalization steps.
652 bool isPreISelOpcode(QueryType Type = IgnoreBundle) const {
653 return hasProperty(MCID::PreISelOpcode, Type);
654 }
655
656 /// Return true if this instruction can have a variable number of operands.
657 /// In this case, the variable operands will be after the normal
658 /// operands but before the implicit definitions and uses (if any are
659 /// present).
660 bool isVariadic(QueryType Type = IgnoreBundle) const {
661 return hasProperty(MCID::Variadic, Type);
662 }
663
664 /// Set if this instruction has an optional definition, e.g.
665 /// ARM instructions which can set condition code if 's' bit is set.
666 bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
667 return hasProperty(MCID::HasOptionalDef, Type);
668 }
669
670 /// Return true if this is a pseudo instruction that doesn't
671 /// correspond to a real machine instruction.
672 bool isPseudo(QueryType Type = IgnoreBundle) const {
673 return hasProperty(MCID::Pseudo, Type);
674 }
675
676 bool isReturn(QueryType Type = AnyInBundle) const {
677 return hasProperty(MCID::Return, Type);
678 }
679
680 /// Return true if this is an instruction that marks the end of an EH scope,
681 /// i.e., a catchpad or a cleanuppad instruction.
682 bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
683 return hasProperty(MCID::EHScopeReturn, Type);
684 }
685
686 bool isCall(QueryType Type = AnyInBundle) const {
687 return hasProperty(MCID::Call, Type);
688 }
689
690 /// Return true if this is a call instruction that may have an associated
691 /// call site entry in the debug info.
692 bool isCandidateForCallSiteEntry(QueryType Type = IgnoreBundle) const;
693 /// Return true if copying, moving, or erasing this instruction requires
694 /// updating Call Site Info (see \ref copyCallSiteInfo, \ref moveCallSiteInfo,
695 /// \ref eraseCallSiteInfo).
696 bool shouldUpdateCallSiteInfo() const;
697
698 /// Returns true if the specified instruction stops control flow
699 /// from executing the instruction immediately following it. Examples include
700 /// unconditional branches and return instructions.
701 bool isBarrier(QueryType Type = AnyInBundle) const {
702 return hasProperty(MCID::Barrier, Type);
703 }
704
705 /// Returns true if this instruction part of the terminator for a basic block.
706 /// Typically this is things like return and branch instructions.
707 ///
708 /// Various passes use this to insert code into the bottom of a basic block,
709 /// but before control flow occurs.
710 bool isTerminator(QueryType Type = AnyInBundle) const {
711 return hasProperty(MCID::Terminator, Type);
712 }
713
714 /// Returns true if this is a conditional, unconditional, or indirect branch.
715 /// Predicates below can be used to discriminate between
716 /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to
717 /// get more information.
718 bool isBranch(QueryType Type = AnyInBundle) const {
719 return hasProperty(MCID::Branch, Type);
720 }
721
722 /// Return true if this is an indirect branch, such as a
723 /// branch through a register.
724 bool isIndirectBranch(QueryType Type = AnyInBundle) const {
725 return hasProperty(MCID::IndirectBranch, Type);
726 }
727
728 /// Return true if this is a branch which may fall
729 /// through to the next instruction or may transfer control flow to some other
730 /// block. The TargetInstrInfo::analyzeBranch method can be used to get more
731 /// information about this branch.
732 bool isConditionalBranch(QueryType Type = AnyInBundle) const {
733 return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type);
734 }
735
736 /// Return true if this is a branch which always
737 /// transfers control flow to some other block. The
738 /// TargetInstrInfo::analyzeBranch method can be used to get more information
739 /// about this branch.
740 bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
741 return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type);
742 }
743
744 /// Return true if this instruction has a predicate operand that
745 /// controls execution. It may be set to 'always', or may be set to other
746 /// values. There are various methods in TargetInstrInfo that can be used to
747 /// control and modify the predicate in this instruction.
748 bool isPredicable(QueryType Type = AllInBundle) const {
749 // If it's a bundle than all bundled instructions must be predicable for this
750 // to return true.
751 return hasProperty(MCID::Predicable, Type);
752 }
753
754 /// Return true if this instruction is a comparison.
755 bool isCompare(QueryType Type = IgnoreBundle) const {
756 return hasProperty(MCID::Compare, Type);
757 }
758
759 /// Return true if this instruction is a move immediate
760 /// (including conditional moves) instruction.
761 bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
762 return hasProperty(MCID::MoveImm, Type);
763 }
764
765 /// Return true if this instruction is a register move.
766 /// (including moving values from subreg to reg)
767 bool isMoveReg(QueryType Type = IgnoreBundle) const {
768 return hasProperty(MCID::MoveReg, Type);
769 }
770
771 /// Return true if this instruction is a bitcast instruction.
772 bool isBitcast(QueryType Type = IgnoreBundle) const {
773 return hasProperty(MCID::Bitcast, Type);
774 }
775
776 /// Return true if this instruction is a select instruction.
777 bool isSelect(QueryType Type = IgnoreBundle) const {
778 return hasProperty(MCID::Select, Type);
779 }
780
781 /// Return true if this instruction cannot be safely duplicated.
782 /// For example, if the instruction has a unique labels attached
783 /// to it, duplicating it would cause multiple definition errors.
784 bool isNotDuplicable(QueryType Type = AnyInBundle) const {
785 return hasProperty(MCID::NotDuplicable, Type);
786 }
787
788 /// Return true if this instruction is convergent.
789 /// Convergent instructions can not be made control-dependent on any
790 /// additional values.
791 bool isConvergent(QueryType Type = AnyInBundle) const {
792 if (isInlineAsm()) {
793 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
794 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
795 return true;
796 }
797 return hasProperty(MCID::Convergent, Type);
798 }
799
800 /// Returns true if the specified instruction has a delay slot
801 /// which must be filled by the code generator.
802 bool hasDelaySlot(QueryType Type = AnyInBundle) const {
803 return hasProperty(MCID::DelaySlot, Type);
804 }
805
806 /// Return true for instructions that can be folded as
807 /// memory operands in other instructions. The most common use for this
808 /// is instructions that are simple loads from memory that don't modify
809 /// the loaded value in any way, but it can also be used for instructions
810 /// that can be expressed as constant-pool loads, such as V_SETALLONES
811 /// on x86, to allow them to be folded when it is beneficial.
812 /// This should only be set on instructions that return a value in their
813 /// only virtual register definition.
814 bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
815 return hasProperty(MCID::FoldableAsLoad, Type);
816 }
817
818 /// Return true if this instruction behaves
819 /// the same way as the generic REG_SEQUENCE instructions.
820 /// E.g., on ARM,
821 /// dX VMOVDRR rY, rZ
822 /// is equivalent to
823 /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
824 ///
825 /// Note that for the optimizers to be able to take advantage of
826 /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
827 /// override accordingly.
828 bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
829 return hasProperty(MCID::RegSequence, Type);
830 }
831
832 /// Return true if this instruction behaves
833 /// the same way as the generic EXTRACT_SUBREG instructions.
834 /// E.g., on ARM,
835 /// rX, rY VMOVRRD dZ
836 /// is equivalent to two EXTRACT_SUBREG:
837 /// rX = EXTRACT_SUBREG dZ, ssub_0
838 /// rY = EXTRACT_SUBREG dZ, ssub_1
839 ///
840 /// Note that for the optimizers to be able to take advantage of
841 /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
842 /// override accordingly.
843 bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
844 return hasProperty(MCID::ExtractSubreg, Type);
845 }
846
847 /// Return true if this instruction behaves
848 /// the same way as the generic INSERT_SUBREG instructions.
849 /// E.g., on ARM,
850 /// dX = VSETLNi32 dY, rZ, Imm
851 /// is equivalent to a INSERT_SUBREG:
852 /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
853 ///
854 /// Note that for the optimizers to be able to take advantage of
855 /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
856 /// override accordingly.
857 bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
858 return hasProperty(MCID::InsertSubreg, Type);
859 }
860
861 //===--------------------------------------------------------------------===//
862 // Side Effect Analysis
863 //===--------------------------------------------------------------------===//
864
865 /// Return true if this instruction could possibly read memory.
866 /// Instructions with this flag set are not necessarily simple load
867 /// instructions, they may load a value and modify it, for example.
868 bool mayLoad(QueryType Type = AnyInBundle) const {
869 if (isInlineAsm()) {
870 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
871 if (ExtraInfo & InlineAsm::Extra_MayLoad)
872 return true;
873 }
874 return hasProperty(MCID::MayLoad, Type);
875 }
876
877 /// Return true if this instruction could possibly modify memory.
878 /// Instructions with this flag set are not necessarily simple store
879 /// instructions, they may store a modified value based on their operands, or
880 /// may not actually modify anything, for example.
881 bool mayStore(QueryType Type = AnyInBundle) const {
882 if (isInlineAsm()) {
883 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
884 if (ExtraInfo & InlineAsm::Extra_MayStore)
885 return true;
886 }
887 return hasProperty(MCID::MayStore, Type);
888 }
889
890 /// Return true if this instruction could possibly read or modify memory.
891 bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
892 return mayLoad(Type) || mayStore(Type);
893 }
894
895 /// Return true if this instruction could possibly raise a floating-point
896 /// exception. This is the case if the instruction is a floating-point
897 /// instruction that can in principle raise an exception, as indicated
898 /// by the MCID::MayRaiseFPException property, *and* at the same time,
899 /// the instruction is used in a context where we expect floating-point
900 /// exceptions are not disabled, as indicated by the NoFPExcept MI flag.
901 bool mayRaiseFPException() const {
902 return hasProperty(MCID::MayRaiseFPException) &&
903 !getFlag(MachineInstr::MIFlag::NoFPExcept);
904 }
905
906 //===--------------------------------------------------------------------===//
907 // Flags that indicate whether an instruction can be modified by a method.
908 //===--------------------------------------------------------------------===//
909
910 /// Return true if this may be a 2- or 3-address
911 /// instruction (of the form "X = op Y, Z, ..."), which produces the same
912 /// result if Y and Z are exchanged. If this flag is set, then the
913 /// TargetInstrInfo::commuteInstruction method may be used to hack on the
914 /// instruction.
915 ///
916 /// Note that this flag may be set on instructions that are only commutable
917 /// sometimes. In these cases, the call to commuteInstruction will fail.
918 /// Also note that some instructions require non-trivial modification to
919 /// commute them.
920 bool isCommutable(QueryType Type = IgnoreBundle) const {
921 return hasProperty(MCID::Commutable, Type);
922 }
923
924 /// Return true if this is a 2-address instruction
925 /// which can be changed into a 3-address instruction if needed. Doing this
926 /// transformation can be profitable in the register allocator, because it
927 /// means that the instruction can use a 2-address form if possible, but
928 /// degrade into a less efficient form if the source and dest register cannot
929 /// be assigned to the same register. For example, this allows the x86
930 /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
931 /// is the same speed as the shift but has bigger code size.
932 ///
933 /// If this returns true, then the target must implement the
934 /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
935 /// is allowed to fail if the transformation isn't valid for this specific
936 /// instruction (e.g. shl reg, 4 on x86).
937 ///
938 bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
939 return hasProperty(MCID::ConvertibleTo3Addr, Type);
940 }
941
942 /// Return true if this instruction requires
943 /// custom insertion support when the DAG scheduler is inserting it into a
944 /// machine basic block. If this is true for the instruction, it basically
945 /// means that it is a pseudo instruction used at SelectionDAG time that is
946 /// expanded out into magic code by the target when MachineInstrs are formed.
947 ///
948 /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
949 /// is used to insert this into the MachineBasicBlock.
950 bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
951 return hasProperty(MCID::UsesCustomInserter, Type);
952 }
953
954 /// Return true if this instruction requires *adjustment*
955 /// after instruction selection by calling a target hook. For example, this
956 /// can be used to fill in ARM 's' optional operand depending on whether
957 /// the conditional flag register is used.
958 bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
959 return hasProperty(MCID::HasPostISelHook, Type);
960 }
961
962 /// Returns true if this instruction is a candidate for remat.
963 /// This flag is deprecated, please don't use it anymore. If this
964 /// flag is set, the isReallyTriviallyReMaterializable() method is called to
965 /// verify the instruction is really rematable.
966 bool isRematerializable(QueryType Type = AllInBundle) const {
967 // It's only possible to re-mat a bundle if all bundled instructions are
968 // re-materializable.
969 return hasProperty(MCID::Rematerializable, Type);
970 }
971
972 /// Returns true if this instruction has the same cost (or less) than a move
973 /// instruction. This is useful during certain types of optimizations
974 /// (e.g., remat during two-address conversion or machine licm)
975 /// where we would like to remat or hoist the instruction, but not if it costs
976 /// more than moving the instruction into the appropriate register. Note, we
977 /// are not marking copies from and to the same register class with this flag.
978 bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
979 // Only returns true for a bundle if all bundled instructions are cheap.
980 return hasProperty(MCID::CheapAsAMove, Type);
981 }
982
983 /// Returns true if this instruction source operands
984 /// have special register allocation requirements that are not captured by the
985 /// operand register classes. e.g. ARM::STRD's two source registers must be an
986 /// even / odd pair, ARM::STM registers have to be in ascending order.
987 /// Post-register allocation passes should not attempt to change allocations
988 /// for sources of instructions with this flag.
989 bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
990 return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
991 }
992
993 /// Returns true if this instruction def operands
994 /// have special register allocation requirements that are not captured by the
995 /// operand register classes. e.g. ARM::LDRD's two def registers must be an
996 /// even / odd pair, ARM::LDM registers have to be in ascending order.
997 /// Post-register allocation passes should not attempt to change allocations
998 /// for definitions of instructions with this flag.
999 bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
1000 return hasProperty(MCID::ExtraDefRegAllocReq, Type);
1001 }
1002
1003 enum MICheckType {
1004 CheckDefs, // Check all operands for equality
1005 CheckKillDead, // Check all operands including kill / dead markers
1006 IgnoreDefs, // Ignore all definitions
1007 IgnoreVRegDefs // Ignore virtual register definitions
1008 };
1009
1010 /// Return true if this instruction is identical to \p Other.
1011 /// Two instructions are identical if they have the same opcode and all their
1012 /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
1013 /// Note that this means liveness related flags (dead, undef, kill) do not
1014 /// affect the notion of identical.
1015 bool isIdenticalTo(const MachineInstr &Other,
1016 MICheckType Check = CheckDefs) const;
1017
1018 /// Unlink 'this' from the containing basic block, and return it without
1019 /// deleting it.
1020 ///
1021 /// This function can not be used on bundled instructions, use
1022 /// removeFromBundle() to remove individual instructions from a bundle.
1023 MachineInstr *removeFromParent();
1024
1025 /// Unlink this instruction from its basic block and return it without
1026 /// deleting it.
1027 ///
1028 /// If the instruction is part of a bundle, the other instructions in the
1029 /// bundle remain bundled.
1030 MachineInstr *removeFromBundle();
1031
1032 /// Unlink 'this' from the containing basic block and delete it.
1033 ///
1034 /// If this instruction is the header of a bundle, the whole bundle is erased.
1035 /// This function can not be used for instructions inside a bundle, use
1036 /// eraseFromBundle() to erase individual bundled instructions.
1037 void eraseFromParent();
1038
1039 /// Unlink 'this' from the containing basic block and delete it.
1040 ///
1041 /// For all definitions mark their uses in DBG_VALUE nodes
1042 /// as undefined. Otherwise like eraseFromParent().
1043 void eraseFromParentAndMarkDBGValuesForRemoval();
1044
1045 /// Unlink 'this' form its basic block and delete it.
1046 ///
1047 /// If the instruction is part of a bundle, the other instructions in the
1048 /// bundle remain bundled.
1049 void eraseFromBundle();
1050
1051 bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
1052 bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
1053 bool isAnnotationLabel() const {
1054 return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
1055 }
1056
1057 /// Returns true if the MachineInstr represents a label.
1058 bool isLabel() const {
1059 return isEHLabel() || isGCLabel() || isAnnotationLabel();
1060 }
1061
1062 bool isCFIInstruction() const {
1063 return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
1064 }
1065
1066 // True if the instruction represents a position in the function.
1067 bool isPosition() const { return isLabel() || isCFIInstruction(); }
1068
1069 bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
1070 bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
1071 bool isDebugInstr() const { return isDebugValue() || isDebugLabel(); }
1072
1073 /// A DBG_VALUE is indirect iff the first operand is a register and
1074 /// the second operand is an immediate.
1075 bool isIndirectDebugValue() const {
1076 return isDebugValue()
1077 && getOperand(0).isReg()
1078 && getOperand(1).isImm();
1079 }
1080
1081 /// A DBG_VALUE is an entry value iff its debug expression contains the
1082 /// DW_OP_LLVM_entry_value operation.
1083 bool isDebugEntryValue() const;
1084
1085 /// Return true if the instruction is a debug value which describes a part of
1086 /// a variable as unavailable.
1087 bool isUndefDebugValue() const {
1088 return isDebugValue() && getOperand(0).isReg() && !getOperand(0).getReg().isValid();
1089 }
1090
1091 bool isPHI() const {
1092 return getOpcode() == TargetOpcode::PHI ||
51
Assuming the condition is false
53
Returning zero, which participates in a condition later
1093 getOpcode() == TargetOpcode::G_PHI;
52
Assuming the condition is false
1094 }
1095 bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
1096 bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
1097 bool isInlineAsm() const {
1098 return getOpcode() == TargetOpcode::INLINEASM ||
1099 getOpcode() == TargetOpcode::INLINEASM_BR;
1100 }
1101
1102 /// FIXME: Seems like a layering violation that the AsmDialect, which is X86
1103 /// specific, be attached to a generic MachineInstr.
1104 bool isMSInlineAsm() const {
1105 return isInlineAsm() && getInlineAsmDialect() == InlineAsm::AD_Intel;
1106 }
1107
1108 bool isStackAligningInlineAsm() const;
1109 InlineAsm::AsmDialect getInlineAsmDialect() const;
1110
1111 bool isInsertSubreg() const {
1112 return getOpcode() == TargetOpcode::INSERT_SUBREG;
1113 }
1114
1115 bool isSubregToReg() const {
1116 return getOpcode() == TargetOpcode::SUBREG_TO_REG;
1117 }
1118
1119 bool isRegSequence() const {
1120 return getOpcode() == TargetOpcode::REG_SEQUENCE;
1121 }
1122
1123 bool isBundle() const {
1124 return getOpcode() == TargetOpcode::BUNDLE;
1125 }
1126
1127 bool isCopy() const {
1128 return getOpcode() == TargetOpcode::COPY;
1129 }
1130
1131 bool isFullCopy() const {
1132 return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
1133 }
1134
1135 bool isExtractSubreg() const {
1136 return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
1137 }
1138
1139 /// Return true if the instruction behaves like a copy.
1140 /// This does not include native copy instructions.
1141 bool isCopyLike() const {
1142 return isCopy() || isSubregToReg();
1143 }
1144
1145 /// Return true is the instruction is an identity copy.
1146 bool isIdentityCopy() const {
1147 return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
1148 getOperand(0).getSubReg() == getOperand(1).getSubReg();
1149 }
1150
1151 /// Return true if this instruction doesn't produce any output in the form of
1152 /// executable instructions.
1153 bool isMetaInstruction() const {
1154 switch (getOpcode()) {
1155 default:
1156 return false;
1157 case TargetOpcode::IMPLICIT_DEF:
1158 case TargetOpcode::KILL:
1159 case TargetOpcode::CFI_INSTRUCTION:
1160 case TargetOpcode::EH_LABEL:
1161 case TargetOpcode::GC_LABEL:
1162 case TargetOpcode::DBG_VALUE:
1163 case TargetOpcode::DBG_LABEL:
1164 case TargetOpcode::LIFETIME_START:
1165 case TargetOpcode::LIFETIME_END:
1166 return true;
1167 }
1168 }
1169
1170 /// Return true if this is a transient instruction that is either very likely
1171 /// to be eliminated during register allocation (such as copy-like
1172 /// instructions), or if this instruction doesn't have an execution-time cost.
1173 bool isTransient() const {
1174 switch (getOpcode()) {
1175 default:
1176 return isMetaInstruction();
1177 // Copy-like instructions are usually eliminated during register allocation.
1178 case TargetOpcode::PHI:
1179 case TargetOpcode::G_PHI:
1180 case TargetOpcode::COPY:
1181 case TargetOpcode::INSERT_SUBREG:
1182 case TargetOpcode::SUBREG_TO_REG:
1183 case TargetOpcode::REG_SEQUENCE:
1184 return true;
1185 }
1186 }
1187
1188 /// Return the number of instructions inside the MI bundle, excluding the
1189 /// bundle header.
1190 ///
1191 /// This is the number of instructions that MachineBasicBlock::iterator
1192 /// skips, 0 for unbundled instructions.
1193 unsigned getBundleSize() const;
1194
1195 /// Return true if the MachineInstr reads the specified register.
1196 /// If TargetRegisterInfo is passed, then it also checks if there
1197 /// is a read of a super-register.
1198 /// This does not count partial redefines of virtual registers as reads:
1199 /// %reg1024:6 = OP.
1200 bool readsRegister(Register Reg,
1201 const TargetRegisterInfo *TRI = nullptr) const {
1202 return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
1203 }
1204
1205 /// Return true if the MachineInstr reads the specified virtual register.
1206 /// Take into account that a partial define is a
1207 /// read-modify-write operation.
1208 bool readsVirtualRegister(Register Reg) const {
1209 return readsWritesVirtualRegister(Reg).first;
1210 }
1211
1212 /// Return a pair of bools (reads, writes) indicating if this instruction
1213 /// reads or writes Reg. This also considers partial defines.
1214 /// If Ops is not null, all operand indices for Reg are added.
1215 std::pair<bool,bool> readsWritesVirtualRegister(Register Reg,
1216 SmallVectorImpl<unsigned> *Ops = nullptr) const;
1217
1218 /// Return true if the MachineInstr kills the specified register.
1219 /// If TargetRegisterInfo is passed, then it also checks if there is
1220 /// a kill of a super-register.
1221 bool killsRegister(Register Reg,
1222 const TargetRegisterInfo *TRI = nullptr) const {
1223 return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
1224 }
1225
1226 /// Return true if the MachineInstr fully defines the specified register.
1227 /// If TargetRegisterInfo is passed, then it also checks
1228 /// if there is a def of a super-register.
1229 /// NOTE: It's ignoring subreg indices on virtual registers.
1230 bool definesRegister(Register Reg,
1231 const TargetRegisterInfo *TRI = nullptr) const {
1232 return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
1233 }
1234
1235 /// Return true if the MachineInstr modifies (fully define or partially
1236 /// define) the specified register.
1237 /// NOTE: It's ignoring subreg indices on virtual registers.
1238 bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1239 return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
1240 }
1241
1242 /// Returns true if the register is dead in this machine instruction.
1243 /// If TargetRegisterInfo is passed, then it also checks
1244 /// if there is a dead def of a super-register.
1245 bool registerDefIsDead(Register Reg,
1246 const TargetRegisterInfo *TRI = nullptr) const {
1247 return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
1248 }
1249
1250 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1251 /// the given register (not considering sub/super-registers).
1252 bool hasRegisterImplicitUseOperand(Register Reg) const;
1253
1254 /// Returns the operand index that is a use of the specific register or -1
1255 /// if it is not found. It further tightens the search criteria to a use
1256 /// that kills the register if isKill is true.
1257 int findRegisterUseOperandIdx(Register Reg, bool isKill = false,
1258 const TargetRegisterInfo *TRI = nullptr) const;
1259
1260 /// Wrapper for findRegisterUseOperandIdx, it returns
1261 /// a pointer to the MachineOperand rather than an index.
1262 MachineOperand *findRegisterUseOperand(Register Reg, bool isKill = false,
1263 const TargetRegisterInfo *TRI = nullptr) {
1264 int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
1265 return (Idx == -1) ? nullptr : &getOperand(Idx);
1266 }
1267
1268 const MachineOperand *findRegisterUseOperand(
1269 Register Reg, bool isKill = false,
1270 const TargetRegisterInfo *TRI = nullptr) const {
1271 return const_cast<MachineInstr *>(this)->
1272 findRegisterUseOperand(Reg, isKill, TRI);
1273 }
1274
1275 /// Returns the operand index that is a def of the specified register or
1276 /// -1 if it is not found. If isDead is true, defs that are not dead are
1277 /// skipped. If Overlap is true, then it also looks for defs that merely
1278 /// overlap the specified register. If TargetRegisterInfo is non-null,
1279 /// then it also checks if there is a def of a super-register.
1280 /// This may also return a register mask operand when Overlap is true.
1281 int findRegisterDefOperandIdx(Register Reg,
1282 bool isDead = false, bool Overlap = false,
1283 const TargetRegisterInfo *TRI = nullptr) const;
1284
1285 /// Wrapper for findRegisterDefOperandIdx, it returns
1286 /// a pointer to the MachineOperand rather than an index.
1287 MachineOperand *
1288 findRegisterDefOperand(Register Reg, bool isDead = false,
1289 bool Overlap = false,
1290 const TargetRegisterInfo *TRI = nullptr) {
1291 int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI);
1292 return (Idx == -1) ? nullptr : &getOperand(Idx);
1293 }
1294
1295 const MachineOperand *
1296 findRegisterDefOperand(Register Reg, bool isDead = false,
1297 bool Overlap = false,
1298 const TargetRegisterInfo *TRI = nullptr) const {
1299 return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
1300 Reg, isDead, Overlap, TRI);
1301 }
1302
1303 /// Find the index of the first operand in the
1304 /// operand list that is used to represent the predicate. It returns -1 if
1305 /// none is found.
1306 int findFirstPredOperandIdx() const;
1307
1308 /// Find the index of the flag word operand that
1309 /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if
1310 /// getOperand(OpIdx) does not belong to an inline asm operand group.
1311 ///
1312 /// If GroupNo is not NULL, it will receive the number of the operand group
1313 /// containing OpIdx.
1314 ///
1315 /// The flag operand is an immediate that can be decoded with methods like
1316 /// InlineAsm::hasRegClassConstraint().
1317 int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1318
1319 /// Compute the static register class constraint for operand OpIdx.
1320 /// For normal instructions, this is derived from the MCInstrDesc.
1321 /// For inline assembly it is derived from the flag words.
1322 ///
1323 /// Returns NULL if the static register class constraint cannot be
1324 /// determined.
1325 const TargetRegisterClass*
1326 getRegClassConstraint(unsigned OpIdx,
1327 const TargetInstrInfo *TII,
1328 const TargetRegisterInfo *TRI) const;
1329
1330 /// Applies the constraints (def/use) implied by this MI on \p Reg to
1331 /// the given \p CurRC.
1332 /// If \p ExploreBundle is set and MI is part of a bundle, all the
1333 /// instructions inside the bundle will be taken into account. In other words,
1334 /// this method accumulates all the constraints of the operand of this MI and
1335 /// the related bundle if MI is a bundle or inside a bundle.
1336 ///
1337 /// Returns the register class that satisfies both \p CurRC and the
1338 /// constraints set by MI. Returns NULL if such a register class does not
1339 /// exist.
1340 ///
1341 /// \pre CurRC must not be NULL.
1342 const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1343 Register Reg, const TargetRegisterClass *CurRC,
1344 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1345 bool ExploreBundle = false) const;
1346
1347 /// Applies the constraints (def/use) implied by the \p OpIdx operand
1348 /// to the given \p CurRC.
1349 ///
1350 /// Returns the register class that satisfies both \p CurRC and the
1351 /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1352 /// does not exist.
1353 ///
1354 /// \pre CurRC must not be NULL.
1355 /// \pre The operand at \p OpIdx must be a register.
1356 const TargetRegisterClass *
1357 getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1358 const TargetInstrInfo *TII,
1359 const TargetRegisterInfo *TRI) const;
1360
1361 /// Add a tie between the register operands at DefIdx and UseIdx.
1362 /// The tie will cause the register allocator to ensure that the two
1363 /// operands are assigned the same physical register.
1364 ///
1365 /// Tied operands are managed automatically for explicit operands in the
1366 /// MCInstrDesc. This method is for exceptional cases like inline asm.
1367 void tieOperands(unsigned DefIdx, unsigned UseIdx);
1368
1369 /// Given the index of a tied register operand, find the
1370 /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1371 /// index of the tied operand which must exist.
1372 unsigned findTiedOperandIdx(unsigned OpIdx) const;
1373
1374 /// Given the index of a register def operand,
1375 /// check if the register def is tied to a source operand, due to either
1376 /// two-address elimination or inline assembly constraints. Returns the
1377 /// first tied use operand index by reference if UseOpIdx is not null.
1378 bool isRegTiedToUseOperand(unsigned DefOpIdx,
1379 unsigned *UseOpIdx = nullptr) const {
1380 const MachineOperand &MO = getOperand(DefOpIdx);
1381 if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1382 return false;
1383 if (UseOpIdx)
1384 *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1385 return true;
1386 }
1387
1388 /// Return true if the use operand of the specified index is tied to a def
1389 /// operand. It also returns the def operand index by reference if DefOpIdx
1390 /// is not null.
1391 bool isRegTiedToDefOperand(unsigned UseOpIdx,
1392 unsigned *DefOpIdx = nullptr) const {
1393 const MachineOperand &MO = getOperand(UseOpIdx);
1394 if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1395 return false;
1396 if (DefOpIdx)
1397 *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1398 return true;
1399 }
1400
1401 /// Clears kill flags on all operands.
1402 void clearKillInfo();
1403
1404 /// Replace all occurrences of FromReg with ToReg:SubIdx,
1405 /// properly composing subreg indices where necessary.
1406 void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx,
1407 const TargetRegisterInfo &RegInfo);
1408
1409 /// We have determined MI kills a register. Look for the
1410 /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1411 /// add a implicit operand if it's not found. Returns true if the operand
1412 /// exists / is added.
1413 bool addRegisterKilled(Register IncomingReg,
1414 const TargetRegisterInfo *RegInfo,
1415 bool AddIfNotFound = false);
1416
1417 /// Clear all kill flags affecting Reg. If RegInfo is provided, this includes
1418 /// all aliasing registers.
1419 void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo);
1420
1421 /// We have determined MI defined a register without a use.
1422 /// Look for the operand that defines it and mark it as IsDead. If
1423 /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1424 /// true if the operand exists / is added.
1425 bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo,
1426 bool AddIfNotFound = false);
1427
1428 /// Clear all dead flags on operands defining register @p Reg.
1429 void clearRegisterDeads(Register Reg);
1430
1431 /// Mark all subregister defs of register @p Reg with the undef flag.
1432 /// This function is used when we determined to have a subregister def in an
1433 /// otherwise undefined super register.
1434 void setRegisterDefReadUndef(Register Reg, bool IsUndef = true);
1435
1436 /// We have determined MI defines a register. Make sure there is an operand
1437 /// defining Reg.
1438 void addRegisterDefined(Register Reg,
1439 const TargetRegisterInfo *RegInfo = nullptr);
1440
1441 /// Mark every physreg used by this instruction as
1442 /// dead except those in the UsedRegs list.
1443 ///
1444 /// On instructions with register mask operands, also add implicit-def
1445 /// operands for all registers in UsedRegs.
1446 void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
1447 const TargetRegisterInfo &TRI);
1448
1449 /// Return true if it is safe to move this instruction. If
1450 /// SawStore is set to true, it means that there is a store (or call) between
1451 /// the instruction's location and its intended destination.
1452 bool isSafeToMove(AAResults *AA, bool &SawStore) const;
1453
1454 /// Returns true if this instruction's memory access aliases the memory
1455 /// access of Other.
1456 //
1457 /// Assumes any physical registers used to compute addresses
1458 /// have the same value for both instructions. Returns false if neither
1459 /// instruction writes to memory.
1460 ///
1461 /// @param AA Optional alias analysis, used to compare memory operands.
1462 /// @param Other MachineInstr to check aliasing against.
1463 /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1464 bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const;
1465
1466 /// Return true if this instruction may have an ordered
1467 /// or volatile memory reference, or if the information describing the memory
1468 /// reference is not available. Return false if it is known to have no
1469 /// ordered or volatile memory references.
1470 bool hasOrderedMemoryRef() const;
1471
1472 /// Return true if this load instruction never traps and points to a memory
1473 /// location whose value doesn't change during the execution of this function.
1474 ///
1475 /// Examples include loading a value from the constant pool or from the
1476 /// argument area of a function (if it does not change). If the instruction
1477 /// does multiple loads, this returns true only if all of the loads are
1478 /// dereferenceable and invariant.
1479 bool isDereferenceableInvariantLoad(AAResults *AA) const;
1480
1481 /// If the specified instruction is a PHI that always merges together the
1482 /// same virtual register, return the register, otherwise return 0.
1483 unsigned isConstantValuePHI() const;
1484
1485 /// Return true if this instruction has side effects that are not modeled
1486 /// by mayLoad / mayStore, etc.
1487 /// For all instructions, the property is encoded in MCInstrDesc::Flags
1488 /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1489 /// INLINEASM instruction, in which case the side effect property is encoded
1490 /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1491 ///
1492 bool hasUnmodeledSideEffects() const;
1493
1494 /// Returns true if it is illegal to fold a load across this instruction.
1495 bool isLoadFoldBarrier() const;
1496
1497 /// Return true if all the defs of this instruction are dead.
1498 bool allDefsAreDead() const;
1499
1500 /// Return a valid size if the instruction is a spill instruction.
1501 Optional<unsigned> getSpillSize(const TargetInstrInfo *TII) const;
1502
1503 /// Return a valid size if the instruction is a folded spill instruction.
1504 Optional<unsigned> getFoldedSpillSize(const TargetInstrInfo *TII) const;
1505
1506 /// Return a valid size if the instruction is a restore instruction.
1507 Optional<unsigned> getRestoreSize(const TargetInstrInfo *TII) const;
1508
1509 /// Return a valid size if the instruction is a folded restore instruction.
1510 Optional<unsigned>
1511 getFoldedRestoreSize(const TargetInstrInfo *TII) const;
1512
1513 /// Copy implicit register operands from specified
1514 /// instruction to this instruction.
1515 void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1516
1517 /// Debugging support
1518 /// @{
1519 /// Determine the generic type to be printed (if needed) on uses and defs.
1520 LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1521 const MachineRegisterInfo &MRI) const;
1522
1523 /// Return true when an instruction has tied register that can't be determined
1524 /// by the instruction's descriptor. This is useful for MIR printing, to
1525 /// determine whether we need to print the ties or not.
1526 bool hasComplexRegisterTies() const;
1527
1528 /// Print this MI to \p OS.
1529 /// Don't print information that can be inferred from other instructions if
1530 /// \p IsStandalone is false. It is usually true when only a fragment of the
1531 /// function is printed.
1532 /// Only print the defs and the opcode if \p SkipOpers is true.
1533 /// Otherwise, also print operands if \p SkipDebugLoc is true.
1534 /// Otherwise, also print the debug loc, with a terminating newline.
1535 /// \p TII is used to print the opcode name. If it's not present, but the
1536 /// MI is in a function, the opcode will be printed using the function's TII.
1537 void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1538 bool SkipDebugLoc = false, bool AddNewLine = true,
1539 const TargetInstrInfo *TII = nullptr) const;
1540 void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1541 bool SkipOpers = false, bool SkipDebugLoc = false,
1542 bool AddNewLine = true,
1543 const TargetInstrInfo *TII = nullptr) const;
1544 void dump() const;
1545 /// Print on dbgs() the current instruction and the instructions defining its
1546 /// operands and so on until we reach \p MaxDepth.
1547 void dumpr(const MachineRegisterInfo &MRI,
1548 unsigned MaxDepth = UINT_MAX(2147483647 *2U +1U)) const;
1549 /// @}
1550
1551 //===--------------------------------------------------------------------===//
1552 // Accessors used to build up machine instructions.
1553
1554 /// Add the specified operand to the instruction. If it is an implicit
1555 /// operand, it is added to the end of the operand list. If it is an
1556 /// explicit operand it is added at the end of the explicit operand list
1557 /// (before the first implicit operand).
1558 ///
1559 /// MF must be the machine function that was used to allocate this
1560 /// instruction.
1561 ///
1562 /// MachineInstrBuilder provides a more convenient interface for creating
1563 /// instructions and adding operands.
1564 void addOperand(MachineFunction &MF, const MachineOperand &Op);
1565
1566 /// Add an operand without providing an MF reference. This only works for
1567 /// instructions that are inserted in a basic block.
1568 ///
1569 /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1570 /// preferred.
1571 void addOperand(const MachineOperand &Op);
1572
1573 /// Replace the instruction descriptor (thus opcode) of
1574 /// the current instruction with a new one.
1575 void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1576
1577 /// Replace current source information with new such.
1578 /// Avoid using this, the constructor argument is preferable.
1579 void setDebugLoc(DebugLoc dl) {
1580 debugLoc = std::move(dl);
1581 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")((debugLoc.hasTrivialDestructor() && "Expected trivial destructor"
) ? static_cast<void> (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/MachineInstr.h"
, 1581, __PRETTY_FUNCTION__))
;
1582 }
1583
1584 /// Erase an operand from an instruction, leaving it with one
1585 /// fewer operand than it started with.
1586 void RemoveOperand(unsigned OpNo);
1587
1588 /// Clear this MachineInstr's memory reference descriptor list. This resets
1589 /// the memrefs to their most conservative state. This should be used only
1590 /// as a last resort since it greatly pessimizes our knowledge of the memory
1591 /// access performed by the instruction.
1592 void dropMemRefs(MachineFunction &MF);
1593
1594 /// Assign this MachineInstr's memory reference descriptor list.
1595 ///
1596 /// Unlike other methods, this *will* allocate them into a new array
1597 /// associated with the provided `MachineFunction`.
1598 void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
1599
1600 /// Add a MachineMemOperand to the machine instruction.
1601 /// This function should be used only occasionally. The setMemRefs function
1602 /// is the primary method for setting up a MachineInstr's MemRefs list.
1603 void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1604
1605 /// Clone another MachineInstr's memory reference descriptor list and replace
1606 /// ours with it.
1607 ///
1608 /// Note that `*this` may be the incoming MI!
1609 ///
1610 /// Prefer this API whenever possible as it can avoid allocations in common
1611 /// cases.
1612 void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
1613
1614 /// Clone the merge of multiple MachineInstrs' memory reference descriptors
1615 /// list and replace ours with it.
1616 ///
1617 /// Note that `*this` may be one of the incoming MIs!
1618 ///
1619 /// Prefer this API whenever possible as it can avoid allocations in common
1620 /// cases.
1621 void cloneMergedMemRefs(MachineFunction &MF,
1622 ArrayRef<const MachineInstr *> MIs);
1623
1624 /// Set a symbol that will be emitted just prior to the instruction itself.
1625 ///
1626 /// Setting this to a null pointer will remove any such symbol.
1627 ///
1628 /// FIXME: This is not fully implemented yet.
1629 void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1630
1631 /// Set a symbol that will be emitted just after the instruction itself.
1632 ///
1633 /// Setting this to a null pointer will remove any such symbol.
1634 ///
1635 /// FIXME: This is not fully implemented yet.
1636 void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1637
1638 /// Clone another MachineInstr's pre- and post- instruction symbols and
1639 /// replace ours with it.
1640 void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
1641
1642 /// Set a marker on instructions that denotes where we should create and emit
1643 /// heap alloc site labels. This waits until after instruction selection and
1644 /// optimizations to create the label, so it should still work if the
1645 /// instruction is removed or duplicated.
1646 void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
1647
1648 /// Return the MIFlags which represent both MachineInstrs. This
1649 /// should be used when merging two MachineInstrs into one. This routine does
1650 /// not modify the MIFlags of this MachineInstr.
1651 uint16_t mergeFlagsWith(const MachineInstr& Other) const;
1652
1653 static uint16_t copyFlagsFromInstruction(const Instruction &I);
1654
1655 /// Copy all flags to MachineInst MIFlags
1656 void copyIRFlags(const Instruction &I);
1657
1658 /// Break any tie involving OpIdx.
1659 void untieRegOperand(unsigned OpIdx) {
1660 MachineOperand &MO = getOperand(OpIdx);
1661 if (MO.isReg() && MO.isTied()) {
1662 getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1663 MO.TiedTo = 0;
1664 }
1665 }
1666
1667 /// Add all implicit def and use operands to this instruction.
1668 void addImplicitDefUseOperands(MachineFunction &MF);
1669
1670 /// Scan instructions immediately following MI and collect any matching
1671 /// DBG_VALUEs.
1672 void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
1673
1674 /// Find all DBG_VALUEs that point to the register def in this instruction
1675 /// and point them to \p Reg instead.
1676 void changeDebugValuesDefReg(Register Reg);
1677
1678 /// Returns the Intrinsic::ID for this instruction.
1679 /// \pre Must have an intrinsic ID operand.
1680 unsigned getIntrinsicID() const {
1681 return getOperand(getNumExplicitDefs()).getIntrinsicID();
1682 }
1683
1684private:
1685 /// If this instruction is embedded into a MachineFunction, return the
1686 /// MachineRegisterInfo object for the current function, otherwise
1687 /// return null.
1688 MachineRegisterInfo *getRegInfo();
1689
1690 /// Unlink all of the register operands in this instruction from their
1691 /// respective use lists. This requires that the operands already be on their
1692 /// use lists.
1693 void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1694
1695 /// Add all of the register operands in this instruction from their
1696 /// respective use lists. This requires that the operands not be on their
1697 /// use lists yet.
1698 void AddRegOperandsToUseLists(MachineRegisterInfo&);
1699
1700 /// Slow path for hasProperty when we're dealing with a bundle.
1701 bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
1702
1703 /// Implements the logic of getRegClassConstraintEffectForVReg for the
1704 /// this MI and the given operand index \p OpIdx.
1705 /// If the related operand does not constrained Reg, this returns CurRC.
1706 const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1707 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
1708 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1709
1710 /// Stores extra instruction information inline or allocates as ExtraInfo
1711 /// based on the number of pointers.
1712 void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
1713 MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
1714 MDNode *HeapAllocMarker);
1715};
1716
1717/// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1718/// instruction rather than by pointer value.
1719/// The hashing and equality testing functions ignore definitions so this is
1720/// useful for CSE, etc.
1721struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1722 static inline MachineInstr *getEmptyKey() {
1723 return nullptr;
1724 }
1725
1726 static inline MachineInstr *getTombstoneKey() {
1727 return reinterpret_cast<MachineInstr*>(-1);
1728 }
1729
1730 static unsigned getHashValue(const MachineInstr* const &MI);
1731
1732 static bool isEqual(const MachineInstr* const &LHS,
1733 const MachineInstr* const &RHS) {
1734 if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1735 LHS == getEmptyKey() || LHS == getTombstoneKey())
1736 return LHS == RHS;
1737 return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
1738 }
1739};
1740
1741//===----------------------------------------------------------------------===//
1742// Debugging Support
1743
1744inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1745 MI.print(OS);
1746 return OS;
1747}
1748
1749} // end namespace llvm
1750
1751#endif // LLVM_CODEGEN_MACHINEINSTR_H