Bug Summary

File:llvm/lib/CodeGen/InlineSpiller.cpp
Warning:line 472, column 55
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-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/InlineSpiller.cpp

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- 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 some templates that are useful if you are working with the
10// STL at all.
11//
12// No library is required when using these functions.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_STLEXTRAS_H
17#define LLVM_ADT_STLEXTRAS_H
18
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/iterator.h"
21#include "llvm/ADT/iterator_range.h"
22#include "llvm/Config/abi-breaking.h"
23#include "llvm/Support/ErrorHandling.h"
24#include <algorithm>
25#include <cassert>
26#include <cstddef>
27#include <cstdint>
28#include <cstdlib>
29#include <functional>
30#include <initializer_list>
31#include <iterator>
32#include <limits>
33#include <memory>
34#include <tuple>
35#include <type_traits>
36#include <utility>
37
38#ifdef EXPENSIVE_CHECKS
39#include <random> // for std::mt19937
40#endif
41
42namespace llvm {
43
44// Only used by compiler if both template types are the same. Useful when
45// using SFINAE to test for the existence of member functions.
46template <typename T, T> struct SameType;
47
48namespace detail {
49
50template <typename RangeT>
51using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
52
53} // end namespace detail
54
55//===----------------------------------------------------------------------===//
56// Extra additions to <type_traits>
57//===----------------------------------------------------------------------===//
58
59template <typename T>
60struct negation : std::integral_constant<bool, !bool(T::value)> {};
61
62template <typename...> struct conjunction : std::true_type {};
63template <typename B1> struct conjunction<B1> : B1 {};
64template <typename B1, typename... Bn>
65struct conjunction<B1, Bn...>
66 : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
67
68template <typename T> struct make_const_ptr {
69 using type =
70 typename std::add_pointer<typename std::add_const<T>::type>::type;
71};
72
73template <typename T> struct make_const_ref {
74 using type = typename std::add_lvalue_reference<
75 typename std::add_const<T>::type>::type;
76};
77
78//===----------------------------------------------------------------------===//
79// Extra additions to <functional>
80//===----------------------------------------------------------------------===//
81
82template <class Ty> struct identity {
83 using argument_type = Ty;
84
85 Ty &operator()(Ty &self) const {
86 return self;
87 }
88 const Ty &operator()(const Ty &self) const {
89 return self;
90 }
91};
92
93/// An efficient, type-erasing, non-owning reference to a callable. This is
94/// intended for use as the type of a function parameter that is not used
95/// after the function in question returns.
96///
97/// This class does not own the callable, so it is not in general safe to store
98/// a function_ref.
99template<typename Fn> class function_ref;
100
101template<typename Ret, typename ...Params>
102class function_ref<Ret(Params...)> {
103 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
104 intptr_t callable;
105
106 template<typename Callable>
107 static Ret callback_fn(intptr_t callable, Params ...params) {
108 return (*reinterpret_cast<Callable*>(callable))(
109 std::forward<Params>(params)...);
110 }
111
112public:
113 function_ref() = default;
114 function_ref(std::nullptr_t) {}
115
116 template <typename Callable>
117 function_ref(Callable &&callable,
118 std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>,
119 function_ref>::value> * = nullptr)
120 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
121 callable(reinterpret_cast<intptr_t>(&callable)) {}
122
123 Ret operator()(Params ...params) const {
124 return callback(callable, std::forward<Params>(params)...);
125 }
126
127 operator bool() const { return callback; }
128};
129
130// deleter - Very very very simple method that is used to invoke operator
131// delete on something. It is used like this:
132//
133// for_each(V.begin(), B.end(), deleter<Interval>);
134template <class T>
135inline void deleter(T *Ptr) {
136 delete Ptr;
137}
138
139//===----------------------------------------------------------------------===//
140// Extra additions to <iterator>
141//===----------------------------------------------------------------------===//
142
143namespace adl_detail {
144
145using std::begin;
146
147template <typename ContainerTy>
148decltype(auto) adl_begin(ContainerTy &&container) {
149 return begin(std::forward<ContainerTy>(container));
150}
151
152using std::end;
153
154template <typename ContainerTy>
155decltype(auto) adl_end(ContainerTy &&container) {
156 return end(std::forward<ContainerTy>(container));
157}
158
159using std::swap;
160
161template <typename T>
162void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
163 std::declval<T>()))) {
164 swap(std::forward<T>(lhs), std::forward<T>(rhs));
165}
166
167} // end namespace adl_detail
168
169template <typename ContainerTy>
170decltype(auto) adl_begin(ContainerTy &&container) {
171 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
172}
173
174template <typename ContainerTy>
175decltype(auto) adl_end(ContainerTy &&container) {
176 return adl_detail::adl_end(std::forward<ContainerTy>(container));
177}
178
179template <typename T>
180void adl_swap(T &&lhs, T &&rhs) noexcept(
181 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
182 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
183}
184
185/// Test whether \p RangeOrContainer is empty. Similar to C++17 std::empty.
186template <typename T>
187constexpr bool empty(const T &RangeOrContainer) {
188 return adl_begin(RangeOrContainer) == adl_end(RangeOrContainer);
189}
190
191/// Return a range covering \p RangeOrContainer with the first N elements
192/// excluded.
193template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N) {
194 return make_range(std::next(adl_begin(RangeOrContainer), N),
195 adl_end(RangeOrContainer));
196}
197
198// mapped_iterator - This is a simple iterator adapter that causes a function to
199// be applied whenever operator* is invoked on the iterator.
200
201template <typename ItTy, typename FuncTy,
202 typename FuncReturnTy =
203 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
204class mapped_iterator
205 : public iterator_adaptor_base<
206 mapped_iterator<ItTy, FuncTy>, ItTy,
207 typename std::iterator_traits<ItTy>::iterator_category,
208 typename std::remove_reference<FuncReturnTy>::type> {
209public:
210 mapped_iterator(ItTy U, FuncTy F)
211 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
212
213 ItTy getCurrent() { return this->I; }
214
215 FuncReturnTy operator*() { return F(*this->I); }
216
217private:
218 FuncTy F;
219};
220
221// map_iterator - Provide a convenient way to create mapped_iterators, just like
222// make_pair is useful for creating pairs...
223template <class ItTy, class FuncTy>
224inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
225 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
226}
227
228template <class ContainerTy, class FuncTy>
229auto map_range(ContainerTy &&C, FuncTy F) {
230 return make_range(map_iterator(C.begin(), F), map_iterator(C.end(), F));
231}
232
233/// Helper to determine if type T has a member called rbegin().
234template <typename Ty> class has_rbegin_impl {
235 using yes = char[1];
236 using no = char[2];
237
238 template <typename Inner>
239 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
240
241 template <typename>
242 static no& test(...);
243
244public:
245 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
246};
247
248/// Metafunction to determine if T& or T has a member called rbegin().
249template <typename Ty>
250struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
251};
252
253// Returns an iterator_range over the given container which iterates in reverse.
254// Note that the container must have rbegin()/rend() methods for this to work.
255template <typename ContainerTy>
256auto reverse(ContainerTy &&C,
257 std::enable_if_t<has_rbegin<ContainerTy>::value> * = nullptr) {
258 return make_range(C.rbegin(), C.rend());
259}
260
261// Returns a std::reverse_iterator wrapped around the given iterator.
262template <typename IteratorTy>
263std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
264 return std::reverse_iterator<IteratorTy>(It);
265}
266
267// Returns an iterator_range over the given container which iterates in reverse.
268// Note that the container must have begin()/end() methods which return
269// bidirectional iterators for this to work.
270template <typename ContainerTy>
271auto reverse(ContainerTy &&C,
272 std::enable_if_t<!has_rbegin<ContainerTy>::value> * = nullptr) {
273 return make_range(llvm::make_reverse_iterator(std::end(C)),
274 llvm::make_reverse_iterator(std::begin(C)));
275}
276
277/// An iterator adaptor that filters the elements of given inner iterators.
278///
279/// The predicate parameter should be a callable object that accepts the wrapped
280/// iterator's reference type and returns a bool. When incrementing or
281/// decrementing the iterator, it will call the predicate on each element and
282/// skip any where it returns false.
283///
284/// \code
285/// int A[] = { 1, 2, 3, 4 };
286/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
287/// // R contains { 1, 3 }.
288/// \endcode
289///
290/// Note: filter_iterator_base implements support for forward iteration.
291/// filter_iterator_impl exists to provide support for bidirectional iteration,
292/// conditional on whether the wrapped iterator supports it.
293template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
294class filter_iterator_base
295 : public iterator_adaptor_base<
296 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
297 WrappedIteratorT,
298 typename std::common_type<
299 IterTag, typename std::iterator_traits<
300 WrappedIteratorT>::iterator_category>::type> {
301 using BaseT = iterator_adaptor_base<
302 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
303 WrappedIteratorT,
304 typename std::common_type<
305 IterTag, typename std::iterator_traits<
306 WrappedIteratorT>::iterator_category>::type>;
307
308protected:
309 WrappedIteratorT End;
310 PredicateT Pred;
311
312 void findNextValid() {
313 while (this->I != End && !Pred(*this->I))
314 BaseT::operator++();
315 }
316
317 // Construct the iterator. The begin iterator needs to know where the end
318 // is, so that it can properly stop when it gets there. The end iterator only
319 // needs the predicate to support bidirectional iteration.
320 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
321 PredicateT Pred)
322 : BaseT(Begin), End(End), Pred(Pred) {
323 findNextValid();
324 }
325
326public:
327 using BaseT::operator++;
328
329 filter_iterator_base &operator++() {
330 BaseT::operator++();
331 findNextValid();
332 return *this;
333 }
334};
335
336/// Specialization of filter_iterator_base for forward iteration only.
337template <typename WrappedIteratorT, typename PredicateT,
338 typename IterTag = std::forward_iterator_tag>
339class filter_iterator_impl
340 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
341 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>;
342
343public:
344 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
345 PredicateT Pred)
346 : BaseT(Begin, End, Pred) {}
347};
348
349/// Specialization of filter_iterator_base for bidirectional iteration.
350template <typename WrappedIteratorT, typename PredicateT>
351class filter_iterator_impl<WrappedIteratorT, PredicateT,
352 std::bidirectional_iterator_tag>
353 : public filter_iterator_base<WrappedIteratorT, PredicateT,
354 std::bidirectional_iterator_tag> {
355 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
356 std::bidirectional_iterator_tag>;
357 void findPrevValid() {
358 while (!this->Pred(*this->I))
359 BaseT::operator--();
360 }
361
362public:
363 using BaseT::operator--;
364
365 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
366 PredicateT Pred)
367 : BaseT(Begin, End, Pred) {}
368
369 filter_iterator_impl &operator--() {
370 BaseT::operator--();
371 findPrevValid();
372 return *this;
373 }
374};
375
376namespace detail {
377
378template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
379 using type = std::forward_iterator_tag;
380};
381
382template <> struct fwd_or_bidi_tag_impl<true> {
383 using type = std::bidirectional_iterator_tag;
384};
385
386/// Helper which sets its type member to forward_iterator_tag if the category
387/// of \p IterT does not derive from bidirectional_iterator_tag, and to
388/// bidirectional_iterator_tag otherwise.
389template <typename IterT> struct fwd_or_bidi_tag {
390 using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
391 std::bidirectional_iterator_tag,
392 typename std::iterator_traits<IterT>::iterator_category>::value>::type;
393};
394
395} // namespace detail
396
397/// Defines filter_iterator to a suitable specialization of
398/// filter_iterator_impl, based on the underlying iterator's category.
399template <typename WrappedIteratorT, typename PredicateT>
400using filter_iterator = filter_iterator_impl<
401 WrappedIteratorT, PredicateT,
402 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
403
404/// Convenience function that takes a range of elements and a predicate,
405/// and return a new filter_iterator range.
406///
407/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
408/// lifetime of that temporary is not kept by the returned range object, and the
409/// temporary is going to be dropped on the floor after the make_iterator_range
410/// full expression that contains this function call.
411template <typename RangeT, typename PredicateT>
412iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
413make_filter_range(RangeT &&Range, PredicateT Pred) {
414 using FilterIteratorT =
415 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
416 return make_range(
417 FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
418 std::end(std::forward<RangeT>(Range)), Pred),
419 FilterIteratorT(std::end(std::forward<RangeT>(Range)),
420 std::end(std::forward<RangeT>(Range)), Pred));
421}
422
423/// A pseudo-iterator adaptor that is designed to implement "early increment"
424/// style loops.
425///
426/// This is *not a normal iterator* and should almost never be used directly. It
427/// is intended primarily to be used with range based for loops and some range
428/// algorithms.
429///
430/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
431/// somewhere between them. The constraints of these iterators are:
432///
433/// - On construction or after being incremented, it is comparable and
434/// dereferencable. It is *not* incrementable.
435/// - After being dereferenced, it is neither comparable nor dereferencable, it
436/// is only incrementable.
437///
438/// This means you can only dereference the iterator once, and you can only
439/// increment it once between dereferences.
440template <typename WrappedIteratorT>
441class early_inc_iterator_impl
442 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
443 WrappedIteratorT, std::input_iterator_tag> {
444 using BaseT =
445 iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
446 WrappedIteratorT, std::input_iterator_tag>;
447
448 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
449
450protected:
451#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
452 bool IsEarlyIncremented = false;
453#endif
454
455public:
456 early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
457
458 using BaseT::operator*;
459 typename BaseT::reference operator*() {
460#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
461 assert(!IsEarlyIncremented && "Cannot dereference twice!")((!IsEarlyIncremented && "Cannot dereference twice!")
? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot dereference twice!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h"
, 461, __PRETTY_FUNCTION__))
;
462 IsEarlyIncremented = true;
463#endif
464 return *(this->I)++;
465 }
466
467 using BaseT::operator++;
468 early_inc_iterator_impl &operator++() {
469#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
470 assert(IsEarlyIncremented && "Cannot increment before dereferencing!")((IsEarlyIncremented && "Cannot increment before dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("IsEarlyIncremented && \"Cannot increment before dereferencing!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h"
, 470, __PRETTY_FUNCTION__))
;
471 IsEarlyIncremented = false;
472#endif
473 return *this;
474 }
475
476 using BaseT::operator==;
477 bool operator==(const early_inc_iterator_impl &RHS) const {
478#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
479 assert(!IsEarlyIncremented && "Cannot compare after dereferencing!")((!IsEarlyIncremented && "Cannot compare after dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot compare after dereferencing!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h"
, 479, __PRETTY_FUNCTION__))
;
480#endif
481 return BaseT::operator==(RHS);
482 }
483};
484
485/// Make a range that does early increment to allow mutation of the underlying
486/// range without disrupting iteration.
487///
488/// The underlying iterator will be incremented immediately after it is
489/// dereferenced, allowing deletion of the current node or insertion of nodes to
490/// not disrupt iteration provided they do not invalidate the *next* iterator --
491/// the current iterator can be invalidated.
492///
493/// This requires a very exact pattern of use that is only really suitable to
494/// range based for loops and other range algorithms that explicitly guarantee
495/// to dereference exactly once each element, and to increment exactly once each
496/// element.
497template <typename RangeT>
498iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
499make_early_inc_range(RangeT &&Range) {
500 using EarlyIncIteratorT =
501 early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
502 return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
503 EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
504}
505
506// forward declarations required by zip_shortest/zip_first/zip_longest
507template <typename R, typename UnaryPredicate>
508bool all_of(R &&range, UnaryPredicate P);
509template <typename R, typename UnaryPredicate>
510bool any_of(R &&range, UnaryPredicate P);
511
512namespace detail {
513
514using std::declval;
515
516// We have to alias this since inlining the actual type at the usage site
517// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
518template<typename... Iters> struct ZipTupleType {
519 using type = std::tuple<decltype(*declval<Iters>())...>;
520};
521
522template <typename ZipType, typename... Iters>
523using zip_traits = iterator_facade_base<
524 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
525 typename std::iterator_traits<
526 Iters>::iterator_category...>::type,
527 // ^ TODO: Implement random access methods.
528 typename ZipTupleType<Iters...>::type,
529 typename std::iterator_traits<typename std::tuple_element<
530 0, std::tuple<Iters...>>::type>::difference_type,
531 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
532 // inner iterators have the same difference_type. It would fail if, for
533 // instance, the second field's difference_type were non-numeric while the
534 // first is.
535 typename ZipTupleType<Iters...>::type *,
536 typename ZipTupleType<Iters...>::type>;
537
538template <typename ZipType, typename... Iters>
539struct zip_common : public zip_traits<ZipType, Iters...> {
540 using Base = zip_traits<ZipType, Iters...>;
541 using value_type = typename Base::value_type;
542
543 std::tuple<Iters...> iterators;
544
545protected:
546 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
547 return value_type(*std::get<Ns>(iterators)...);
548 }
549
550 template <size_t... Ns>
551 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
552 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
553 }
554
555 template <size_t... Ns>
556 decltype(iterators) tup_dec(std::index_sequence<Ns...>) const {
557 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
558 }
559
560public:
561 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
562
563 value_type operator*() { return deref(std::index_sequence_for<Iters...>{}); }
564
565 const value_type operator*() const {
566 return deref(std::index_sequence_for<Iters...>{});
567 }
568
569 ZipType &operator++() {
570 iterators = tup_inc(std::index_sequence_for<Iters...>{});
571 return *reinterpret_cast<ZipType *>(this);
572 }
573
574 ZipType &operator--() {
575 static_assert(Base::IsBidirectional,
576 "All inner iterators must be at least bidirectional.");
577 iterators = tup_dec(std::index_sequence_for<Iters...>{});
578 return *reinterpret_cast<ZipType *>(this);
579 }
580};
581
582template <typename... Iters>
583struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
584 using Base = zip_common<zip_first<Iters...>, Iters...>;
585
586 bool operator==(const zip_first<Iters...> &other) const {
587 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
588 }
589
590 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
591};
592
593template <typename... Iters>
594class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
595 template <size_t... Ns>
596 bool test(const zip_shortest<Iters...> &other,
597 std::index_sequence<Ns...>) const {
598 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
599 std::get<Ns>(other.iterators)...},
600 identity<bool>{});
601 }
602
603public:
604 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
605
606 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
607
608 bool operator==(const zip_shortest<Iters...> &other) const {
609 return !test(other, std::index_sequence_for<Iters...>{});
610 }
611};
612
613template <template <typename...> class ItType, typename... Args> class zippy {
614public:
615 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
616 using iterator_category = typename iterator::iterator_category;
617 using value_type = typename iterator::value_type;
618 using difference_type = typename iterator::difference_type;
619 using pointer = typename iterator::pointer;
620 using reference = typename iterator::reference;
621
622private:
623 std::tuple<Args...> ts;
624
625 template <size_t... Ns>
626 iterator begin_impl(std::index_sequence<Ns...>) const {
627 return iterator(std::begin(std::get<Ns>(ts))...);
628 }
629 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
630 return iterator(std::end(std::get<Ns>(ts))...);
631 }
632
633public:
634 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
635
636 iterator begin() const {
637 return begin_impl(std::index_sequence_for<Args...>{});
638 }
639 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
640};
641
642} // end namespace detail
643
644/// zip iterator for two or more iteratable types.
645template <typename T, typename U, typename... Args>
646detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
647 Args &&... args) {
648 return detail::zippy<detail::zip_shortest, T, U, Args...>(
649 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
650}
651
652/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
653/// be the shortest.
654template <typename T, typename U, typename... Args>
655detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
656 Args &&... args) {
657 return detail::zippy<detail::zip_first, T, U, Args...>(
658 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
659}
660
661namespace detail {
662template <typename Iter>
663static Iter next_or_end(const Iter &I, const Iter &End) {
664 if (I == End)
665 return End;
666 return std::next(I);
667}
668
669template <typename Iter>
670static auto deref_or_none(const Iter &I, const Iter &End) -> llvm::Optional<
671 std::remove_const_t<std::remove_reference_t<decltype(*I)>>> {
672 if (I == End)
673 return None;
674 return *I;
675}
676
677template <typename Iter> struct ZipLongestItemType {
678 using type =
679 llvm::Optional<typename std::remove_const<typename std::remove_reference<
680 decltype(*std::declval<Iter>())>::type>::type>;
681};
682
683template <typename... Iters> struct ZipLongestTupleType {
684 using type = std::tuple<typename ZipLongestItemType<Iters>::type...>;
685};
686
687template <typename... Iters>
688class zip_longest_iterator
689 : public iterator_facade_base<
690 zip_longest_iterator<Iters...>,
691 typename std::common_type<
692 std::forward_iterator_tag,
693 typename std::iterator_traits<Iters>::iterator_category...>::type,
694 typename ZipLongestTupleType<Iters...>::type,
695 typename std::iterator_traits<typename std::tuple_element<
696 0, std::tuple<Iters...>>::type>::difference_type,
697 typename ZipLongestTupleType<Iters...>::type *,
698 typename ZipLongestTupleType<Iters...>::type> {
699public:
700 using value_type = typename ZipLongestTupleType<Iters...>::type;
701
702private:
703 std::tuple<Iters...> iterators;
704 std::tuple<Iters...> end_iterators;
705
706 template <size_t... Ns>
707 bool test(const zip_longest_iterator<Iters...> &other,
708 std::index_sequence<Ns...>) const {
709 return llvm::any_of(
710 std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
711 std::get<Ns>(other.iterators)...},
712 identity<bool>{});
713 }
714
715 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
716 return value_type(
717 deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
718 }
719
720 template <size_t... Ns>
721 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
722 return std::tuple<Iters...>(
723 next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
724 }
725
726public:
727 zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts)
728 : iterators(std::forward<Iters>(ts.first)...),
729 end_iterators(std::forward<Iters>(ts.second)...) {}
730
731 value_type operator*() { return deref(std::index_sequence_for<Iters...>{}); }
732
733 value_type operator*() const {
734 return deref(std::index_sequence_for<Iters...>{});
735 }
736
737 zip_longest_iterator<Iters...> &operator++() {
738 iterators = tup_inc(std::index_sequence_for<Iters...>{});
739 return *this;
740 }
741
742 bool operator==(const zip_longest_iterator<Iters...> &other) const {
743 return !test(other, std::index_sequence_for<Iters...>{});
744 }
745};
746
747template <typename... Args> class zip_longest_range {
748public:
749 using iterator =
750 zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>;
751 using iterator_category = typename iterator::iterator_category;
752 using value_type = typename iterator::value_type;
753 using difference_type = typename iterator::difference_type;
754 using pointer = typename iterator::pointer;
755 using reference = typename iterator::reference;
756
757private:
758 std::tuple<Args...> ts;
759
760 template <size_t... Ns>
761 iterator begin_impl(std::index_sequence<Ns...>) const {
762 return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)),
763 adl_end(std::get<Ns>(ts)))...);
764 }
765
766 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
767 return iterator(std::make_pair(adl_end(std::get<Ns>(ts)),
768 adl_end(std::get<Ns>(ts)))...);
769 }
770
771public:
772 zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
773
774 iterator begin() const {
775 return begin_impl(std::index_sequence_for<Args...>{});
776 }
777 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
778};
779} // namespace detail
780
781/// Iterate over two or more iterators at the same time. Iteration continues
782/// until all iterators reach the end. The llvm::Optional only contains a value
783/// if the iterator has not reached the end.
784template <typename T, typename U, typename... Args>
785detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u,
786 Args &&... args) {
787 return detail::zip_longest_range<T, U, Args...>(
788 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
789}
790
791/// Iterator wrapper that concatenates sequences together.
792///
793/// This can concatenate different iterators, even with different types, into
794/// a single iterator provided the value types of all the concatenated
795/// iterators expose `reference` and `pointer` types that can be converted to
796/// `ValueT &` and `ValueT *` respectively. It doesn't support more
797/// interesting/customized pointer or reference types.
798///
799/// Currently this only supports forward or higher iterator categories as
800/// inputs and always exposes a forward iterator interface.
801template <typename ValueT, typename... IterTs>
802class concat_iterator
803 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
804 std::forward_iterator_tag, ValueT> {
805 using BaseT = typename concat_iterator::iterator_facade_base;
806
807 /// We store both the current and end iterators for each concatenated
808 /// sequence in a tuple of pairs.
809 ///
810 /// Note that something like iterator_range seems nice at first here, but the
811 /// range properties are of little benefit and end up getting in the way
812 /// because we need to do mutation on the current iterators.
813 std::tuple<IterTs...> Begins;
814 std::tuple<IterTs...> Ends;
815
816 /// Attempts to increment a specific iterator.
817 ///
818 /// Returns true if it was able to increment the iterator. Returns false if
819 /// the iterator is already at the end iterator.
820 template <size_t Index> bool incrementHelper() {
821 auto &Begin = std::get<Index>(Begins);
822 auto &End = std::get<Index>(Ends);
823 if (Begin == End)
824 return false;
825
826 ++Begin;
827 return true;
828 }
829
830 /// Increments the first non-end iterator.
831 ///
832 /// It is an error to call this with all iterators at the end.
833 template <size_t... Ns> void increment(std::index_sequence<Ns...>) {
834 // Build a sequence of functions to increment each iterator if possible.
835 bool (concat_iterator::*IncrementHelperFns[])() = {
836 &concat_iterator::incrementHelper<Ns>...};
837
838 // Loop over them, and stop as soon as we succeed at incrementing one.
839 for (auto &IncrementHelperFn : IncrementHelperFns)
840 if ((this->*IncrementHelperFn)())
841 return;
842
843 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h"
, 843)
;
844 }
845
846 /// Returns null if the specified iterator is at the end. Otherwise,
847 /// dereferences the iterator and returns the address of the resulting
848 /// reference.
849 template <size_t Index> ValueT *getHelper() const {
850 auto &Begin = std::get<Index>(Begins);
851 auto &End = std::get<Index>(Ends);
852 if (Begin == End)
853 return nullptr;
854
855 return &*Begin;
856 }
857
858 /// Finds the first non-end iterator, dereferences, and returns the resulting
859 /// reference.
860 ///
861 /// It is an error to call this with all iterators at the end.
862 template <size_t... Ns> ValueT &get(std::index_sequence<Ns...>) const {
863 // Build a sequence of functions to get from iterator if possible.
864 ValueT *(concat_iterator::*GetHelperFns[])() const = {
865 &concat_iterator::getHelper<Ns>...};
866
867 // Loop over them, and return the first result we find.
868 for (auto &GetHelperFn : GetHelperFns)
869 if (ValueT *P = (this->*GetHelperFn)())
870 return *P;
871
872 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h"
, 872)
;
873 }
874
875public:
876 /// Constructs an iterator from a squence of ranges.
877 ///
878 /// We need the full range to know how to switch between each of the
879 /// iterators.
880 template <typename... RangeTs>
881 explicit concat_iterator(RangeTs &&... Ranges)
882 : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
883
884 using BaseT::operator++;
885
886 concat_iterator &operator++() {
887 increment(std::index_sequence_for<IterTs...>());
888 return *this;
889 }
890
891 ValueT &operator*() const {
892 return get(std::index_sequence_for<IterTs...>());
893 }
894
895 bool operator==(const concat_iterator &RHS) const {
896 return Begins == RHS.Begins && Ends == RHS.Ends;
897 }
898};
899
900namespace detail {
901
902/// Helper to store a sequence of ranges being concatenated and access them.
903///
904/// This is designed to facilitate providing actual storage when temporaries
905/// are passed into the constructor such that we can use it as part of range
906/// based for loops.
907template <typename ValueT, typename... RangeTs> class concat_range {
908public:
909 using iterator =
910 concat_iterator<ValueT,
911 decltype(std::begin(std::declval<RangeTs &>()))...>;
912
913private:
914 std::tuple<RangeTs...> Ranges;
915
916 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) {
917 return iterator(std::get<Ns>(Ranges)...);
918 }
919 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
920 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
921 std::end(std::get<Ns>(Ranges)))...);
922 }
923
924public:
925 concat_range(RangeTs &&... Ranges)
926 : Ranges(std::forward<RangeTs>(Ranges)...) {}
927
928 iterator begin() { return begin_impl(std::index_sequence_for<RangeTs...>{}); }
929 iterator end() { return end_impl(std::index_sequence_for<RangeTs...>{}); }
930};
931
932} // end namespace detail
933
934/// Concatenated range across two or more ranges.
935///
936/// The desired value type must be explicitly specified.
937template <typename ValueT, typename... RangeTs>
938detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
939 static_assert(sizeof...(RangeTs) > 1,
940 "Need more than one range to concatenate!");
941 return detail::concat_range<ValueT, RangeTs...>(
942 std::forward<RangeTs>(Ranges)...);
943}
944
945//===----------------------------------------------------------------------===//
946// Extra additions to <utility>
947//===----------------------------------------------------------------------===//
948
949/// Function object to check whether the first component of a std::pair
950/// compares less than the first component of another std::pair.
951struct less_first {
952 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
953 return lhs.first < rhs.first;
954 }
955};
956
957/// Function object to check whether the second component of a std::pair
958/// compares less than the second component of another std::pair.
959struct less_second {
960 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
961 return lhs.second < rhs.second;
962 }
963};
964
965/// \brief Function object to apply a binary function to the first component of
966/// a std::pair.
967template<typename FuncTy>
968struct on_first {
969 FuncTy func;
970
971 template <typename T>
972 decltype(auto) operator()(const T &lhs, const T &rhs) const {
973 return func(lhs.first, rhs.first);
974 }
975};
976
977/// Utility type to build an inheritance chain that makes it easy to rank
978/// overload candidates.
979template <int N> struct rank : rank<N - 1> {};
980template <> struct rank<0> {};
981
982/// traits class for checking whether type T is one of any of the given
983/// types in the variadic list.
984template <typename T, typename... Ts> struct is_one_of {
985 static const bool value = false;
986};
987
988template <typename T, typename U, typename... Ts>
989struct is_one_of<T, U, Ts...> {
990 static const bool value =
991 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
992};
993
994/// traits class for checking whether type T is a base class for all
995/// the given types in the variadic list.
996template <typename T, typename... Ts> struct are_base_of {
997 static const bool value = true;
998};
999
1000template <typename T, typename U, typename... Ts>
1001struct are_base_of<T, U, Ts...> {
1002 static const bool value =
1003 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
1004};
1005
1006//===----------------------------------------------------------------------===//
1007// Extra additions for arrays
1008//===----------------------------------------------------------------------===//
1009
1010// We have a copy here so that LLVM behaves the same when using different
1011// standard libraries.
1012template <class Iterator, class RNG>
1013void shuffle(Iterator first, Iterator last, RNG &&g) {
1014 // It would be better to use a std::uniform_int_distribution,
1015 // but that would be stdlib dependent.
1016 for (auto size = last - first; size > 1; ++first, (void)--size)
1017 std::iter_swap(first, first + g() % size);
1018}
1019
1020/// Find the length of an array.
1021template <class T, std::size_t N>
1022constexpr inline size_t array_lengthof(T (&)[N]) {
1023 return N;
1024}
1025
1026/// Adapt std::less<T> for array_pod_sort.
1027template<typename T>
1028inline int array_pod_sort_comparator(const void *P1, const void *P2) {
1029 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
1030 *reinterpret_cast<const T*>(P2)))
1031 return -1;
1032 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
1033 *reinterpret_cast<const T*>(P1)))
1034 return 1;
1035 return 0;
1036}
1037
1038/// get_array_pod_sort_comparator - This is an internal helper function used to
1039/// get type deduction of T right.
1040template<typename T>
1041inline int (*get_array_pod_sort_comparator(const T &))
1042 (const void*, const void*) {
1043 return array_pod_sort_comparator<T>;
1044}
1045
1046#ifdef EXPENSIVE_CHECKS
1047namespace detail {
1048
1049inline unsigned presortShuffleEntropy() {
1050 static unsigned Result(std::random_device{}());
1051 return Result;
1052}
1053
1054template <class IteratorTy>
1055inline void presortShuffle(IteratorTy Start, IteratorTy End) {
1056 std::mt19937 Generator(presortShuffleEntropy());
1057 std::shuffle(Start, End, Generator);
1058}
1059
1060} // end namespace detail
1061#endif
1062
1063/// array_pod_sort - This sorts an array with the specified start and end
1064/// extent. This is just like std::sort, except that it calls qsort instead of
1065/// using an inlined template. qsort is slightly slower than std::sort, but
1066/// most sorts are not performance critical in LLVM and std::sort has to be
1067/// template instantiated for each type, leading to significant measured code
1068/// bloat. This function should generally be used instead of std::sort where
1069/// possible.
1070///
1071/// This function assumes that you have simple POD-like types that can be
1072/// compared with std::less and can be moved with memcpy. If this isn't true,
1073/// you should use std::sort.
1074///
1075/// NOTE: If qsort_r were portable, we could allow a custom comparator and
1076/// default to std::less.
1077template<class IteratorTy>
1078inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
1079 // Don't inefficiently call qsort with one element or trigger undefined
1080 // behavior with an empty sequence.
1081 auto NElts = End - Start;
1082 if (NElts <= 1) return;
1083#ifdef EXPENSIVE_CHECKS
1084 detail::presortShuffle<IteratorTy>(Start, End);
1085#endif
1086 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
1087}
1088
1089template <class IteratorTy>
1090inline void array_pod_sort(
1091 IteratorTy Start, IteratorTy End,
1092 int (*Compare)(
1093 const typename std::iterator_traits<IteratorTy>::value_type *,
1094 const typename std::iterator_traits<IteratorTy>::value_type *)) {
1095 // Don't inefficiently call qsort with one element or trigger undefined
1096 // behavior with an empty sequence.
1097 auto NElts = End - Start;
1098 if (NElts <= 1) return;
1099#ifdef EXPENSIVE_CHECKS
1100 detail::presortShuffle<IteratorTy>(Start, End);
1101#endif
1102 qsort(&*Start, NElts, sizeof(*Start),
1103 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
1104}
1105
1106// Provide wrappers to std::sort which shuffle the elements before sorting
1107// to help uncover non-deterministic behavior (PR35135).
1108template <typename IteratorTy>
1109inline void sort(IteratorTy Start, IteratorTy End) {
1110#ifdef EXPENSIVE_CHECKS
1111 detail::presortShuffle<IteratorTy>(Start, End);
1112#endif
1113 std::sort(Start, End);
1114}
1115
1116template <typename Container> inline void sort(Container &&C) {
1117 llvm::sort(adl_begin(C), adl_end(C));
1118}
1119
1120template <typename IteratorTy, typename Compare>
1121inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
1122#ifdef EXPENSIVE_CHECKS
1123 detail::presortShuffle<IteratorTy>(Start, End);
1124#endif
1125 std::sort(Start, End, Comp);
1126}
1127
1128template <typename Container, typename Compare>
1129inline void sort(Container &&C, Compare Comp) {
1130 llvm::sort(adl_begin(C), adl_end(C), Comp);
1131}
1132
1133//===----------------------------------------------------------------------===//
1134// Extra additions to <algorithm>
1135//===----------------------------------------------------------------------===//
1136
1137/// For a container of pointers, deletes the pointers and then clears the
1138/// container.
1139template<typename Container>
1140void DeleteContainerPointers(Container &C) {
1141 for (auto V : C)
1142 delete V;
1143 C.clear();
1144}
1145
1146/// In a container of pairs (usually a map) whose second element is a pointer,
1147/// deletes the second elements and then clears the container.
1148template<typename Container>
1149void DeleteContainerSeconds(Container &C) {
1150 for (auto &V : C)
1151 delete V.second;
1152 C.clear();
1153}
1154
1155/// Get the size of a range. This is a wrapper function around std::distance
1156/// which is only enabled when the operation is O(1).
1157template <typename R>
1158auto size(R &&Range,
1159 std::enable_if_t<std::is_same<typename std::iterator_traits<decltype(
1160 Range.begin())>::iterator_category,
1161 std::random_access_iterator_tag>::value,
1162 void> * = nullptr) {
1163 return std::distance(Range.begin(), Range.end());
1164}
1165
1166/// Provide wrappers to std::for_each which take ranges instead of having to
1167/// pass begin/end explicitly.
1168template <typename R, typename UnaryPredicate>
1169UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
1170 return std::for_each(adl_begin(Range), adl_end(Range), P);
1171}
1172
1173/// Provide wrappers to std::all_of which take ranges instead of having to pass
1174/// begin/end explicitly.
1175template <typename R, typename UnaryPredicate>
1176bool all_of(R &&Range, UnaryPredicate P) {
1177 return std::all_of(adl_begin(Range), adl_end(Range), P);
1178}
1179
1180/// Provide wrappers to std::any_of which take ranges instead of having to pass
1181/// begin/end explicitly.
1182template <typename R, typename UnaryPredicate>
1183bool any_of(R &&Range, UnaryPredicate P) {
1184 return std::any_of(adl_begin(Range), adl_end(Range), P);
1185}
1186
1187/// Provide wrappers to std::none_of which take ranges instead of having to pass
1188/// begin/end explicitly.
1189template <typename R, typename UnaryPredicate>
1190bool none_of(R &&Range, UnaryPredicate P) {
1191 return std::none_of(adl_begin(Range), adl_end(Range), P);
1192}
1193
1194/// Provide wrappers to std::find which take ranges instead of having to pass
1195/// begin/end explicitly.
1196template <typename R, typename T> auto find(R &&Range, const T &Val) {
1197 return std::find(adl_begin(Range), adl_end(Range), Val);
1198}
1199
1200/// Provide wrappers to std::find_if which take ranges instead of having to pass
1201/// begin/end explicitly.
1202template <typename R, typename UnaryPredicate>
1203auto find_if(R &&Range, UnaryPredicate P) {
1204 return std::find_if(adl_begin(Range), adl_end(Range), P);
1205}
1206
1207template <typename R, typename UnaryPredicate>
1208auto find_if_not(R &&Range, UnaryPredicate P) {
1209 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1210}
1211
1212/// Provide wrappers to std::remove_if which take ranges instead of having to
1213/// pass begin/end explicitly.
1214template <typename R, typename UnaryPredicate>
1215auto remove_if(R &&Range, UnaryPredicate P) {
1216 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1217}
1218
1219/// Provide wrappers to std::copy_if which take ranges instead of having to
1220/// pass begin/end explicitly.
1221template <typename R, typename OutputIt, typename UnaryPredicate>
1222OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1223 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1224}
1225
1226template <typename R, typename OutputIt>
1227OutputIt copy(R &&Range, OutputIt Out) {
1228 return std::copy(adl_begin(Range), adl_end(Range), Out);
1229}
1230
1231/// Wrapper function around std::find to detect if an element exists
1232/// in a container.
1233template <typename R, typename E>
1234bool is_contained(R &&Range, const E &Element) {
1235 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
9
Assuming the condition is false
10
Returning zero, which participates in a condition later
1236}
1237
1238/// Wrapper function around std::count to count the number of times an element
1239/// \p Element occurs in the given range \p Range.
1240template <typename R, typename E> auto count(R &&Range, const E &Element) {
1241 return std::count(adl_begin(Range), adl_end(Range), Element);
1242}
1243
1244/// Wrapper function around std::count_if to count the number of times an
1245/// element satisfying a given predicate occurs in a range.
1246template <typename R, typename UnaryPredicate>
1247auto count_if(R &&Range, UnaryPredicate P) {
1248 return std::count_if(adl_begin(Range), adl_end(Range), P);
1249}
1250
1251/// Wrapper function around std::transform to apply a function to a range and
1252/// store the result elsewhere.
1253template <typename R, typename OutputIt, typename UnaryPredicate>
1254OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
1255 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
1256}
1257
1258/// Provide wrappers to std::partition which take ranges instead of having to
1259/// pass begin/end explicitly.
1260template <typename R, typename UnaryPredicate>
1261auto partition(R &&Range, UnaryPredicate P) {
1262 return std::partition(adl_begin(Range), adl_end(Range), P);
1263}
1264
1265/// Provide wrappers to std::lower_bound which take ranges instead of having to
1266/// pass begin/end explicitly.
1267template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) {
1268 return std::lower_bound(adl_begin(Range), adl_end(Range),
1269 std::forward<T>(Value));
1270}
1271
1272template <typename R, typename T, typename Compare>
1273auto lower_bound(R &&Range, T &&Value, Compare C) {
1274 return std::lower_bound(adl_begin(Range), adl_end(Range),
1275 std::forward<T>(Value), C);
1276}
1277
1278/// Provide wrappers to std::upper_bound which take ranges instead of having to
1279/// pass begin/end explicitly.
1280template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) {
1281 return std::upper_bound(adl_begin(Range), adl_end(Range),
1282 std::forward<T>(Value));
1283}
1284
1285template <typename R, typename T, typename Compare>
1286auto upper_bound(R &&Range, T &&Value, Compare C) {
1287 return std::upper_bound(adl_begin(Range), adl_end(Range),
1288 std::forward<T>(Value), C);
1289}
1290
1291template <typename R>
1292void stable_sort(R &&Range) {
1293 std::stable_sort(adl_begin(Range), adl_end(Range));
1294}
1295
1296template <typename R, typename Compare>
1297void stable_sort(R &&Range, Compare C) {
1298 std::stable_sort(adl_begin(Range), adl_end(Range), C);
1299}
1300
1301/// Binary search for the first iterator in a range where a predicate is false.
1302/// Requires that C is always true below some limit, and always false above it.
1303template <typename R, typename Predicate,
1304 typename Val = decltype(*adl_begin(std::declval<R>()))>
1305auto partition_point(R &&Range, Predicate P) {
1306 return std::partition_point(adl_begin(Range), adl_end(Range), P);
1307}
1308
1309/// Wrapper function around std::equal to detect if all elements
1310/// in a container are same.
1311template <typename R>
1312bool is_splat(R &&Range) {
1313 size_t range_size = size(Range);
1314 return range_size != 0 && (range_size == 1 ||
1315 std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
1316}
1317
1318/// Provide a container algorithm similar to C++ Library Fundamentals v2's
1319/// `erase_if` which is equivalent to:
1320///
1321/// C.erase(remove_if(C, pred), C.end());
1322///
1323/// This version works for any container with an erase method call accepting
1324/// two iterators.
1325template <typename Container, typename UnaryPredicate>
1326void erase_if(Container &C, UnaryPredicate P) {
1327 C.erase(remove_if(C, P), C.end());
1328}
1329
1330/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
1331/// the range [ValIt, ValEnd) (which is not from the same container).
1332template<typename Container, typename RandomAccessIterator>
1333void replace(Container &Cont, typename Container::iterator ContIt,
1334 typename Container::iterator ContEnd, RandomAccessIterator ValIt,
1335 RandomAccessIterator ValEnd) {
1336 while (true) {
1337 if (ValIt == ValEnd) {
1338 Cont.erase(ContIt, ContEnd);
1339 return;
1340 } else if (ContIt == ContEnd) {
1341 Cont.insert(ContIt, ValIt, ValEnd);
1342 return;
1343 }
1344 *ContIt++ = *ValIt++;
1345 }
1346}
1347
1348/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
1349/// the range R.
1350template<typename Container, typename Range = std::initializer_list<
1351 typename Container::value_type>>
1352void replace(Container &Cont, typename Container::iterator ContIt,
1353 typename Container::iterator ContEnd, Range R) {
1354 replace(Cont, ContIt, ContEnd, R.begin(), R.end());
1355}
1356
1357//===----------------------------------------------------------------------===//
1358// Extra additions to <memory>
1359//===----------------------------------------------------------------------===//
1360
1361struct FreeDeleter {
1362 void operator()(void* v) {
1363 ::free(v);
1364 }
1365};
1366
1367template<typename First, typename Second>
1368struct pair_hash {
1369 size_t operator()(const std::pair<First, Second> &P) const {
1370 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1371 }
1372};
1373
1374/// Binary functor that adapts to any other binary functor after dereferencing
1375/// operands.
1376template <typename T> struct deref {
1377 T func;
1378
1379 // Could be further improved to cope with non-derivable functors and
1380 // non-binary functors (should be a variadic template member function
1381 // operator()).
1382 template <typename A, typename B> auto operator()(A &lhs, B &rhs) const {
1383 assert(lhs)((lhs) ? static_cast<void> (0) : __assert_fail ("lhs", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h"
, 1383, __PRETTY_FUNCTION__))
;
1384 assert(rhs)((rhs) ? static_cast<void> (0) : __assert_fail ("rhs", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h"
, 1384, __PRETTY_FUNCTION__))
;
1385 return func(*lhs, *rhs);
1386 }
1387};
1388
1389namespace detail {
1390
1391template <typename R> class enumerator_iter;
1392
1393template <typename R> struct result_pair {
1394 using value_reference =
1395 typename std::iterator_traits<IterOfRange<R>>::reference;
1396
1397 friend class enumerator_iter<R>;
1398
1399 result_pair() = default;
1400 result_pair(std::size_t Index, IterOfRange<R> Iter)
1401 : Index(Index), Iter(Iter) {}
1402
1403 result_pair<R>(const result_pair<R> &Other)
1404 : Index(Other.Index), Iter(Other.Iter) {}
1405 result_pair<R> &operator=(const result_pair<R> &Other) {
1406 Index = Other.Index;
1407 Iter = Other.Iter;
1408 return *this;
1409 }
1410
1411 std::size_t index() const { return Index; }
1412 const value_reference value() const { return *Iter; }
1413 value_reference value() { return *Iter; }
1414
1415private:
1416 std::size_t Index = std::numeric_limits<std::size_t>::max();
1417 IterOfRange<R> Iter;
1418};
1419
1420template <typename R>
1421class enumerator_iter
1422 : public iterator_facade_base<
1423 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1424 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1425 typename std::iterator_traits<IterOfRange<R>>::pointer,
1426 typename std::iterator_traits<IterOfRange<R>>::reference> {
1427 using result_type = result_pair<R>;
1428
1429public:
1430 explicit enumerator_iter(IterOfRange<R> EndIter)
1431 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1432
1433 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1434 : Result(Index, Iter) {}
1435
1436 result_type &operator*() { return Result; }
1437 const result_type &operator*() const { return Result; }
1438
1439 enumerator_iter<R> &operator++() {
1440 assert(Result.Index != std::numeric_limits<size_t>::max())((Result.Index != std::numeric_limits<size_t>::max()) ?
static_cast<void> (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/STLExtras.h"
, 1440, __PRETTY_FUNCTION__))
;
1441 ++Result.Iter;
1442 ++Result.Index;
1443 return *this;
1444 }
1445
1446 bool operator==(const enumerator_iter<R> &RHS) const {
1447 // Don't compare indices here, only iterators. It's possible for an end
1448 // iterator to have different indices depending on whether it was created
1449 // by calling std::end() versus incrementing a valid iterator.
1450 return Result.Iter == RHS.Result.Iter;
1451 }
1452
1453 enumerator_iter<R>(const enumerator_iter<R> &Other) : Result(Other.Result) {}
1454 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1455 Result = Other.Result;
1456 return *this;
1457 }
1458
1459private:
1460 result_type Result;
1461};
1462
1463template <typename R> class enumerator {
1464public:
1465 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1466
1467 enumerator_iter<R> begin() {
1468 return enumerator_iter<R>(0, std::begin(TheRange));
1469 }
1470
1471 enumerator_iter<R> end() {
1472 return enumerator_iter<R>(std::end(TheRange));
1473 }
1474
1475private:
1476 R TheRange;
1477};
1478
1479} // end namespace detail
1480
1481/// Given an input range, returns a new range whose values are are pair (A,B)
1482/// such that A is the 0-based index of the item in the sequence, and B is
1483/// the value from the original sequence. Example:
1484///
1485/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1486/// for (auto X : enumerate(Items)) {
1487/// printf("Item %d - %c\n", X.index(), X.value());
1488/// }
1489///
1490/// Output:
1491/// Item 0 - A
1492/// Item 1 - B
1493/// Item 2 - C
1494/// Item 3 - D
1495///
1496template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1497 return detail::enumerator<R>(std::forward<R>(TheRange));
1498}
1499
1500namespace detail {
1501
1502template <typename F, typename Tuple, std::size_t... I>
1503decltype(auto) apply_tuple_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {
1504 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1505}
1506
1507} // end namespace detail
1508
1509/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1510/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1511/// return the result.
1512template <typename F, typename Tuple>
1513decltype(auto) apply_tuple(F &&f, Tuple &&t) {
1514 using Indices = std::make_index_sequence<
1515 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1516
1517 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1518 Indices{});
1519}
1520
1521/// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N)
1522/// time. Not meant for use with random-access iterators.
1523template <typename IterTy>
1524bool hasNItems(
1525 IterTy &&Begin, IterTy &&End, unsigned N,
1526 std::enable_if_t<
1527 !std::is_same<typename std::iterator_traits<std::remove_reference_t<
1528 decltype(Begin)>>::iterator_category,
1529 std::random_access_iterator_tag>::value,
1530 void> * = nullptr) {
1531 for (; N; --N, ++Begin)
1532 if (Begin == End)
1533 return false; // Too few.
1534 return Begin == End;
1535}
1536
1537/// Return true if the sequence [Begin, End) has N or more items. Runs in O(N)
1538/// time. Not meant for use with random-access iterators.
1539template <typename IterTy>
1540bool hasNItemsOrMore(
1541 IterTy &&Begin, IterTy &&End, unsigned N,
1542 std::enable_if_t<
1543 !std::is_same<typename std::iterator_traits<std::remove_reference_t<
1544 decltype(Begin)>>::iterator_category,
1545 std::random_access_iterator_tag>::value,
1546 void> * = nullptr) {
1547 for (; N; --N, ++Begin)
1548 if (Begin == End)
1549 return false; // Too few.
1550 return true;
1551}
1552
1553/// Returns a raw pointer that represents the same address as the argument.
1554///
1555/// This implementation can be removed once we move to C++20 where it's defined
1556/// as std::to_addres().
1557///
1558/// The std::pointer_traits<>::to_address(p) variations of these overloads has
1559/// not been implemented.
1560template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); }
1561template <class T> constexpr T *to_address(T *P) { return P; }
1562
1563} // end namespace llvm
1564
1565#endif // LLVM_ADT_STLEXTRAS_H

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

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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 ScheduleDAGMI;
56class ScheduleHazardRecognizer;
57class SDNode;
58class SelectionDAG;
59class RegScavenger;
60class TargetRegisterClass;
61class TargetRegisterInfo;
62class TargetSchedModel;
63class TargetSubtargetInfo;
64
65template <class T> class SmallVectorImpl;
66
67using ParamLoadedValue = std::pair<MachineOperand, DIExpression*>;
68
69struct DestSourcePair {
70 const MachineOperand *Destination;
71 const MachineOperand *Source;
72
73 DestSourcePair(const MachineOperand &Dest, const MachineOperand &Src)
74 : Destination(&Dest), Source(&Src) {}
75};
76
77/// Used to describe a register and immediate addition.
78struct RegImmPair {
79 Register Reg;
80 int64_t Imm;
81
82 RegImmPair(Register Reg, int64_t Imm) : Reg(Reg), Imm(Imm) {}
83};
84
85//---------------------------------------------------------------------------
86///
87/// TargetInstrInfo - Interface to description of machine instruction set
88///
89class TargetInstrInfo : public MCInstrInfo {
90public:
91 TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
92 unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u)
93 : CallFrameSetupOpcode(CFSetupOpcode),
94 CallFrameDestroyOpcode(CFDestroyOpcode), CatchRetOpcode(CatchRetOpcode),
95 ReturnOpcode(ReturnOpcode) {}
96 TargetInstrInfo(const TargetInstrInfo &) = delete;
97 TargetInstrInfo &operator=(const TargetInstrInfo &) = delete;
98 virtual ~TargetInstrInfo();
99
100 static bool isGenericOpcode(unsigned Opc) {
101 return Opc <= TargetOpcode::GENERIC_OP_END;
102 }
103
104 /// Given a machine instruction descriptor, returns the register
105 /// class constraint for OpNum, or NULL.
106 virtual
107 const TargetRegisterClass *getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
108 const TargetRegisterInfo *TRI,
109 const MachineFunction &MF) const;
110
111 /// Return true if the instruction is trivially rematerializable, meaning it
112 /// has no side effects and requires no operands that aren't always available.
113 /// This means the only allowed uses are constants and unallocatable physical
114 /// registers so that the instructions result is independent of the place
115 /// in the function.
116 bool isTriviallyReMaterializable(const MachineInstr &MI,
117 AAResults *AA = nullptr) const {
118 return MI.getOpcode() == TargetOpcode::IMPLICIT_DEF ||
119 (MI.getDesc().isRematerializable() &&
120 (isReallyTriviallyReMaterializable(MI, AA) ||
121 isReallyTriviallyReMaterializableGeneric(MI, AA)));
122 }
123
124protected:
125 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
126 /// set, this hook lets the target specify whether the instruction is actually
127 /// trivially rematerializable, taking into consideration its operands. This
128 /// predicate must return false if the instruction has any side effects other
129 /// than producing a value, or if it requres any address registers that are
130 /// not always available.
131 /// Requirements must be check as stated in isTriviallyReMaterializable() .
132 virtual bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
133 AAResults *AA) const {
134 return false;
135 }
136
137 /// This method commutes the operands of the given machine instruction MI.
138 /// The operands to be commuted are specified by their indices OpIdx1 and
139 /// OpIdx2.
140 ///
141 /// If a target has any instructions that are commutable but require
142 /// converting to different instructions or making non-trivial changes
143 /// to commute them, this method can be overloaded to do that.
144 /// The default implementation simply swaps the commutable operands.
145 ///
146 /// If NewMI is false, MI is modified in place and returned; otherwise, a
147 /// new machine instruction is created and returned.
148 ///
149 /// Do not call this method for a non-commutable instruction.
150 /// Even though the instruction is commutable, the method may still
151 /// fail to commute the operands, null pointer is returned in such cases.
152 virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
153 unsigned OpIdx1,
154 unsigned OpIdx2) const;
155
156 /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
157 /// operand indices to (ResultIdx1, ResultIdx2).
158 /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
159 /// predefined to some indices or be undefined (designated by the special
160 /// value 'CommuteAnyOperandIndex').
161 /// The predefined result indices cannot be re-defined.
162 /// The function returns true iff after the result pair redefinition
163 /// the fixed result pair is equal to or equivalent to the source pair of
164 /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
165 /// the pairs (x,y) and (y,x) are equivalent.
166 static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2,
167 unsigned CommutableOpIdx1,
168 unsigned CommutableOpIdx2);
169
170private:
171 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
172 /// set and the target hook isReallyTriviallyReMaterializable returns false,
173 /// this function does target-independent tests to determine if the
174 /// instruction is really trivially rematerializable.
175 bool isReallyTriviallyReMaterializableGeneric(const MachineInstr &MI,
176 AAResults *AA) const;
177
178public:
179 /// These methods return the opcode of the frame setup/destroy instructions
180 /// if they exist (-1 otherwise). Some targets use pseudo instructions in
181 /// order to abstract away the difference between operating with a frame
182 /// pointer and operating without, through the use of these two instructions.
183 ///
184 unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
185 unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
186
187 /// Returns true if the argument is a frame pseudo instruction.
188 bool isFrameInstr(const MachineInstr &I) const {
189 return I.getOpcode() == getCallFrameSetupOpcode() ||
190 I.getOpcode() == getCallFrameDestroyOpcode();
191 }
192
193 /// Returns true if the argument is a frame setup pseudo instruction.
194 bool isFrameSetup(const MachineInstr &I) const {
195 return I.getOpcode() == getCallFrameSetupOpcode();
196 }
197
198 /// Returns size of the frame associated with the given frame instruction.
199 /// For frame setup instruction this is frame that is set up space set up
200 /// after the instruction. For frame destroy instruction this is the frame
201 /// freed by the caller.
202 /// Note, in some cases a call frame (or a part of it) may be prepared prior
203 /// to the frame setup instruction. It occurs in the calls that involve
204 /// inalloca arguments. This function reports only the size of the frame part
205 /// that is set up between the frame setup and destroy pseudo instructions.
206 int64_t getFrameSize(const MachineInstr &I) const {
207 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 207, __PRETTY_FUNCTION__))
;
208 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 208, __PRETTY_FUNCTION__))
;
209 return I.getOperand(0).getImm();
210 }
211
212 /// Returns the total frame size, which is made up of the space set up inside
213 /// the pair of frame start-stop instructions and the space that is set up
214 /// prior to the pair.
215 int64_t getFrameTotalSize(const MachineInstr &I) const {
216 if (isFrameSetup(I)) {
217 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 218, __PRETTY_FUNCTION__))
218 "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-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 218, __PRETTY_FUNCTION__))
;
219 return getFrameSize(I) + I.getOperand(1).getImm();
220 }
221 return getFrameSize(I);
222 }
223
224 unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
225 unsigned getReturnOpcode() const { return ReturnOpcode; }
226
227 /// Returns the actual stack pointer adjustment made by an instruction
228 /// as part of a call sequence. By default, only call frame setup/destroy
229 /// instructions adjust the stack, but targets may want to override this
230 /// to enable more fine-grained adjustment, or adjust by a different value.
231 virtual int getSPAdjust(const MachineInstr &MI) const;
232
233 /// Return true if the instruction is a "coalescable" extension instruction.
234 /// That is, it's like a copy where it's legal for the source to overlap the
235 /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
236 /// expected the pre-extension value is available as a subreg of the result
237 /// register. This also returns the sub-register index in SubIdx.
238 virtual bool isCoalescableExtInstr(const MachineInstr &MI, unsigned &SrcReg,
239 unsigned &DstReg, unsigned &SubIdx) const {
240 return false;
241 }
242
243 /// If the specified machine instruction is a direct
244 /// load from a stack slot, return the virtual or physical register number of
245 /// the destination along with the FrameIndex of the loaded stack slot. If
246 /// not, return 0. This predicate must return 0 if the instruction has
247 /// any side effects other than loading from the stack slot.
248 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
249 int &FrameIndex) const {
250 return 0;
251 }
252
253 /// Optional extension of isLoadFromStackSlot that returns the number of
254 /// bytes loaded from the stack. This must be implemented if a backend
255 /// supports partial stack slot spills/loads to further disambiguate
256 /// what the load does.
257 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
258 int &FrameIndex,
259 unsigned &MemBytes) const {
260 MemBytes = 0;
261 return isLoadFromStackSlot(MI, FrameIndex);
262 }
263
264 /// Check for post-frame ptr elimination stack locations as well.
265 /// This uses a heuristic so it isn't reliable for correctness.
266 virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
267 int &FrameIndex) const {
268 return 0;
269 }
270
271 /// If the specified machine instruction has a load from a stack slot,
272 /// return true along with the FrameIndices of the loaded stack slot and the
273 /// machine mem operands containing the reference.
274 /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
275 /// any instructions that loads from the stack. This is just a hint, as some
276 /// cases may be missed.
277 virtual bool hasLoadFromStackSlot(
278 const MachineInstr &MI,
279 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
280
281 /// If the specified machine instruction is a direct
282 /// store to a stack slot, return the virtual or physical register number of
283 /// the source reg along with the FrameIndex of the loaded stack slot. If
284 /// not, return 0. This predicate must return 0 if the instruction has
285 /// any side effects other than storing to the stack slot.
286 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
287 int &FrameIndex) const {
288 return 0;
35
Returning without writing to 'FrameIndex'
289 }
290
291 /// Optional extension of isStoreToStackSlot that returns the number of
292 /// bytes stored to the stack. This must be implemented if a backend
293 /// supports partial stack slot spills/loads to further disambiguate
294 /// what the store does.
295 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
296 int &FrameIndex,
297 unsigned &MemBytes) const {
298 MemBytes = 0;
299 return isStoreToStackSlot(MI, FrameIndex);
300 }
301
302 /// Check for post-frame ptr elimination stack locations as well.
303 /// This uses a heuristic, so it isn't reliable for correctness.
304 virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
305 int &FrameIndex) const {
306 return 0;
307 }
308
309 /// If the specified machine instruction has a store to a stack slot,
310 /// return true along with the FrameIndices of the loaded stack slot and the
311 /// machine mem operands containing the reference.
312 /// If not, return false. Unlike isStoreToStackSlot,
313 /// this returns true for any instructions that stores to the
314 /// stack. This is just a hint, as some cases may be missed.
315 virtual bool hasStoreToStackSlot(
316 const MachineInstr &MI,
317 SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
318
319 /// Return true if the specified machine instruction
320 /// is a copy of one stack slot to another and has no other effect.
321 /// Provide the identity of the two frame indices.
322 virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
323 int &SrcFrameIndex) const {
324 return false;
325 }
326
327 /// Compute the size in bytes and offset within a stack slot of a spilled
328 /// register or subregister.
329 ///
330 /// \param [out] Size in bytes of the spilled value.
331 /// \param [out] Offset in bytes within the stack slot.
332 /// \returns true if both Size and Offset are successfully computed.
333 ///
334 /// Not all subregisters have computable spill slots. For example,
335 /// subregisters registers may not be byte-sized, and a pair of discontiguous
336 /// subregisters has no single offset.
337 ///
338 /// Targets with nontrivial bigendian implementations may need to override
339 /// this, particularly to support spilled vector registers.
340 virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
341 unsigned &Size, unsigned &Offset,
342 const MachineFunction &MF) const;
343
344 /// Returns the size in bytes of the specified MachineInstr, or ~0U
345 /// when this function is not implemented by a target.
346 virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
347 return ~0U;
348 }
349
350 /// Return true if the instruction is as cheap as a move instruction.
351 ///
352 /// Targets for different archs need to override this, and different
353 /// micro-architectures can also be finely tuned inside.
354 virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
355 return MI.isAsCheapAsAMove();
356 }
357
358 /// Return true if the instruction should be sunk by MachineSink.
359 ///
360 /// MachineSink determines on its own whether the instruction is safe to sink;
361 /// this gives the target a hook to override the default behavior with regards
362 /// to which instructions should be sunk.
363 virtual bool shouldSink(const MachineInstr &MI) const { return true; }
364
365 /// Re-issue the specified 'original' instruction at the
366 /// specific location targeting a new destination register.
367 /// The register in Orig->getOperand(0).getReg() will be substituted by
368 /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
369 /// SubIdx.
370 virtual void reMaterialize(MachineBasicBlock &MBB,
371 MachineBasicBlock::iterator MI, unsigned DestReg,
372 unsigned SubIdx, const MachineInstr &Orig,
373 const TargetRegisterInfo &TRI) const;
374
375 /// Clones instruction or the whole instruction bundle \p Orig and
376 /// insert into \p MBB before \p InsertBefore. The target may update operands
377 /// that are required to be unique.
378 ///
379 /// \p Orig must not return true for MachineInstr::isNotDuplicable().
380 virtual MachineInstr &duplicate(MachineBasicBlock &MBB,
381 MachineBasicBlock::iterator InsertBefore,
382 const MachineInstr &Orig) const;
383
384 /// This method must be implemented by targets that
385 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
386 /// may be able to convert a two-address instruction into one or more true
387 /// three-address instructions on demand. This allows the X86 target (for
388 /// example) to convert ADD and SHL instructions into LEA instructions if they
389 /// would require register copies due to two-addressness.
390 ///
391 /// This method returns a null pointer if the transformation cannot be
392 /// performed, otherwise it returns the last new instruction.
393 ///
394 virtual MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
395 MachineInstr &MI,
396 LiveVariables *LV) const {
397 return nullptr;
398 }
399
400 // This constant can be used as an input value of operand index passed to
401 // the method findCommutedOpIndices() to tell the method that the
402 // corresponding operand index is not pre-defined and that the method
403 // can pick any commutable operand.
404 static const unsigned CommuteAnyOperandIndex = ~0U;
405
406 /// This method commutes the operands of the given machine instruction MI.
407 ///
408 /// The operands to be commuted are specified by their indices OpIdx1 and
409 /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
410 /// 'CommuteAnyOperandIndex', which means that the method is free to choose
411 /// any arbitrarily chosen commutable operand. If both arguments are set to
412 /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
413 /// operands; then commutes them if such operands could be found.
414 ///
415 /// If NewMI is false, MI is modified in place and returned; otherwise, a
416 /// new machine instruction is created and returned.
417 ///
418 /// Do not call this method for a non-commutable instruction or
419 /// for non-commuable operands.
420 /// Even though the instruction is commutable, the method may still
421 /// fail to commute the operands, null pointer is returned in such cases.
422 MachineInstr *
423 commuteInstruction(MachineInstr &MI, bool NewMI = false,
424 unsigned OpIdx1 = CommuteAnyOperandIndex,
425 unsigned OpIdx2 = CommuteAnyOperandIndex) const;
426
427 /// Returns true iff the routine could find two commutable operands in the
428 /// given machine instruction.
429 /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
430 /// If any of the INPUT values is set to the special value
431 /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
432 /// operand, then returns its index in the corresponding argument.
433 /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
434 /// looks for 2 commutable operands.
435 /// If INPUT values refer to some operands of MI, then the method simply
436 /// returns true if the corresponding operands are commutable and returns
437 /// false otherwise.
438 ///
439 /// For example, calling this method this way:
440 /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
441 /// findCommutedOpIndices(MI, Op1, Op2);
442 /// can be interpreted as a query asking to find an operand that would be
443 /// commutable with the operand#1.
444 virtual bool findCommutedOpIndices(const MachineInstr &MI,
445 unsigned &SrcOpIdx1,
446 unsigned &SrcOpIdx2) const;
447
448 /// A pair composed of a register and a sub-register index.
449 /// Used to give some type checking when modeling Reg:SubReg.
450 struct RegSubRegPair {
451 unsigned Reg;
452 unsigned SubReg;
453
454 RegSubRegPair(unsigned Reg = 0, unsigned SubReg = 0)
455 : Reg(Reg), SubReg(SubReg) {}
456
457 bool operator==(const RegSubRegPair& P) const {
458 return Reg == P.Reg && SubReg == P.SubReg;
459 }
460 bool operator!=(const RegSubRegPair& P) const {
461 return !(*this == P);
462 }
463 };
464
465 /// A pair composed of a pair of a register and a sub-register index,
466 /// and another sub-register index.
467 /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
468 struct RegSubRegPairAndIdx : RegSubRegPair {
469 unsigned SubIdx;
470
471 RegSubRegPairAndIdx(unsigned Reg = 0, unsigned SubReg = 0,
472 unsigned SubIdx = 0)
473 : RegSubRegPair(Reg, SubReg), SubIdx(SubIdx) {}
474 };
475
476 /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
477 /// and \p DefIdx.
478 /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
479 /// the list is modeled as <Reg:SubReg, SubIdx>. Operands with the undef
480 /// flag are not added to this list.
481 /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
482 /// two elements:
483 /// - %1:sub1, sub0
484 /// - %2<:0>, sub1
485 ///
486 /// \returns true if it is possible to build such an input sequence
487 /// with the pair \p MI, \p DefIdx. False otherwise.
488 ///
489 /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
490 ///
491 /// \note The generic implementation does not provide any support for
492 /// MI.isRegSequenceLike(). In other words, one has to override
493 /// getRegSequenceLikeInputs for target specific instructions.
494 bool
495 getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
496 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
497
498 /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
499 /// and \p DefIdx.
500 /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
501 /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
502 /// - %1:sub1, sub0
503 ///
504 /// \returns true if it is possible to build such an input sequence
505 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
506 /// False otherwise.
507 ///
508 /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
509 ///
510 /// \note The generic implementation does not provide any support for
511 /// MI.isExtractSubregLike(). In other words, one has to override
512 /// getExtractSubregLikeInputs for target specific instructions.
513 bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
514 RegSubRegPairAndIdx &InputReg) const;
515
516 /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
517 /// and \p DefIdx.
518 /// \p [out] BaseReg and \p [out] InsertedReg contain
519 /// the equivalent inputs of INSERT_SUBREG.
520 /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
521 /// - BaseReg: %0:sub0
522 /// - InsertedReg: %1:sub1, sub3
523 ///
524 /// \returns true if it is possible to build such an input sequence
525 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
526 /// False otherwise.
527 ///
528 /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
529 ///
530 /// \note The generic implementation does not provide any support for
531 /// MI.isInsertSubregLike(). In other words, one has to override
532 /// getInsertSubregLikeInputs for target specific instructions.
533 bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
534 RegSubRegPair &BaseReg,
535 RegSubRegPairAndIdx &InsertedReg) const;
536
537 /// Return true if two machine instructions would produce identical values.
538 /// By default, this is only true when the two instructions
539 /// are deemed identical except for defs. If this function is called when the
540 /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
541 /// aggressive checks.
542 virtual bool produceSameValue(const MachineInstr &MI0,
543 const MachineInstr &MI1,
544 const MachineRegisterInfo *MRI = nullptr) const;
545
546 /// \returns true if a branch from an instruction with opcode \p BranchOpc
547 /// bytes is capable of jumping to a position \p BrOffset bytes away.
548 virtual bool isBranchOffsetInRange(unsigned BranchOpc,
549 int64_t BrOffset) const {
550 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 550)
;
551 }
552
553 /// \returns The block that branch instruction \p MI jumps to.
554 virtual MachineBasicBlock *getBranchDestBlock(const MachineInstr &MI) const {
555 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 555)
;
556 }
557
558 /// Insert an unconditional indirect branch at the end of \p MBB to \p
559 /// NewDestBB. \p BrOffset indicates the offset of \p NewDestBB relative to
560 /// the offset of the position to insert the new branch.
561 ///
562 /// \returns The number of bytes added to the block.
563 virtual unsigned insertIndirectBranch(MachineBasicBlock &MBB,
564 MachineBasicBlock &NewDestBB,
565 const DebugLoc &DL,
566 int64_t BrOffset = 0,
567 RegScavenger *RS = nullptr) const {
568 llvm_unreachable("target did not implement")::llvm::llvm_unreachable_internal("target did not implement",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 568)
;
569 }
570
571 /// Analyze the branching code at the end of MBB, returning
572 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
573 /// implemented for a target). Upon success, this returns false and returns
574 /// with the following information in various cases:
575 ///
576 /// 1. If this block ends with no branches (it just falls through to its succ)
577 /// just return false, leaving TBB/FBB null.
578 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
579 /// the destination block.
580 /// 3. If this block ends with a conditional branch and it falls through to a
581 /// successor block, it sets TBB to be the branch destination block and a
582 /// list of operands that evaluate the condition. These operands can be
583 /// passed to other TargetInstrInfo methods to create new branches.
584 /// 4. If this block ends with a conditional branch followed by an
585 /// unconditional branch, it returns the 'true' destination in TBB, the
586 /// 'false' destination in FBB, and a list of operands that evaluate the
587 /// condition. These operands can be passed to other TargetInstrInfo
588 /// methods to create new branches.
589 ///
590 /// Note that removeBranch and insertBranch must be implemented to support
591 /// cases where this method returns success.
592 ///
593 /// If AllowModify is true, then this routine is allowed to modify the basic
594 /// block (e.g. delete instructions after the unconditional branch).
595 ///
596 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
597 /// before calling this function.
598 virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
599 MachineBasicBlock *&FBB,
600 SmallVectorImpl<MachineOperand> &Cond,
601 bool AllowModify = false) const {
602 return true;
603 }
604
605 /// Represents a predicate at the MachineFunction level. The control flow a
606 /// MachineBranchPredicate represents is:
607 ///
608 /// Reg = LHS `Predicate` RHS == ConditionDef
609 /// if Reg then goto TrueDest else goto FalseDest
610 ///
611 struct MachineBranchPredicate {
612 enum ComparePredicate {
613 PRED_EQ, // True if two values are equal
614 PRED_NE, // True if two values are not equal
615 PRED_INVALID // Sentinel value
616 };
617
618 ComparePredicate Predicate = PRED_INVALID;
619 MachineOperand LHS = MachineOperand::CreateImm(0);
620 MachineOperand RHS = MachineOperand::CreateImm(0);
621 MachineBasicBlock *TrueDest = nullptr;
622 MachineBasicBlock *FalseDest = nullptr;
623 MachineInstr *ConditionDef = nullptr;
624
625 /// SingleUseCondition is true if ConditionDef is dead except for the
626 /// branch(es) at the end of the basic block.
627 ///
628 bool SingleUseCondition = false;
629
630 explicit MachineBranchPredicate() = default;
631 };
632
633 /// Analyze the branching code at the end of MBB and parse it into the
634 /// MachineBranchPredicate structure if possible. Returns false on success
635 /// and true on failure.
636 ///
637 /// If AllowModify is true, then this routine is allowed to modify the basic
638 /// block (e.g. delete instructions after the unconditional branch).
639 ///
640 virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB,
641 MachineBranchPredicate &MBP,
642 bool AllowModify = false) const {
643 return true;
644 }
645
646 /// Remove the branching code at the end of the specific MBB.
647 /// This is only invoked in cases where analyzeBranch returns success. It
648 /// returns the number of instructions that were removed.
649 /// If \p BytesRemoved is non-null, report the change in code size from the
650 /// removed instructions.
651 virtual unsigned removeBranch(MachineBasicBlock &MBB,
652 int *BytesRemoved = nullptr) const {
653 llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::removeBranch!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 653)
;
654 }
655
656 /// Insert branch code into the end of the specified MachineBasicBlock. The
657 /// operands to this method are the same as those returned by analyzeBranch.
658 /// This is only invoked in cases where analyzeBranch returns success. It
659 /// returns the number of instructions inserted. If \p BytesAdded is non-null,
660 /// report the change in code size from the added instructions.
661 ///
662 /// It is also invoked by tail merging to add unconditional branches in
663 /// cases where analyzeBranch doesn't apply because there was no original
664 /// branch to analyze. At least this much must be implemented, else tail
665 /// merging needs to be disabled.
666 ///
667 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
668 /// before calling this function.
669 virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
670 MachineBasicBlock *FBB,
671 ArrayRef<MachineOperand> Cond,
672 const DebugLoc &DL,
673 int *BytesAdded = nullptr) const {
674 llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!")::llvm::llvm_unreachable_internal("Target didn't implement TargetInstrInfo::insertBranch!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 674)
;
675 }
676
677 unsigned insertUnconditionalBranch(MachineBasicBlock &MBB,
678 MachineBasicBlock *DestBB,
679 const DebugLoc &DL,
680 int *BytesAdded = nullptr) const {
681 return insertBranch(MBB, DestBB, nullptr, ArrayRef<MachineOperand>(), DL,
682 BytesAdded);
683 }
684
685 /// Object returned by analyzeLoopForPipelining. Allows software pipelining
686 /// implementations to query attributes of the loop being pipelined and to
687 /// apply target-specific updates to the loop once pipelining is complete.
688 class PipelinerLoopInfo {
689 public:
690 virtual ~PipelinerLoopInfo();
691 /// Return true if the given instruction should not be pipelined and should
692 /// be ignored. An example could be a loop comparison, or induction variable
693 /// update with no users being pipelined.
694 virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const = 0;
695
696 /// Create a condition to determine if the trip count of the loop is greater
697 /// than TC.
698 ///
699 /// If the trip count is statically known to be greater than TC, return
700 /// true. If the trip count is statically known to be not greater than TC,
701 /// return false. Otherwise return nullopt and fill out Cond with the test
702 /// condition.
703 virtual Optional<bool>
704 createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
705 SmallVectorImpl<MachineOperand> &Cond) = 0;
706
707 /// Modify the loop such that the trip count is
708 /// OriginalTC + TripCountAdjust.
709 virtual void adjustTripCount(int TripCountAdjust) = 0;
710
711 /// Called when the loop's preheader has been modified to NewPreheader.
712 virtual void setPreheader(MachineBasicBlock *NewPreheader) = 0;
713
714 /// Called when the loop is being removed. Any instructions in the preheader
715 /// should be removed.
716 ///
717 /// Once this function is called, no other functions on this object are
718 /// valid; the loop has been removed.
719 virtual void disposed() = 0;
720 };
721
722 /// Analyze loop L, which must be a single-basic-block loop, and if the
723 /// conditions can be understood enough produce a PipelinerLoopInfo object.
724 virtual std::unique_ptr<PipelinerLoopInfo>
725 analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
726 return nullptr;
727 }
728
729 /// Analyze the loop code, return true if it cannot be understoo. Upon
730 /// success, this function returns false and returns information about the
731 /// induction variable and compare instruction used at the end.
732 virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
733 MachineInstr *&CmpInst) const {
734 return true;
735 }
736
737 /// Generate code to reduce the loop iteration by one and check if the loop
738 /// is finished. Return the value/register of the new loop count. We need
739 /// this function when peeling off one or more iterations of a loop. This
740 /// function assumes the nth iteration is peeled first.
741 virtual unsigned reduceLoopCount(MachineBasicBlock &MBB,
742 MachineBasicBlock &PreHeader,
743 MachineInstr *IndVar, MachineInstr &Cmp,
744 SmallVectorImpl<MachineOperand> &Cond,
745 SmallVectorImpl<MachineInstr *> &PrevInsts,
746 unsigned Iter, unsigned MaxIter) const {
747 llvm_unreachable("Target didn't implement ReduceLoopCount")::llvm::llvm_unreachable_internal("Target didn't implement ReduceLoopCount"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/TargetInstrInfo.h"
, 747)
;
748 }
749
750 /// Delete the instruction OldInst and everything after it, replacing it with
751 /// an unconditional branch to NewDest. This is used by the tail merging pass.
752 virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
753 MachineBasicBlock *NewDest) const;
754
755 /// Return true if it's legal to split the given basic
756 /// block at the specified instruction (i.e. instruction would be the start
757 /// of a new basic block).
758 virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
759 MachineBasicBlock::iterator MBBI) const {
760 return true;
761 }
762
763 /// Return true if it's profitable to predicate
764 /// instructions with accumulated instruction latency of "NumCycles"
765 /// of the specified basic block, where the probability of the instructions
766 /// being executed is given by Probability, and Confidence is a measure
767