Bug Summary

File:llvm/lib/CodeGen/InlineSpiller.cpp
Warning:line 307, column 62
The left operand of '==' is a garbage value

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp

1//===- InlineSpiller.cpp - Insert spills and restores inline --------------===//
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// The inline spiller modifies the machine function directly instead of
10// inserting spills and restores in VirtRegMap.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SplitKit.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/MapVector.h"
18#include "llvm/ADT/None.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/CodeGen/LiveInterval.h"
26#include "llvm/CodeGen/LiveIntervalCalc.h"
27#include "llvm/CodeGen/LiveIntervals.h"
28#include "llvm/CodeGen/LiveRangeEdit.h"
29#include "llvm/CodeGen/LiveStacks.h"
30#include "llvm/CodeGen/MachineBasicBlock.h"
31#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32#include "llvm/CodeGen/MachineDominators.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineFunctionPass.h"
35#include "llvm/CodeGen/MachineInstr.h"
36#include "llvm/CodeGen/MachineInstrBuilder.h"
37#include "llvm/CodeGen/MachineInstrBundle.h"
38#include "llvm/CodeGen/MachineLoopInfo.h"
39#include "llvm/CodeGen/MachineOperand.h"
40#include "llvm/CodeGen/MachineRegisterInfo.h"
41#include "llvm/CodeGen/SlotIndexes.h"
42#include "llvm/CodeGen/Spiller.h"
43#include "llvm/CodeGen/StackMaps.h"
44#include "llvm/CodeGen/TargetInstrInfo.h"
45#include "llvm/CodeGen/TargetOpcodes.h"
46#include "llvm/CodeGen/TargetRegisterInfo.h"
47#include "llvm/CodeGen/TargetSubtargetInfo.h"
48#include "llvm/CodeGen/VirtRegMap.h"
49#include "llvm/Config/llvm-config.h"
50#include "llvm/Support/BlockFrequency.h"
51#include "llvm/Support/BranchProbability.h"
52#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/Support/Debug.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/raw_ostream.h"
57#include <cassert>
58#include <iterator>
59#include <tuple>
60#include <utility>
61#include <vector>
62
63using namespace llvm;
64
65#define DEBUG_TYPE"regalloc" "regalloc"
66
67STATISTIC(NumSpilledRanges, "Number of spilled live ranges")static llvm::Statistic NumSpilledRanges = {"regalloc", "NumSpilledRanges"
, "Number of spilled live ranges"}
;
68STATISTIC(NumSnippets, "Number of spilled snippets")static llvm::Statistic NumSnippets = {"regalloc", "NumSnippets"
, "Number of spilled snippets"}
;
69STATISTIC(NumSpills, "Number of spills inserted")static llvm::Statistic NumSpills = {"regalloc", "NumSpills", "Number of spills inserted"
}
;
70STATISTIC(NumSpillsRemoved, "Number of spills removed")static llvm::Statistic NumSpillsRemoved = {"regalloc", "NumSpillsRemoved"
, "Number of spills removed"}
;
71STATISTIC(NumReloads, "Number of reloads inserted")static llvm::Statistic NumReloads = {"regalloc", "NumReloads"
, "Number of reloads inserted"}
;
72STATISTIC(NumReloadsRemoved, "Number of reloads removed")static llvm::Statistic NumReloadsRemoved = {"regalloc", "NumReloadsRemoved"
, "Number of reloads removed"}
;
73STATISTIC(NumFolded, "Number of folded stack accesses")static llvm::Statistic NumFolded = {"regalloc", "NumFolded", "Number of folded stack accesses"
}
;
74STATISTIC(NumFoldedLoads, "Number of folded loads")static llvm::Statistic NumFoldedLoads = {"regalloc", "NumFoldedLoads"
, "Number of folded loads"}
;
75STATISTIC(NumRemats, "Number of rematerialized defs for spilling")static llvm::Statistic NumRemats = {"regalloc", "NumRemats", "Number of rematerialized defs for spilling"
}
;
76
77static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
78 cl::desc("Disable inline spill hoisting"));
79static cl::opt<bool>
80RestrictStatepointRemat("restrict-statepoint-remat",
81 cl::init(false), cl::Hidden,
82 cl::desc("Restrict remat for statepoint operands"));
83
84namespace {
85
86class HoistSpillHelper : private LiveRangeEdit::Delegate {
87 MachineFunction &MF;
88 LiveIntervals &LIS;
89 LiveStacks &LSS;
90 AliasAnalysis *AA;
91 MachineDominatorTree &MDT;
92 MachineLoopInfo &Loops;
93 VirtRegMap &VRM;
94 MachineRegisterInfo &MRI;
95 const TargetInstrInfo &TII;
96 const TargetRegisterInfo &TRI;
97 const MachineBlockFrequencyInfo &MBFI;
98
99 InsertPointAnalysis IPA;
100
101 // Map from StackSlot to the LiveInterval of the original register.
102 // Note the LiveInterval of the original register may have been deleted
103 // after it is spilled. We keep a copy here to track the range where
104 // spills can be moved.
105 DenseMap<int, std::unique_ptr<LiveInterval>> StackSlotToOrigLI;
106
107 // Map from pair of (StackSlot and Original VNI) to a set of spills which
108 // have the same stackslot and have equal values defined by Original VNI.
109 // These spills are mergeable and are hoist candiates.
110 using MergeableSpillsMap =
111 MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
112 MergeableSpillsMap MergeableSpills;
113
114 /// This is the map from original register to a set containing all its
115 /// siblings. To hoist a spill to another BB, we need to find out a live
116 /// sibling there and use it as the source of the new spill.
117 DenseMap<Register, SmallSetVector<Register, 16>> Virt2SiblingsMap;
118
119 bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
120 MachineBasicBlock &BB, Register &LiveReg);
121
122 void rmRedundantSpills(
123 SmallPtrSet<MachineInstr *, 16> &Spills,
124 SmallVectorImpl<MachineInstr *> &SpillsToRm,
125 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
126
127 void getVisitOrders(
128 MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
129 SmallVectorImpl<MachineDomTreeNode *> &Orders,
130 SmallVectorImpl<MachineInstr *> &SpillsToRm,
131 DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
132 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
133
134 void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI,
135 SmallPtrSet<MachineInstr *, 16> &Spills,
136 SmallVectorImpl<MachineInstr *> &SpillsToRm,
137 DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns);
138
139public:
140 HoistSpillHelper(MachineFunctionPass &pass, MachineFunction &mf,
141 VirtRegMap &vrm)
142 : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
143 LSS(pass.getAnalysis<LiveStacks>()),
144 AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
145 MDT(pass.getAnalysis<MachineDominatorTree>()),
146 Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
147 MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
148 TRI(*mf.getSubtarget().getRegisterInfo()),
149 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
150 IPA(LIS, mf.getNumBlockIDs()) {}
151
152 void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
153 unsigned Original);
154 bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
155 void hoistAllSpills();
156 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
157};
158
159class InlineSpiller : public Spiller {
160 MachineFunction &MF;
161 LiveIntervals &LIS;
162 LiveStacks &LSS;
163 AliasAnalysis *AA;
164 MachineDominatorTree &MDT;
165 MachineLoopInfo &Loops;
166 VirtRegMap &VRM;
167 MachineRegisterInfo &MRI;
168 const TargetInstrInfo &TII;
169 const TargetRegisterInfo &TRI;
170 const MachineBlockFrequencyInfo &MBFI;
171
172 // Variables that are valid during spill(), but used by multiple methods.
173 LiveRangeEdit *Edit;
174 LiveInterval *StackInt;
175 int StackSlot;
176 unsigned Original;
177
178 // All registers to spill to StackSlot, including the main register.
179 SmallVector<Register, 8> RegsToSpill;
180
181 // All COPY instructions to/from snippets.
182 // They are ignored since both operands refer to the same stack slot.
183 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
184
185 // Values that failed to remat at some point.
186 SmallPtrSet<VNInfo*, 8> UsedValues;
187
188 // Dead defs generated during spilling.
189 SmallVector<MachineInstr*, 8> DeadDefs;
190
191 // Object records spills information and does the hoisting.
192 HoistSpillHelper HSpiller;
193
194 ~InlineSpiller() override = default;
195
196public:
197 InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
198 : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
199 LSS(pass.getAnalysis<LiveStacks>()),
200 AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
201 MDT(pass.getAnalysis<MachineDominatorTree>()),
202 Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
203 MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
204 TRI(*mf.getSubtarget().getRegisterInfo()),
205 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
206 HSpiller(pass, mf, vrm) {}
207
208 void spill(LiveRangeEdit &) override;
209 void postOptimization() override;
210
211private:
212 bool isSnippet(const LiveInterval &SnipLI);
213 void collectRegsToSpill();
214
215 bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); }
216
217 bool isSibling(Register Reg);
218 bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
219 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
220
221 void markValueUsed(LiveInterval*, VNInfo*);
222 bool canGuaranteeAssignmentAfterRemat(Register VReg, MachineInstr &MI);
223 bool reMaterializeFor(LiveInterval &, MachineInstr &MI);
224 void reMaterializeAll();
225
226 bool coalesceStackAccess(MachineInstr *MI, Register Reg);
227 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
228 MachineInstr *LoadMI = nullptr);
229 void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
230 void insertSpill(Register VReg, bool isKill, MachineBasicBlock::iterator MI);
231
232 void spillAroundUses(Register Reg);
233 void spillAll();
234};
235
236} // end anonymous namespace
237
238Spiller::~Spiller() = default;
239
240void Spiller::anchor() {}
241
242Spiller *llvm::createInlineSpiller(MachineFunctionPass &pass,
243 MachineFunction &mf,
244 VirtRegMap &vrm) {
245 return new InlineSpiller(pass, mf, vrm);
246}
247
248//===----------------------------------------------------------------------===//
249// Snippets
250//===----------------------------------------------------------------------===//
251
252// When spilling a virtual register, we also spill any snippets it is connected
253// to. The snippets are small live ranges that only have a single real use,
254// leftovers from live range splitting. Spilling them enables memory operand
255// folding or tightens the live range around the single use.
256//
257// This minimizes register pressure and maximizes the store-to-load distance for
258// spill slots which can be important in tight loops.
259
260/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
261/// otherwise return 0.
262static Register isFullCopyOf(const MachineInstr &MI, Register Reg) {
263 if (!MI.isFullCopy())
6
Calling 'MachineInstr::isFullCopy'
8
Returning from 'MachineInstr::isFullCopy'
9
Taking true branch
264 return Register();
265 if (MI.getOperand(0).getReg() == Reg)
266 return MI.getOperand(1).getReg();
267 if (MI.getOperand(1).getReg() == Reg)
268 return MI.getOperand(0).getReg();
269 return Register();
270}
271
272/// isSnippet - Identify if a live interval is a snippet that should be spilled.
273/// It is assumed that SnipLI is a virtual register with the same original as
274/// Edit->getReg().
275bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
276 Register Reg = Edit->getReg();
277
278 // A snippet is a tiny live range with only a single instruction using it
279 // besides copies to/from Reg or spills/fills. We accept:
280 //
281 // %snip = COPY %Reg / FILL fi#
282 // %snip = USE %snip
283 // %Reg = COPY %snip / SPILL %snip, fi#
284 //
285 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
1
Assuming the condition is false
2
Assuming the condition is false
3
Taking false branch
286 return false;
287
288 MachineInstr *UseMI = nullptr;
289
290 // Check that all uses satisfy our criteria.
291 for (MachineRegisterInfo::reg_instr_nodbg_iterator
4
Loop condition is true. Entering loop body
292 RI = MRI.reg_instr_nodbg_begin(SnipLI.reg()),
293 E = MRI.reg_instr_nodbg_end();
294 RI != E;) {
295 MachineInstr &MI = *RI++;
296
297 // Allow copies to/from Reg.
298 if (isFullCopyOf(MI, Reg))
5
Calling 'isFullCopyOf'
10
Returning from 'isFullCopyOf'
11
Calling 'Register::operator unsigned int'
13
Returning from 'Register::operator unsigned int'
14
Taking false branch
299 continue;
300
301 // Allow stack slot loads.
302 int FI;
15
'FI' declared without an initial value
303 if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
16
Calling 'TargetInstrInfo::isLoadFromStackSlot'
18
Returning from 'TargetInstrInfo::isLoadFromStackSlot'
19
Taking false branch
304 continue;
305
306 // Allow stack slot stores.
307 if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
20
Calling 'TargetInstrInfo::isStoreToStackSlot'
22
Returning from 'TargetInstrInfo::isStoreToStackSlot'
23
Calling 'Register::operator=='
26
Returning from 'Register::operator=='
27
The left operand of '==' is a garbage value
308 continue;
309
310 // Allow a single additional instruction.
311 if (UseMI && &MI != UseMI)
312 return false;
313 UseMI = &MI;
314 }
315 return true;
316}
317
318/// collectRegsToSpill - Collect live range snippets that only have a single
319/// real use.
320void InlineSpiller::collectRegsToSpill() {
321 Register Reg = Edit->getReg();
322
323 // Main register always spills.
324 RegsToSpill.assign(1, Reg);
325 SnippetCopies.clear();
326
327 // Snippets all have the same original, so there can't be any for an original
328 // register.
329 if (Original == Reg)
330 return;
331
332 for (MachineRegisterInfo::reg_instr_iterator
333 RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
334 MachineInstr &MI = *RI++;
335 Register SnipReg = isFullCopyOf(MI, Reg);
336 if (!isSibling(SnipReg))
337 continue;
338 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
339 if (!isSnippet(SnipLI))
340 continue;
341 SnippetCopies.insert(&MI);
342 if (isRegToSpill(SnipReg))
343 continue;
344 RegsToSpill.push_back(SnipReg);
345 LLVM_DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\talso spill snippet " <<
SnipLI << '\n'; } } while (false)
;
346 ++NumSnippets;
347 }
348}
349
350bool InlineSpiller::isSibling(Register Reg) {
351 return Reg.isVirtual() && VRM.getOriginal(Reg) == Original;
352}
353
354/// It is beneficial to spill to earlier place in the same BB in case
355/// as follows:
356/// There is an alternative def earlier in the same MBB.
357/// Hoist the spill as far as possible in SpillMBB. This can ease
358/// register pressure:
359///
360/// x = def
361/// y = use x
362/// s = copy x
363///
364/// Hoisting the spill of s to immediately after the def removes the
365/// interference between x and y:
366///
367/// x = def
368/// spill x
369/// y = use killed x
370///
371/// This hoist only helps when the copy kills its source.
372///
373bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
374 MachineInstr &CopyMI) {
375 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
376#ifndef NDEBUG
377 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
378 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy")((VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy"
) ? static_cast<void> (0) : __assert_fail ("VNI && VNI->def == Idx.getRegSlot() && \"Not defined by copy\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 378, __PRETTY_FUNCTION__))
;
379#endif
380
381 Register SrcReg = CopyMI.getOperand(1).getReg();
382 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
383 VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
384 LiveQueryResult SrcQ = SrcLI.Query(Idx);
385 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
386 if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
387 return false;
388
389 // Conservatively extend the stack slot range to the range of the original
390 // value. We may be able to do better with stack slot coloring by being more
391 // careful here.
392 assert(StackInt && "No stack slot assigned yet.")((StackInt && "No stack slot assigned yet.") ? static_cast
<void> (0) : __assert_fail ("StackInt && \"No stack slot assigned yet.\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 392, __PRETTY_FUNCTION__))
;
393 LiveInterval &OrigLI = LIS.getInterval(Original);
394 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
395 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
396 LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tmerged orig valno " <<
OrigVNI->id << ": " << *StackInt << '\n'
; } } while (false)
397 << *StackInt << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tmerged orig valno " <<
OrigVNI->id << ": " << *StackInt << '\n'
; } } while (false)
;
398
399 // We are going to spill SrcVNI immediately after its def, so clear out
400 // any later spills of the same value.
401 eliminateRedundantSpills(SrcLI, SrcVNI);
402
403 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SrcVNI->def);
404 MachineBasicBlock::iterator MII;
405 if (SrcVNI->isPHIDef())
406 MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
407 else {
408 MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def);
409 assert(DefMI && "Defining instruction disappeared")((DefMI && "Defining instruction disappeared") ? static_cast
<void> (0) : __assert_fail ("DefMI && \"Defining instruction disappeared\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 409, __PRETTY_FUNCTION__))
;
410 MII = DefMI;
411 ++MII;
412 }
413 // Insert spill without kill flag immediately after def.
414 TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
415 MRI.getRegClass(SrcReg), &TRI);
416 --MII; // Point to store instruction.
417 LIS.InsertMachineInstrInMaps(*MII);
418 LLVM_DEBUG(dbgs() << "\thoisted: " << SrcVNI->def << '\t' << *MII)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\thoisted: " << SrcVNI
->def << '\t' << *MII; } } while (false)
;
419
420 HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
421 ++NumSpills;
422 return true;
423}
424
425/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
426/// redundant spills of this value in SLI.reg and sibling copies.
427void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
428 assert(VNI && "Missing value")((VNI && "Missing value") ? static_cast<void> (
0) : __assert_fail ("VNI && \"Missing value\"", "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 428, __PRETTY_FUNCTION__))
;
429 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
430 WorkList.push_back(std::make_pair(&SLI, VNI));
431 assert(StackInt && "No stack slot assigned yet.")((StackInt && "No stack slot assigned yet.") ? static_cast
<void> (0) : __assert_fail ("StackInt && \"No stack slot assigned yet.\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 431, __PRETTY_FUNCTION__))
;
432
433 do {
434 LiveInterval *LI;
435 std::tie(LI, VNI) = WorkList.pop_back_val();
436 Register Reg = LI->reg();
437 LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Checking redundant spills for "
<< VNI->id << '@' << VNI->def <<
" in " << *LI << '\n'; } } while (false)
438 << VNI->def << " in " << *LI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Checking redundant spills for "
<< VNI->id << '@' << VNI->def <<
" in " << *LI << '\n'; } } while (false)
;
439
440 // Regs to spill are taken care of.
441 if (isRegToSpill(Reg))
442 continue;
443
444 // Add all of VNI's live range to StackInt.
445 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
446 LLVM_DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Merged to stack int: " <<
*StackInt << '\n'; } } while (false)
;
447
448 // Find all spills and copies of VNI.
449 for (MachineRegisterInfo::use_instr_nodbg_iterator
450 UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
451 UI != E; ) {
452 MachineInstr &MI = *UI++;
453 if (!MI.isCopy() && !MI.mayStore())
454 continue;
455 SlotIndex Idx = LIS.getInstructionIndex(MI);
456 if (LI->getVNInfoAt(Idx) != VNI)
457 continue;
458
459 // Follow sibling copies down the dominator tree.
460 if (Register DstReg = isFullCopyOf(MI, Reg)) {
461 if (isSibling(DstReg)) {
462 LiveInterval &DstLI = LIS.getInterval(DstReg);
463 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
464 assert(DstVNI && "Missing defined value")((DstVNI && "Missing defined value") ? static_cast<
void> (0) : __assert_fail ("DstVNI && \"Missing defined value\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 464, __PRETTY_FUNCTION__))
;
465 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot")((DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot"
) ? static_cast<void> (0) : __assert_fail ("DstVNI->def == Idx.getRegSlot() && \"Wrong copy def slot\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 465, __PRETTY_FUNCTION__))
;
466 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
467 }
468 continue;
469 }
470
471 // Erase spills.
472 int FI;
473 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
474 LLVM_DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Redundant spill " << Idx
<< '\t' << MI; } } while (false)
;
475 // eliminateDeadDefs won't normally remove stores, so switch opcode.
476 MI.setDesc(TII.get(TargetOpcode::KILL));
477 DeadDefs.push_back(&MI);
478 ++NumSpillsRemoved;
479 if (HSpiller.rmFromMergeableSpills(MI, StackSlot))
480 --NumSpills;
481 }
482 }
483 } while (!WorkList.empty());
484}
485
486//===----------------------------------------------------------------------===//
487// Rematerialization
488//===----------------------------------------------------------------------===//
489
490/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
491/// instruction cannot be eliminated. See through snippet copies
492void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
493 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
494 WorkList.push_back(std::make_pair(LI, VNI));
495 do {
496 std::tie(LI, VNI) = WorkList.pop_back_val();
497 if (!UsedValues.insert(VNI).second)
498 continue;
499
500 if (VNI->isPHIDef()) {
501 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
502 for (MachineBasicBlock *P : MBB->predecessors()) {
503 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
504 if (PVNI)
505 WorkList.push_back(std::make_pair(LI, PVNI));
506 }
507 continue;
508 }
509
510 // Follow snippet copies.
511 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
512 if (!SnippetCopies.count(MI))
513 continue;
514 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
515 assert(isRegToSpill(SnipLI.reg()) && "Unexpected register in copy")((isRegToSpill(SnipLI.reg()) && "Unexpected register in copy"
) ? static_cast<void> (0) : __assert_fail ("isRegToSpill(SnipLI.reg()) && \"Unexpected register in copy\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 515, __PRETTY_FUNCTION__))
;
516 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
517 assert(SnipVNI && "Snippet undefined before copy")((SnipVNI && "Snippet undefined before copy") ? static_cast
<void> (0) : __assert_fail ("SnipVNI && \"Snippet undefined before copy\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 517, __PRETTY_FUNCTION__))
;
518 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
519 } while (!WorkList.empty());
520}
521
522bool InlineSpiller::canGuaranteeAssignmentAfterRemat(Register VReg,
523 MachineInstr &MI) {
524 if (!RestrictStatepointRemat)
525 return true;
526 // Here's a quick explanation of the problem we're trying to handle here:
527 // * There are some pseudo instructions with more vreg uses than there are
528 // physical registers on the machine.
529 // * This is normally handled by spilling the vreg, and folding the reload
530 // into the user instruction. (Thus decreasing the number of used vregs
531 // until the remainder can be assigned to physregs.)
532 // * However, since we may try to spill vregs in any order, we can end up
533 // trying to spill each operand to the instruction, and then rematting it
534 // instead. When that happens, the new live intervals (for the remats) are
535 // expected to be trivially assignable (i.e. RS_Done). However, since we
536 // may have more remats than physregs, we're guaranteed to fail to assign
537 // one.
538 // At the moment, we only handle this for STATEPOINTs since they're the only
539 // pseudo op where we've seen this. If we start seeing other instructions
540 // with the same problem, we need to revisit this.
541 if (MI.getOpcode() != TargetOpcode::STATEPOINT)
542 return true;
543 // For STATEPOINTs we allow re-materialization for fixed arguments only hoping
544 // that number of physical registers is enough to cover all fixed arguments.
545 // If it is not true we need to revisit it.
546 for (unsigned Idx = StatepointOpers(&MI).getVarIdx(),
547 EndIdx = MI.getNumOperands();
548 Idx < EndIdx; ++Idx) {
549 MachineOperand &MO = MI.getOperand(Idx);
550 if (MO.isReg() && MO.getReg() == VReg)
551 return false;
552 }
553 return true;
554}
555
556/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
557bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) {
558 // Analyze instruction
559 SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
560 VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, VirtReg.reg(), &Ops);
561
562 if (!RI.Reads)
563 return false;
564
565 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
566 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
567
568 if (!ParentVNI) {
569 LLVM_DEBUG(dbgs() << "\tadding <undef> flags: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tadding <undef> flags: "
; } } while (false)
;
570 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
571 MachineOperand &MO = MI.getOperand(i);
572 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg())
573 MO.setIsUndef();
574 }
575 LLVM_DEBUG(dbgs() << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << UseIdx << '\t' <<
MI; } } while (false)
;
576 return true;
577 }
578
579 if (SnippetCopies.count(&MI))
580 return false;
581
582 LiveInterval &OrigLI = LIS.getInterval(Original);
583 VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
584 LiveRangeEdit::Remat RM(ParentVNI);
585 RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
586
587 if (!Edit->canRematerializeAt(RM, OrigVNI, UseIdx, false)) {
588 markValueUsed(&VirtReg, ParentVNI);
589 LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tcannot remat for " <<
UseIdx << '\t' << MI; } } while (false)
;
590 return false;
591 }
592
593 // If the instruction also writes VirtReg.reg, it had better not require the
594 // same register for uses and defs.
595 if (RI.Tied) {
596 markValueUsed(&VirtReg, ParentVNI);
597 LLVM_DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tcannot remat tied reg: " <<
UseIdx << '\t' << MI; } } while (false)
;
598 return false;
599 }
600
601 // Before rematerializing into a register for a single instruction, try to
602 // fold a load into the instruction. That avoids allocating a new register.
603 if (RM.OrigMI->canFoldAsLoad() &&
604 foldMemoryOperand(Ops, RM.OrigMI)) {
605 Edit->markRematerialized(RM.ParentVNI);
606 ++NumFoldedLoads;
607 return true;
608 }
609
610 // If we can't guarantee that we'll be able to actually assign the new vreg,
611 // we can't remat.
612 if (!canGuaranteeAssignmentAfterRemat(VirtReg.reg(), MI)) {
613 markValueUsed(&VirtReg, ParentVNI);
614 LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tcannot remat for " <<
UseIdx << '\t' << MI; } } while (false)
;
615 return false;
616 }
617
618 // Allocate a new register for the remat.
619 Register NewVReg = Edit->createFrom(Original);
620
621 // Finally we can rematerialize OrigMI before MI.
622 SlotIndex DefIdx =
623 Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM, TRI);
624
625 // We take the DebugLoc from MI, since OrigMI may be attributed to a
626 // different source location.
627 auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
628 NewMI->setDebugLoc(MI.getDebugLoc());
629
630 (void)DefIdx;
631 LLVM_DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremat: " << DefIdx <<
'\t' << *LIS.getInstructionFromIndex(DefIdx); } } while
(false)
632 << *LIS.getInstructionFromIndex(DefIdx))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\tremat: " << DefIdx <<
'\t' << *LIS.getInstructionFromIndex(DefIdx); } } while
(false)
;
633
634 // Replace operands
635 for (const auto &OpPair : Ops) {
636 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
637 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg()) {
638 MO.setReg(NewVReg);
639 MO.setIsKill();
640 }
641 }
642 LLVM_DEBUG(dbgs() << "\t " << UseIdx << '\t' << MI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\t " << UseIdx <<
'\t' << MI << '\n'; } } while (false)
;
643
644 ++NumRemats;
645 return true;
646}
647
648/// reMaterializeAll - Try to rematerialize as many uses as possible,
649/// and trim the live ranges after.
650void InlineSpiller::reMaterializeAll() {
651 if (!Edit->anyRematerializable(AA))
652 return;
653
654 UsedValues.clear();
655
656 // Try to remat before all uses of snippets.
657 bool anyRemat = false;
658 for (Register Reg : RegsToSpill) {
659 LiveInterval &LI = LIS.getInterval(Reg);
660 for (MachineRegisterInfo::reg_bundle_iterator
661 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
662 RegI != E; ) {
663 MachineInstr &MI = *RegI++;
664
665 // Debug values are not allowed to affect codegen.
666 if (MI.isDebugValue())
667 continue;
668
669 assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "((!MI.isDebugInstr() && "Did not expect to find a use in debug "
"instruction that isn't a DBG_VALUE") ? static_cast<void>
(0) : __assert_fail ("!MI.isDebugInstr() && \"Did not expect to find a use in debug \" \"instruction that isn't a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 670, __PRETTY_FUNCTION__))
670 "instruction that isn't a DBG_VALUE")((!MI.isDebugInstr() && "Did not expect to find a use in debug "
"instruction that isn't a DBG_VALUE") ? static_cast<void>
(0) : __assert_fail ("!MI.isDebugInstr() && \"Did not expect to find a use in debug \" \"instruction that isn't a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 670, __PRETTY_FUNCTION__))
;
671
672 anyRemat |= reMaterializeFor(LI, MI);
673 }
674 }
675 if (!anyRemat)
676 return;
677
678 // Remove any values that were completely rematted.
679 for (Register Reg : RegsToSpill) {
680 LiveInterval &LI = LIS.getInterval(Reg);
681 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
682 I != E; ++I) {
683 VNInfo *VNI = *I;
684 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
685 continue;
686 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
687 MI->addRegisterDead(Reg, &TRI);
688 if (!MI->allDefsAreDead())
689 continue;
690 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "All defs dead: " << *MI
; } } while (false)
;
691 DeadDefs.push_back(MI);
692 }
693 }
694
695 // Eliminate dead code after remat. Note that some snippet copies may be
696 // deleted here.
697 if (DeadDefs.empty())
698 return;
699 LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Remat created " << DeadDefs
.size() << " dead defs.\n"; } } while (false)
;
700 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
701
702 // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
703 // after rematerialization. To remove a VNI for a vreg from its LiveInterval,
704 // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
705 // removed, PHI VNI are still left in the LiveInterval.
706 // So to get rid of unused reg, we need to check whether it has non-dbg
707 // reference instead of whether it has non-empty interval.
708 unsigned ResultPos = 0;
709 for (Register Reg : RegsToSpill) {
710 if (MRI.reg_nodbg_empty(Reg)) {
711 Edit->eraseVirtReg(Reg);
712 continue;
713 }
714
715 assert(LIS.hasInterval(Reg) &&((LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty
() || !MRI.reg_nodbg_empty(Reg)) && "Empty and not used live-range?!"
) ? static_cast<void> (0) : __assert_fail ("LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) && \"Empty and not used live-range?!\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 717, __PRETTY_FUNCTION__))
716 (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&((LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty
() || !MRI.reg_nodbg_empty(Reg)) && "Empty and not used live-range?!"
) ? static_cast<void> (0) : __assert_fail ("LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) && \"Empty and not used live-range?!\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 717, __PRETTY_FUNCTION__))
717 "Empty and not used live-range?!")((LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty
() || !MRI.reg_nodbg_empty(Reg)) && "Empty and not used live-range?!"
) ? static_cast<void> (0) : __assert_fail ("LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) && \"Empty and not used live-range?!\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 717, __PRETTY_FUNCTION__))
;
718
719 RegsToSpill[ResultPos++] = Reg;
720 }
721 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
722 LLVM_DEBUG(dbgs() << RegsToSpill.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << RegsToSpill.size() << " registers to spill after remat.\n"
; } } while (false)
723 << " registers to spill after remat.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << RegsToSpill.size() << " registers to spill after remat.\n"
; } } while (false)
;
724}
725
726//===----------------------------------------------------------------------===//
727// Spilling
728//===----------------------------------------------------------------------===//
729
730/// If MI is a load or store of StackSlot, it can be removed.
731bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
732 int FI = 0;
733 Register InstrReg = TII.isLoadFromStackSlot(*MI, FI);
734 bool IsLoad = InstrReg;
735 if (!IsLoad)
736 InstrReg = TII.isStoreToStackSlot(*MI, FI);
737
738 // We have a stack access. Is it the right register and slot?
739 if (InstrReg != Reg || FI != StackSlot)
740 return false;
741
742 if (!IsLoad)
743 HSpiller.rmFromMergeableSpills(*MI, StackSlot);
744
745 LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Coalescing stack access: " <<
*MI; } } while (false)
;
746 LIS.RemoveMachineInstrFromMaps(*MI);
747 MI->eraseFromParent();
748
749 if (IsLoad) {
750 ++NumReloadsRemoved;
751 --NumReloads;
752 } else {
753 ++NumSpillsRemoved;
754 --NumSpills;
755 }
756
757 return true;
758}
759
760#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
761LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__))
762// Dump the range of instructions from B to E with their slot indexes.
763static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
764 MachineBasicBlock::iterator E,
765 LiveIntervals const &LIS,
766 const char *const header,
767 Register VReg = Register()) {
768 char NextLine = '\n';
769 char SlotIndent = '\t';
770
771 if (std::next(B) == E) {
772 NextLine = ' ';
773 SlotIndent = ' ';
774 }
775
776 dbgs() << '\t' << header << ": " << NextLine;
777
778 for (MachineBasicBlock::iterator I = B; I != E; ++I) {
779 SlotIndex Idx = LIS.getInstructionIndex(*I).getRegSlot();
780
781 // If a register was passed in and this instruction has it as a
782 // destination that is marked as an early clobber, print the
783 // early-clobber slot index.
784 if (VReg) {
785 MachineOperand *MO = I->findRegisterDefOperand(VReg);
786 if (MO && MO->isEarlyClobber())
787 Idx = Idx.getRegSlot(true);
788 }
789
790 dbgs() << SlotIndent << Idx << '\t' << *I;
791 }
792}
793#endif
794
795/// foldMemoryOperand - Try folding stack slot references in Ops into their
796/// instructions.
797///
798/// @param Ops Operand indices from AnalyzeVirtRegInBundle().
799/// @param LoadMI Load instruction to use instead of stack slot when non-null.
800/// @return True on success.
801bool InlineSpiller::
802foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
803 MachineInstr *LoadMI) {
804 if (Ops.empty())
805 return false;
806 // Don't attempt folding in bundles.
807 MachineInstr *MI = Ops.front().first;
808 if (Ops.back().first != MI || MI->isBundled())
809 return false;
810
811 bool WasCopy = MI->isCopy();
812 Register ImpReg;
813
814 // TII::foldMemoryOperand will do what we need here for statepoint
815 // (fold load into use and remove corresponding def). We will replace
816 // uses of removed def with loads (spillAroundUses).
817 // For that to work we need to untie def and use to pass it through
818 // foldMemoryOperand and signal foldPatchpoint that it is allowed to
819 // fold them.
820 bool UntieRegs = MI->getOpcode() == TargetOpcode::STATEPOINT;
821
822 // Spill subregs if the target allows it.
823 // We always want to spill subregs for stackmap/patchpoint pseudos.
824 bool SpillSubRegs = TII.isSubregFoldable() ||
825 MI->getOpcode() == TargetOpcode::STATEPOINT ||
826 MI->getOpcode() == TargetOpcode::PATCHPOINT ||
827 MI->getOpcode() == TargetOpcode::STACKMAP;
828
829 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
830 // operands.
831 SmallVector<unsigned, 8> FoldOps;
832 for (const auto &OpPair : Ops) {
833 unsigned Idx = OpPair.second;
834 assert(MI == OpPair.first && "Instruction conflict during operand folding")((MI == OpPair.first && "Instruction conflict during operand folding"
) ? static_cast<void> (0) : __assert_fail ("MI == OpPair.first && \"Instruction conflict during operand folding\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 834, __PRETTY_FUNCTION__))
;
835 MachineOperand &MO = MI->getOperand(Idx);
836 if (MO.isImplicit()) {
837 ImpReg = MO.getReg();
838 continue;
839 }
840
841 if (UntieRegs && MO.isTied())
842 MI->untieRegOperand(Idx);
843
844 if (!SpillSubRegs && MO.getSubReg())
845 return false;
846 // We cannot fold a load instruction into a def.
847 if (LoadMI && MO.isDef())
848 return false;
849 // Tied use operands should not be passed to foldMemoryOperand.
850 if (!MI->isRegTiedToDefOperand(Idx))
851 FoldOps.push_back(Idx);
852 }
853
854 // If we only have implicit uses, we won't be able to fold that.
855 // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
856 if (FoldOps.empty())
857 return false;
858
859 MachineInstrSpan MIS(MI, MI->getParent());
860
861 MachineInstr *FoldMI =
862 LoadMI ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, &LIS)
863 : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, &LIS, &VRM);
864 if (!FoldMI)
865 return false;
866
867 // Remove LIS for any dead defs in the original MI not in FoldMI.
868 for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
869 if (!MO->isReg())
870 continue;
871 Register Reg = MO->getReg();
872 if (!Reg || Register::isVirtualRegister(Reg) || MRI.isReserved(Reg)) {
873 continue;
874 }
875 // Skip non-Defs, including undef uses and internal reads.
876 if (MO->isUse())
877 continue;
878 PhysRegInfo RI = AnalyzePhysRegInBundle(*FoldMI, Reg, &TRI);
879 if (RI.FullyDefined)
880 continue;
881 // FoldMI does not define this physreg. Remove the LI segment.
882 assert(MO->isDead() && "Cannot fold physreg def")((MO->isDead() && "Cannot fold physreg def") ? static_cast
<void> (0) : __assert_fail ("MO->isDead() && \"Cannot fold physreg def\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 882, __PRETTY_FUNCTION__))
;
883 SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
884 LIS.removePhysRegDefAt(Reg.asMCReg(), Idx);
885 }
886
887 int FI;
888 if (TII.isStoreToStackSlot(*MI, FI) &&
889 HSpiller.rmFromMergeableSpills(*MI, FI))
890 --NumSpills;
891 LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
892 // Update the call site info.
893 if (MI->isCandidateForCallSiteEntry())
894 MI->getMF()->moveCallSiteInfo(MI, FoldMI);
895 MI->eraseFromParent();
896
897 // Insert any new instructions other than FoldMI into the LIS maps.
898 assert(!MIS.empty() && "Unexpected empty span of instructions!")((!MIS.empty() && "Unexpected empty span of instructions!"
) ? static_cast<void> (0) : __assert_fail ("!MIS.empty() && \"Unexpected empty span of instructions!\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 898, __PRETTY_FUNCTION__))
;
899 for (MachineInstr &MI : MIS)
900 if (&MI != FoldMI)
901 LIS.InsertMachineInstrInMaps(MI);
902
903 // TII.foldMemoryOperand may have left some implicit operands on the
904 // instruction. Strip them.
905 if (ImpReg)
906 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
907 MachineOperand &MO = FoldMI->getOperand(i - 1);
908 if (!MO.isReg() || !MO.isImplicit())
909 break;
910 if (MO.getReg() == ImpReg)
911 FoldMI->RemoveOperand(i - 1);
912 }
913
914 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(MIS.begin(
), MIS.end(), LIS, "folded"); } } while (false)
915 "folded"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(MIS.begin(
), MIS.end(), LIS, "folded"); } } while (false)
;
916
917 if (!WasCopy)
918 ++NumFolded;
919 else if (Ops.front().second == 0) {
920 ++NumSpills;
921 HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
922 } else
923 ++NumReloads;
924 return true;
925}
926
927void InlineSpiller::insertReload(Register NewVReg,
928 SlotIndex Idx,
929 MachineBasicBlock::iterator MI) {
930 MachineBasicBlock &MBB = *MI->getParent();
931
932 MachineInstrSpan MIS(MI, &MBB);
933 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
934 MRI.getRegClass(NewVReg), &TRI);
935
936 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
937
938 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(MIS.begin(
), MI, LIS, "reload", NewVReg); } } while (false)
939 NewVReg))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(MIS.begin(
), MI, LIS, "reload", NewVReg); } } while (false)
;
940 ++NumReloads;
941}
942
943/// Check if \p Def fully defines a VReg with an undefined value.
944/// If that's the case, that means the value of VReg is actually
945/// not relevant.
946static bool isRealSpill(const MachineInstr &Def) {
947 if (!Def.isImplicitDef())
948 return true;
949 assert(Def.getNumOperands() == 1 &&((Def.getNumOperands() == 1 && "Implicit def with more than one definition"
) ? static_cast<void> (0) : __assert_fail ("Def.getNumOperands() == 1 && \"Implicit def with more than one definition\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 950, __PRETTY_FUNCTION__))
950 "Implicit def with more than one definition")((Def.getNumOperands() == 1 && "Implicit def with more than one definition"
) ? static_cast<void> (0) : __assert_fail ("Def.getNumOperands() == 1 && \"Implicit def with more than one definition\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 950, __PRETTY_FUNCTION__))
;
951 // We can say that the VReg defined by Def is undef, only if it is
952 // fully defined by Def. Otherwise, some of the lanes may not be
953 // undef and the value of the VReg matters.
954 return Def.getOperand(0).getSubReg();
955}
956
957/// insertSpill - Insert a spill of NewVReg after MI.
958void InlineSpiller::insertSpill(Register NewVReg, bool isKill,
959 MachineBasicBlock::iterator MI) {
960 // Spill are not terminators, so inserting spills after terminators will
961 // violate invariants in MachineVerifier.
962 assert(!MI->isTerminator() && "Inserting a spill after a terminator")((!MI->isTerminator() && "Inserting a spill after a terminator"
) ? static_cast<void> (0) : __assert_fail ("!MI->isTerminator() && \"Inserting a spill after a terminator\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 962, __PRETTY_FUNCTION__))
;
963 MachineBasicBlock &MBB = *MI->getParent();
964
965 MachineInstrSpan MIS(MI, &MBB);
966 MachineBasicBlock::iterator SpillBefore = std::next(MI);
967 bool IsRealSpill = isRealSpill(*MI);
968 if (IsRealSpill)
969 TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot,
970 MRI.getRegClass(NewVReg), &TRI);
971 else
972 // Don't spill undef value.
973 // Anything works for undef, in particular keeping the memory
974 // uninitialized is a viable option and it saves code size and
975 // run time.
976 BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
977 .addReg(NewVReg, getKillRegState(isKill));
978
979 MachineBasicBlock::iterator Spill = std::next(MI);
980 LIS.InsertMachineInstrRangeInMaps(Spill, MIS.end());
981
982 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(Spill, MIS
.end(), LIS, "spill"); } } while (false)
983 dumpMachineInstrRangeWithSlotIndex(Spill, MIS.end(), LIS, "spill"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dumpMachineInstrRangeWithSlotIndex(Spill, MIS
.end(), LIS, "spill"); } } while (false)
;
984 ++NumSpills;
985 if (IsRealSpill)
986 HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
987}
988
989/// spillAroundUses - insert spill code around each use of Reg.
990void InlineSpiller::spillAroundUses(Register Reg) {
991 LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "spillAroundUses " << printReg
(Reg) << '\n'; } } while (false)
;
992 LiveInterval &OldLI = LIS.getInterval(Reg);
993
994 // Iterate over instructions using Reg.
995 for (MachineRegisterInfo::reg_bundle_iterator
996 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
997 RegI != E; ) {
998 MachineInstr *MI = &*(RegI++);
999
1000 // Debug values are not allowed to affect codegen.
1001 if (MI->isDebugValue()) {
1002 // Modify DBG_VALUE now that the value is in a spill slot.
1003 MachineBasicBlock *MBB = MI->getParent();
1004 LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Modifying debug info due to spill:\t"
<< *MI; } } while (false)
;
1005 buildDbgValueForSpill(*MBB, MI, *MI, StackSlot);
1006 MBB->erase(MI);
1007 continue;
1008 }
1009
1010 assert(!MI->isDebugInstr() && "Did not expect to find a use in debug "((!MI->isDebugInstr() && "Did not expect to find a use in debug "
"instruction that isn't a DBG_VALUE") ? static_cast<void>
(0) : __assert_fail ("!MI->isDebugInstr() && \"Did not expect to find a use in debug \" \"instruction that isn't a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1011, __PRETTY_FUNCTION__))
1011 "instruction that isn't a DBG_VALUE")((!MI->isDebugInstr() && "Did not expect to find a use in debug "
"instruction that isn't a DBG_VALUE") ? static_cast<void>
(0) : __assert_fail ("!MI->isDebugInstr() && \"Did not expect to find a use in debug \" \"instruction that isn't a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1011, __PRETTY_FUNCTION__))
;
1012
1013 // Ignore copies to/from snippets. We'll delete them.
1014 if (SnippetCopies.count(MI))
1015 continue;
1016
1017 // Stack slot accesses may coalesce away.
1018 if (coalesceStackAccess(MI, Reg))
1019 continue;
1020
1021 // Analyze instruction.
1022 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1023 VirtRegInfo RI = AnalyzeVirtRegInBundle(*MI, Reg, &Ops);
1024
1025 // Find the slot index where this instruction reads and writes OldLI.
1026 // This is usually the def slot, except for tied early clobbers.
1027 SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
1028 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1029 if (SlotIndex::isSameInstr(Idx, VNI->def))
1030 Idx = VNI->def;
1031
1032 // Check for a sibling copy.
1033 Register SibReg = isFullCopyOf(*MI, Reg);
1034 if (SibReg && isSibling(SibReg)) {
1035 // This may actually be a copy between snippets.
1036 if (isRegToSpill(SibReg)) {
1037 LLVM_DEBUG(dbgs() << "Found new snippet copy: " << *MI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Found new snippet copy: " <<
*MI; } } while (false)
;
1038 SnippetCopies.insert(MI);
1039 continue;
1040 }
1041 if (RI.Writes) {
1042 if (hoistSpillInsideBB(OldLI, *MI)) {
1043 // This COPY is now dead, the value is already in the stack slot.
1044 MI->getOperand(0).setIsDead();
1045 DeadDefs.push_back(MI);
1046 continue;
1047 }
1048 } else {
1049 // This is a reload for a sib-reg copy. Drop spills downstream.
1050 LiveInterval &SibLI = LIS.getInterval(SibReg);
1051 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1052 // The COPY will fold to a reload below.
1053 }
1054 }
1055
1056 // Attempt to fold memory ops.
1057 if (foldMemoryOperand(Ops))
1058 continue;
1059
1060 // Create a new virtual register for spill/fill.
1061 // FIXME: Infer regclass from instruction alone.
1062 Register NewVReg = Edit->createFrom(Reg);
1063
1064 if (RI.Reads)
1065 insertReload(NewVReg, Idx, MI);
1066
1067 // Rewrite instruction operands.
1068 bool hasLiveDef = false;
1069 for (const auto &OpPair : Ops) {
1070 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1071 MO.setReg(NewVReg);
1072 if (MO.isUse()) {
1073 if (!OpPair.first->isRegTiedToDefOperand(OpPair.second))
1074 MO.setIsKill();
1075 } else {
1076 if (!MO.isDead())
1077 hasLiveDef = true;
1078 }
1079 }
1080 LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\trewrite: " << Idx <<
'\t' << *MI << '\n'; } } while (false)
;
1081
1082 // FIXME: Use a second vreg if instruction has no tied ops.
1083 if (RI.Writes)
1084 if (hasLiveDef)
1085 insertSpill(NewVReg, true, MI);
1086 }
1087}
1088
1089/// spillAll - Spill all registers remaining after rematerialization.
1090void InlineSpiller::spillAll() {
1091 // Update LiveStacks now that we are committed to spilling.
1092 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1093 StackSlot = VRM.assignVirt2StackSlot(Original);
1094 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1095 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1096 } else
1097 StackInt = &LSS.getInterval(StackSlot);
1098
1099 if (Original != Edit->getReg())
1100 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1101
1102 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values")((StackInt->getNumValNums() == 1 && "Bad stack interval values"
) ? static_cast<void> (0) : __assert_fail ("StackInt->getNumValNums() == 1 && \"Bad stack interval values\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1102, __PRETTY_FUNCTION__))
;
1103 for (Register Reg : RegsToSpill)
1104 StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
1105 StackInt->getValNumInfo(0));
1106 LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Merged spilled regs: " <<
*StackInt << '\n'; } } while (false)
;
1107
1108 // Spill around uses of all RegsToSpill.
1109 for (Register Reg : RegsToSpill)
1110 spillAroundUses(Reg);
1111
1112 // Hoisted spills may cause dead code.
1113 if (!DeadDefs.empty()) {
1114 LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Eliminating " << DeadDefs
.size() << " dead defs\n"; } } while (false)
;
1115 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
1116 }
1117
1118 // Finally delete the SnippetCopies.
1119 for (Register Reg : RegsToSpill) {
1120 for (MachineRegisterInfo::reg_instr_iterator
1121 RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end();
1122 RI != E; ) {
1123 MachineInstr &MI = *(RI++);
1124 assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy")((SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy"
) ? static_cast<void> (0) : __assert_fail ("SnippetCopies.count(&MI) && \"Remaining use wasn't a snippet copy\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1124, __PRETTY_FUNCTION__))
;
1125 // FIXME: Do this with a LiveRangeEdit callback.
1126 LIS.RemoveMachineInstrFromMaps(MI);
1127 MI.eraseFromParent();
1128 }
1129 }
1130
1131 // Delete all spilled registers.
1132 for (Register Reg : RegsToSpill)
1133 Edit->eraseVirtReg(Reg);
1134}
1135
1136void InlineSpiller::spill(LiveRangeEdit &edit) {
1137 ++NumSpilledRanges;
1138 Edit = &edit;
1139 assert(!Register::isStackSlot(edit.getReg()) &&((!Register::isStackSlot(edit.getReg()) && "Trying to spill a stack slot."
) ? static_cast<void> (0) : __assert_fail ("!Register::isStackSlot(edit.getReg()) && \"Trying to spill a stack slot.\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1140, __PRETTY_FUNCTION__))
1140 "Trying to spill a stack slot.")((!Register::isStackSlot(edit.getReg()) && "Trying to spill a stack slot."
) ? static_cast<void> (0) : __assert_fail ("!Register::isStackSlot(edit.getReg()) && \"Trying to spill a stack slot.\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1140, __PRETTY_FUNCTION__))
;
1141 // Share a stack slot among all descendants of Original.
1142 Original = VRM.getOriginal(edit.getReg());
1143 StackSlot = VRM.getStackSlot(Original);
1144 StackInt = nullptr;
1145
1146 LLVM_DEBUG(dbgs() << "Inline spilling "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Inline spilling " << TRI
.getRegClassName(MRI.getRegClass(edit.getReg())) << ':'
<< edit.getParent() << "\nFrom original " <<
printReg(Original) << '\n'; } } while (false)
1147 << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Inline spilling " << TRI
.getRegClassName(MRI.getRegClass(edit.getReg())) << ':'
<< edit.getParent() << "\nFrom original " <<
printReg(Original) << '\n'; } } while (false)
1148 << ':' << edit.getParent() << "\nFrom original "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Inline spilling " << TRI
.getRegClassName(MRI.getRegClass(edit.getReg())) << ':'
<< edit.getParent() << "\nFrom original " <<
printReg(Original) << '\n'; } } while (false)
1149 << printReg(Original) << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Inline spilling " << TRI
.getRegClassName(MRI.getRegClass(edit.getReg())) << ':'
<< edit.getParent() << "\nFrom original " <<
printReg(Original) << '\n'; } } while (false)
;
1150 assert(edit.getParent().isSpillable() &&((edit.getParent().isSpillable() && "Attempting to spill already spilled value."
) ? static_cast<void> (0) : __assert_fail ("edit.getParent().isSpillable() && \"Attempting to spill already spilled value.\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1151, __PRETTY_FUNCTION__))
1151 "Attempting to spill already spilled value.")((edit.getParent().isSpillable() && "Attempting to spill already spilled value."
) ? static_cast<void> (0) : __assert_fail ("edit.getParent().isSpillable() && \"Attempting to spill already spilled value.\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1151, __PRETTY_FUNCTION__))
;
1152 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs")((DeadDefs.empty() && "Previous spill didn't remove dead defs"
) ? static_cast<void> (0) : __assert_fail ("DeadDefs.empty() && \"Previous spill didn't remove dead defs\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1152, __PRETTY_FUNCTION__))
;
1153
1154 collectRegsToSpill();
1155 reMaterializeAll();
1156
1157 // Remat may handle everything.
1158 if (!RegsToSpill.empty())
1159 spillAll();
1160
1161 Edit->calculateRegClassAndHint(MF, Loops, MBFI);
1162}
1163
1164/// Optimizations after all the reg selections and spills are done.
1165void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
1166
1167/// When a spill is inserted, add the spill to MergeableSpills map.
1168void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
1169 unsigned Original) {
1170 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1171 LiveInterval &OrigLI = LIS.getInterval(Original);
1172 // save a copy of LiveInterval in StackSlotToOrigLI because the original
1173 // LiveInterval may be cleared after all its references are spilled.
1174 if (StackSlotToOrigLI.find(StackSlot) == StackSlotToOrigLI.end()) {
1175 auto LI = std::make_unique<LiveInterval>(OrigLI.reg(), OrigLI.weight());
1176 LI->assign(OrigLI, Allocator);
1177 StackSlotToOrigLI[StackSlot] = std::move(LI);
1178 }
1179 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1180 VNInfo *OrigVNI = StackSlotToOrigLI[StackSlot]->getVNInfoAt(Idx.getRegSlot());
1181 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1182 MergeableSpills[MIdx].insert(&Spill);
1183}
1184
1185/// When a spill is removed, remove the spill from MergeableSpills map.
1186/// Return true if the spill is removed successfully.
1187bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
1188 int StackSlot) {
1189 auto It = StackSlotToOrigLI.find(StackSlot);
1190 if (It == StackSlotToOrigLI.end())
1191 return false;
1192 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1193 VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
1194 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1195 return MergeableSpills[MIdx].erase(&Spill);
1196}
1197
1198/// Check BB to see if it is a possible target BB to place a hoisted spill,
1199/// i.e., there should be a living sibling of OrigReg at the insert point.
1200bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
1201 MachineBasicBlock &BB, Register &LiveReg) {
1202 SlotIndex Idx;
1203 Register OrigReg = OrigLI.reg();
1204 MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, BB);
1205 if (MI != BB.end())
1206 Idx = LIS.getInstructionIndex(*MI);
1207 else
1208 Idx = LIS.getMBBEndIdx(&BB).getPrevSlot();
1209 SmallSetVector<Register, 16> &Siblings = Virt2SiblingsMap[OrigReg];
1210 assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI")((OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI"
) ? static_cast<void> (0) : __assert_fail ("OrigLI.getVNInfoAt(Idx) == &OrigVNI && \"Unexpected VNI\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1210, __PRETTY_FUNCTION__))
;
1211
1212 for (const Register &SibReg : Siblings) {
1213 LiveInterval &LI = LIS.getInterval(SibReg);
1214 VNInfo *VNI = LI.getVNInfoAt(Idx);
1215 if (VNI) {
1216 LiveReg = SibReg;
1217 return true;
1218 }
1219 }
1220 return false;
1221}
1222
1223/// Remove redundant spills in the same BB. Save those redundant spills in
1224/// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map.
1225void HoistSpillHelper::rmRedundantSpills(
1226 SmallPtrSet<MachineInstr *, 16> &Spills,
1227 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1228 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1229 // For each spill saw, check SpillBBToSpill[] and see if its BB already has
1230 // another spill inside. If a BB contains more than one spill, only keep the
1231 // earlier spill with smaller SlotIndex.
1232 for (const auto CurrentSpill : Spills) {
1233 MachineBasicBlock *Block = CurrentSpill->getParent();
1234 MachineDomTreeNode *Node = MDT.getBase().getNode(Block);
1235 MachineInstr *PrevSpill = SpillBBToSpill[Node];
1236 if (PrevSpill) {
1237 SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
1238 SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
1239 MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
1240 MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
1241 SpillsToRm.push_back(SpillToRm);
1242 SpillBBToSpill[MDT.getBase().getNode(Block)] = SpillToKeep;
1243 } else {
1244 SpillBBToSpill[MDT.getBase().getNode(Block)] = CurrentSpill;
1245 }
1246 }
1247 for (const auto SpillToRm : SpillsToRm)
1248 Spills.erase(SpillToRm);
1249}
1250
1251/// Starting from \p Root find a top-down traversal order of the dominator
1252/// tree to visit all basic blocks containing the elements of \p Spills.
1253/// Redundant spills will be found and put into \p SpillsToRm at the same
1254/// time. \p SpillBBToSpill will be populated as part of the process and
1255/// maps a basic block to the first store occurring in the basic block.
1256/// \post SpillsToRm.union(Spills\@post) == Spills\@pre
1257void HoistSpillHelper::getVisitOrders(
1258 MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
1259 SmallVectorImpl<MachineDomTreeNode *> &Orders,
1260 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1261 DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
1262 DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1263 // The set contains all the possible BB nodes to which we may hoist
1264 // original spills.
1265 SmallPtrSet<MachineDomTreeNode *, 8> WorkSet;
1266 // Save the BB nodes on the path from the first BB node containing
1267 // non-redundant spill to the Root node.
1268 SmallPtrSet<MachineDomTreeNode *, 8> NodesOnPath;
1269 // All the spills to be hoisted must originate from a single def instruction
1270 // to the OrigReg. It means the def instruction should dominate all the spills
1271 // to be hoisted. We choose the BB where the def instruction is located as
1272 // the Root.
1273 MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
1274 // For every node on the dominator tree with spill, walk up on the dominator
1275 // tree towards the Root node until it is reached. If there is other node
1276 // containing spill in the middle of the path, the previous spill saw will
1277 // be redundant and the node containing it will be removed. All the nodes on
1278 // the path starting from the first node with non-redundant spill to the Root
1279 // node will be added to the WorkSet, which will contain all the possible
1280 // locations where spills may be hoisted to after the loop below is done.
1281 for (const auto Spill : Spills) {
1282 MachineBasicBlock *Block = Spill->getParent();
1283 MachineDomTreeNode *Node = MDT[Block];
1284 MachineInstr *SpillToRm = nullptr;
1285 while (Node != RootIDomNode) {
1286 // If Node dominates Block, and it already contains a spill, the spill in
1287 // Block will be redundant.
1288 if (Node != MDT[Block] && SpillBBToSpill[Node]) {
1289 SpillToRm = SpillBBToSpill[MDT[Block]];
1290 break;
1291 /// If we see the Node already in WorkSet, the path from the Node to
1292 /// the Root node must already be traversed by another spill.
1293 /// Then no need to repeat.
1294 } else if (WorkSet.count(Node)) {
1295 break;
1296 } else {
1297 NodesOnPath.insert(Node);
1298 }
1299 Node = Node->getIDom();
1300 }
1301 if (SpillToRm) {
1302 SpillsToRm.push_back(SpillToRm);
1303 } else {
1304 // Add a BB containing the original spills to SpillsToKeep -- i.e.,
1305 // set the initial status before hoisting start. The value of BBs
1306 // containing original spills is set to 0, in order to descriminate
1307 // with BBs containing hoisted spills which will be inserted to
1308 // SpillsToKeep later during hoisting.
1309 SpillsToKeep[MDT[Block]] = 0;
1310 WorkSet.insert(NodesOnPath.begin(), NodesOnPath.end());
1311 }
1312 NodesOnPath.clear();
1313 }
1314
1315 // Sort the nodes in WorkSet in top-down order and save the nodes
1316 // in Orders. Orders will be used for hoisting in runHoistSpills.
1317 unsigned idx = 0;
1318 Orders.push_back(MDT.getBase().getNode(Root));
1319 do {
1320 MachineDomTreeNode *Node = Orders[idx++];
1321 for (MachineDomTreeNode *Child : Node->children()) {
1322 if (WorkSet.count(Child))
1323 Orders.push_back(Child);
1324 }
1325 } while (idx != Orders.size());
1326 assert(Orders.size() == WorkSet.size() &&((Orders.size() == WorkSet.size() && "Orders have different size with WorkSet"
) ? static_cast<void> (0) : __assert_fail ("Orders.size() == WorkSet.size() && \"Orders have different size with WorkSet\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1327, __PRETTY_FUNCTION__))
1327 "Orders have different size with WorkSet")((Orders.size() == WorkSet.size() && "Orders have different size with WorkSet"
) ? static_cast<void> (0) : __assert_fail ("Orders.size() == WorkSet.size() && \"Orders have different size with WorkSet\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1327, __PRETTY_FUNCTION__))
;
1328
1329#ifndef NDEBUG
1330 LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "Orders size is " << Orders
.size() << "\n"; } } while (false)
;
1331 SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1332 for (; RIt != Orders.rend(); RIt++)
1333 LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "BB" << (*RIt)->getBlock
()->getNumber() << ","; } } while (false)
;
1334 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { dbgs() << "\n"; } } while (false)
;
1335#endif
1336}
1337
1338/// Try to hoist spills according to BB hotness. The spills to removed will
1339/// be saved in \p SpillsToRm. The spills to be inserted will be saved in
1340/// \p SpillsToIns.
1341void HoistSpillHelper::runHoistSpills(
1342 LiveInterval &OrigLI, VNInfo &OrigVNI,
1343 SmallPtrSet<MachineInstr *, 16> &Spills,
1344 SmallVectorImpl<MachineInstr *> &SpillsToRm,
1345 DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns) {
1346 // Visit order of dominator tree nodes.
1347 SmallVector<MachineDomTreeNode *, 32> Orders;
1348 // SpillsToKeep contains all the nodes where spills are to be inserted
1349 // during hoisting. If the spill to be inserted is an original spill
1350 // (not a hoisted one), the value of the map entry is 0. If the spill
1351 // is a hoisted spill, the value of the map entry is the VReg to be used
1352 // as the source of the spill.
1353 DenseMap<MachineDomTreeNode *, unsigned> SpillsToKeep;
1354 // Map from BB to the first spill inside of it.
1355 DenseMap<MachineDomTreeNode *, MachineInstr *> SpillBBToSpill;
1356
1357 rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
1358
1359 MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
1360 getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
1361 SpillBBToSpill);
1362
1363 // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
1364 // nodes set and the cost of all the spills inside those nodes.
1365 // The nodes set are the locations where spills are to be inserted
1366 // in the subtree of current node.
1367 using NodesCostPair =
1368 std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
1369 DenseMap<MachineDomTreeNode *, NodesCostPair> SpillsInSubTreeMap;
1370
1371 // Iterate Orders set in reverse order, which will be a bottom-up order
1372 // in the dominator tree. Once we visit a dom tree node, we know its
1373 // children have already been visited and the spill locations in the
1374 // subtrees of all the children have been determined.
1375 SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1376 for (; RIt != Orders.rend(); RIt++) {
1377 MachineBasicBlock *Block = (*RIt)->getBlock();
1378
1379 // If Block contains an original spill, simply continue.
1380 if (SpillsToKeep.find(*RIt) != SpillsToKeep.end() && !SpillsToKeep[*RIt]) {
1381 SpillsInSubTreeMap[*RIt].first.insert(*RIt);
1382 // SpillsInSubTreeMap[*RIt].second contains the cost of spill.
1383 SpillsInSubTreeMap[*RIt].second = MBFI.getBlockFreq(Block);
1384 continue;
1385 }
1386
1387 // Collect spills in subtree of current node (*RIt) to
1388 // SpillsInSubTreeMap[*RIt].first.
1389 for (MachineDomTreeNode *Child : (*RIt)->children()) {
1390 if (SpillsInSubTreeMap.find(Child) == SpillsInSubTreeMap.end())
1391 continue;
1392 // The stmt "SpillsInSubTree = SpillsInSubTreeMap[*RIt].first" below
1393 // should be placed before getting the begin and end iterators of
1394 // SpillsInSubTreeMap[Child].first, or else the iterators may be
1395 // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
1396 // and the map grows and then the original buckets in the map are moved.
1397 SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1398 SpillsInSubTreeMap[*RIt].first;
1399 BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1400 SubTreeCost += SpillsInSubTreeMap[Child].second;
1401 auto BI = SpillsInSubTreeMap[Child].first.begin();
1402 auto EI = SpillsInSubTreeMap[Child].first.end();
1403 SpillsInSubTree.insert(BI, EI);
1404 SpillsInSubTreeMap.erase(Child);
1405 }
1406
1407 SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1408 SpillsInSubTreeMap[*RIt].first;
1409 BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1410 // No spills in subtree, simply continue.
1411 if (SpillsInSubTree.empty())
1412 continue;
1413
1414 // Check whether Block is a possible candidate to insert spill.
1415 Register LiveReg;
1416 if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
1417 continue;
1418
1419 // If there are multiple spills that could be merged, bias a little
1420 // to hoist the spill.
1421 BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
1422 ? BranchProbability(9, 10)
1423 : BranchProbability(1, 1);
1424 if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
1425 // Hoist: Move spills to current Block.
1426 for (const auto SpillBB : SpillsInSubTree) {
1427 // When SpillBB is a BB contains original spill, insert the spill
1428 // to SpillsToRm.
1429 if (SpillsToKeep.find(SpillBB) != SpillsToKeep.end() &&
1430 !SpillsToKeep[SpillBB]) {
1431 MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
1432 SpillsToRm.push_back(SpillToRm);
1433 }
1434 // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
1435 SpillsToKeep.erase(SpillBB);
1436 }
1437 // Current Block is the BB containing the new hoisted spill. Add it to
1438 // SpillsToKeep. LiveReg is the source of the new spill.
1439 SpillsToKeep[*RIt] = LiveReg;
1440 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1441 dbgs() << "spills in BB: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1442 for (const auto Rspill : SpillsInSubTree)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1443 dbgs() << Rspill->getBlock()->getNumber() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1444 dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1445 << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
1446 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "spills in BB: "; for (const
auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock
()->getNumber() << " "; dbgs() << "were promoted to BB"
<< (*RIt)->getBlock()->getNumber() << "\n"
; }; } } while (false)
;
1447 SpillsInSubTree.clear();
1448 SpillsInSubTree.insert(*RIt);
1449 SubTreeCost = MBFI.getBlockFreq(Block);
1450 }
1451 }
1452 // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
1453 // save them to SpillsToIns.
1454 for (const auto &Ent : SpillsToKeep) {
1455 if (Ent.second)
1456 SpillsToIns[Ent.first->getBlock()] = Ent.second;
1457 }
1458}
1459
1460/// For spills with equal values, remove redundant spills and hoist those left
1461/// to less hot spots.
1462///
1463/// Spills with equal values will be collected into the same set in
1464/// MergeableSpills when spill is inserted. These equal spills are originated
1465/// from the same defining instruction and are dominated by the instruction.
1466/// Before hoisting all the equal spills, redundant spills inside in the same
1467/// BB are first marked to be deleted. Then starting from the spills left, walk
1468/// up on the dominator tree towards the Root node where the define instruction
1469/// is located, mark the dominated spills to be deleted along the way and
1470/// collect the BB nodes on the path from non-dominated spills to the define
1471/// instruction into a WorkSet. The nodes in WorkSet are the candidate places
1472/// where we are considering to hoist the spills. We iterate the WorkSet in
1473/// bottom-up order, and for each node, we will decide whether to hoist spills
1474/// inside its subtree to that node. In this way, we can get benefit locally
1475/// even if hoisting all the equal spills to one cold place is impossible.
1476void HoistSpillHelper::hoistAllSpills() {
1477 SmallVector<Register, 4> NewVRegs;
1478 LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
1479
1480 for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
1481 Register Reg = Register::index2VirtReg(i);
1482 Register Original = VRM.getPreSplitReg(Reg);
1483 if (!MRI.def_empty(Reg))
1484 Virt2SiblingsMap[Original].insert(Reg);
1485 }
1486
1487 // Each entry in MergeableSpills contains a spill set with equal values.
1488 for (auto &Ent : MergeableSpills) {
1489 int Slot = Ent.first.first;
1490 LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
1491 VNInfo *OrigVNI = Ent.first.second;
1492 SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
1493 if (Ent.second.empty())
1494 continue;
1495
1496 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1497 dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1498 << "Equal spills in BB: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1499 for (const auto spill : EqValSpills)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1500 dbgs() << spill->getParent()->getNumber() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1501 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
1502 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "\nFor Slot" << Slot <<
" and VN" << OrigVNI->id << ":\n" << "Equal spills in BB: "
; for (const auto spill : EqValSpills) dbgs() << spill->
getParent()->getNumber() << " "; dbgs() << "\n"
; }; } } while (false)
;
1503
1504 // SpillsToRm is the spill set to be removed from EqValSpills.
1505 SmallVector<MachineInstr *, 16> SpillsToRm;
1506 // SpillsToIns is the spill set to be newly inserted after hoisting.
1507 DenseMap<MachineBasicBlock *, unsigned> SpillsToIns;
1508
1509 runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
1510
1511 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1512 dbgs() << "Finally inserted spills in BB: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1513 for (const auto &Ispill : SpillsToIns)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1514 dbgs() << Ispill.first->getNumber() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1515 dbgs() << "\nFinally removed spills in BB: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1516 for (const auto Rspill : SpillsToRm)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1517 dbgs() << Rspill->getParent()->getNumber() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1518 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
1519 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc")) { { dbgs() << "Finally inserted spills in BB: "
; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill
.first->getNumber() << " "; dbgs() << "\nFinally removed spills in BB: "
; for (const auto Rspill : SpillsToRm) dbgs() << Rspill
->getParent()->getNumber() << " "; dbgs() <<
"\n"; }; } } while (false)
;
1520
1521 // Stack live range update.
1522 LiveInterval &StackIntvl = LSS.getInterval(Slot);
1523 if (!SpillsToIns.empty() || !SpillsToRm.empty())
1524 StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
1525 StackIntvl.getValNumInfo(0));
1526
1527 // Insert hoisted spills.
1528 for (auto const &Insert : SpillsToIns) {
1529 MachineBasicBlock *BB = Insert.first;
1530 Register LiveReg = Insert.second;
1531 MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, *BB);
1532 TII.storeRegToStackSlot(*BB, MI, LiveReg, false, Slot,
1533 MRI.getRegClass(LiveReg), &TRI);
1534 LIS.InsertMachineInstrRangeInMaps(std::prev(MI), MI);
1535 ++NumSpills;
1536 }
1537
1538 // Remove redundant spills or change them to dead instructions.
1539 NumSpills -= SpillsToRm.size();
1540 for (auto const RMEnt : SpillsToRm) {
1541 RMEnt->setDesc(TII.get(TargetOpcode::KILL));
1542 for (unsigned i = RMEnt->getNumOperands(); i; --i) {
1543 MachineOperand &MO = RMEnt->getOperand(i - 1);
1544 if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
1545 RMEnt->RemoveOperand(i - 1);
1546 }
1547 }
1548 Edit.eliminateDeadDefs(SpillsToRm, None, AA);
1549 }
1550}
1551
1552/// For VirtReg clone, the \p New register should have the same physreg or
1553/// stackslot as the \p old register.
1554void HoistSpillHelper::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
1555 if (VRM.hasPhys(Old))
1556 VRM.assignVirt2Phys(New, VRM.getPhys(Old));
1557 else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT)
1558 VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
1559 else
1560 llvm_unreachable("VReg should be assigned either physreg or stackslot")::llvm::llvm_unreachable_internal("VReg should be assigned either physreg or stackslot"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/lib/CodeGen/InlineSpiller.cpp"
, 1560)
;
1561}

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

/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/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 constexpr Register(unsigned Val = 0): Reg(Val) {}
24 constexpr 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 static_assert(std::numeric_limits<decltype(Reg)>::max() >= 0xFFFFFFFF,
37 "Reg isn't large enough to hold full range.");
38
39 /// isStackSlot - Sometimes it is useful the be able to store a non-negative
40 /// frame index in a variable that normally holds a register. isStackSlot()
41 /// returns true if Reg is in the range used for stack slots.
42 ///
43 /// FIXME: remove in favor of member.
44 static bool isStackSlot(unsigned Reg) {
45 return MCRegister::isStackSlot(Reg);
46 }
47
48 /// Return true if this is a stack slot.
49 bool isStack() const { return MCRegister::isStackSlot(Reg); }
50
51 /// Compute the frame index from a register value representing a stack slot.
52 static int stackSlot2Index(Register Reg) {
53 assert(Reg.isStack() && "Not a stack slot")((Reg.isStack() && "Not a stack slot") ? static_cast<
void> (0) : __assert_fail ("Reg.isStack() && \"Not a stack slot\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/Register.h"
, 53, __PRETTY_FUNCTION__))
;
54 return int(Reg - MCRegister::FirstStackSlot);
55 }
56
57 /// Convert a non-negative frame index to a stack slot register value.
58 static Register index2StackSlot(int FI) {
59 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-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/Register.h"
, 59, __PRETTY_FUNCTION__))
;
60 return Register(FI + MCRegister::FirstStackSlot);
61 }
62
63 /// Return true if the specified register number is in
64 /// the physical register namespace.
65 static bool isPhysicalRegister(unsigned Reg) {
66 return MCRegister::isPhysicalRegister(Reg);
67 }
68
69 /// Return true if the specified register number is in
70 /// the virtual register namespace.
71 static bool isVirtualRegister(unsigned Reg) {
72 return Reg & MCRegister::VirtualRegFlag && !isStackSlot(Reg);
73 }
74
75 /// Convert a virtual register number to a 0-based index.
76 /// The first virtual register in a function will get the index 0.
77 static unsigned virtReg2Index(Register Reg) {
78 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-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/Register.h"
, 78, __PRETTY_FUNCTION__))
;
79 return Reg & ~MCRegister::VirtualRegFlag;
80 }
81
82 /// Convert a 0-based index to a virtual register number.
83 /// This is the inverse operation of VirtReg2IndexFunctor below.
84 static Register index2VirtReg(unsigned Index) {
85 assert(Index < (1u << 31) && "Index too large for virtual register range.")((Index < (1u << 31) && "Index too large for virtual register range."
) ? static_cast<void> (0) : __assert_fail ("Index < (1u << 31) && \"Index too large for virtual register range.\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/Register.h"
, 85, __PRETTY_FUNCTION__))
;
86 return Index | MCRegister::VirtualRegFlag;
87 }
88
89 /// Return true if the specified register number is in the virtual register
90 /// namespace.
91 bool isVirtual() const {
92 return isVirtualRegister(Reg);
93 }
94
95 /// Return true if the specified register number is in the physical register
96 /// namespace.
97 bool isPhysical() const {
98 return isPhysicalRegister(Reg);
99 }
100
101 /// Convert a virtual register number to a 0-based index. The first virtual
102 /// register in a function will get the index 0.
103 unsigned virtRegIndex() const {
104 return virtReg2Index(Reg);
105 }
106
107 constexpr operator unsigned() const {
108 return Reg;
12
Returning zero, which participates in a condition later
109 }
110
111 unsigned id() const { return Reg; }
112
113 operator MCRegister() const {
114 return MCRegister(Reg);
115 }
116
117 /// Utility to check-convert this value to a MCRegister. The caller is
118 /// expected to have already validated that this Register is, indeed,
119 /// physical.
120 MCRegister asMCReg() const {
121 assert(Reg == MCRegister::NoRegister ||((Reg == MCRegister::NoRegister || MCRegister::isPhysicalRegister
(Reg)) ? static_cast<void> (0) : __assert_fail ("Reg == MCRegister::NoRegister || MCRegister::isPhysicalRegister(Reg)"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/Register.h"
, 122, __PRETTY_FUNCTION__))
122 MCRegister::isPhysicalRegister(Reg))((Reg == MCRegister::NoRegister || MCRegister::isPhysicalRegister
(Reg)) ? static_cast<void> (0) : __assert_fail ("Reg == MCRegister::NoRegister || MCRegister::isPhysicalRegister(Reg)"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/Register.h"
, 122, __PRETTY_FUNCTION__))
;
123 return MCRegister(Reg);
124 }
125
126 bool isValid() const { return Reg != MCRegister::NoRegister; }
127
128 /// Comparisons between register objects
129 bool operator==(const Register &Other) const { return Reg == Other.Reg; }
130 bool operator!=(const Register &Other) const { return Reg != Other.Reg; }
131 bool operator==(const MCRegister &Other) const { return Reg == Other.id(); }
132 bool operator!=(const MCRegister &Other) const { return Reg != Other.id(); }
133
134 /// Comparisons against register constants. E.g.
135 /// * R == AArch64::WZR
136 /// * R == 0
137 /// * R == VirtRegMap::NO_PHYS_REG
138 bool operator==(unsigned Other) const { return Reg == Other; }
24
Assuming 'Other' is equal to field 'Reg'
25
Returning the value 1, which participates in a condition later
139 bool operator!=(unsigned Other) const { return Reg != Other; }
140 bool operator==(int Other) const { return Reg == unsigned(Other); }
141 bool operator!=(int Other) const { return Reg != unsigned(Other); }
142 // MSVC requires that we explicitly declare these two as well.
143 bool operator==(MCPhysReg Other) const { return Reg == unsigned(Other); }
144 bool operator!=(MCPhysReg Other) const { return Reg != unsigned(Other); }
145};
146
147// Provide DenseMapInfo for Register
148template<> struct DenseMapInfo<Register> {
149 static inline unsigned getEmptyKey() {
150 return DenseMapInfo<unsigned>::getEmptyKey();
151 }
152 static inline unsigned getTombstoneKey() {
153 return DenseMapInfo<unsigned>::getTombstoneKey();
154 }
155 static unsigned getHashValue(const Register &Val) {
156 return DenseMapInfo<unsigned>::getHashValue(Val.id());
157 }
158 static bool isEqual(const Register &LHS, const Register &RHS) {
159 return DenseMapInfo<unsigned>::isEqual(LHS.id(), RHS.id());
160 }
161};
162
163}
164
165#endif // ifndef LLVM_CODEGEN_REGISTER_H

/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h

1//===- llvm/CodeGen/TargetInstrInfo.h - Instruction Info --------*- 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 describes the target machine instruction set to the code generator.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TARGET_TARGETINSTRINFO_H
14#define LLVM_TARGET_TARGETINSTRINFO_H
15
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseMapInfo.h"
19#include "llvm/ADT/None.h"
20#include "llvm/CodeGen/MIRFormatter.h"
21#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/MachineCombinerPattern.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineInstr.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineOperand.h"
27#include "llvm/CodeGen/MachineOutliner.h"
28#include "llvm/CodeGen/VirtRegMap.h"
29#include "llvm/MC/MCInstrInfo.h"
30#include "llvm/Support/BranchProbability.h"
31#include "llvm/Support/ErrorHandling.h"
32#include <cassert>
33#include <cstddef>
34#include <cstdint>
35#include <utility>
36#include <vector>
37
38namespace llvm {
39
40class AAResults;
41class DFAPacketizer;
42class InstrItineraryData;
43class LiveIntervals;
44class LiveVariables;
45class MachineLoop;
46class MachineMemOperand;
47class MachineRegisterInfo;
48class MCAsmInfo;
49class MCInst;
50struct MCSchedModel;
51class Module;
52class ScheduleDAG;
53class ScheduleDAGMI;
54class ScheduleHazardRecognizer;
55class SDNode;
56class SelectionDAG;
57class RegScavenger;
58class TargetRegisterClass;
59class TargetRegisterInfo;
60class TargetSchedModel;
61class TargetSubtargetInfo;
62
63template <class T> class SmallVectorImpl;
64
65using ParamLoadedValue = std::pair<MachineOperand, DIExpression*>;
66
67struct DestSourcePair {
68 const MachineOperand *Destination;
69 const MachineOperand *Source;
70
71 DestSourcePair(const MachineOperand &Dest, const MachineOperand &Src)
72 : Destination(&Dest), Source(&Src) {}
73};
74
75/// Used to describe a register and immediate addition.
76struct RegImmPair {
77 Register Reg;
78 int64_t Imm;
79
80 RegImmPair(Register Reg, int64_t Imm) : Reg(Reg), Imm(Imm) {}
81};
82
83/// Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
84/// It holds the register values, the scale value and the displacement.
85struct ExtAddrMode {
86 Register BaseReg;
87 Register ScaledReg;
88 int64_t Scale;
89 int64_t Displacement;
90};
91
92//---------------------------------------------------------------------------
93///
94/// TargetInstrInfo - Interface to description of machine instruction set
95///
96class TargetInstrInfo : public MCInstrInfo {
97public:
98 TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
99 unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u)
100 : CallFrameSetupOpcode(CFSetupOpcode),
101 CallFrameDestroyOpcode(CFDestroyOpcode), CatchRetOpcode(CatchRetOpcode),
102 ReturnOpcode(ReturnOpcode) {}
103 TargetInstrInfo(const TargetInstrInfo &) = delete;
104 TargetInstrInfo &operator=(const TargetInstrInfo &) = delete;
105 virtual ~TargetInstrInfo();
106
107 static bool isGenericOpcode(unsigned Opc) {
108 return Opc <= TargetOpcode::GENERIC_OP_END;
109 }
110
111 /// Given a machine instruction descriptor, returns the register
112 /// class constraint for OpNum, or NULL.
113 virtual
114 const TargetRegisterClass *getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
115 const TargetRegisterInfo *TRI,
116 const MachineFunction &MF) const;
117
118 /// Return true if the instruction is trivially rematerializable, meaning it
119 /// has no side effects and requires no operands that aren't always available.
120 /// This means the only allowed uses are constants and unallocatable physical
121 /// registers so that the instructions result is independent of the place
122 /// in the function.
123 bool isTriviallyReMaterializable(const MachineInstr &MI,
124 AAResults *AA = nullptr) const {
125 return MI.getOpcode() == TargetOpcode::IMPLICIT_DEF ||
126 (MI.getDesc().isRematerializable() &&
127 (isReallyTriviallyReMaterializable(MI, AA) ||
128 isReallyTriviallyReMaterializableGeneric(MI, AA)));
129 }
130
131protected:
132 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
133 /// set, this hook lets the target specify whether the instruction is actually
134 /// trivially rematerializable, taking into consideration its operands. This
135 /// predicate must return false if the instruction has any side effects other
136 /// than producing a value, or if it requres any address registers that are
137 /// not always available.
138 /// Requirements must be check as stated in isTriviallyReMaterializable() .
139 virtual bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
140 AAResults *AA) const {
141 return false;
142 }
143
144 /// This method commutes the operands of the given machine instruction MI.
145 /// The operands to be commuted are specified by their indices OpIdx1 and
146 /// OpIdx2.
147 ///
148 /// If a target has any instructions that are commutable but require
149 /// converting to different instructions or making non-trivial changes
150 /// to commute them, this method can be overloaded to do that.
151 /// The default implementation simply swaps the commutable operands.
152 ///
153 /// If NewMI is false, MI is modified in place and returned; otherwise, a
154 /// new machine instruction is created and returned.
155 ///
156 /// Do not call this method for a non-commutable instruction.
157 /// Even though the instruction is commutable, the method may still
158 /// fail to commute the operands, null pointer is returned in such cases.
159 virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
160 unsigned OpIdx1,
161 unsigned OpIdx2) const;
162
163 /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
164 /// operand indices to (ResultIdx1, ResultIdx2).
165 /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
166 /// predefined to some indices or be undefined (designated by the special
167 /// value 'CommuteAnyOperandIndex').
168 /// The predefined result indices cannot be re-defined.
169 /// The function returns true iff after the result pair redefinition
170 /// the fixed result pair is equal to or equivalent to the source pair of
171 /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
172 /// the pairs (x,y) and (y,x) are equivalent.
173 static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2,
174 unsigned CommutableOpIdx1,
175 unsigned CommutableOpIdx2);
176
177private:
178 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
179 /// set and the target hook isReallyTriviallyReMaterializable returns false,
180 /// this function does target-independent tests to determine if the
181 /// instruction is really trivially rematerializable.
182 bool isReallyTriviallyReMaterializableGeneric(const MachineInstr &MI,
183 AAResults *AA) const;
184
185public:
186 /// These methods return the opcode of the frame setup/destroy instructions
187 /// if they exist (-1 otherwise). Some targets use pseudo instructions in
188 /// order to abstract away the difference between operating with a frame
189 /// pointer and operating without, through the use of these two instructions.
190 ///
191 unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
192 unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
193
194 /// Returns true if the argument is a frame pseudo instruction.
195 bool isFrameInstr(const MachineInstr &I) const {
196 return I.getOpcode() == getCallFrameSetupOpcode() ||
197 I.getOpcode() == getCallFrameDestroyOpcode();
198 }
199
200 /// Returns true if the argument is a frame setup pseudo instruction.
201 bool isFrameSetup(const MachineInstr &I) const {
202 return I.getOpcode() == getCallFrameSetupOpcode();
203 }
204
205 /// Returns size of the frame associated with the given frame instruction.
206 /// For frame setup instruction this is frame that is set up space set up
207 /// after the instruction. For frame destroy instruction this is the frame
208 /// freed by the caller.
209 /// Note, in some cases a call frame (or a part of it) may be prepared prior
210 /// to the frame setup instruction. It occurs in the calls that involve
211 /// inalloca arguments. This function reports only the size of the frame part
212 /// that is set up between the frame setup and destroy pseudo instructions.
213 int64_t getFrameSize(const MachineInstr &I) const {
214 assert(isFrameInstr(I) && "Not a frame instruction")((isFrameInstr(I) && "Not a frame instruction") ? static_cast
<void> (0) : __assert_fail ("isFrameInstr(I) && \"Not a frame instruction\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 214, __PRETTY_FUNCTION__))
;
215 assert(I.getOperand(0).getImm() >= 0)((I.getOperand(0).getImm() >= 0) ? static_cast<void>
(0) : __assert_fail ("I.getOperand(0).getImm() >= 0", "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 215, __PRETTY_FUNCTION__))
;
216 return I.getOperand(0).getImm();
217 }
218
219 /// Returns the total frame size, which is made up of the space set up inside
220 /// the pair of frame start-stop instructions and the space that is set up
221 /// prior to the pair.
222 int64_t getFrameTotalSize(const MachineInstr &I) const {
223 if (isFrameSetup(I)) {
224 assert(I.getOperand(1).getImm() >= 0 &&((I.getOperand(1).getImm() >= 0 && "Frame size must not be negative"
) ? static_cast<void> (0) : __assert_fail ("I.getOperand(1).getImm() >= 0 && \"Frame size must not be negative\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 225, __PRETTY_FUNCTION__))
225 "Frame size must not be negative")((I.getOperand(1).getImm() >= 0 && "Frame size must not be negative"
) ? static_cast<void> (0) : __assert_fail ("I.getOperand(1).getImm() >= 0 && \"Frame size must not be negative\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 225, __PRETTY_FUNCTION__))
;
226 return getFrameSize(I) + I.getOperand(1).getImm();
227 }
228 return getFrameSize(I);
229 }
230
231 unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
232 unsigned getReturnOpcode() const { return ReturnOpcode; }
233
234 /// Returns the actual stack pointer adjustment made by an instruction
235 /// as part of a call sequence. By default, only call frame setup/destroy
236 /// instructions adjust the stack, but targets may want to override this
237 /// to enable more fine-grained adjustment, or adjust by a different value.
238 virtual int getSPAdjust(const MachineInstr &MI) const;
239
240 /// Return true if the instruction is a "coalescable" extension instruction.
241 /// That is, it's like a copy where it's legal for the source to overlap the
242 /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
243 /// expected the pre-extension value is available as a subreg of the result
244 /// register. This also returns the sub-register index in SubIdx.
245 virtual bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg,
246 Register &DstReg, unsigned &SubIdx) const {
247 return false;
248 }
249
250 /// If the specified machine instruction is a direct
251 /// load from a stack slot, return the virtual or physical register number of
252 /// the destination along with the FrameIndex of the loaded stack slot. If
253 /// not, return 0. This predicate must return 0 if the instruction has
254 /// any side effects other than loading from the stack slot.
255 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
256 int &FrameIndex) const {
257 return 0;
17
Returning without writing to 'FrameIndex'
258 }
259
260 /// Optional extension of isLoadFromStackSlot that returns the number of
261 /// bytes loaded from the stack. This must be implemented if a backend
262 /// supports partial stack slot spills/loads to further disambiguate
263 /// what the load does.
264 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
265 int &FrameIndex,
266 unsigned &MemBytes) const {
267 MemBytes = 0;
268 return isLoadFromStackSlot(MI, FrameIndex);
269 }
270
271 /// Check for post-frame ptr elimination stack locations as well.
272 /// This uses a heuristic so it isn't reliable for correctness.
273 virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
274 int &FrameIndex) const {
275 return 0;
276 }
277
278 /// If the specified machine instruction has a load from a stack slot,
279 /// return true along with the FrameIndices of the loaded stack slot and the
280 /// machine mem operands containing the reference.
281 /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
282 /// any instructions that loads from the stack. This is just a hint, as some
283 /// cases may be missed.
284 virtual bool hasLoadFromStackSlot(
285 const MachineInstr &MI,
286 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
287
288 /// If the specified machine instruction is a direct
289 /// store to a stack slot, return the virtual or physical register number of
290 /// the source reg along with the FrameIndex of the loaded stack slot. If
291 /// not, return 0. This predicate must return 0 if the instruction has
292 /// any side effects other than storing to the stack slot.
293 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
294 int &FrameIndex) const {
295 return 0;
21
Returning without writing to 'FrameIndex'
296 }
297
298 /// Optional extension of isStoreToStackSlot that returns the number of
299 /// bytes stored to the stack. This must be implemented if a backend
300 /// supports partial stack slot spills/loads to further disambiguate
301 /// what the store does.
302 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
303 int &FrameIndex,
304 unsigned &MemBytes) const {
305 MemBytes = 0;
306 return isStoreToStackSlot(MI, FrameIndex);
307 }
308
309 /// Check for post-frame ptr elimination stack locations as well.
310 /// This uses a heuristic, so it isn't reliable for correctness.
311 virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
312 int &FrameIndex) const {
313 return 0;
314 }
315
316 /// If the specified machine instruction has a store to a stack slot,
317 /// return true along with the FrameIndices of the loaded stack slot and the
318 /// machine mem operands containing the reference.
319 /// If not, return false. Unlike isStoreToStackSlot,
320 /// this returns true for any instructions that stores to the
321 /// stack. This is just a hint, as some cases may be missed.
322 virtual bool hasStoreToStackSlot(
323 const MachineInstr &MI,
324 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
325
326 /// Return true if the specified machine instruction
327 /// is a copy of one stack slot to another and has no other effect.
328 /// Provide the identity of the two frame indices.
329 virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
330 int &SrcFrameIndex) const {
331 return false;
332 }
333
334 /// Compute the size in bytes and offset within a stack slot of a spilled
335 /// register or subregister.
336 ///
337 /// \param [out] Size in bytes of the spilled value.
338 /// \param [out] Offset in bytes within the stack slot.
339 /// \returns true if both Size and Offset are successfully computed.
340 ///
341 /// Not all subregisters have computable spill slots. For example,
342 /// subregisters registers may not be byte-sized, and a pair of discontiguous
343 /// subregisters has no single offset.
344 ///
345 /// Targets with nontrivial bigendian implementations may need to override
346 /// this, particularly to support spilled vector registers.
347 virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
348 unsigned &Size, unsigned &Offset,
349 const MachineFunction &MF) const;
350
351 /// Returns the size in bytes of the specified MachineInstr, or ~0U
352 /// when this function is not implemented by a target.
353 virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
354 return ~0U;
355 }
356
357 /// Return true if the instruction is as cheap as a move instruction.
358 ///
359 /// Targets for different archs need to override this, and different
360 /// micro-architectures can also be finely tuned inside.
361 virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
362 return MI.isAsCheapAsAMove();
363 }
364
365 /// Return true if the instruction should be sunk by MachineSink.
366 ///
367 /// MachineSink determines on its own whether the instruction is safe to sink;
368 /// this gives the target a hook to override the default behavior with regards
369 /// to which instructions should be sunk.
370 virtual bool shouldSink(const MachineInstr &MI) const { return true; }
371
372 /// Re-issue the specified 'original' instruction at the
373 /// specific location targeting a new destination register.
374 /// The register in Orig->getOperand(0).getReg() will be substituted by
375 /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
376 /// SubIdx.
377 virtual void reMaterialize(MachineBasicBlock &MBB,
378 MachineBasicBlock::iterator MI, Register DestReg,
379 unsigned SubIdx, const MachineInstr &Orig,
380 const TargetRegisterInfo &TRI) const;
381
382 /// Clones instruction or the whole instruction bundle \p Orig and
383 /// insert into \p MBB before \p InsertBefore. The target may update operands
384 /// that are required to be unique.
385 ///
386 /// \p Orig must not return true for MachineInstr::isNotDuplicable().
387 virtual MachineInstr &duplicate(MachineBasicBlock &MBB,
388 MachineBasicBlock::iterator InsertBefore,
389 const MachineInstr &Orig) const;
390
391 /// This method must be implemented by targets that
392 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
393 /// may be able to convert a two-address instruction into one or more true
394 /// three-address instructions on demand. This allows the X86 target (for
395 /// example) to convert ADD and SHL instructions into LEA instructions if they
396 /// would require register copies due to two-addressness.
397 ///
398 /// This method returns a null pointer if the transformation cannot be
399 /// performed, otherwise it returns the last new instruction.
400 ///
401 virtual MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
402 MachineInstr &MI,
403 LiveVariables *LV) const {
404 return nullptr;
405 }
406
407 // This constant can be used as an input value of operand index passed to
408 // the method findCommutedOpIndices() to tell the method that the
409 // corresponding operand index is not pre-defined and that the method
410 // can pick any commutable operand.
411 static const unsigned CommuteAnyOperandIndex = ~0U;
412
413 /// This method commutes the operands of the given machine instruction MI.
414 ///
415 /// The operands to be commuted are specified by their indices OpIdx1 and
416 /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
417 /// 'CommuteAnyOperandIndex', which means that the method is free to choose
418 /// any arbitrarily chosen commutable operand. If both arguments are set to
419 /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
420 /// operands; then commutes them if such operands could be found.
421 ///
422 /// If NewMI is false, MI is modified in place and returned; otherwise, a
423 /// new machine instruction is created and returned.
424 ///
425 /// Do not call this method for a non-commutable instruction or
426 /// for non-commuable operands.
427 /// Even though the instruction is commutable, the method may still
428 /// fail to commute the operands, null pointer is returned in such cases.
429 MachineInstr *
430 commuteInstruction(MachineInstr &MI, bool NewMI = false,
431 unsigned OpIdx1 = CommuteAnyOperandIndex,
432 unsigned OpIdx2 = CommuteAnyOperandIndex) const;
433
434 /// Returns true iff the routine could find two commutable operands in the
435 /// given machine instruction.
436 /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
437 /// If any of the INPUT values is set to the special value
438 /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
439 /// operand, then returns its index in the corresponding argument.
440 /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
441 /// looks for 2 commutable operands.
442 /// If INPUT values refer to some operands of MI, then the method simply
443 /// returns true if the corresponding operands are commutable and returns
444 /// false otherwise.
445 ///
446 /// For example, calling this method this way:
447 /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
448 /// findCommutedOpIndices(MI, Op1, Op2);
449 /// can be interpreted as a query asking to find an operand that would be
450 /// commutable with the operand#1.
451 virtual bool findCommutedOpIndices(const MachineInstr &MI,
452 unsigned &SrcOpIdx1,
453 unsigned &SrcOpIdx2) const;
454
455 /// A pair composed of a register and a sub-register index.
456 /// Used to give some type checking when modeling Reg:SubReg.
457 struct RegSubRegPair {
458 Register Reg;
459 unsigned SubReg;
460
461 RegSubRegPair(Register Reg = Register(), unsigned SubReg = 0)
462 : Reg(Reg), SubReg(SubReg) {}
463
464 bool operator==(const RegSubRegPair& P) const {
465 return Reg == P.Reg && SubReg == P.SubReg;
466 }
467 bool operator!=(const RegSubRegPair& P) const {
468 return !(*this == P);
469 }
470 };
471
472 /// A pair composed of a pair of a register and a sub-register index,
473 /// and another sub-register index.
474 /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
475 struct RegSubRegPairAndIdx : RegSubRegPair {
476 unsigned SubIdx;
477
478 RegSubRegPairAndIdx(Register Reg = Register(), unsigned SubReg = 0,
479 unsigned SubIdx = 0)
480 : RegSubRegPair(Reg, SubReg), SubIdx(SubIdx) {}
481 };
482
483 /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
484 /// and \p DefIdx.
485 /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
486 /// the list is modeled as <Reg:SubReg, SubIdx>. Operands with the undef
487 /// flag are not added to this list.
488 /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
489 /// two elements:
490 /// - %1:sub1, sub0
491 /// - %2<:0>, sub1
492 ///
493 /// \returns true if it is possible to build such an input sequence
494 /// with the pair \p MI, \p DefIdx. False otherwise.
495 ///
496 /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
497 ///
498 /// \note The generic implementation does not provide any support for
499 /// MI.isRegSequenceLike(). In other words, one has to override
500 /// getRegSequenceLikeInputs for target specific instructions.
501 bool
502 getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
503 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
504
505 /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
506 /// and \p DefIdx.
507 /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
508 /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
509 /// - %1:sub1, sub0
510 ///
511 /// \returns true if it is possible to build such an input sequence
512 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
513 /// False otherwise.
514 ///
515 /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
516 ///
517 /// \note The generic implementation does not provide any support for
518 /// MI.isExtractSubregLike(). In other words, one has to override
519 /// getExtractSubregLikeInputs for target specific instructions.
520 bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
521 RegSubRegPairAndIdx &InputReg) const;
522
523 /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
524 /// and \p DefIdx.
525 /// \p [out] BaseReg and \p [out] InsertedReg contain
526 /// the equivalent inputs of INSERT_SUBREG.
527 /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
528 /// - BaseReg: %0:sub0
529 /// - InsertedReg: %1:sub1, sub3
530 ///
531 /// \returns true if it is possible to build such an input sequence
532 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
533 /// False otherwise.
534 ///
535 /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
536 ///
537 /// \note The generic implementation does not provide any support for
538 /// MI.isInsertSubregLike(). In other words, one has to override
539 /// getInsertSubregLikeInputs for target specific instructions.
540 bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
541 RegSubRegPair &BaseReg,
542 RegSubRegPairAndIdx &InsertedReg) const;
543
544 /// Return true if two machine instructions would produce identical values.
545 /// By default, this is only true when the two instructions
546 /// are deemed identical except for defs. If this function is called when the
547 /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
548 /// aggressive checks.
549 virtual bool produceSameValue(const MachineInstr &MI0,
550 const MachineInstr &MI1,
551 const MachineRegisterInfo *MRI = nullptr) const;
552
553 /// \returns true if a branch from an instruction with opcode \p BranchOpc
554 /// bytes is capable of jumping to a position \p BrOffset bytes away.
555 virtual bool isBranchOffsetInRange(unsigned BranchOpc,
556 int64_t BrOffset) const {
557 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 557)
;
558 }
559
560 /// \returns The block that branch instruction \p MI jumps to.
561 virtual MachineBasicBlock *getBranchDestBlock(const MachineInstr &MI) const {
562 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 562)
;
563 }
564
565 /// Insert an unconditional indirect branch at the end of \p MBB to \p
566 /// NewDestBB. \p BrOffset indicates the offset of \p NewDestBB relative to
567 /// the offset of the position to insert the new branch.
568 ///
569 /// \returns The number of bytes added to the block.
570 virtual unsigned insertIndirectBranch(MachineBasicBlock &MBB,
571 MachineBasicBlock &NewDestBB,
572 const DebugLoc &DL,
573 int64_t BrOffset = 0,
574 RegScavenger *RS = nullptr) const {
575 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 575)
;
576 }
577
578 /// Analyze the branching code at the end of MBB, returning
579 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
580 /// implemented for a target). Upon success, this returns false and returns
581 /// with the following information in various cases:
582 ///
583 /// 1. If this block ends with no branches (it just falls through to its succ)
584 /// just return false, leaving TBB/FBB null.
585 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
586 /// the destination block.
587 /// 3. If this block ends with a conditional branch and it falls through to a
588 /// successor block, it sets TBB to be the branch destination block and a
589 /// list of operands that evaluate the condition. These operands can be
590 /// passed to other TargetInstrInfo methods to create new branches.
591 /// 4. If this block ends with a conditional branch followed by an
592 /// unconditional branch, it returns the 'true' destination in TBB, the
593 /// 'false' destination in FBB, and a list of operands that evaluate the
594 /// condition. These operands can be passed to other TargetInstrInfo
595 /// methods to create new branches.
596 ///
597 /// Note that removeBranch and insertBranch must be implemented to support
598 /// cases where this method returns success.
599 ///
600 /// If AllowModify is true, then this routine is allowed to modify the basic
601 /// block (e.g. delete instructions after the unconditional branch).
602 ///
603 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
604 /// before calling this function.
605 virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
606 MachineBasicBlock *&FBB,
607 SmallVectorImpl<MachineOperand> &Cond,
608 bool AllowModify = false) const {
609 return true;
610 }
611
612 /// Represents a predicate at the MachineFunction level. The control flow a
613 /// MachineBranchPredicate represents is:
614 ///
615 /// Reg = LHS `Predicate` RHS == ConditionDef
616 /// if Reg then goto TrueDest else goto FalseDest
617 ///
618 struct MachineBranchPredicate {
619 enum ComparePredicate {
620 PRED_EQ, // True if two values are equal
621 PRED_NE, // True if two values are not equal
622 PRED_INVALID // Sentinel value
623 };
624
625 ComparePredicate Predicate = PRED_INVALID;
626 MachineOperand LHS = MachineOperand::CreateImm(0);
627 MachineOperand RHS = MachineOperand::CreateImm(0);
628 MachineBasicBlock *TrueDest = nullptr;
629 MachineBasicBlock *FalseDest = nullptr;
630 MachineInstr *ConditionDef = nullptr;
631
632 /// SingleUseCondition is true if ConditionDef is dead except for the
633 /// branch(es) at the end of the basic block.
634 ///
635 bool SingleUseCondition = false;
636
637 explicit MachineBranchPredicate() = default;
638 };
639
640 /// Analyze the branching code at the end of MBB and parse it into the
641 /// MachineBranchPredicate structure if possible. Returns false on success
642 /// and true on failure.
643 ///
644 /// If AllowModify is true, then this routine is allowed to modify the basic
645 /// block (e.g. delete instructions after the unconditional branch).
646 ///
647 virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB,
648 MachineBranchPredicate &MBP,
649 bool AllowModify = false) const {
650 return true;
651 }
652
653 /// Remove the branching code at the end of the specific MBB.
654 /// This is only invoked in cases where analyzeBranch returns success. It
655 /// returns the number of instructions that were removed.
656 /// If \p BytesRemoved is non-null, report the change in code size from the
657 /// removed instructions.
658 virtual unsigned removeBranch(MachineBasicBlock &MBB,
659 int *BytesRemoved = nullptr) const {
660 llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::removeBranch!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 660)
;
661 }
662
663 /// Insert branch code into the end of the specified MachineBasicBlock. The
664 /// operands to this method are the same as those returned by analyzeBranch.
665 /// This is only invoked in cases where analyzeBranch returns success. It
666 /// returns the number of instructions inserted. If \p BytesAdded is non-null,
667 /// report the change in code size from the added instructions.
668 ///
669 /// It is also invoked by tail merging to add unconditional branches in
670 /// cases where analyzeBranch doesn't apply because there was no original
671 /// branch to analyze. At least this much must be implemented, else tail
672 /// merging needs to be disabled.
673 ///
674 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
675 /// before calling this function.
676 virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
677 MachineBasicBlock *FBB,
678 ArrayRef<MachineOperand> Cond,
679 const DebugLoc &DL,
680 int *BytesAdded = nullptr) const {
681 llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertBranch!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 681)
;
682 }
683
684 unsigned insertUnconditionalBranch(MachineBasicBlock &MBB,
685 MachineBasicBlock *DestBB,
686 const DebugLoc &DL,
687 int *BytesAdded = nullptr) const {
688 return insertBranch(MBB, DestBB, nullptr, ArrayRef<MachineOperand>(), DL,
689 BytesAdded);
690 }
691
692 /// Object returned by analyzeLoopForPipelining. Allows software pipelining
693 /// implementations to query attributes of the loop being pipelined and to
694 /// apply target-specific updates to the loop once pipelining is complete.
695 class PipelinerLoopInfo {
696 public:
697 virtual ~PipelinerLoopInfo();
698 /// Return true if the given instruction should not be pipelined and should
699 /// be ignored. An example could be a loop comparison, or induction variable
700 /// update with no users being pipelined.
701 virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const = 0;
702
703 /// Create a condition to determine if the trip count of the loop is greater
704 /// than TC.
705 ///
706 /// If the trip count is statically known to be greater than TC, return
707 /// true. If the trip count is statically known to be not greater than TC,
708 /// return false. Otherwise return nullopt and fill out Cond with the test
709 /// condition.
710 virtual Optional<bool>
711 createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
712 SmallVectorImpl<MachineOperand> &Cond) = 0;
713
714 /// Modify the loop such that the trip count is
715 /// OriginalTC + TripCountAdjust.
716 virtual void adjustTripCount(int TripCountAdjust) = 0;
717
718 /// Called when the loop's preheader has been modified to NewPreheader.
719 virtual void setPreheader(MachineBasicBlock *NewPreheader) = 0;
720
721 /// Called when the loop is being removed. Any instructions in the preheader
722 /// should be removed.
723 ///
724 /// Once this function is called, no other functions on this object are
725 /// valid; the loop has been removed.
726 virtual void disposed() = 0;
727 };
728
729 /// Analyze loop L, which must be a single-basic-block loop, and if the
730 /// conditions can be understood enough produce a PipelinerLoopInfo object.
731 virtual std::unique_ptr<PipelinerLoopInfo>
732 analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
733 return nullptr;
734 }
735
736 /// Analyze the loop code, return true if it cannot be understood. Upon
737 /// success, this function returns false and returns information about the
738 /// induction variable and compare instruction used at the end.
739 virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
740 MachineInstr *&CmpInst) const {
741 return true;
742 }
743
744 /// Generate code to reduce the loop iteration by one and check if the loop
745 /// is finished. Return the value/register of the new loop count. We need
746 /// this function when peeling off one or more iterations of a loop. This
747 /// function assumes the nth iteration is peeled first.
748 virtual unsigned reduceLoopCount(MachineBasicBlock &MBB,
749 MachineBasicBlock &PreHeader,
750 MachineInstr *IndVar, MachineInstr &Cmp,
751 SmallVectorImpl<MachineOperand> &Cond,
752 SmallVectorImpl<MachineInstr *> &PrevInsts,
753 unsigned Iter, unsigned MaxIter) const {
754 llvm_unreachable("Target didn't implement ReduceLoopCount")::llvm::llvm_unreachable_internal("Target didn't implement ReduceLoopCount"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 754)
;
755 }
756
757 /// Delete the instruction OldInst and everything after it, replacing it with
758 /// an unconditional branch to NewDest. This is used by the tail merging pass.
759 virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
760 MachineBasicBlock *NewDest) const;
761
762 /// Return true if it's legal to split the given basic
763 /// block at the specified instruction (i.e. instruction would be the start
764 /// of a new basic block).
765 virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
766 MachineBasicBlock::iterator MBBI) const {
767 return true;
768 }
769
770 /// Return true if it's profitable to predicate
771 /// instructions with accumulated instruction latency of "NumCycles"
772 /// of the specified basic block, where the probability of the instructions
773 /// being executed is given by Probability, and Confidence is a measure
774 /// of our confidence that it will be properly predicted.
775 virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
776 unsigned ExtraPredCycles,
777 BranchProbability Probability) const {
778 return false;
779 }
780
781 /// Second variant of isProfitableToIfCvt. This one
782 /// checks for the case where two basic blocks from true and false path
783 /// of a if-then-else (diamond) are predicated on mutually exclusive
784 /// predicates, where the probability of the true path being taken is given
785 /// by Probability, and Confidence is a measure of our confidence that it
786 /// will be properly predicted.
787 virtual bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumTCycles,
788 unsigned ExtraTCycles,
789 MachineBasicBlock &FMBB, unsigned NumFCycles,
790 unsigned ExtraFCycles,
791 BranchProbability Probability) const {
792 return false;
793 }
794
795 /// Return true if it's profitable for if-converter to duplicate instructions
796 /// of specified accumulated instruction latencies in the specified MBB to
797 /// enable if-conversion.
798 /// The probability of the instructions being executed is given by
799 /// Probability, and Confidence is a measure of our confidence that it
800 /// will be properly predicted.
801 virtual bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB,
802 unsigned NumCycles,
803 BranchProbability Probability) const {
804 return false;
805 }
806
807 /// Return the increase in code size needed to predicate a contiguous run of
808 /// NumInsts instructions.
809 virtual unsigned extraSizeToPredicateInstructions(const MachineFunction &MF,
810 unsigned NumInsts) const {
811 return 0;
812 }
813
814 /// Return an estimate for the code size reduction (in bytes) which will be
815 /// caused by removing the given branch instruction during if-conversion.
816 virtual unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const {
817 return getInstSizeInBytes(MI);
818 }
819
820 /// Return true if it's profitable to unpredicate
821 /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
822 /// exclusive predicates.
823 /// e.g.
824 /// subeq r0, r1, #1
825 /// addne r0, r1, #1
826 /// =>
827 /// sub r0, r1, #1
828 /// addne r0, r1, #1
829 ///
830 /// This may be profitable is conditional instructions are always executed.
831 virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
832 MachineBasicBlock &FMBB) const {
833 return false;
834 }
835
836 /// Return true if it is possible to insert a select
837 /// instruction that chooses between TrueReg and FalseReg based on the
838 /// condition code in Cond.
839 ///
840 /// When successful, also return the latency in cycles from TrueReg,
841 /// FalseReg, and Cond to the destination register. In most cases, a select
842 /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
843 ///
844 /// Some x86 implementations have 2-cycle cmov instructions.
845 ///
846 /// @param MBB Block where select instruction would be inserted.
847 /// @param Cond Condition returned by analyzeBranch.
848 /// @param DstReg Virtual dest register that the result should write to.
849 /// @param TrueReg Virtual register to select when Cond is true.
850 /// @param FalseReg Virtual register to select when Cond is false.
851 /// @param CondCycles Latency from Cond+Branch to select output.
852 /// @param TrueCycles Latency from TrueReg to select output.
853 /// @param FalseCycles Latency from FalseReg to select output.
854 virtual bool canInsertSelect(const MachineBasicBlock &MBB,
855 ArrayRef<MachineOperand> Cond, Register DstReg,
856 Register TrueReg, Register FalseReg,
857 int &CondCycles, int &TrueCycles,
858 int &FalseCycles) const {
859 return false;
860 }
861
862 /// Insert a select instruction into MBB before I that will copy TrueReg to
863 /// DstReg when Cond is true, and FalseReg to DstReg when Cond is false.
864 ///
865 /// This function can only be called after canInsertSelect() returned true.
866 /// The condition in Cond comes from analyzeBranch, and it can be assumed
867 /// that the same flags or registers required by Cond are available at the
868 /// insertion point.
869 ///
870 /// @param MBB Block where select instruction should be inserted.
871 /// @param I Insertion point.
872 /// @param DL Source location for debugging.
873 /// @param DstReg Virtual register to be defined by select instruction.
874 /// @param Cond Condition as computed by analyzeBranch.
875 /// @param TrueReg Virtual register to copy when Cond is true.
876 /// @param FalseReg Virtual register to copy when Cons is false.
877 virtual void insertSelect(MachineBasicBlock &MBB,
878 MachineBasicBlock::iterator I, const DebugLoc &DL,
879 Register DstReg, ArrayRef<MachineOperand> Cond,
880 Register TrueReg, Register FalseReg) const {
881 llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertSelect!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 881)
;
882 }
883
884 /// Analyze the given select instruction, returning true if
885 /// it cannot be understood. It is assumed that MI->isSelect() is true.
886 ///
887 /// When successful, return the controlling condition and the operands that
888 /// determine the true and false result values.
889 ///
890 /// Result = SELECT Cond, TrueOp, FalseOp
891 ///
892 /// Some targets can optimize select instructions, for example by predicating
893 /// the instruction defining one of the operands. Such targets should set
894 /// Optimizable.
895 ///
896 /// @param MI Select instruction to analyze.
897 /// @param Cond Condition controlling the select.
898 /// @param TrueOp Operand number of the value selected when Cond is true.
899 /// @param FalseOp Operand number of the value selected when Cond is false.
900 /// @param Optimizable Returned as true if MI is optimizable.
901 /// @returns False on success.
902 virtual bool analyzeSelect(const MachineInstr &MI,
903 SmallVectorImpl<MachineOperand> &Cond,
904 unsigned &TrueOp, unsigned &FalseOp,
905 bool &Optimizable) const {
906 assert(MI.getDesc().isSelect() && "MI must be a select instruction")((MI.getDesc().isSelect() && "MI must be a select instruction"
) ? static_cast<void> (0) : __assert_fail ("MI.getDesc().isSelect() && \"MI must be a select instruction\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 906, __PRETTY_FUNCTION__))
;
907 return true;
908 }
909
910 /// Given a select instruction that was understood by
911 /// analyzeSelect and returned Optimizable = true, attempt to optimize MI by
912 /// merging it with one of its operands. Returns NULL on failure.
913 ///
914 /// When successful, returns the new select instruction. The client is
915 /// responsible for deleting MI.
916 ///
917 /// If both sides of the select can be optimized, PreferFalse is used to pick
918 /// a side.
919 ///
920 /// @param MI Optimizable select instruction.
921 /// @param NewMIs Set that record all MIs in the basic block up to \p
922 /// MI. Has to be updated with any newly created MI or deleted ones.
923 /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
924 /// @returns Optimized instruction or NULL.
925 virtual MachineInstr *optimizeSelect(MachineInstr &MI,
926 SmallPtrSetImpl<MachineInstr *> &NewMIs,
927 bool PreferFalse = false) const {
928 // This function must be implemented if Optimizable is ever set.
929 llvm_unreachable("Target must implement TargetInstrInfo::optimizeSelect!")::llvm::llvm_unreachable_internal("Target must implement TargetInstrInfo::optimizeSelect!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 929)
;
930 }
931
932 /// Emit instructions to copy a pair of physical registers.
933 ///
934 /// This function should support copies within any legal register class as
935 /// well as any cross-class copies created during instruction selection.
936 ///
937 /// The source and destination registers may overlap, which may require a
938 /// careful implementation when multiple copy instructions are required for
939 /// large registers. See for example the ARM target.
940 virtual void copyPhysReg(MachineBasicBlock &MBB,
941 MachineBasicBlock::iterator MI, const DebugLoc &DL,
942 MCRegister DestReg, MCRegister SrcReg,
943 bool KillSrc) const {
944 llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::copyPhysReg!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 944)
;
945 }
946
947protected:
948 /// Target-dependent implementation for IsCopyInstr.
949 /// If the specific machine instruction is a instruction that moves/copies
950 /// value from one register to another register return destination and source
951 /// registers as machine operands.
952 virtual Optional<DestSourcePair>
953 isCopyInstrImpl(const MachineInstr &MI) const {
954 return None;
955 }
956
957public:
958 /// If the specific machine instruction is a instruction that moves/copies
959 /// value from one register to another register return destination and source
960 /// registers as machine operands.
961 /// For COPY-instruction the method naturally returns destination and source
962 /// registers as machine operands, for all other instructions the method calls
963 /// target-dependent implementation.
964 Optional<DestSourcePair> isCopyInstr(const MachineInstr &MI) const {
965 if (MI.isCopy()) {
966 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
967 }
968 return isCopyInstrImpl(MI);
969 }
970
971 /// If the specific machine instruction is an instruction that adds an
972 /// immediate value and a physical register, and stores the result in
973 /// the given physical register \c Reg, return a pair of the source
974 /// register and the offset which has been added.
975 virtual Optional<RegImmPair> isAddImmediate(const MachineInstr &MI,
976 Register Reg) const {
977 return None;
978 }
979
980 /// Returns true if MI is an instruction that defines Reg to have a constant
981 /// value and the value is recorded in ImmVal. The ImmVal is a result that
982 /// should be interpreted as modulo size of Reg.
983 virtual bool getConstValDefinedInReg(const MachineInstr &MI,
984 const Register Reg,
985 int64_t &ImmVal) const {
986 return false;
987 }
988
989 /// Store the specified register of the given register class to the specified
990 /// stack frame index. The store instruction is to be added to the given
991 /// machine basic block before the specified machine instruction. If isKill
992 /// is true, the register operand is the last use and must be marked kill.
993 virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
994 MachineBasicBlock::iterator MI,
995 Register SrcReg, bool isKill, int FrameIndex,
996 const TargetRegisterClass *RC,
997 const TargetRegisterInfo *TRI) const {
998 llvm_unreachable("Target didn't implement "::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::storeRegToStackSlot!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 999)
999 "TargetInstrInfo::storeRegToStackSlot!")::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::storeRegToStackSlot!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 999)
;
1000 }
1001
1002 /// Load the specified register of the given register class from the specified
1003 /// stack frame index. The load instruction is to be added to the given
1004 /// machine basic block before the specified machine instruction.
1005 virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
1006 MachineBasicBlock::iterator MI,
1007 Register DestReg, int FrameIndex,
1008 const TargetRegisterClass *RC,
1009 const TargetRegisterInfo *TRI) const {
1010 llvm_unreachable("Target didn't implement "::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::loadRegFromStackSlot!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1011)
1011 "TargetInstrInfo::loadRegFromStackSlot!")::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::loadRegFromStackSlot!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1011)
;
1012 }
1013
1014 /// This function is called for all pseudo instructions
1015 /// that remain after register allocation. Many pseudo instructions are
1016 /// created to help register allocation. This is the place to convert them
1017 /// into real instructions. The target can edit MI in place, or it can insert
1018 /// new instructions and erase MI. The function should return true if
1019 /// anything was changed.
1020 virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }
1021
1022 /// Check whether the target can fold a load that feeds a subreg operand
1023 /// (or a subreg operand that feeds a store).
1024 /// For example, X86 may want to return true if it can fold
1025 /// movl (%esp), %eax
1026 /// subb, %al, ...
1027 /// Into:
1028 /// subb (%esp), ...
1029 ///
1030 /// Ideally, we'd like the target implementation of foldMemoryOperand() to
1031 /// reject subregs - but since this behavior used to be enforced in the
1032 /// target-independent code, moving this responsibility to the targets
1033 /// has the potential of causing nasty silent breakage in out-of-tree targets.
1034 virtual bool isSubregFoldable() const { return false; }
1035
1036 /// Attempt to fold a load or store of the specified stack
1037 /// slot into the specified machine instruction for the specified operand(s).
1038 /// If this is possible, a new instruction is returned with the specified
1039 /// operand folded, otherwise NULL is returned.
1040 /// The new instruction is inserted before MI, and the client is responsible
1041 /// for removing the old instruction.
1042 /// If VRM is passed, the assigned physregs can be inspected by target to
1043 /// decide on using an opcode (note that those assignments can still change).
1044 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1045 int FI,
1046 LiveIntervals *LIS = nullptr,
1047 VirtRegMap *VRM = nullptr) const;
1048
1049 /// Same as the previous version except it allows folding of any load and
1050 /// store from / to any address, not just from a specific stack slot.
1051 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1052 MachineInstr &LoadMI,
1053 LiveIntervals *LIS = nullptr) const;
1054
1055 /// Return true when there is potentially a faster code sequence
1056 /// for an instruction chain ending in \p Root. All potential patterns are
1057 /// returned in the \p Pattern vector. Pattern should be sorted in priority
1058 /// order since the pattern evaluator stops checking as soon as it finds a
1059 /// faster sequence.
1060 /// \param Root - Instruction that could be combined with one of its operands
1061 /// \param Patterns - Vector of possible combination patterns
1062 virtual bool getMachineCombinerPatterns(
1063 MachineInstr &Root,
1064 SmallVectorImpl<MachineCombinerPattern> &Patterns) const;
1065
1066 /// Return true when a code sequence can improve throughput. It
1067 /// should be called only for instructions in loops.
1068 /// \param Pattern - combiner pattern
1069 virtual bool isThroughputPattern(MachineCombinerPattern Pattern) const;
1070
1071 /// Return true if the input \P Inst is part of a chain of dependent ops
1072 /// that are suitable for reassociation, otherwise return false.
1073 /// If the instruction's operands must be commuted to have a previous
1074 /// instruction of the same type define the first source operand, \P Commuted
1075 /// will be set to true.
1076 bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const;
1077
1078 /// Return true when \P Inst is both associative and commutative.
1079 virtual bool isAssociativeAndCommutative(const MachineInstr &Inst) const {
1080 return false;
1081 }
1082
1083 /// Return true when \P Inst has reassociable operands in the same \P MBB.
1084 virtual bool hasReassociableOperands(const MachineInstr &Inst,
1085 const MachineBasicBlock *MBB) const;
1086
1087 /// Return true when \P Inst has reassociable sibling.
1088 bool hasReassociableSibling(const MachineInstr &Inst, bool &Commuted) const;
1089
1090 /// When getMachineCombinerPatterns() finds patterns, this function generates
1091 /// the instructions that could replace the original code sequence. The client
1092 /// has to decide whether the actual replacement is beneficial or not.
1093 /// \param Root - Instruction that could be combined with one of its operands
1094 /// \param Pattern - Combination pattern for Root
1095 /// \param InsInstrs - Vector of new instructions that implement P
1096 /// \param DelInstrs - Old instructions, including Root, that could be
1097 /// replaced by InsInstr
1098 /// \param InstIdxForVirtReg - map of virtual register to instruction in
1099 /// InsInstr that defines it
1100 virtual void genAlternativeCodeSequence(
1101 MachineInstr &Root, MachineCombinerPattern Pattern,
1102 SmallVectorImpl<MachineInstr *> &InsInstrs,
1103 SmallVectorImpl<MachineInstr *> &DelInstrs,
1104 DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const;
1105
1106 /// Attempt to reassociate \P Root and \P Prev according to \P Pattern to
1107 /// reduce critical path length.
1108 void reassociateOps(MachineInstr &Root, MachineInstr &Prev,
1109 MachineCombinerPattern Pattern,
1110 SmallVectorImpl<MachineInstr *> &InsInstrs,
1111 SmallVectorImpl<MachineInstr *> &DelInstrs,
1112 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
1113
1114 /// The limit on resource length extension we accept in MachineCombiner Pass.
1115 virtual int getExtendResourceLenLimit() const { return 0; }
1116
1117 /// This is an architecture-specific helper function of reassociateOps.
1118 /// Set special operand attributes for new instructions after reassociation.
1119 virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
1120 MachineInstr &NewMI1,
1121 MachineInstr &NewMI2) const {}
1122
1123 virtual void setSpecialOperandAttr(MachineInstr &MI, uint16_t Flags) const {}
1124
1125 /// Return true when a target supports MachineCombiner.
1126 virtual bool useMachineCombiner() const { return false; }
1127
1128 /// Return true if the given SDNode can be copied during scheduling
1129 /// even if it has glue.
1130 virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const { return false; }
1131
1132protected:
1133 /// Target-dependent implementation for foldMemoryOperand.
1134 /// Target-independent code in foldMemoryOperand will
1135 /// take care of adding a MachineMemOperand to the newly created instruction.
1136 /// The instruction and any auxiliary instructions necessary will be inserted
1137 /// at InsertPt.
1138 virtual MachineInstr *
1139 foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
1140 ArrayRef<unsigned> Ops,
1141 MachineBasicBlock::iterator InsertPt, int FrameIndex,
1142 LiveIntervals *LIS = nullptr,
1143 VirtRegMap *VRM = nullptr) const {
1144 return nullptr;
1145 }
1146
1147 /// Target-dependent implementation for foldMemoryOperand.
1148 /// Target-independent code in foldMemoryOperand will
1149 /// take care of adding a MachineMemOperand to the newly created instruction.
1150 /// The instruction and any auxiliary instructions necessary will be inserted
1151 /// at InsertPt.
1152 virtual MachineInstr *foldMemoryOperandImpl(
1153 MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
1154 MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
1155 LiveIntervals *LIS = nullptr) const {
1156 return nullptr;
1157 }
1158
1159 /// Target-dependent implementation of getRegSequenceInputs.
1160 ///
1161 /// \returns true if it is possible to build the equivalent
1162 /// REG_SEQUENCE inputs with the pair \p MI, \p DefIdx. False otherwise.
1163 ///
1164 /// \pre MI.isRegSequenceLike().
1165 ///
1166 /// \see TargetInstrInfo::getRegSequenceInputs.
1167 virtual bool getRegSequenceLikeInputs(
1168 const MachineInstr &MI, unsigned DefIdx,
1169 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1170 return false;
1171 }
1172
1173 /// Target-dependent implementation of getExtractSubregInputs.
1174 ///
1175 /// \returns true if it is possible to build the equivalent
1176 /// EXTRACT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1177 ///
1178 /// \pre MI.isExtractSubregLike().
1179 ///
1180 /// \see TargetInstrInfo::getExtractSubregInputs.
1181 virtual bool getExtractSubregLikeInputs(const MachineInstr &MI,
1182 unsigned DefIdx,
1183 RegSubRegPairAndIdx &InputReg) const {
1184 return false;
1185 }
1186
1187 /// Target-dependent implementation of getInsertSubregInputs.
1188 ///
1189 /// \returns true if it is possible to build the equivalent
1190 /// INSERT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1191 ///
1192 /// \pre MI.isInsertSubregLike().
1193 ///
1194 /// \see TargetInstrInfo::getInsertSubregInputs.
1195 virtual bool
1196 getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
1197 RegSubRegPair &BaseReg,
1198 RegSubRegPairAndIdx &InsertedReg) const {
1199 return false;
1200 }
1201
1202public:
1203 /// getAddressSpaceForPseudoSourceKind - Given the kind of memory
1204 /// (e.g. stack) the target returns the corresponding address space.
1205 virtual unsigned
1206 getAddressSpaceForPseudoSourceKind(unsigned Kind) const {
1207 return 0;
1208 }
1209
1210 /// unfoldMemoryOperand - Separate a single instruction which folded a load or
1211 /// a store or a load and a store into two or more instruction. If this is
1212 /// possible, returns true as well as the new instructions by reference.
1213 virtual bool
1214 unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, unsigned Reg,
1215 bool UnfoldLoad, bool UnfoldStore,
1216 SmallVectorImpl<MachineInstr *> &NewMIs) const {
1217 return false;
1218 }
1219
1220 virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
1221 SmallVectorImpl<SDNode *> &NewNodes) const {
1222 return false;
1223 }
1224
1225 /// Returns the opcode of the would be new
1226 /// instruction after load / store are unfolded from an instruction of the
1227 /// specified opcode. It returns zero if the specified unfolding is not
1228 /// possible. If LoadRegIndex is non-null, it is filled in with the operand
1229 /// index of the operand which will hold the register holding the loaded
1230 /// value.
1231 virtual unsigned
1232 getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore,
1233 unsigned *LoadRegIndex = nullptr) const {
1234 return 0;
1235 }
1236
1237 /// This is used by the pre-regalloc scheduler to determine if two loads are
1238 /// loading from the same base address. It should only return true if the base
1239 /// pointers are the same and the only differences between the two addresses
1240 /// are the offset. It also returns the offsets by reference.
1241 virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1242 int64_t &Offset1,
1243 int64_t &Offset2) const {
1244 return false;
1245 }
1246
1247 /// This is a used by the pre-regalloc scheduler to determine (in conjunction
1248 /// with areLoadsFromSameBasePtr) if two loads should be scheduled together.
1249 /// On some targets if two loads are loading from
1250 /// addresses in the same cache line, it's better if they are scheduled
1251 /// together. This function takes two integers that represent the load offsets
1252 /// from the common base address. It returns true if it decides it's desirable
1253 /// to schedule the two loads together. "NumLoads" is the number of loads that
1254 /// have already been scheduled after Load1.
1255 virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1256 int64_t Offset1, int64_t Offset2,
1257 unsigned NumLoads) const {
1258 return false;
1259 }
1260
1261 /// Get the base operand and byte offset of an instruction that reads/writes
1262 /// memory. This is a convenience function for callers that are only prepared
1263 /// to handle a single base operand.
1264 bool getMemOperandWithOffset(const MachineInstr &MI,
1265 const MachineOperand *&BaseOp, int64_t &Offset,
1266 bool &OffsetIsScalable,
1267 const TargetRegisterInfo *TRI) const;
1268
1269 /// Get the base operands and byte offset of an instruction that reads/writes
1270 /// memory.
1271 /// It returns false if MI does not read/write memory.
1272 /// It returns false if no base operands and offset was found.
1273 /// It is not guaranteed to always recognize base operands and offsets in all
1274 /// cases.
1275 virtual bool getMemOperandsWithOffsetWidth(
1276 const MachineInstr &MI, SmallVectorImpl<const MachineOperand *> &BaseOps,
1277 int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
1278 const TargetRegisterInfo *TRI) const {
1279 return false;
1280 }
1281
1282 /// Return true if the instruction contains a base register and offset. If
1283 /// true, the function also sets the operand position in the instruction
1284 /// for the base register and offset.
1285 virtual bool getBaseAndOffsetPosition(const MachineInstr &MI,
1286 unsigned &BasePos,
1287 unsigned &OffsetPos) const {
1288 return false;
1289 }
1290
1291 /// Target dependent implementation to get the values constituting the address
1292 /// MachineInstr that is accessing memory. These values are returned as a
1293 /// struct ExtAddrMode which contains all relevant information to make up the
1294 /// address.
1295 virtual Optional<ExtAddrMode>
1296 getAddrModeFromMemoryOp(const MachineInstr &MemI,
1297 const TargetRegisterInfo *TRI) const {
1298 return None;
1299 }
1300
1301 /// Returns true if MI's Def is NullValueReg, and the MI
1302 /// does not change the Zero value. i.e. cases such as rax = shr rax, X where
1303 /// NullValueReg = rax. Note that if the NullValueReg is non-zero, this
1304 /// function can return true even if becomes zero. Specifically cases such as
1305 /// NullValueReg = shl NullValueReg, 63.
1306 virtual bool preservesZeroValueInReg(const MachineInstr *MI,
1307 const Register NullValueReg,
1308 const TargetRegisterInfo *TRI) const {
1309 return false;
1310 }
1311
1312 /// If the instruction is an increment of a constant value, return the amount.
1313 virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const {
1314 return false;
1315 }
1316
1317 /// Returns true if the two given memory operations should be scheduled
1318 /// adjacent. Note that you have to add:
1319 /// DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1320 /// or
1321 /// DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
1322 /// to TargetPassConfig::createMachineScheduler() to have an effect.
1323 ///
1324 /// \p BaseOps1 and \p BaseOps2 are memory operands of two memory operations.
1325 /// \p NumLoads is the number of loads that will be in the cluster if this
1326 /// hook returns true.
1327 /// \p NumBytes is the number of bytes that will be loaded from all the
1328 /// clustered loads if this hook returns true.
1329 virtual bool shouldClusterMemOps(ArrayRef<const MachineOperand *> BaseOps1,
1330 ArrayRef<const MachineOperand *> BaseOps2,
1331 unsigned NumLoads, unsigned NumBytes) const {
1332 llvm_unreachable("target did not implement shouldClusterMemOps()")::llvm::llvm_unreachable_internal("target did not implement shouldClusterMemOps()"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1332)
;
1333 }
1334
1335 /// Reverses the branch condition of the specified condition list,
1336 /// returning false on success and true if it cannot be reversed.
1337 virtual bool
1338 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1339 return true;
1340 }
1341
1342 /// Insert a noop into the instruction stream at the specified point.
1343 virtual void insertNoop(MachineBasicBlock &MBB,
1344 MachineBasicBlock::iterator MI) const;
1345
1346 /// Insert noops into the instruction stream at the specified point.
1347 virtual void insertNoops(MachineBasicBlock &MBB,
1348 MachineBasicBlock::iterator MI,
1349 unsigned Quantity) const;
1350
1351 /// Return the noop instruction to use for a noop.
1352 virtual void getNoop(MCInst &NopInst) const;
1353
1354 /// Return true for post-incremented instructions.
1355 virtual bool isPostIncrement(const MachineInstr &MI) const { return false; }
1356
1357 /// Returns true if the instruction is already predicated.
1358 virtual bool isPredicated(const MachineInstr &MI) const { return false; }
1359
1360 // Returns a MIRPrinter comment for this machine operand.
1361 virtual std::string
1362 createMIROperandComment(const MachineInstr &MI, const MachineOperand &Op,
1363 unsigned OpIdx, const TargetRegisterInfo *TRI) const;
1364
1365 /// Returns true if the instruction is a
1366 /// terminator instruction that has not been predicated.
1367 bool isUnpredicatedTerminator(const MachineInstr &MI) const;
1368
1369 /// Returns true if MI is an unconditional tail call.
1370 virtual bool isUnconditionalTailCall(const MachineInstr &MI) const {
1371 return false;
1372 }
1373
1374 /// Returns true if the tail call can be made conditional on BranchCond.
1375 virtual bool canMakeTailCallConditional(SmallVectorImpl<MachineOperand> &Cond,
1376 const MachineInstr &TailCall) const {
1377 return false;
1378 }
1379
1380 /// Replace the conditional branch in MBB with a conditional tail call.
1381 virtual void replaceBranchWithTailCall(MachineBasicBlock &MBB,
1382 SmallVectorImpl<MachineOperand> &Cond,
1383 const MachineInstr &TailCall) const {
1384 llvm_unreachable("Target didn't implement replaceBranchWithTailCall!")::llvm::llvm_unreachable_internal("Target didn't implement replaceBranchWithTailCall!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1384)
;
1385 }
1386
1387 /// Convert the instruction into a predicated instruction.
1388 /// It returns true if the operation was successful.
1389 virtual bool PredicateInstruction(MachineInstr &MI,
1390 ArrayRef<MachineOperand> Pred) const;
1391
1392 /// Returns true if the first specified predicate
1393 /// subsumes the second, e.g. GE subsumes GT.
1394 virtual bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1395 ArrayRef<MachineOperand> Pred2) const {
1396 return false;
1397 }
1398
1399 /// If the specified instruction defines any predicate
1400 /// or condition code register(s) used for predication, returns true as well
1401 /// as the definition predicate(s) by reference.
1402 /// SkipDead should be set to false at any point that dead
1403 /// predicate instructions should be considered as being defined.
1404 /// A dead predicate instruction is one that is guaranteed to be removed
1405 /// after a call to PredicateInstruction.
1406 virtual bool ClobbersPredicate(MachineInstr &MI,
1407 std::vector<MachineOperand> &Pred,
1408 bool SkipDead) const {
1409 return false;
1410 }
1411
1412 /// Return true if the specified instruction can be predicated.
1413 /// By default, this returns true for every instruction with a
1414 /// PredicateOperand.
1415 virtual bool isPredicable(const MachineInstr &MI) const {
1416 return MI.getDesc().isPredicable();
1417 }
1418
1419 /// Return true if it's safe to move a machine
1420 /// instruction that defines the specified register class.
1421 virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
1422 return true;
1423 }
1424
1425 /// Test if the given instruction should be considered a scheduling boundary.
1426 /// This primarily includes labels and terminators.
1427 virtual bool isSchedulingBoundary(const MachineInstr &MI,
1428 const MachineBasicBlock *MBB,
1429 const MachineFunction &MF) const;
1430
1431 /// Measure the specified inline asm to determine an approximation of its
1432 /// length.
1433 virtual unsigned getInlineAsmLength(
1434 const char *Str, const MCAsmInfo &MAI,
1435 const TargetSubtargetInfo *STI = nullptr) const;
1436
1437 /// Allocate and return a hazard recognizer to use for this target when
1438 /// scheduling the machine instructions before register allocation.
1439 virtual ScheduleHazardRecognizer *
1440 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1441 const ScheduleDAG *DAG) const;
1442
1443 /// Allocate and return a hazard recognizer to use for this target when
1444 /// scheduling the machine instructions before register allocation.
1445 virtual ScheduleHazardRecognizer *
1446 CreateTargetMIHazardRecognizer(const InstrItineraryData *,
1447 const ScheduleDAGMI *DAG) const;
1448
1449 /// Allocate and return a hazard recognizer to use for this target when
1450 /// scheduling the machine instructions after register allocation.
1451 virtual ScheduleHazardRecognizer *
1452 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *,
1453 const ScheduleDAG *DAG) const;
1454
1455 /// Allocate and return a hazard recognizer to use for by non-scheduling
1456 /// passes.
1457 virtual ScheduleHazardRecognizer *
1458 CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
1459 return nullptr;
1460 }
1461
1462 /// Provide a global flag for disabling the PreRA hazard recognizer that
1463 /// targets may choose to honor.
1464 bool usePreRAHazardRecognizer() const;
1465
1466 /// For a comparison instruction, return the source registers
1467 /// in SrcReg and SrcReg2 if having two register operands, and the value it
1468 /// compares against in CmpValue. Return true if the comparison instruction
1469 /// can be analyzed.
1470 virtual bool analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1471 Register &SrcReg2, int &Mask, int &Value) const {
1472 return false;
1473 }
1474
1475 /// See if the comparison instruction can be converted
1476 /// into something more efficient. E.g., on ARM most instructions can set the
1477 /// flags register, obviating the need for a separate CMP.
1478 virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
1479 Register SrcReg2, int Mask, int Value,
1480 const MachineRegisterInfo *MRI) const {
1481 return false;
1482 }
1483 virtual bool optimizeCondBranch(MachineInstr &MI) const { return false; }
1484
1485 /// Try to remove the load by folding it to a register operand at the use.
1486 /// We fold the load instructions if and only if the
1487 /// def and use are in the same BB. We only look at one load and see
1488 /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
1489 /// defined by the load we are trying to fold. DefMI returns the machine
1490 /// instruction that defines FoldAsLoadDefReg, and the function returns
1491 /// the machine instruction generated due to folding.
1492 virtual MachineInstr *optimizeLoadInstr(MachineInstr &MI,
1493 const MachineRegisterInfo *MRI,
1494 Register &FoldAsLoadDefReg,
1495 MachineInstr *&DefMI) const {
1496 return nullptr;
1497 }
1498
1499 /// 'Reg' is known to be defined by a move immediate instruction,
1500 /// try to fold the immediate into the use instruction.
1501 /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
1502 /// then the caller may assume that DefMI has been erased from its parent
1503 /// block. The caller may assume that it will not be erased by this
1504 /// function otherwise.
1505 virtual bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1506 Register Reg, MachineRegisterInfo *MRI) const {
1507 return false;
1508 }
1509
1510 /// Return the number of u-operations the given machine
1511 /// instruction will be decoded to on the target cpu. The itinerary's
1512 /// IssueWidth is the number of microops that can be dispatched each
1513 /// cycle. An instruction with zero microops takes no dispatch resources.
1514 virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
1515 const MachineInstr &MI) const;
1516
1517 /// Return true for pseudo instructions that don't consume any
1518 /// machine resources in their current form. These are common cases that the
1519 /// scheduler should consider free, rather than conservatively handling them
1520 /// as instructions with no itinerary.
1521 bool isZeroCost(unsigned Opcode) const {
1522 return Opcode <= TargetOpcode::COPY;
1523 }
1524
1525 virtual int getOperandLatency(const InstrItineraryData *ItinData,
1526 SDNode *DefNode, unsigned DefIdx,
1527 SDNode *UseNode, unsigned UseIdx) const;
1528
1529 /// Compute and return the use operand latency of a given pair of def and use.
1530 /// In most cases, the static scheduling itinerary was enough to determine the
1531 /// operand latency. But it may not be possible for instructions with variable
1532 /// number of defs / uses.
1533 ///
1534 /// This is a raw interface to the itinerary that may be directly overridden
1535 /// by a target. Use computeOperandLatency to get the best estimate of
1536 /// latency.
1537 virtual int getOperandLatency(const InstrItineraryData *ItinData,
1538 const MachineInstr &DefMI, unsigned DefIdx,
1539 const MachineInstr &UseMI,
1540 unsigned UseIdx) const;
1541
1542 /// Compute the instruction latency of a given instruction.
1543 /// If the instruction has higher cost when predicated, it's returned via
1544 /// PredCost.
1545 virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1546 const MachineInstr &MI,
1547 unsigned *PredCost = nullptr) const;
1548
1549 virtual unsigned getPredicationCost(const MachineInstr &MI) const;
1550
1551 virtual int getInstrLatency(const InstrItineraryData *ItinData,
1552 SDNode *Node) const;
1553
1554 /// Return the default expected latency for a def based on its opcode.
1555 unsigned defaultDefLatency(const MCSchedModel &SchedModel,
1556 const MachineInstr &DefMI) const;
1557
1558 int computeDefOperandLatency(const InstrItineraryData *ItinData,
1559 const MachineInstr &DefMI) const;
1560
1561 /// Return true if this opcode has high latency to its result.
1562 virtual bool isHighLatencyDef(int opc) const { return false; }
1563
1564 /// Compute operand latency between a def of 'Reg'
1565 /// and a use in the current loop. Return true if the target considered
1566 /// it 'high'. This is used by optimization passes such as machine LICM to
1567 /// determine whether it makes sense to hoist an instruction out even in a
1568 /// high register pressure situation.
1569 virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
1570 const MachineRegisterInfo *MRI,
1571 const MachineInstr &DefMI, unsigned DefIdx,
1572 const MachineInstr &UseMI,
1573 unsigned UseIdx) const {
1574 return false;
1575 }
1576
1577 /// Compute operand latency of a def of 'Reg'. Return true
1578 /// if the target considered it 'low'.
1579 virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel,
1580 const MachineInstr &DefMI,
1581 unsigned DefIdx) const;
1582
1583 /// Perform target-specific instruction verification.
1584 virtual bool verifyInstruction(const MachineInstr &MI,
1585 StringRef &ErrInfo) const {
1586 return true;
1587 }
1588
1589 /// Return the current execution domain and bit mask of
1590 /// possible domains for instruction.
1591 ///
1592 /// Some micro-architectures have multiple execution domains, and multiple
1593 /// opcodes that perform the same operation in different domains. For
1594 /// example, the x86 architecture provides the por, orps, and orpd
1595 /// instructions that all do the same thing. There is a latency penalty if a
1596 /// register is written in one domain and read in another.
1597 ///
1598 /// This function returns a pair (domain, mask) containing the execution
1599 /// domain of MI, and a bit mask of possible domains. The setExecutionDomain
1600 /// function can be used to change the opcode to one of the domains in the
1601 /// bit mask. Instructions whose execution domain can't be changed should
1602 /// return a 0 mask.
1603 ///
1604 /// The execution domain numbers don't have any special meaning except domain
1605 /// 0 is used for instructions that are not associated with any interesting
1606 /// execution domain.
1607 ///
1608 virtual std::pair<uint16_t, uint16_t>
1609 getExecutionDomain(const MachineInstr &MI) const {
1610 return std::make_pair(0, 0);
1611 }
1612
1613 /// Change the opcode of MI to execute in Domain.
1614 ///
1615 /// The bit (1 << Domain) must be set in the mask returned from
1616 /// getExecutionDomain(MI).
1617 virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const {}
1618
1619 /// Returns the preferred minimum clearance
1620 /// before an instruction with an unwanted partial register update.
1621 ///
1622 /// Some instructions only write part of a register, and implicitly need to
1623 /// read the other parts of the register. This may cause unwanted stalls
1624 /// preventing otherwise unrelated instructions from executing in parallel in
1625 /// an out-of-order CPU.
1626 ///
1627 /// For example, the x86 instruction cvtsi2ss writes its result to bits
1628 /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
1629 /// the instruction needs to wait for the old value of the register to become
1630 /// available:
1631 ///
1632 /// addps %xmm1, %xmm0
1633 /// movaps %xmm0, (%rax)
1634 /// cvtsi2ss %rbx, %xmm0
1635 ///
1636 /// In the code above, the cvtsi2ss instruction needs to wait for the addps
1637 /// instruction before it can issue, even though the high bits of %xmm0
1638 /// probably aren't needed.
1639 ///
1640 /// This hook returns the preferred clearance before MI, measured in
1641 /// instructions. Other defs of MI's operand OpNum are avoided in the last N
1642 /// instructions before MI. It should only return a positive value for
1643 /// unwanted dependencies. If the old bits of the defined register have
1644 /// useful values, or if MI is determined to otherwise read the dependency,
1645 /// the hook should return 0.
1646 ///
1647 /// The unwanted dependency may be handled by:
1648 ///
1649 /// 1. Allocating the same register for an MI def and use. That makes the
1650 /// unwanted dependency identical to a required dependency.
1651 ///
1652 /// 2. Allocating a register for the def that has no defs in the previous N
1653 /// instructions.
1654 ///
1655 /// 3. Calling breakPartialRegDependency() with the same arguments. This
1656 /// allows the target to insert a dependency breaking instruction.
1657 ///
1658 virtual unsigned
1659 getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum,
1660 const TargetRegisterInfo *TRI) const {
1661 // The default implementation returns 0 for no partial register dependency.
1662 return 0;
1663 }
1664
1665 /// Return the minimum clearance before an instruction that reads an
1666 /// unused register.
1667 ///
1668 /// For example, AVX instructions may copy part of a register operand into
1669 /// the unused high bits of the destination register.
1670 ///
1671 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
1672 ///
1673 /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
1674 /// false dependence on any previous write to %xmm0.
1675 ///
1676 /// This hook works similarly to getPartialRegUpdateClearance, except that it
1677 /// does not take an operand index. Instead sets \p OpNum to the index of the
1678 /// unused register.
1679 virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned OpNum,
1680 const TargetRegisterInfo *TRI) const {
1681 // The default implementation returns 0 for no undef register dependency.
1682 return 0;
1683 }
1684
1685 /// Insert a dependency-breaking instruction
1686 /// before MI to eliminate an unwanted dependency on OpNum.
1687 ///
1688 /// If it wasn't possible to avoid a def in the last N instructions before MI
1689 /// (see getPartialRegUpdateClearance), this hook will be called to break the
1690 /// unwanted dependency.
1691 ///
1692 /// On x86, an xorps instruction can be used as a dependency breaker:
1693 ///
1694 /// addps %xmm1, %xmm0
1695 /// movaps %xmm0, (%rax)
1696 /// xorps %xmm0, %xmm0
1697 /// cvtsi2ss %rbx, %xmm0
1698 ///
1699 /// An <imp-kill> operand should be added to MI if an instruction was
1700 /// inserted. This ties the instructions together in the post-ra scheduler.
1701 ///
1702 virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
1703 const TargetRegisterInfo *TRI) const {}
1704
1705 /// Create machine specific model for scheduling.
1706 virtual DFAPacketizer *
1707 CreateTargetScheduleState(const TargetSubtargetInfo &) const {
1708 return nullptr;
1709 }
1710
1711 /// Sometimes, it is possible for the target
1712 /// to tell, even without aliasing information, that two MIs access different
1713 /// memory addresses. This function returns true if two MIs access different
1714 /// memory addresses and false otherwise.
1715 ///
1716 /// Assumes any physical registers used to compute addresses have the same
1717 /// value for both instructions. (This is the most useful assumption for
1718 /// post-RA scheduling.)
1719 ///
1720 /// See also MachineInstr::mayAlias, which is implemented on top of this
1721 /// function.
1722 virtual bool
1723 areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
1724 const MachineInstr &MIb) const {
1725 assert(MIa.mayLoadOrStore() &&((MIa.mayLoadOrStore() && "MIa must load from or modify a memory location"
) ? static_cast<void> (0) : __assert_fail ("MIa.mayLoadOrStore() && \"MIa must load from or modify a memory location\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1726, __PRETTY_FUNCTION__))
1726 "MIa must load from or modify a memory location")((MIa.mayLoadOrStore() && "MIa must load from or modify a memory location"
) ? static_cast<void> (0) : __assert_fail ("MIa.mayLoadOrStore() && \"MIa must load from or modify a memory location\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1726, __PRETTY_FUNCTION__))
;
1727 assert(MIb.mayLoadOrStore() &&((MIb.mayLoadOrStore() && "MIb must load from or modify a memory location"
) ? static_cast<void> (0) : __assert_fail ("MIb.mayLoadOrStore() && \"MIb must load from or modify a memory location\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1728, __PRETTY_FUNCTION__))
1728 "MIb must load from or modify a memory location")((MIb.mayLoadOrStore() && "MIb must load from or modify a memory location"
) ? static_cast<void> (0) : __assert_fail ("MIb.mayLoadOrStore() && \"MIb must load from or modify a memory location\""
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1728, __PRETTY_FUNCTION__))
;
1729 return false;
1730 }
1731
1732 /// Return the value to use for the MachineCSE's LookAheadLimit,
1733 /// which is a heuristic used for CSE'ing phys reg defs.
1734 virtual unsigned getMachineCSELookAheadLimit() const {
1735 // The default lookahead is small to prevent unprofitable quadratic
1736 // behavior.
1737 return 5;
1738 }
1739
1740 /// Return an array that contains the ids of the target indices (used for the
1741 /// TargetIndex machine operand) and their names.
1742 ///
1743 /// MIR Serialization is able to serialize only the target indices that are
1744 /// defined by this method.
1745 virtual ArrayRef<std::pair<int, const char *>>
1746 getSerializableTargetIndices() const {
1747 return None;
1748 }
1749
1750 /// Decompose the machine operand's target flags into two values - the direct
1751 /// target flag value and any of bit flags that are applied.
1752 virtual std::pair<unsigned, unsigned>
1753 decomposeMachineOperandsTargetFlags(unsigned /*TF*/) const {
1754 return std::make_pair(0u, 0u);
1755 }
1756
1757 /// Return an array that contains the direct target flag values and their
1758 /// names.
1759 ///
1760 /// MIR Serialization is able to serialize only the target flags that are
1761 /// defined by this method.
1762 virtual ArrayRef<std::pair<unsigned, const char *>>
1763 getSerializableDirectMachineOperandTargetFlags() const {
1764 return None;
1765 }
1766
1767 /// Return an array that contains the bitmask target flag values and their
1768 /// names.
1769 ///
1770 /// MIR Serialization is able to serialize only the target flags that are
1771 /// defined by this method.
1772 virtual ArrayRef<std::pair<unsigned, const char *>>
1773 getSerializableBitmaskMachineOperandTargetFlags() const {
1774 return None;
1775 }
1776
1777 /// Return an array that contains the MMO target flag values and their
1778 /// names.
1779 ///
1780 /// MIR Serialization is able to serialize only the MMO target flags that are
1781 /// defined by this method.
1782 virtual ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
1783 getSerializableMachineMemOperandTargetFlags() const {
1784 return None;
1785 }
1786
1787 /// Determines whether \p Inst is a tail call instruction. Override this
1788 /// method on targets that do not properly set MCID::Return and MCID::Call on
1789 /// tail call instructions."
1790 virtual bool isTailCall(const MachineInstr &Inst) const {
1791 return Inst.isReturn() && Inst.isCall();
1792 }
1793
1794 /// True if the instruction is bound to the top of its basic block and no
1795 /// other instructions shall be inserted before it. This can be implemented
1796 /// to prevent register allocator to insert spills before such instructions.
1797 virtual bool isBasicBlockPrologue(const MachineInstr &MI) const {
1798 return false;
1799 }
1800
1801 /// During PHI eleimination lets target to make necessary checks and
1802 /// insert the copy to the PHI destination register in a target specific
1803 /// manner.
1804 virtual MachineInstr *createPHIDestinationCopy(
1805 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
1806 const DebugLoc &DL, Register Src, Register Dst) const {
1807 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
1808 .addReg(Src);
1809 }
1810
1811 /// During PHI eleimination lets target to make necessary checks and
1812 /// insert the copy to the PHI destination register in a target specific
1813 /// manner.
1814 virtual MachineInstr *createPHISourceCopy(MachineBasicBlock &MBB,
1815 MachineBasicBlock::iterator InsPt,
1816 const DebugLoc &DL, Register Src,
1817 unsigned SrcSubReg,
1818 Register Dst) const {
1819 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
1820 .addReg(Src, 0, SrcSubReg);
1821 }
1822
1823 /// Returns a \p outliner::OutlinedFunction struct containing target-specific
1824 /// information for a set of outlining candidates.
1825 virtual outliner::OutlinedFunction getOutliningCandidateInfo(
1826 std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
1827 llvm_unreachable(::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1828)
1828 "Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1828)
;
1829 }
1830
1831 /// Returns how or if \p MI should be outlined.
1832 virtual outliner::InstrType
1833 getOutliningType(MachineBasicBlock::iterator &MIT, unsigned Flags) const {
1834 llvm_unreachable(::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::getOutliningType!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1835)
1835 "Target didn't implement TargetInstrInfo::getOutliningType!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::getOutliningType!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1835)
;
1836 }
1837
1838 /// Optional target hook that returns true if \p MBB is safe to outline from,
1839 /// and returns any target-specific information in \p Flags.
1840 virtual bool isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
1841 unsigned &Flags) const {
1842 return true;
1843 }
1844
1845 /// Insert a custom frame for outlined functions.
1846 virtual void buildOutlinedFrame(MachineBasicBlock &MBB, MachineFunction &MF,
1847 const outliner::OutlinedFunction &OF) const {
1848 llvm_unreachable(::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::buildOutlinedFrame!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1849)
1849 "Target didn't implement TargetInstrInfo::buildOutlinedFrame!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::buildOutlinedFrame!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1849)
;
1850 }
1851
1852 /// Insert a call to an outlined function into the program.
1853 /// Returns an iterator to the spot where we inserted the call. This must be
1854 /// implemented by the target.
1855 virtual MachineBasicBlock::iterator
1856 insertOutlinedCall(Module &M, MachineBasicBlock &MBB,
1857 MachineBasicBlock::iterator &It, MachineFunction &MF,
1858 const outliner::Candidate &C) const {
1859 llvm_unreachable(::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertOutlinedCall!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1860)
1860 "Target didn't implement TargetInstrInfo::insertOutlinedCall!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertOutlinedCall!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1860)
;
1861 }
1862
1863 /// Return true if the function can safely be outlined from.
1864 /// A function \p MF is considered safe for outlining if an outlined function
1865 /// produced from instructions in F will produce a program which produces the
1866 /// same output for any set of given inputs.
1867 virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF,
1868 bool OutlineFromLinkOnceODRs) const {
1869 llvm_unreachable("Target didn't implement "::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::isFunctionSafeToOutlineFrom!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1870)
1870 "TargetInstrInfo::isFunctionSafeToOutlineFrom!")::llvm::llvm_unreachable_internal("Target didn't implement " "TargetInstrInfo::isFunctionSafeToOutlineFrom!"
, "/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 1870)
;
1871 }
1872
1873 /// Return true if the function should be outlined from by default.
1874 virtual bool shouldOutlineFromFunctionByDefault(MachineFunction &MF) const {
1875 return false;
1876 }
1877
1878 /// Produce the expression describing the \p MI loading a value into
1879 /// the physical register \p Reg. This hook should only be used with
1880 /// \p MIs belonging to VReg-less functions.
1881 virtual Optional<ParamLoadedValue> describeLoadedValue(const MachineInstr &MI,
1882 Register Reg) const;
1883
1884 /// Return MIR formatter to format/parse MIR operands. Target can override
1885 /// this virtual function and return target specific MIR formatter.
1886 virtual const MIRFormatter *getMIRFormatter() const {
1887 if (!Formatter.get())
1888 Formatter = std::make_unique<MIRFormatter>();
1889 return Formatter.get();
1890 }
1891
1892private:
1893 mutable std::unique_ptr<MIRFormatter> Formatter;
1894 unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
1895 unsigned CatchRetOpcode;
1896 unsigned ReturnOpcode;
1897};
1898
1899/// Provide DenseMapInfo for TargetInstrInfo::RegSubRegPair.
1900template <> struct DenseMapInfo<TargetInstrInfo::RegSubRegPair> {
1901 using RegInfo = DenseMapInfo<unsigned>;
1902
1903 static inline TargetInstrInfo::RegSubRegPair getEmptyKey() {
1904 return TargetInstrInfo::RegSubRegPair(RegInfo::getEmptyKey(),
1905 RegInfo::getEmptyKey());
1906 }
1907
1908 static inline TargetInstrInfo::RegSubRegPair getTombstoneKey() {
1909 return TargetInstrInfo::RegSubRegPair(RegInfo::getTombstoneKey(),
1910 RegInfo::getTombstoneKey());
1911 }
1912
1913 /// Reuse getHashValue implementation from
1914 /// std::pair<unsigned, unsigned>.
1915 static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val) {
1916 std::pair<unsigned, unsigned> PairVal = std::make_pair(Val.Reg, Val.SubReg);
1917 return DenseMapInfo<std::pair<unsigned, unsigned>>::getHashValue(PairVal);
1918 }
1919
1920 static bool isEqual(const TargetInstrInfo::RegSubRegPair &LHS,
1921 const TargetInstrInfo::RegSubRegPair &RHS) {
1922 return RegInfo::isEqual(LHS.Reg, RHS.Reg) &&
1923 RegInfo::isEqual(LHS.SubReg, RHS.SubReg);
1924 }
1925};
1926
1927} // end namespace llvm
1928
1929#endif // LLVM_TARGET_TARGETINSTRINFO_H