Bug Summary

File:llvm/lib/CodeGen/InlineSpiller.cpp
Warning:line 302, column 61
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~++20200915100651+00ba1a3de7f/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f/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~++20200915100651+00ba1a3de7f/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f=. -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-09-15-222444-33637-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f/llvm/lib/CodeGen/InlineSpiller.cpp

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

/build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f/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~++20200915100651+00ba1a3de7f/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~++20200915100651+00ba1a3de7f/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 /// Emit an error referring to the source location of this instruction.
460 /// This should only be used for inline assembly that is somehow
461 /// impossible to compile. Other errors should have been handled much
462 /// earlier.
463 ///
464 /// If this method returns, the caller should try to recover from the error.
465 void emitError(StringRef Msg) const;
466
467 /// Returns the target instruction descriptor of this MachineInstr.
468 const MCInstrDesc &getDesc() const { return *MCID; }
469
470 /// Returns the opcode of this MachineInstr.
471 unsigned getOpcode() const { return MCID->Opcode; }
472
473 /// Retuns the total number of operands.
474 unsigned getNumOperands() const { return NumOperands; }
475
476 /// Returns the total number of operands which are debug locations.
477 unsigned getNumDebugOperands() const {
478 return std::distance(debug_operands().begin(), debug_operands().end());
479 }
480
481 const MachineOperand& getOperand(unsigned i) const {
482 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 482, __PRETTY_FUNCTION__))
;
483 return Operands[i];
484 }
485 MachineOperand& getOperand(unsigned i) {
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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 486, __PRETTY_FUNCTION__))
;
487 return Operands[i];
488 }
489
490 MachineOperand &getDebugOperand(unsigned Index) {
491 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 491, __PRETTY_FUNCTION__))
;
492 return *(debug_operands().begin() + Index);
493 }
494 const MachineOperand &getDebugOperand(unsigned Index) const {
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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 495, __PRETTY_FUNCTION__))
;
496 return *(debug_operands().begin() + Index);
497 }
498
499 /// Returns a pointer to the operand corresponding to a debug use of Reg, or
500 /// nullptr if Reg is not used in any debug operand.
501 const MachineOperand *getDebugOperandForReg(Register Reg) const {
502 const MachineOperand *RegOp =
503 find_if(debug_operands(), [Reg](const MachineOperand &Op) {
504 return Op.isReg() && Op.getReg() == Reg;
505 });
506 return RegOp == adl_end(debug_operands()) ? nullptr : RegOp;
507 }
508 MachineOperand *getDebugOperandForReg(Register Reg) {
509 MachineOperand *RegOp =
510 find_if(debug_operands(), [Reg](const MachineOperand &Op) {
511 return Op.isReg() && Op.getReg() == Reg;
512 });
513 return RegOp == adl_end(debug_operands()) ? nullptr : RegOp;
514 }
515
516 unsigned getDebugOperandIndex(const MachineOperand *Op) const {
517 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 518, __PRETTY_FUNCTION__))
518 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 518, __PRETTY_FUNCTION__))
;
519 return std::distance(adl_begin(debug_operands()), Op);
520 }
521
522 /// Returns the total number of definitions.
523 unsigned getNumDefs() const {
524 return getNumExplicitDefs() + MCID->getNumImplicitDefs();
525 }
526
527 /// Returns true if the instruction has implicit definition.
528 bool hasImplicitDef() const {
529 for (unsigned I = getNumExplicitOperands(), E = getNumOperands();
530 I != E; ++I) {
531 const MachineOperand &MO = getOperand(I);
532 if (MO.isDef() && MO.isImplicit())
533 return true;
534 }
535 return false;
536 }
537
538 /// Returns the implicit operands number.
539 unsigned getNumImplicitOperands() const {
540 return getNumOperands() - getNumExplicitOperands();
541 }
542
543 /// Return true if operand \p OpIdx is a subregister index.
544 bool isOperandSubregIdx(unsigned OpIdx) const {
545 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 546, __PRETTY_FUNCTION__))
546 "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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 546, __PRETTY_FUNCTION__))
;
547 if (isExtractSubreg() && OpIdx == 2)
548 return true;
549 if (isInsertSubreg() && OpIdx == 3)
550 return true;
551 if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
552 return true;
553 if (isSubregToReg() && OpIdx == 3)
554 return true;
555 return false;
556 }
557
558 /// Returns the number of non-implicit operands.
559 unsigned getNumExplicitOperands() const;
560
561 /// Returns the number of non-implicit definitions.
562 unsigned getNumExplicitDefs() const;
563
564 /// iterator/begin/end - Iterate over all operands of a machine instruction.
565 using mop_iterator = MachineOperand *;
566 using const_mop_iterator = const MachineOperand *;
567
568 mop_iterator operands_begin() { return Operands; }
569 mop_iterator operands_end() { return Operands + NumOperands; }
570
571 const_mop_iterator operands_begin() const { return Operands; }
572 const_mop_iterator operands_end() const { return Operands + NumOperands; }
573
574 iterator_range<mop_iterator> operands() {
575 return make_range(operands_begin(), operands_end());
576 }
577 iterator_range<const_mop_iterator> operands() const {
578 return make_range(operands_begin(), operands_end());
579 }
580 iterator_range<mop_iterator> explicit_operands() {
581 return make_range(operands_begin(),
582 operands_begin() + getNumExplicitOperands());
583 }
584 iterator_range<const_mop_iterator> explicit_operands() const {
585 return make_range(operands_begin(),
586 operands_begin() + getNumExplicitOperands());
587 }
588 iterator_range<mop_iterator> implicit_operands() {
589 return make_range(explicit_operands().end(), operands_end());
590 }
591 iterator_range<const_mop_iterator> implicit_operands() const {
592 return make_range(explicit_operands().end(), operands_end());
593 }
594 /// Returns a range over all operands that are used to determine the variable
595 /// location for this DBG_VALUE instruction.
596 iterator_range<mop_iterator> debug_operands() {
597 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 597, __PRETTY_FUNCTION__))
;
598 return make_range(operands_begin(), operands_begin() + 1);
599 }
600 /// \copydoc debug_operands()
601 iterator_range<const_mop_iterator> debug_operands() const {
602 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 602, __PRETTY_FUNCTION__))
;
603 return make_range(operands_begin(), operands_begin() + 1);
604 }
605 /// Returns a range over all explicit operands that are register definitions.
606 /// Implicit definition are not included!
607 iterator_range<mop_iterator> defs() {
608 return make_range(operands_begin(),
609 operands_begin() + getNumExplicitDefs());
610 }
611 /// \copydoc defs()
612 iterator_range<const_mop_iterator> defs() const {
613 return make_range(operands_begin(),
614 operands_begin() + getNumExplicitDefs());
615 }
616 /// Returns a range that includes all operands that are register uses.
617 /// This may include unrelated operands which are not register uses.
618 iterator_range<mop_iterator> uses() {
619 return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
620 }
621 /// \copydoc uses()
622 iterator_range<const_mop_iterator> uses() const {
623 return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
624 }
625 iterator_range<mop_iterator> explicit_uses() {
626 return make_range(operands_begin() + getNumExplicitDefs(),
627 operands_begin() + getNumExplicitOperands());
628 }
629 iterator_range<const_mop_iterator> explicit_uses() const {
630 return make_range(operands_begin() + getNumExplicitDefs(),
631 operands_begin() + getNumExplicitOperands());
632 }
633
634 /// Returns the number of the operand iterator \p I points to.
635 unsigned getOperandNo(const_mop_iterator I) const {
636 return I - operands_begin();
637 }
638
639 /// Access to memory operands of the instruction. If there are none, that does
640 /// not imply anything about whether the function accesses memory. Instead,
641 /// the caller must behave conservatively.
642 ArrayRef<MachineMemOperand *> memoperands() const {
643 if (!Info)
644 return {};
645
646 if (Info.is<EIIK_MMO>())
647 return makeArrayRef(Info.getAddrOfZeroTagPointer(), 1);
648
649 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
650 return EI->getMMOs();
651
652 return {};
653 }
654
655 /// Access to memory operands of the instruction.
656 ///
657 /// If `memoperands_begin() == memoperands_end()`, that does not imply
658 /// anything about whether the function accesses memory. Instead, the caller
659 /// must behave conservatively.
660 mmo_iterator memoperands_begin() const { return memoperands().begin(); }
661
662 /// Access to memory operands of the instruction.
663 ///
664 /// If `memoperands_begin() == memoperands_end()`, that does not imply
665 /// anything about whether the function accesses memory. Instead, the caller
666 /// must behave conservatively.
667 mmo_iterator memoperands_end() const { return memoperands().end(); }
668
669 /// Return true if we don't have any memory operands which described the
670 /// memory access done by this instruction. If this is true, calling code
671 /// must be conservative.
672 bool memoperands_empty() const { return memoperands().empty(); }
673
674 /// Return true if this instruction has exactly one MachineMemOperand.
675 bool hasOneMemOperand() const { return memoperands().size() == 1; }
676
677 /// Return the number of memory operands.
678 unsigned getNumMemOperands() const { return memoperands().size(); }
679
680 /// Helper to extract a pre-instruction symbol if one has been added.
681 MCSymbol *getPreInstrSymbol() const {
682 if (!Info)
683 return nullptr;
684 if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
685 return S;
686 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
687 return EI->getPreInstrSymbol();
688
689 return nullptr;
690 }
691
692 /// Helper to extract a post-instruction symbol if one has been added.
693 MCSymbol *getPostInstrSymbol() const {
694 if (!Info)
695 return nullptr;
696 if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
697 return S;
698 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
699 return EI->getPostInstrSymbol();
700
701 return nullptr;
702 }
703
704 /// Helper to extract a heap alloc marker if one has been added.
705 MDNode *getHeapAllocMarker() const {
706 if (!Info)
707 return nullptr;
708 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
709 return EI->getHeapAllocMarker();
710
711 return nullptr;
712 }
713
714 /// API for querying MachineInstr properties. They are the same as MCInstrDesc
715 /// queries but they are bundle aware.
716
717 enum QueryType {
718 IgnoreBundle, // Ignore bundles
719 AnyInBundle, // Return true if any instruction in bundle has property
720 AllInBundle // Return true if all instructions in bundle have property
721 };
722
723 /// Return true if the instruction (or in the case of a bundle,
724 /// the instructions inside the bundle) has the specified property.
725 /// The first argument is the property being queried.
726 /// The second argument indicates whether the query should look inside
727 /// instruction bundles.
728 bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
729 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 730, __PRETTY_FUNCTION__))
730 "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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 730, __PRETTY_FUNCTION__))
;
731 // Inline the fast path for unbundled or bundle-internal instructions.
732 if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
733 return getDesc().getFlags() & (1ULL << MCFlag);
734
735 // If this is the first instruction in a bundle, take the slow path.
736 return hasPropertyInBundle(1ULL << MCFlag, Type);
737 }
738
739 /// Return true if this is an instruction that should go through the usual
740 /// legalization steps.
741 bool isPreISelOpcode(QueryType Type = IgnoreBundle) const {
742 return hasProperty(MCID::PreISelOpcode, Type);
743 }
744
745 /// Return true if this instruction can have a variable number of operands.
746 /// In this case, the variable operands will be after the normal
747 /// operands but before the implicit definitions and uses (if any are
748 /// present).
749 bool isVariadic(QueryType Type = IgnoreBundle) const {
750 return hasProperty(MCID::Variadic, Type);
751 }
752
753 /// Set if this instruction has an optional definition, e.g.
754 /// ARM instructions which can set condition code if 's' bit is set.
755 bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
756 return hasProperty(MCID::HasOptionalDef, Type);
757 }
758
759 /// Return true if this is a pseudo instruction that doesn't
760 /// correspond to a real machine instruction.
761 bool isPseudo(QueryType Type = IgnoreBundle) const {
762 return hasProperty(MCID::Pseudo, Type);
763 }
764
765 bool isReturn(QueryType Type = AnyInBundle) const {
766 return hasProperty(MCID::Return, Type);
767 }
768
769 /// Return true if this is an instruction that marks the end of an EH scope,
770 /// i.e., a catchpad or a cleanuppad instruction.
771 bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
772 return hasProperty(MCID::EHScopeReturn, Type);
773 }
774
775 bool isCall(QueryType Type = AnyInBundle) const {
776 return hasProperty(MCID::Call, Type);
777 }
778
779 /// Return true if this is a call instruction that may have an associated
780 /// call site entry in the debug info.
781 bool isCandidateForCallSiteEntry(QueryType Type = IgnoreBundle) const;
782 /// Return true if copying, moving, or erasing this instruction requires
783 /// updating Call Site Info (see \ref copyCallSiteInfo, \ref moveCallSiteInfo,
784 /// \ref eraseCallSiteInfo).
785 bool shouldUpdateCallSiteInfo() const;
786
787 /// Returns true if the specified instruction stops control flow
788 /// from executing the instruction immediately following it. Examples include
789 /// unconditional branches and return instructions.
790 bool isBarrier(QueryType Type = AnyInBundle) const {
791 return hasProperty(MCID::Barrier, Type);
792 }
793
794 /// Returns true if this instruction part of the terminator for a basic block.
795 /// Typically this is things like return and branch instructions.
796 ///
797 /// Various passes use this to insert code into the bottom of a basic block,
798 /// but before control flow occurs.
799 bool isTerminator(QueryType Type = AnyInBundle) const {
800 return hasProperty(MCID::Terminator, Type);
801 }
802
803 /// Returns true if this is a conditional, unconditional, or indirect branch.
804 /// Predicates below can be used to discriminate between
805 /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to
806 /// get more information.
807 bool isBranch(QueryType Type = AnyInBundle) const {
808 return hasProperty(MCID::Branch, Type);
809 }
810
811 /// Return true if this is an indirect branch, such as a
812 /// branch through a register.
813 bool isIndirectBranch(QueryType Type = AnyInBundle) const {
814 return hasProperty(MCID::IndirectBranch, Type);
815 }
816
817 /// Return true if this is a branch which may fall
818 /// through to the next instruction or may transfer control flow to some other
819 /// block. The TargetInstrInfo::analyzeBranch method can be used to get more
820 /// information about this branch.
821 bool isConditionalBranch(QueryType Type = AnyInBundle) const {
822 return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type);
823 }
824
825 /// Return true if this is a branch which always
826 /// transfers control flow to some other block. The
827 /// TargetInstrInfo::analyzeBranch method can be used to get more information
828 /// about this branch.
829 bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
830 return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type);
831 }
832
833 /// Return true if this instruction has a predicate operand that
834 /// controls execution. It may be set to 'always', or may be set to other
835 /// values. There are various methods in TargetInstrInfo that can be used to
836 /// control and modify the predicate in this instruction.
837 bool isPredicable(QueryType Type = AllInBundle) const {
838 // If it's a bundle than all bundled instructions must be predicable for this
839 // to return true.
840 return hasProperty(MCID::Predicable, Type);
841 }
842
843 /// Return true if this instruction is a comparison.
844 bool isCompare(QueryType Type = IgnoreBundle) const {
845 return hasProperty(MCID::Compare, Type);
846 }
847
848 /// Return true if this instruction is a move immediate
849 /// (including conditional moves) instruction.
850 bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
851 return hasProperty(MCID::MoveImm, Type);
852 }
853
854 /// Return true if this instruction is a register move.
855 /// (including moving values from subreg to reg)
856 bool isMoveReg(QueryType Type = IgnoreBundle) const {
857 return hasProperty(MCID::MoveReg, Type);
858 }
859
860 /// Return true if this instruction is a bitcast instruction.
861 bool isBitcast(QueryType Type = IgnoreBundle) const {
862 return hasProperty(MCID::Bitcast, Type);
863 }
864
865 /// Return true if this instruction is a select instruction.
866 bool isSelect(QueryType Type = IgnoreBundle) const {
867 return hasProperty(MCID::Select, Type);
868 }
869
870 /// Return true if this instruction cannot be safely duplicated.
871 /// For example, if the instruction has a unique labels attached
872 /// to it, duplicating it would cause multiple definition errors.
873 bool isNotDuplicable(QueryType Type = AnyInBundle) const {
874 return hasProperty(MCID::NotDuplicable, Type);
875 }
876
877 /// Return true if this instruction is convergent.
878 /// Convergent instructions can not be made control-dependent on any
879 /// additional values.
880 bool isConvergent(QueryType Type = AnyInBundle) const {
881 if (isInlineAsm()) {
882 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
883 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
884 return true;
885 }
886 return hasProperty(MCID::Convergent, Type);
887 }
888
889 /// Returns true if the specified instruction has a delay slot
890 /// which must be filled by the code generator.
891 bool hasDelaySlot(QueryType Type = AnyInBundle) const {
892 return hasProperty(MCID::DelaySlot, Type);
893 }
894
895 /// Return true for instructions that can be folded as
896 /// memory operands in other instructions. The most common use for this
897 /// is instructions that are simple loads from memory that don't modify
898 /// the loaded value in any way, but it can also be used for instructions
899 /// that can be expressed as constant-pool loads, such as V_SETALLONES
900 /// on x86, to allow them to be folded when it is beneficial.
901 /// This should only be set on instructions that return a value in their
902 /// only virtual register definition.
903 bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
904 return hasProperty(MCID::FoldableAsLoad, Type);
905 }
906
907 /// Return true if this instruction behaves
908 /// the same way as the generic REG_SEQUENCE instructions.
909 /// E.g., on ARM,
910 /// dX VMOVDRR rY, rZ
911 /// is equivalent to
912 /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
913 ///
914 /// Note that for the optimizers to be able to take advantage of
915 /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
916 /// override accordingly.
917 bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
918 return hasProperty(MCID::RegSequence, Type);
919 }
920
921 /// Return true if this instruction behaves
922 /// the same way as the generic EXTRACT_SUBREG instructions.
923 /// E.g., on ARM,
924 /// rX, rY VMOVRRD dZ
925 /// is equivalent to two EXTRACT_SUBREG:
926 /// rX = EXTRACT_SUBREG dZ, ssub_0
927 /// rY = EXTRACT_SUBREG dZ, ssub_1
928 ///
929 /// Note that for the optimizers to be able to take advantage of
930 /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
931 /// override accordingly.
932 bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
933 return hasProperty(MCID::ExtractSubreg, Type);
934 }
935
936 /// Return true if this instruction behaves
937 /// the same way as the generic INSERT_SUBREG instructions.
938 /// E.g., on ARM,
939 /// dX = VSETLNi32 dY, rZ, Imm
940 /// is equivalent to a INSERT_SUBREG:
941 /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
942 ///
943 /// Note that for the optimizers to be able to take advantage of
944 /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
945 /// override accordingly.
946 bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
947 return hasProperty(MCID::InsertSubreg, Type);
948 }
949
950 //===--------------------------------------------------------------------===//
951 // Side Effect Analysis
952 //===--------------------------------------------------------------------===//
953
954 /// Return true if this instruction could possibly read memory.
955 /// Instructions with this flag set are not necessarily simple load
956 /// instructions, they may load a value and modify it, for example.
957 bool mayLoad(QueryType Type = AnyInBundle) const {
958 if (isInlineAsm()) {
959 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
960 if (ExtraInfo & InlineAsm::Extra_MayLoad)
961 return true;
962 }
963 return hasProperty(MCID::MayLoad, Type);
964 }
965
966 /// Return true if this instruction could possibly modify memory.
967 /// Instructions with this flag set are not necessarily simple store
968 /// instructions, they may store a modified value based on their operands, or
969 /// may not actually modify anything, for example.
970 bool mayStore(QueryType Type = AnyInBundle) const {
971 if (isInlineAsm()) {
972 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
973 if (ExtraInfo & InlineAsm::Extra_MayStore)
974 return true;
975 }
976 return hasProperty(MCID::MayStore, Type);
977 }
978
979 /// Return true if this instruction could possibly read or modify memory.
980 bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
981 return mayLoad(Type) || mayStore(Type);
982 }
983
984 /// Return true if this instruction could possibly raise a floating-point
985 /// exception. This is the case if the instruction is a floating-point
986 /// instruction that can in principle raise an exception, as indicated
987 /// by the MCID::MayRaiseFPException property, *and* at the same time,
988 /// the instruction is used in a context where we expect floating-point
989 /// exceptions are not disabled, as indicated by the NoFPExcept MI flag.
990 bool mayRaiseFPException() const {
991 return hasProperty(MCID::MayRaiseFPException) &&
992 !getFlag(MachineInstr::MIFlag::NoFPExcept);
993 }
994
995 //===--------------------------------------------------------------------===//
996 // Flags that indicate whether an instruction can be modified by a method.
997 //===--------------------------------------------------------------------===//
998
999 /// Return true if this may be a 2- or 3-address
1000 /// instruction (of the form "X = op Y, Z, ..."), which produces the same
1001 /// result if Y and Z are exchanged. If this flag is set, then the
1002 /// TargetInstrInfo::commuteInstruction method may be used to hack on the
1003 /// instruction.
1004 ///
1005 /// Note that this flag may be set on instructions that are only commutable
1006 /// sometimes. In these cases, the call to commuteInstruction will fail.
1007 /// Also note that some instructions require non-trivial modification to
1008 /// commute them.
1009 bool isCommutable(QueryType Type = IgnoreBundle) const {
1010 return hasProperty(MCID::Commutable, Type);
1011 }
1012
1013 /// Return true if this is a 2-address instruction
1014 /// which can be changed into a 3-address instruction if needed. Doing this
1015 /// transformation can be profitable in the register allocator, because it
1016 /// means that the instruction can use a 2-address form if possible, but
1017 /// degrade into a less efficient form if the source and dest register cannot
1018 /// be assigned to the same register. For example, this allows the x86
1019 /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
1020 /// is the same speed as the shift but has bigger code size.
1021 ///
1022 /// If this returns true, then the target must implement the
1023 /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
1024 /// is allowed to fail if the transformation isn't valid for this specific
1025 /// instruction (e.g. shl reg, 4 on x86).
1026 ///
1027 bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
1028 return hasProperty(MCID::ConvertibleTo3Addr, Type);
1029 }
1030
1031 /// Return true if this instruction requires
1032 /// custom insertion support when the DAG scheduler is inserting it into a
1033 /// machine basic block. If this is true for the instruction, it basically
1034 /// means that it is a pseudo instruction used at SelectionDAG time that is
1035 /// expanded out into magic code by the target when MachineInstrs are formed.
1036 ///
1037 /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
1038 /// is used to insert this into the MachineBasicBlock.
1039 bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
1040 return hasProperty(MCID::UsesCustomInserter, Type);
1041 }
1042
1043 /// Return true if this instruction requires *adjustment*
1044 /// after instruction selection by calling a target hook. For example, this
1045 /// can be used to fill in ARM 's' optional operand depending on whether
1046 /// the conditional flag register is used.
1047 bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
1048 return hasProperty(MCID::HasPostISelHook, Type);
1049 }
1050
1051 /// Returns true if this instruction is a candidate for remat.
1052 /// This flag is deprecated, please don't use it anymore. If this
1053 /// flag is set, the isReallyTriviallyReMaterializable() method is called to
1054 /// verify the instruction is really rematable.
1055 bool isRematerializable(QueryType Type = AllInBundle) const {
1056 // It's only possible to re-mat a bundle if all bundled instructions are
1057 // re-materializable.
1058 return hasProperty(MCID::Rematerializable, Type);
1059 }
1060
1061 /// Returns true if this instruction has the same cost (or less) than a move
1062 /// instruction. This is useful during certain types of optimizations
1063 /// (e.g., remat during two-address conversion or machine licm)
1064 /// where we would like to remat or hoist the instruction, but not if it costs
1065 /// more than moving the instruction into the appropriate register. Note, we
1066 /// are not marking copies from and to the same register class with this flag.
1067 bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
1068 // Only returns true for a bundle if all bundled instructions are cheap.
1069 return hasProperty(MCID::CheapAsAMove, Type);
1070 }
1071
1072 /// Returns true if this instruction source operands
1073 /// have special register allocation requirements that are not captured by the
1074 /// operand register classes. e.g. ARM::STRD's two source registers must be an
1075 /// even / odd pair, ARM::STM registers have to be in ascending order.
1076 /// Post-register allocation passes should not attempt to change allocations
1077 /// for sources of instructions with this flag.
1078 bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
1079 return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
1080 }
1081
1082 /// Returns true if this instruction def operands
1083 /// have special register allocation requirements that are not captured by the
1084 /// operand register classes. e.g. ARM::LDRD's two def registers must be an
1085 /// even / odd pair, ARM::LDM registers have to be in ascending order.
1086 /// Post-register allocation passes should not attempt to change allocations
1087 /// for definitions of instructions with this flag.
1088 bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
1089 return hasProperty(MCID::ExtraDefRegAllocReq, Type);
1090 }
1091
1092 enum MICheckType {
1093 CheckDefs, // Check all operands for equality
1094 CheckKillDead, // Check all operands including kill / dead markers
1095 IgnoreDefs, // Ignore all definitions
1096 IgnoreVRegDefs // Ignore virtual register definitions
1097 };
1098
1099 /// Return true if this instruction is identical to \p Other.
1100 /// Two instructions are identical if they have the same opcode and all their
1101 /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
1102 /// Note that this means liveness related flags (dead, undef, kill) do not
1103 /// affect the notion of identical.
1104 bool isIdenticalTo(const MachineInstr &Other,
1105 MICheckType Check = CheckDefs) const;
1106
1107 /// Unlink 'this' from the containing basic block, and return it without
1108 /// deleting it.
1109 ///
1110 /// This function can not be used on bundled instructions, use
1111 /// removeFromBundle() to remove individual instructions from a bundle.
1112 MachineInstr *removeFromParent();
1113
1114 /// Unlink this instruction from its basic block and return it without
1115 /// deleting it.
1116 ///
1117 /// If the instruction is part of a bundle, the other instructions in the
1118 /// bundle remain bundled.
1119 MachineInstr *removeFromBundle();
1120
1121 /// Unlink 'this' from the containing basic block and delete it.
1122 ///
1123 /// If this instruction is the header of a bundle, the whole bundle is erased.
1124 /// This function can not be used for instructions inside a bundle, use
1125 /// eraseFromBundle() to erase individual bundled instructions.
1126 void eraseFromParent();
1127
1128 /// Unlink 'this' from the containing basic block and delete it.
1129 ///
1130 /// For all definitions mark their uses in DBG_VALUE nodes
1131 /// as undefined. Otherwise like eraseFromParent().
1132 void eraseFromParentAndMarkDBGValuesForRemoval();
1133
1134 /// Unlink 'this' form its basic block and delete it.
1135 ///
1136 /// If the instruction is part of a bundle, the other instructions in the
1137 /// bundle remain bundled.
1138 void eraseFromBundle();
1139
1140 bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
1141 bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
1142 bool isAnnotationLabel() const {
1143 return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
1144 }
1145
1146 /// Returns true if the MachineInstr represents a label.
1147 bool isLabel() const {
1148 return isEHLabel() || isGCLabel() || isAnnotationLabel();
1149 }
1150
1151 bool isCFIInstruction() const {
1152 return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
1153 }
1154
1155 // True if the instruction represents a position in the function.
1156 bool isPosition() const { return isLabel() || isCFIInstruction(); }
1157
1158 bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
1159 bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
1160 bool isDebugRef() const { return getOpcode() == TargetOpcode::DBG_INSTR_REF; }
1161 bool isDebugInstr() const {
1162 return isDebugValue() || isDebugLabel() || isDebugRef();
1163 }
1164
1165 bool isDebugOffsetImm() const { return getDebugOffset().isImm(); }
1166
1167 /// A DBG_VALUE is indirect iff the location operand is a register and
1168 /// the offset operand is an immediate.
1169 bool isIndirectDebugValue() const {
1170 return isDebugValue() && getDebugOperand(0).isReg() && isDebugOffsetImm();
1171 }
1172
1173 /// A DBG_VALUE is an entry value iff its debug expression contains the
1174 /// DW_OP_LLVM_entry_value operation.
1175 bool isDebugEntryValue() const;
1176
1177 /// Return true if the instruction is a debug value which describes a part of
1178 /// a variable as unavailable.
1179 bool isUndefDebugValue() const {
1180 return isDebugValue() && getDebugOperand(0).isReg() &&
1181 !getDebugOperand(0).getReg().isValid();
1182 }
1183
1184 bool isPHI() const {
1185 return getOpcode() == TargetOpcode::PHI ||
1186 getOpcode() == TargetOpcode::G_PHI;
1187 }
1188 bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
1189 bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
1190 bool isInlineAsm() const {
1191 return getOpcode() == TargetOpcode::INLINEASM ||
1192 getOpcode() == TargetOpcode::INLINEASM_BR;
1193 }
1194
1195 /// FIXME: Seems like a layering violation that the AsmDialect, which is X86
1196 /// specific, be attached to a generic MachineInstr.
1197 bool isMSInlineAsm() const {
1198 return isInlineAsm() && getInlineAsmDialect() == InlineAsm::AD_Intel;
1199 }
1200
1201 bool isStackAligningInlineAsm() const;
1202 InlineAsm::AsmDialect getInlineAsmDialect() const;
1203
1204 bool isInsertSubreg() const {
1205 return getOpcode() == TargetOpcode::INSERT_SUBREG;
1206 }
1207
1208 bool isSubregToReg() const {
1209 return getOpcode() == TargetOpcode::SUBREG_TO_REG;
1210 }
1211
1212 bool isRegSequence() const {
1213 return getOpcode() == TargetOpcode::REG_SEQUENCE;
1214 }
1215
1216 bool isBundle() const {
1217 return getOpcode() == TargetOpcode::BUNDLE;
1218 }
1219
1220 bool isCopy() const {
1221 return getOpcode() == TargetOpcode::COPY;
1222 }
1223
1224 bool isFullCopy() const {
1225 return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
7
Returning zero, which participates in a condition later
1226 }
1227
1228 bool isExtractSubreg() const {
1229 return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
1230 }
1231
1232 /// Return true if the instruction behaves like a copy.
1233 /// This does not include native copy instructions.
1234 bool isCopyLike() const {
1235 return isCopy() || isSubregToReg();
1236 }
1237
1238 /// Return true is the instruction is an identity copy.
1239 bool isIdentityCopy() const {
1240 return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
1241 getOperand(0).getSubReg() == getOperand(1).getSubReg();
1242 }
1243
1244 /// Return true if this instruction doesn't produce any output in the form of
1245 /// executable instructions.
1246 bool isMetaInstruction() const {
1247 switch (getOpcode()) {
1248 default:
1249 return false;
1250 case TargetOpcode::IMPLICIT_DEF:
1251 case TargetOpcode::KILL:
1252 case TargetOpcode::CFI_INSTRUCTION:
1253 case TargetOpcode::EH_LABEL:
1254 case TargetOpcode::GC_LABEL:
1255 case TargetOpcode::DBG_VALUE:
1256 case TargetOpcode::DBG_INSTR_REF:
1257 case TargetOpcode::DBG_LABEL:
1258 case TargetOpcode::LIFETIME_START:
1259 case TargetOpcode::LIFETIME_END:
1260 return true;
1261 }
1262 }
1263
1264 /// Return true if this is a transient instruction that is either very likely
1265 /// to be eliminated during register allocation (such as copy-like
1266 /// instructions), or if this instruction doesn't have an execution-time cost.
1267 bool isTransient() const {
1268 switch (getOpcode()) {
1269 default:
1270 return isMetaInstruction();
1271 // Copy-like instructions are usually eliminated during register allocation.
1272 case TargetOpcode::PHI:
1273 case TargetOpcode::G_PHI:
1274 case TargetOpcode::COPY:
1275 case TargetOpcode::INSERT_SUBREG:
1276 case TargetOpcode::SUBREG_TO_REG:
1277 case TargetOpcode::REG_SEQUENCE:
1278 return true;
1279 }
1280 }
1281
1282 /// Return the number of instructions inside the MI bundle, excluding the
1283 /// bundle header.
1284 ///
1285 /// This is the number of instructions that MachineBasicBlock::iterator
1286 /// skips, 0 for unbundled instructions.
1287 unsigned getBundleSize() const;
1288
1289 /// Return true if the MachineInstr reads the specified register.
1290 /// If TargetRegisterInfo is passed, then it also checks if there
1291 /// is a read of a super-register.
1292 /// This does not count partial redefines of virtual registers as reads:
1293 /// %reg1024:6 = OP.
1294 bool readsRegister(Register Reg,
1295 const TargetRegisterInfo *TRI = nullptr) const {
1296 return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
1297 }
1298
1299 /// Return true if the MachineInstr reads the specified virtual register.
1300 /// Take into account that a partial define is a
1301 /// read-modify-write operation.
1302 bool readsVirtualRegister(Register Reg) const {
1303 return readsWritesVirtualRegister(Reg).first;
1304 }
1305
1306 /// Return a pair of bools (reads, writes) indicating if this instruction
1307 /// reads or writes Reg. This also considers partial defines.
1308 /// If Ops is not null, all operand indices for Reg are added.
1309 std::pair<bool,bool> readsWritesVirtualRegister(Register Reg,
1310 SmallVectorImpl<unsigned> *Ops = nullptr) const;
1311
1312 /// Return true if the MachineInstr kills the specified register.
1313 /// If TargetRegisterInfo is passed, then it also checks if there is
1314 /// a kill of a super-register.
1315 bool killsRegister(Register Reg,
1316 const TargetRegisterInfo *TRI = nullptr) const {
1317 return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
1318 }
1319
1320 /// Return true if the MachineInstr fully defines the specified register.
1321 /// If TargetRegisterInfo is passed, then it also checks
1322 /// if there is a def of a super-register.
1323 /// NOTE: It's ignoring subreg indices on virtual registers.
1324 bool definesRegister(Register Reg,
1325 const TargetRegisterInfo *TRI = nullptr) const {
1326 return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
1327 }
1328
1329 /// Return true if the MachineInstr modifies (fully define or partially
1330 /// define) the specified register.
1331 /// NOTE: It's ignoring subreg indices on virtual registers.
1332 bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1333 return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
1334 }
1335
1336 /// Returns true if the register is dead in this machine instruction.
1337 /// If TargetRegisterInfo is passed, then it also checks
1338 /// if there is a dead def of a super-register.
1339 bool registerDefIsDead(Register Reg,
1340 const TargetRegisterInfo *TRI = nullptr) const {
1341 return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
1342 }
1343
1344 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1345 /// the given register (not considering sub/super-registers).
1346 bool hasRegisterImplicitUseOperand(Register Reg) const;
1347
1348 /// Returns the operand index that is a use of the specific register or -1
1349 /// if it is not found. It further tightens the search criteria to a use
1350 /// that kills the register if isKill is true.
1351 int findRegisterUseOperandIdx(Register Reg, bool isKill = false,
1352 const TargetRegisterInfo *TRI = nullptr) const;
1353
1354 /// Wrapper for findRegisterUseOperandIdx, it returns
1355 /// a pointer to the MachineOperand rather than an index.
1356 MachineOperand *findRegisterUseOperand(Register Reg, bool isKill = false,
1357 const TargetRegisterInfo *TRI = nullptr) {
1358 int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
1359 return (Idx == -1) ? nullptr : &getOperand(Idx);
1360 }
1361
1362 const MachineOperand *findRegisterUseOperand(
1363 Register Reg, bool isKill = false,
1364 const TargetRegisterInfo *TRI = nullptr) const {
1365 return const_cast<MachineInstr *>(this)->
1366 findRegisterUseOperand(Reg, isKill, TRI);
1367 }
1368
1369 /// Returns the operand index that is a def of the specified register or
1370 /// -1 if it is not found. If isDead is true, defs that are not dead are
1371 /// skipped. If Overlap is true, then it also looks for defs that merely
1372 /// overlap the specified register. If TargetRegisterInfo is non-null,
1373 /// then it also checks if there is a def of a super-register.
1374 /// This may also return a register mask operand when Overlap is true.
1375 int findRegisterDefOperandIdx(Register Reg,
1376 bool isDead = false, bool Overlap = false,
1377 const TargetRegisterInfo *TRI = nullptr) const;
1378
1379 /// Wrapper for findRegisterDefOperandIdx, it returns
1380 /// a pointer to the MachineOperand rather than an index.
1381 MachineOperand *
1382 findRegisterDefOperand(Register Reg, bool isDead = false,
1383 bool Overlap = false,
1384 const TargetRegisterInfo *TRI = nullptr) {
1385 int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI);
1386 return (Idx == -1) ? nullptr : &getOperand(Idx);
1387 }
1388
1389 const MachineOperand *
1390 findRegisterDefOperand(Register Reg, bool isDead = false,
1391 bool Overlap = false,
1392 const TargetRegisterInfo *TRI = nullptr) const {
1393 return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
1394 Reg, isDead, Overlap, TRI);
1395 }
1396
1397 /// Find the index of the first operand in the
1398 /// operand list that is used to represent the predicate. It returns -1 if
1399 /// none is found.
1400 int findFirstPredOperandIdx() const;
1401
1402 /// Find the index of the flag word operand that
1403 /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if
1404 /// getOperand(OpIdx) does not belong to an inline asm operand group.
1405 ///
1406 /// If GroupNo is not NULL, it will receive the number of the operand group
1407 /// containing OpIdx.
1408 ///
1409 /// The flag operand is an immediate that can be decoded with methods like
1410 /// InlineAsm::hasRegClassConstraint().
1411 int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1412
1413 /// Compute the static register class constraint for operand OpIdx.
1414 /// For normal instructions, this is derived from the MCInstrDesc.
1415 /// For inline assembly it is derived from the flag words.
1416 ///
1417 /// Returns NULL if the static register class constraint cannot be
1418 /// determined.
1419 const TargetRegisterClass*
1420 getRegClassConstraint(unsigned OpIdx,
1421 const TargetInstrInfo *TII,
1422 const TargetRegisterInfo *TRI) const;
1423
1424 /// Applies the constraints (def/use) implied by this MI on \p Reg to
1425 /// the given \p CurRC.
1426 /// If \p ExploreBundle is set and MI is part of a bundle, all the
1427 /// instructions inside the bundle will be taken into account. In other words,
1428 /// this method accumulates all the constraints of the operand of this MI and
1429 /// the related bundle if MI is a bundle or inside a bundle.
1430 ///
1431 /// Returns the register class that satisfies both \p CurRC and the
1432 /// constraints set by MI. Returns NULL if such a register class does not
1433 /// exist.
1434 ///
1435 /// \pre CurRC must not be NULL.
1436 const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1437 Register Reg, const TargetRegisterClass *CurRC,
1438 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1439 bool ExploreBundle = false) const;
1440
1441 /// Applies the constraints (def/use) implied by the \p OpIdx operand
1442 /// to the given \p CurRC.
1443 ///
1444 /// Returns the register class that satisfies both \p CurRC and the
1445 /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1446 /// does not exist.
1447 ///
1448 /// \pre CurRC must not be NULL.
1449 /// \pre The operand at \p OpIdx must be a register.
1450 const TargetRegisterClass *
1451 getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1452 const TargetInstrInfo *TII,
1453 const TargetRegisterInfo *TRI) const;
1454
1455 /// Add a tie between the register operands at DefIdx and UseIdx.
1456 /// The tie will cause the register allocator to ensure that the two
1457 /// operands are assigned the same physical register.
1458 ///
1459 /// Tied operands are managed automatically for explicit operands in the
1460 /// MCInstrDesc. This method is for exceptional cases like inline asm.
1461 void tieOperands(unsigned DefIdx, unsigned UseIdx);
1462
1463 /// Given the index of a tied register operand, find the
1464 /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1465 /// index of the tied operand which must exist.
1466 unsigned findTiedOperandIdx(unsigned OpIdx) const;
1467
1468 /// Given the index of a register def operand,
1469 /// check if the register def is tied to a source operand, due to either
1470 /// two-address elimination or inline assembly constraints. Returns the
1471 /// first tied use operand index by reference if UseOpIdx is not null.
1472 bool isRegTiedToUseOperand(unsigned DefOpIdx,
1473 unsigned *UseOpIdx = nullptr) const {
1474 const MachineOperand &MO = getOperand(DefOpIdx);
1475 if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1476 return false;
1477 if (UseOpIdx)
1478 *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1479 return true;
1480 }
1481
1482 /// Return true if the use operand of the specified index is tied to a def
1483 /// operand. It also returns the def operand index by reference if DefOpIdx
1484 /// is not null.
1485 bool isRegTiedToDefOperand(unsigned UseOpIdx,
1486 unsigned *DefOpIdx = nullptr) const {
1487 const MachineOperand &MO = getOperand(UseOpIdx);
1488 if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1489 return false;
1490 if (DefOpIdx)
1491 *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1492 return true;
1493 }
1494
1495 /// Clears kill flags on all operands.
1496 void clearKillInfo();
1497
1498 /// Replace all occurrences of FromReg with ToReg:SubIdx,
1499 /// properly composing subreg indices where necessary.
1500 void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx,
1501 const TargetRegisterInfo &RegInfo);
1502
1503 /// We have determined MI kills a register. Look for the
1504 /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1505 /// add a implicit operand if it's not found. Returns true if the operand
1506 /// exists / is added.
1507 bool addRegisterKilled(Register IncomingReg,
1508 const TargetRegisterInfo *RegInfo,
1509 bool AddIfNotFound = false);
1510
1511 /// Clear all kill flags affecting Reg. If RegInfo is provided, this includes
1512 /// all aliasing registers.
1513 void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo);
1514
1515 /// We have determined MI defined a register without a use.
1516 /// Look for the operand that defines it and mark it as IsDead. If
1517 /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1518 /// true if the operand exists / is added.
1519 bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo,
1520 bool AddIfNotFound = false);
1521
1522 /// Clear all dead flags on operands defining register @p Reg.
1523 void clearRegisterDeads(Register Reg);
1524
1525 /// Mark all subregister defs of register @p Reg with the undef flag.
1526 /// This function is used when we determined to have a subregister def in an
1527 /// otherwise undefined super register.
1528 void setRegisterDefReadUndef(Register Reg, bool IsUndef = true);
1529
1530 /// We have determined MI defines a register. Make sure there is an operand
1531 /// defining Reg.
1532 void addRegisterDefined(Register Reg,
1533 const TargetRegisterInfo *RegInfo = nullptr);
1534
1535 /// Mark every physreg used by this instruction as
1536 /// dead except those in the UsedRegs list.
1537 ///
1538 /// On instructions with register mask operands, also add implicit-def
1539 /// operands for all registers in UsedRegs.
1540 void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
1541 const TargetRegisterInfo &TRI);
1542
1543 /// Return true if it is safe to move this instruction. If
1544 /// SawStore is set to true, it means that there is a store (or call) between
1545 /// the instruction's location and its intended destination.
1546 bool isSafeToMove(AAResults *AA, bool &SawStore) const;
1547
1548 /// Returns true if this instruction's memory access aliases the memory
1549 /// access of Other.
1550 //
1551 /// Assumes any physical registers used to compute addresses
1552 /// have the same value for both instructions. Returns false if neither
1553 /// instruction writes to memory.
1554 ///
1555 /// @param AA Optional alias analysis, used to compare memory operands.
1556 /// @param Other MachineInstr to check aliasing against.
1557 /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1558 bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const;
1559
1560 /// Return true if this instruction may have an ordered
1561 /// or volatile memory reference, or if the information describing the memory
1562 /// reference is not available. Return false if it is known to have no
1563 /// ordered or volatile memory references.
1564 bool hasOrderedMemoryRef() const;
1565
1566 /// Return true if this load instruction never traps and points to a memory
1567 /// location whose value doesn't change during the execution of this function.
1568 ///
1569 /// Examples include loading a value from the constant pool or from the
1570 /// argument area of a function (if it does not change). If the instruction
1571 /// does multiple loads, this returns true only if all of the loads are
1572 /// dereferenceable and invariant.
1573 bool isDereferenceableInvariantLoad(AAResults *AA) const;
1574
1575 /// If the specified instruction is a PHI that always merges together the
1576 /// same virtual register, return the register, otherwise return 0.
1577 unsigned isConstantValuePHI() const;
1578
1579 /// Return true if this instruction has side effects that are not modeled
1580 /// by mayLoad / mayStore, etc.
1581 /// For all instructions, the property is encoded in MCInstrDesc::Flags
1582 /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1583 /// INLINEASM instruction, in which case the side effect property is encoded
1584 /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1585 ///
1586 bool hasUnmodeledSideEffects() const;
1587
1588 /// Returns true if it is illegal to fold a load across this instruction.
1589 bool isLoadFoldBarrier() const;
1590
1591 /// Return true if all the defs of this instruction are dead.
1592 bool allDefsAreDead() const;
1593
1594 /// Return a valid size if the instruction is a spill instruction.
1595 Optional<unsigned> getSpillSize(const TargetInstrInfo *TII) const;
1596
1597 /// Return a valid size if the instruction is a folded spill instruction.
1598 Optional<unsigned> getFoldedSpillSize(const TargetInstrInfo *TII) const;
1599
1600 /// Return a valid size if the instruction is a restore instruction.
1601 Optional<unsigned> getRestoreSize(const TargetInstrInfo *TII) const;
1602
1603 /// Return a valid size if the instruction is a folded restore instruction.
1604 Optional<unsigned>
1605 getFoldedRestoreSize(const TargetInstrInfo *TII) const;
1606
1607 /// Copy implicit register operands from specified
1608 /// instruction to this instruction.
1609 void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1610
1611 /// Debugging support
1612 /// @{
1613 /// Determine the generic type to be printed (if needed) on uses and defs.
1614 LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1615 const MachineRegisterInfo &MRI) const;
1616
1617 /// Return true when an instruction has tied register that can't be determined
1618 /// by the instruction's descriptor. This is useful for MIR printing, to
1619 /// determine whether we need to print the ties or not.
1620 bool hasComplexRegisterTies() const;
1621
1622 /// Print this MI to \p OS.
1623 /// Don't print information that can be inferred from other instructions if
1624 /// \p IsStandalone is false. It is usually true when only a fragment of the
1625 /// function is printed.
1626 /// Only print the defs and the opcode if \p SkipOpers is true.
1627 /// Otherwise, also print operands if \p SkipDebugLoc is true.
1628 /// Otherwise, also print the debug loc, with a terminating newline.
1629 /// \p TII is used to print the opcode name. If it's not present, but the
1630 /// MI is in a function, the opcode will be printed using the function's TII.
1631 void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1632 bool SkipDebugLoc = false, bool AddNewLine = true,
1633 const TargetInstrInfo *TII = nullptr) const;
1634 void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1635 bool SkipOpers = false, bool SkipDebugLoc = false,
1636 bool AddNewLine = true,
1637 const TargetInstrInfo *TII = nullptr) const;
1638 void dump() const;
1639 /// Print on dbgs() the current instruction and the instructions defining its
1640 /// operands and so on until we reach \p MaxDepth.
1641 void dumpr(const MachineRegisterInfo &MRI,
1642 unsigned MaxDepth = UINT_MAX(2147483647 *2U +1U)) const;
1643 /// @}
1644
1645 //===--------------------------------------------------------------------===//
1646 // Accessors used to build up machine instructions.
1647
1648 /// Add the specified operand to the instruction. If it is an implicit
1649 /// operand, it is added to the end of the operand list. If it is an
1650 /// explicit operand it is added at the end of the explicit operand list
1651 /// (before the first implicit operand).
1652 ///
1653 /// MF must be the machine function that was used to allocate this
1654 /// instruction.
1655 ///
1656 /// MachineInstrBuilder provides a more convenient interface for creating
1657 /// instructions and adding operands.
1658 void addOperand(MachineFunction &MF, const MachineOperand &Op);
1659
1660 /// Add an operand without providing an MF reference. This only works for
1661 /// instructions that are inserted in a basic block.
1662 ///
1663 /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1664 /// preferred.
1665 void addOperand(const MachineOperand &Op);
1666
1667 /// Replace the instruction descriptor (thus opcode) of
1668 /// the current instruction with a new one.
1669 void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1670
1671 /// Replace current source information with new such.
1672 /// Avoid using this, the constructor argument is preferable.
1673 void setDebugLoc(DebugLoc dl) {
1674 debugLoc = std::move(dl);
1675 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 1675, __PRETTY_FUNCTION__))
;
1676 }
1677
1678 /// Erase an operand from an instruction, leaving it with one
1679 /// fewer operand than it started with.
1680 void RemoveOperand(unsigned OpNo);
1681
1682 /// Clear this MachineInstr's memory reference descriptor list. This resets
1683 /// the memrefs to their most conservative state. This should be used only
1684 /// as a last resort since it greatly pessimizes our knowledge of the memory
1685 /// access performed by the instruction.
1686 void dropMemRefs(MachineFunction &MF);
1687
1688 /// Assign this MachineInstr's memory reference descriptor list.
1689 ///
1690 /// Unlike other methods, this *will* allocate them into a new array
1691 /// associated with the provided `MachineFunction`.
1692 void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
1693
1694 /// Add a MachineMemOperand to the machine instruction.
1695 /// This function should be used only occasionally. The setMemRefs function
1696 /// is the primary method for setting up a MachineInstr's MemRefs list.
1697 void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1698
1699 /// Clone another MachineInstr's memory reference descriptor list and replace
1700 /// ours with it.
1701 ///
1702 /// Note that `*this` may be the incoming MI!
1703 ///
1704 /// Prefer this API whenever possible as it can avoid allocations in common
1705 /// cases.
1706 void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
1707
1708 /// Clone the merge of multiple MachineInstrs' memory reference descriptors
1709 /// list and replace ours with it.
1710 ///
1711 /// Note that `*this` may be one of the incoming MIs!
1712 ///
1713 /// Prefer this API whenever possible as it can avoid allocations in common
1714 /// cases.
1715 void cloneMergedMemRefs(MachineFunction &MF,
1716 ArrayRef<const MachineInstr *> MIs);
1717
1718 /// Set a symbol that will be emitted just prior to the instruction itself.
1719 ///
1720 /// Setting this to a null pointer will remove any such symbol.
1721 ///
1722 /// FIXME: This is not fully implemented yet.
1723 void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1724
1725 /// Set a symbol that will be emitted just after the instruction itself.
1726 ///
1727 /// Setting this to a null pointer will remove any such symbol.
1728 ///
1729 /// FIXME: This is not fully implemented yet.
1730 void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1731
1732 /// Clone another MachineInstr's pre- and post- instruction symbols and
1733 /// replace ours with it.
1734 void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
1735
1736 /// Set a marker on instructions that denotes where we should create and emit
1737 /// heap alloc site labels. This waits until after instruction selection and
1738 /// optimizations to create the label, so it should still work if the
1739 /// instruction is removed or duplicated.
1740 void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
1741
1742 /// Return the MIFlags which represent both MachineInstrs. This
1743 /// should be used when merging two MachineInstrs into one. This routine does
1744 /// not modify the MIFlags of this MachineInstr.
1745 uint16_t mergeFlagsWith(const MachineInstr& Other) const;
1746
1747 static uint16_t copyFlagsFromInstruction(const Instruction &I);
1748
1749 /// Copy all flags to MachineInst MIFlags
1750 void copyIRFlags(const Instruction &I);
1751
1752 /// Break any tie involving OpIdx.
1753 void untieRegOperand(unsigned OpIdx) {
1754 MachineOperand &MO = getOperand(OpIdx);
1755 if (MO.isReg() && MO.isTied()) {
1756 getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1757 MO.TiedTo = 0;
1758 }
1759 }
1760
1761 /// Add all implicit def and use operands to this instruction.
1762 void addImplicitDefUseOperands(MachineFunction &MF);
1763
1764 /// Scan instructions immediately following MI and collect any matching
1765 /// DBG_VALUEs.
1766 void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
1767
1768 /// Find all DBG_VALUEs that point to the register def in this instruction
1769 /// and point them to \p Reg instead.
1770 void changeDebugValuesDefReg(Register Reg);
1771
1772 /// Returns the Intrinsic::ID for this instruction.
1773 /// \pre Must have an intrinsic ID operand.
1774 unsigned getIntrinsicID() const {
1775 return getOperand(getNumExplicitDefs()).getIntrinsicID();
1776 }
1777
1778 /// Sets all register debug operands in this debug value instruction to be
1779 /// undef.
1780 void setDebugValueUndef() {
1781 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/MachineInstr.h"
, 1781, __PRETTY_FUNCTION__))
;
1782 for (MachineOperand &MO : debug_operands()) {
1783 if (MO.isReg())
1784 MO.setReg(0);
1785 }
1786 }
1787
1788private:
1789 /// If this instruction is embedded into a MachineFunction, return the
1790 /// MachineRegisterInfo object for the current function, otherwise
1791 /// return null.
1792 MachineRegisterInfo *getRegInfo();
1793
1794 /// Unlink all of the register operands in this instruction from their
1795 /// respective use lists. This requires that the operands already be on their
1796 /// use lists.
1797 void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1798
1799 /// Add all of the register operands in this instruction from their
1800 /// respective use lists. This requires that the operands not be on their
1801 /// use lists yet.
1802 void AddRegOperandsToUseLists(MachineRegisterInfo&);
1803
1804 /// Slow path for hasProperty when we're dealing with a bundle.
1805 bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
1806
1807 /// Implements the logic of getRegClassConstraintEffectForVReg for the
1808 /// this MI and the given operand index \p OpIdx.
1809 /// If the related operand does not constrained Reg, this returns CurRC.
1810 const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1811 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
1812 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1813
1814 /// Stores extra instruction information inline or allocates as ExtraInfo
1815 /// based on the number of pointers.
1816 void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
1817 MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
1818 MDNode *HeapAllocMarker);
1819};
1820
1821/// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1822/// instruction rather than by pointer value.
1823/// The hashing and equality testing functions ignore definitions so this is
1824/// useful for CSE, etc.
1825struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1826 static inline MachineInstr *getEmptyKey() {
1827 return nullptr;
1828 }
1829
1830 static inline MachineInstr *getTombstoneKey() {
1831 return reinterpret_cast<MachineInstr*>(-1);
1832 }
1833
1834 static unsigned getHashValue(const MachineInstr* const &MI);
1835
1836 static bool isEqual(const MachineInstr* const &LHS,
1837 const MachineInstr* const &RHS) {
1838 if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1839 LHS == getEmptyKey() || LHS == getTombstoneKey())
1840 return LHS == RHS;
1841 return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
1842 }
1843};
1844
1845//===----------------------------------------------------------------------===//
1846// Debugging Support
1847
1848inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1849 MI.print(OS);
1850 return OS;
1851}
1852
1853} // end namespace llvm
1854
1855#endif // LLVM_CODEGEN_MACHINEINSTR_H

/build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f/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 /// Note that isVirtualRegister() and isPhysicalRegister() cannot handle stack
44 /// slots, so if a variable may contains a stack slot, always check
45 /// isStackSlot() first.
46 ///
47 static bool isStackSlot(unsigned Reg) {
48 return MCRegister::isStackSlot(Reg);
49 }
50
51 /// Compute the frame index from a register value representing a stack slot.
52 static int stackSlot2Index(unsigned Reg) {
53 assert(isStackSlot(Reg) && "Not a stack slot")((isStackSlot(Reg) && "Not a stack slot") ? static_cast
<void> (0) : __assert_fail ("isStackSlot(Reg) && \"Not a stack slot\""
, "/build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f/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 unsigned 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/Register.h"
, 59, __PRETTY_FUNCTION__))
;
60 return 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 assert(!isStackSlot(Reg) && "Not a register! Check isStackSlot() first.")((!isStackSlot(Reg) && "Not a register! Check isStackSlot() first."
) ? static_cast<void> (0) : __assert_fail ("!isStackSlot(Reg) && \"Not a register! Check isStackSlot() first.\""
, "/build/llvm-toolchain-snapshot-12~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/Register.h"
, 72, __PRETTY_FUNCTION__))
;
73 return Reg & MCRegister::VirtualRegFlag;
74 }
75
76 /// Convert a virtual register number to a 0-based index.
77 /// The first virtual register in a function will get the index 0.
78 static unsigned virtReg2Index(unsigned Reg) {
79 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/Register.h"
, 79, __PRETTY_FUNCTION__))
;
80 return Reg & ~MCRegister::VirtualRegFlag;
81 }
82
83 /// Convert a 0-based index to a virtual register number.
84 /// This is the inverse operation of VirtReg2IndexFunctor below.
85 static unsigned index2VirtReg(unsigned Index) {
86 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~++20200915100651+00ba1a3de7f/llvm/include/llvm/CodeGen/Register.h"
, 86, __PRETTY_FUNCTION__))
;
87 return Index | MCRegister::VirtualRegFlag;
88 }
89
90 /// Return true if the specified register number is in the virtual register
91 /// namespace.
92 bool isVirtual() const {
93 return isVirtualRegister(Reg);
94 }
95
96 /// Return true if the specified register number is in the physical register
97 /// namespace.
98 bool isPhysical() const {
99 return isPhysicalRegister(Reg);
100 }
101
102 /// Convert a virtual register number to a 0-based index. The first virtual
103 /// register in a function will get the index 0.
104 unsigned virtRegIndex() const {
105 return virtReg2Index(Reg);
106 }
107
108 constexpr operator unsigned() const {
109 return Reg;
12
Returning zero, which participates in a condition later
110 }
111
112 unsigned id() const { return Reg; }
113
114 operator MCRegister() const {
115 return MCRegister(Reg);
116 }
117
118 bool isValid() const { return Reg != MCRegister::NoRegister; }
119
120 /// Comparisons between register objects
121 bool operator==(const Register &Other) const { return Reg == Other.Reg; }
122 bool operator!=(const Register &Other) const { return Reg != Other.Reg; }
123 bool operator==(const MCRegister &Other) const { return Reg == Other.id(); }
124 bool operator!=(const MCRegister &Other) const { return Reg != Other.id(); }
125
126 /// Comparisons against register constants. E.g.
127 /// * R == AArch64::WZR
128 /// * R == 0
129 /// * R == VirtRegMap::NO_PHYS_REG
130 bool operator==(unsigned Other) const { return Reg == Other; }
131 bool operator!=(unsigned Other) const { return Reg != Other; }
132 bool operator==(int Other) const { return Reg == unsigned(Other); }
133 bool operator!=(int Other) const { return Reg != unsigned(Other); }
134 // MSVC requires that we explicitly declare these two as well.
135 bool operator==(MCPhysReg Other) const { return Reg == unsigned(Other); }
136 bool operator!=(MCPhysReg Other) const { return Reg != unsigned(Other); }
137};
138
139// Provide DenseMapInfo for Register
140template<> struct DenseMapInfo<Register> {
141 static inline unsigned getEmptyKey() {
142 return DenseMapInfo<unsigned>::getEmptyKey();
143 }
144 static inline unsigned getTombstoneKey() {
145 return DenseMapInfo<unsigned>::getTombstoneKey();
146 }
147 static unsigned getHashValue(const Register &Val) {
148 return DenseMapInfo<unsigned>::getHashValue(Val.id());
149 }
150 static bool isEqual(const Register &LHS, const Register &RHS) {
151 return DenseMapInfo<unsigned>::isEqual(LHS.id(), RHS.id());
152 }
153};
154
155}
156
157#endif // ifndef LLVM_CODEGEN_REGISTER_H

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