Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

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

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/MachineInstr.h

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

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