Bug Summary

File:llvm/lib/CodeGen/MachineInstr.cpp
Warning:line 1815, column 7
Value stored to 'HaveSemi' is never read

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 MachineInstr.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/MachineInstr.cpp
1//===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
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// Methods common to all machine instructions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/MachineInstr.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/FoldingSet.h"
17#include "llvm/ADT/Hashing.h"
18#include "llvm/ADT/None.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallBitVector.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/Loads.h"
25#include "llvm/Analysis/MemoryLocation.h"
26#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
27#include "llvm/CodeGen/MachineBasicBlock.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/MachineInstrBundle.h"
32#include "llvm/CodeGen/MachineMemOperand.h"
33#include "llvm/CodeGen/MachineModuleInfo.h"
34#include "llvm/CodeGen/MachineOperand.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/PseudoSourceValue.h"
37#include "llvm/CodeGen/TargetInstrInfo.h"
38#include "llvm/CodeGen/TargetRegisterInfo.h"
39#include "llvm/CodeGen/TargetSubtargetInfo.h"
40#include "llvm/Config/llvm-config.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DebugInfoMetadata.h"
43#include "llvm/IR/DebugLoc.h"
44#include "llvm/IR/DerivedTypes.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/Metadata.h"
51#include "llvm/IR/Module.h"
52#include "llvm/IR/ModuleSlotTracker.h"
53#include "llvm/IR/Operator.h"
54#include "llvm/IR/Type.h"
55#include "llvm/IR/Value.h"
56#include "llvm/MC/MCInstrDesc.h"
57#include "llvm/MC/MCRegisterInfo.h"
58#include "llvm/MC/MCSymbol.h"
59#include "llvm/Support/Casting.h"
60#include "llvm/Support/CommandLine.h"
61#include "llvm/Support/Compiler.h"
62#include "llvm/Support/Debug.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/FormattedStream.h"
65#include "llvm/Support/LowLevelTypeImpl.h"
66#include "llvm/Support/MathExtras.h"
67#include "llvm/Support/raw_ostream.h"
68#include "llvm/Target/TargetIntrinsicInfo.h"
69#include "llvm/Target/TargetMachine.h"
70#include <algorithm>
71#include <cassert>
72#include <cstddef>
73#include <cstdint>
74#include <cstring>
75#include <iterator>
76#include <utility>
77
78using namespace llvm;
79
80static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
81 if (const MachineBasicBlock *MBB = MI.getParent())
82 if (const MachineFunction *MF = MBB->getParent())
83 return MF;
84 return nullptr;
85}
86
87// Try to crawl up to the machine function and get TRI and IntrinsicInfo from
88// it.
89static void tryToGetTargetInfo(const MachineInstr &MI,
90 const TargetRegisterInfo *&TRI,
91 const MachineRegisterInfo *&MRI,
92 const TargetIntrinsicInfo *&IntrinsicInfo,
93 const TargetInstrInfo *&TII) {
94
95 if (const MachineFunction *MF = getMFIfAvailable(MI)) {
96 TRI = MF->getSubtarget().getRegisterInfo();
97 MRI = &MF->getRegInfo();
98 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
99 TII = MF->getSubtarget().getInstrInfo();
100 }
101}
102
103void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
104 if (MCID->ImplicitDefs)
105 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
106 ++ImpDefs)
107 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
108 if (MCID->ImplicitUses)
109 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
110 ++ImpUses)
111 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
112}
113
114/// MachineInstr ctor - This constructor creates a MachineInstr and adds the
115/// implicit operands. It reserves space for the number of operands specified by
116/// the MCInstrDesc.
117MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
118 DebugLoc dl, bool NoImp)
119 : MCID(&tid), debugLoc(std::move(dl)) {
120 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/lib/CodeGen/MachineInstr.cpp"
, 120, __PRETTY_FUNCTION__))
;
121
122 // Reserve space for the expected number of operands.
123 if (unsigned NumOps = MCID->getNumOperands() +
124 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
125 CapOperands = OperandCapacity::get(NumOps);
126 Operands = MF.allocateOperandArray(CapOperands);
127 }
128
129 if (!NoImp)
130 addImplicitDefUseOperands(MF);
131}
132
133/// MachineInstr ctor - Copies MachineInstr arg exactly
134///
135MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
136 : MCID(&MI.getDesc()), Info(MI.Info), debugLoc(MI.getDebugLoc()) {
137 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/lib/CodeGen/MachineInstr.cpp"
, 137, __PRETTY_FUNCTION__))
;
138
139 CapOperands = OperandCapacity::get(MI.getNumOperands());
140 Operands = MF.allocateOperandArray(CapOperands);
141
142 // Copy operands.
143 for (const MachineOperand &MO : MI.operands())
144 addOperand(MF, MO);
145
146 // Copy all the sensible flags.
147 setFlags(MI.Flags);
148}
149
150/// getRegInfo - If this instruction is embedded into a MachineFunction,
151/// return the MachineRegisterInfo object for the current function, otherwise
152/// return null.
153MachineRegisterInfo *MachineInstr::getRegInfo() {
154 if (MachineBasicBlock *MBB = getParent())
155 return &MBB->getParent()->getRegInfo();
156 return nullptr;
157}
158
159/// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
160/// this instruction from their respective use lists. This requires that the
161/// operands already be on their use lists.
162void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
163 for (MachineOperand &MO : operands())
164 if (MO.isReg())
165 MRI.removeRegOperandFromUseList(&MO);
166}
167
168/// AddRegOperandsToUseLists - Add all of the register operands in
169/// this instruction from their respective use lists. This requires that the
170/// operands not be on their use lists yet.
171void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
172 for (MachineOperand &MO : operands())
173 if (MO.isReg())
174 MRI.addRegOperandToUseList(&MO);
175}
176
177void MachineInstr::addOperand(const MachineOperand &Op) {
178 MachineBasicBlock *MBB = getParent();
179 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs")((MBB && "Use MachineInstrBuilder to add operands to dangling instrs"
) ? static_cast<void> (0) : __assert_fail ("MBB && \"Use MachineInstrBuilder to add operands to dangling instrs\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 179, __PRETTY_FUNCTION__))
;
180 MachineFunction *MF = MBB->getParent();
181 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs")((MF && "Use MachineInstrBuilder to add operands to dangling instrs"
) ? static_cast<void> (0) : __assert_fail ("MF && \"Use MachineInstrBuilder to add operands to dangling instrs\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 181, __PRETTY_FUNCTION__))
;
182 addOperand(*MF, Op);
183}
184
185/// Move NumOps MachineOperands from Src to Dst, with support for overlapping
186/// ranges. If MRI is non-null also update use-def chains.
187static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
188 unsigned NumOps, MachineRegisterInfo *MRI) {
189 if (MRI)
190 return MRI->moveOperands(Dst, Src, NumOps);
191 // MachineOperand is a trivially copyable type so we can just use memmove.
192 assert(Dst && Src && "Unknown operands")((Dst && Src && "Unknown operands") ? static_cast
<void> (0) : __assert_fail ("Dst && Src && \"Unknown operands\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 192, __PRETTY_FUNCTION__))
;
193 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
194}
195
196/// addOperand - Add the specified operand to the instruction. If it is an
197/// implicit operand, it is added to the end of the operand list. If it is
198/// an explicit operand it is added at the end of the explicit operand list
199/// (before the first implicit operand).
200void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
201 assert(MCID && "Cannot add operands before providing an instr descriptor")((MCID && "Cannot add operands before providing an instr descriptor"
) ? static_cast<void> (0) : __assert_fail ("MCID && \"Cannot add operands before providing an instr descriptor\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 201, __PRETTY_FUNCTION__))
;
202
203 // Check if we're adding one of our existing operands.
204 if (&Op >= Operands && &Op < Operands + NumOperands) {
205 // This is unusual: MI->addOperand(MI->getOperand(i)).
206 // If adding Op requires reallocating or moving existing operands around,
207 // the Op reference could go stale. Support it by copying Op.
208 MachineOperand CopyOp(Op);
209 return addOperand(MF, CopyOp);
210 }
211
212 // Find the insert location for the new operand. Implicit registers go at
213 // the end, everything else goes before the implicit regs.
214 //
215 // FIXME: Allow mixed explicit and implicit operands on inline asm.
216 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
217 // implicit-defs, but they must not be moved around. See the FIXME in
218 // InstrEmitter.cpp.
219 unsigned OpNo = getNumOperands();
220 bool isImpReg = Op.isReg() && Op.isImplicit();
221 if (!isImpReg && !isInlineAsm()) {
222 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
223 --OpNo;
224 assert(!Operands[OpNo].isTied() && "Cannot move tied operands")((!Operands[OpNo].isTied() && "Cannot move tied operands"
) ? static_cast<void> (0) : __assert_fail ("!Operands[OpNo].isTied() && \"Cannot move tied operands\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 224, __PRETTY_FUNCTION__))
;
225 }
226 }
227
228#ifndef NDEBUG
229 bool isDebugOp = Op.getType() == MachineOperand::MO_Metadata ||
230 Op.getType() == MachineOperand::MO_MCSymbol;
231 // OpNo now points as the desired insertion point. Unless this is a variadic
232 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
233 // RegMask operands go between the explicit and implicit operands.
234 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||(((isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo
< MCID->getNumOperands() || isDebugOp) && "Trying to add an operand to a machine instr that is already done!"
) ? static_cast<void> (0) : __assert_fail ("(isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo < MCID->getNumOperands() || isDebugOp) && \"Trying to add an operand to a machine instr that is already done!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 236, __PRETTY_FUNCTION__))
235 OpNo < MCID->getNumOperands() || isDebugOp) &&(((isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo
< MCID->getNumOperands() || isDebugOp) && "Trying to add an operand to a machine instr that is already done!"
) ? static_cast<void> (0) : __assert_fail ("(isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo < MCID->getNumOperands() || isDebugOp) && \"Trying to add an operand to a machine instr that is already done!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 236, __PRETTY_FUNCTION__))
236 "Trying to add an operand to a machine instr that is already done!")(((isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo
< MCID->getNumOperands() || isDebugOp) && "Trying to add an operand to a machine instr that is already done!"
) ? static_cast<void> (0) : __assert_fail ("(isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo < MCID->getNumOperands() || isDebugOp) && \"Trying to add an operand to a machine instr that is already done!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 236, __PRETTY_FUNCTION__))
;
237#endif
238
239 MachineRegisterInfo *MRI = getRegInfo();
240
241 // Determine if the Operands array needs to be reallocated.
242 // Save the old capacity and operand array.
243 OperandCapacity OldCap = CapOperands;
244 MachineOperand *OldOperands = Operands;
245 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
246 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
247 Operands = MF.allocateOperandArray(CapOperands);
248 // Move the operands before the insertion point.
249 if (OpNo)
250 moveOperands(Operands, OldOperands, OpNo, MRI);
251 }
252
253 // Move the operands following the insertion point.
254 if (OpNo != NumOperands)
255 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
256 MRI);
257 ++NumOperands;
258
259 // Deallocate the old operand array.
260 if (OldOperands != Operands && OldOperands)
261 MF.deallocateOperandArray(OldCap, OldOperands);
262
263 // Copy Op into place. It still needs to be inserted into the MRI use lists.
264 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
265 NewMO->ParentMI = this;
266
267 // When adding a register operand, tell MRI about it.
268 if (NewMO->isReg()) {
269 // Ensure isOnRegUseList() returns false, regardless of Op's status.
270 NewMO->Contents.Reg.Prev = nullptr;
271 // Ignore existing ties. This is not a property that can be copied.
272 NewMO->TiedTo = 0;
273 // Add the new operand to MRI, but only for instructions in an MBB.
274 if (MRI)
275 MRI->addRegOperandToUseList(NewMO);
276 // The MCID operand information isn't accurate until we start adding
277 // explicit operands. The implicit operands are added first, then the
278 // explicits are inserted before them.
279 if (!isImpReg) {
280 // Tie uses to defs as indicated in MCInstrDesc.
281 if (NewMO->isUse()) {
282 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
283 if (DefIdx != -1)
284 tieOperands(DefIdx, OpNo);
285 }
286 // If the register operand is flagged as early, mark the operand as such.
287 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
288 NewMO->setIsEarlyClobber(true);
289 }
290 }
291}
292
293/// RemoveOperand - Erase an operand from an instruction, leaving it with one
294/// fewer operand than it started with.
295///
296void MachineInstr::RemoveOperand(unsigned OpNo) {
297 assert(OpNo < getNumOperands() && "Invalid operand number")((OpNo < getNumOperands() && "Invalid operand number"
) ? static_cast<void> (0) : __assert_fail ("OpNo < getNumOperands() && \"Invalid operand number\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 297, __PRETTY_FUNCTION__))
;
298 untieRegOperand(OpNo);
299
300#ifndef NDEBUG
301 // Moving tied operands would break the ties.
302 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
303 if (Operands[i].isReg())
304 assert(!Operands[i].isTied() && "Cannot move tied operands")((!Operands[i].isTied() && "Cannot move tied operands"
) ? static_cast<void> (0) : __assert_fail ("!Operands[i].isTied() && \"Cannot move tied operands\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 304, __PRETTY_FUNCTION__))
;
305#endif
306
307 MachineRegisterInfo *MRI = getRegInfo();
308 if (MRI && Operands[OpNo].isReg())
309 MRI->removeRegOperandFromUseList(Operands + OpNo);
310
311 // Don't call the MachineOperand destructor. A lot of this code depends on
312 // MachineOperand having a trivial destructor anyway, and adding a call here
313 // wouldn't make it 'destructor-correct'.
314
315 if (unsigned N = NumOperands - 1 - OpNo)
316 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
317 --NumOperands;
318}
319
320void MachineInstr::setExtraInfo(MachineFunction &MF,
321 ArrayRef<MachineMemOperand *> MMOs,
322 MCSymbol *PreInstrSymbol,
323 MCSymbol *PostInstrSymbol,
324 MDNode *HeapAllocMarker) {
325 bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
326 bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
327 bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
328 int NumPointers =
329 MMOs.size() + HasPreInstrSymbol + HasPostInstrSymbol + HasHeapAllocMarker;
330
331 // Drop all extra info if there is none.
332 if (NumPointers <= 0) {
333 Info.clear();
334 return;
335 }
336
337 // If more than one pointer, then store out of line. Store heap alloc markers
338 // out of line because PointerSumType cannot hold more than 4 tag types with
339 // 32-bit pointers.
340 // FIXME: Maybe we should make the symbols in the extra info mutable?
341 else if (NumPointers > 1 || HasHeapAllocMarker) {
342 Info.set<EIIK_OutOfLine>(MF.createMIExtraInfo(
343 MMOs, PreInstrSymbol, PostInstrSymbol, HeapAllocMarker));
344 return;
345 }
346
347 // Otherwise store the single pointer inline.
348 if (HasPreInstrSymbol)
349 Info.set<EIIK_PreInstrSymbol>(PreInstrSymbol);
350 else if (HasPostInstrSymbol)
351 Info.set<EIIK_PostInstrSymbol>(PostInstrSymbol);
352 else
353 Info.set<EIIK_MMO>(MMOs[0]);
354}
355
356void MachineInstr::dropMemRefs(MachineFunction &MF) {
357 if (memoperands_empty())
358 return;
359
360 setExtraInfo(MF, {}, getPreInstrSymbol(), getPostInstrSymbol(),
361 getHeapAllocMarker());
362}
363
364void MachineInstr::setMemRefs(MachineFunction &MF,
365 ArrayRef<MachineMemOperand *> MMOs) {
366 if (MMOs.empty()) {
367 dropMemRefs(MF);
368 return;
369 }
370
371 setExtraInfo(MF, MMOs, getPreInstrSymbol(), getPostInstrSymbol(),
372 getHeapAllocMarker());
373}
374
375void MachineInstr::addMemOperand(MachineFunction &MF,
376 MachineMemOperand *MO) {
377 SmallVector<MachineMemOperand *, 2> MMOs;
378 MMOs.append(memoperands_begin(), memoperands_end());
379 MMOs.push_back(MO);
380 setMemRefs(MF, MMOs);
381}
382
383void MachineInstr::cloneMemRefs(MachineFunction &MF, const MachineInstr &MI) {
384 if (this == &MI)
385 // Nothing to do for a self-clone!
386 return;
387
388 assert(&MF == MI.getMF() &&((&MF == MI.getMF() && "Invalid machine functions when cloning memory refrences!"
) ? static_cast<void> (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning memory refrences!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 389, __PRETTY_FUNCTION__))
389 "Invalid machine functions when cloning memory refrences!")((&MF == MI.getMF() && "Invalid machine functions when cloning memory refrences!"
) ? static_cast<void> (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning memory refrences!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 389, __PRETTY_FUNCTION__))
;
390 // See if we can just steal the extra info already allocated for the
391 // instruction. We can do this whenever the pre- and post-instruction symbols
392 // are the same (including null).
393 if (getPreInstrSymbol() == MI.getPreInstrSymbol() &&
394 getPostInstrSymbol() == MI.getPostInstrSymbol() &&
395 getHeapAllocMarker() == MI.getHeapAllocMarker()) {
396 Info = MI.Info;
397 return;
398 }
399
400 // Otherwise, fall back on a copy-based clone.
401 setMemRefs(MF, MI.memoperands());
402}
403
404/// Check to see if the MMOs pointed to by the two MemRefs arrays are
405/// identical.
406static bool hasIdenticalMMOs(ArrayRef<MachineMemOperand *> LHS,
407 ArrayRef<MachineMemOperand *> RHS) {
408 if (LHS.size() != RHS.size())
409 return false;
410
411 auto LHSPointees = make_pointee_range(LHS);
412 auto RHSPointees = make_pointee_range(RHS);
413 return std::equal(LHSPointees.begin(), LHSPointees.end(),
414 RHSPointees.begin());
415}
416
417void MachineInstr::cloneMergedMemRefs(MachineFunction &MF,
418 ArrayRef<const MachineInstr *> MIs) {
419 // Try handling easy numbers of MIs with simpler mechanisms.
420 if (MIs.empty()) {
421 dropMemRefs(MF);
422 return;
423 }
424 if (MIs.size() == 1) {
425 cloneMemRefs(MF, *MIs[0]);
426 return;
427 }
428 // Because an empty memoperands list provides *no* information and must be
429 // handled conservatively (assuming the instruction can do anything), the only
430 // way to merge with it is to drop all other memoperands.
431 if (MIs[0]->memoperands_empty()) {
432 dropMemRefs(MF);
433 return;
434 }
435
436 // Handle the general case.
437 SmallVector<MachineMemOperand *, 2> MergedMMOs;
438 // Start with the first instruction.
439 assert(&MF == MIs[0]->getMF() &&((&MF == MIs[0]->getMF() && "Invalid machine functions when cloning memory references!"
) ? static_cast<void> (0) : __assert_fail ("&MF == MIs[0]->getMF() && \"Invalid machine functions when cloning memory references!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 440, __PRETTY_FUNCTION__))
440 "Invalid machine functions when cloning memory references!")((&MF == MIs[0]->getMF() && "Invalid machine functions when cloning memory references!"
) ? static_cast<void> (0) : __assert_fail ("&MF == MIs[0]->getMF() && \"Invalid machine functions when cloning memory references!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 440, __PRETTY_FUNCTION__))
;
441 MergedMMOs.append(MIs[0]->memoperands_begin(), MIs[0]->memoperands_end());
442 // Now walk all the other instructions and accumulate any different MMOs.
443 for (const MachineInstr &MI : make_pointee_range(MIs.slice(1))) {
444 assert(&MF == MI.getMF() &&((&MF == MI.getMF() && "Invalid machine functions when cloning memory references!"
) ? static_cast<void> (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning memory references!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 445, __PRETTY_FUNCTION__))
445 "Invalid machine functions when cloning memory references!")((&MF == MI.getMF() && "Invalid machine functions when cloning memory references!"
) ? static_cast<void> (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning memory references!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 445, __PRETTY_FUNCTION__))
;
446
447 // Skip MIs with identical operands to the first. This is a somewhat
448 // arbitrary hack but will catch common cases without being quadratic.
449 // TODO: We could fully implement merge semantics here if needed.
450 if (hasIdenticalMMOs(MIs[0]->memoperands(), MI.memoperands()))
451 continue;
452
453 // Because an empty memoperands list provides *no* information and must be
454 // handled conservatively (assuming the instruction can do anything), the
455 // only way to merge with it is to drop all other memoperands.
456 if (MI.memoperands_empty()) {
457 dropMemRefs(MF);
458 return;
459 }
460
461 // Otherwise accumulate these into our temporary buffer of the merged state.
462 MergedMMOs.append(MI.memoperands_begin(), MI.memoperands_end());
463 }
464
465 setMemRefs(MF, MergedMMOs);
466}
467
468void MachineInstr::setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
469 // Do nothing if old and new symbols are the same.
470 if (Symbol == getPreInstrSymbol())
471 return;
472
473 // If there was only one symbol and we're removing it, just clear info.
474 if (!Symbol && Info.is<EIIK_PreInstrSymbol>()) {
475 Info.clear();
476 return;
477 }
478
479 setExtraInfo(MF, memoperands(), Symbol, getPostInstrSymbol(),
480 getHeapAllocMarker());
481}
482
483void MachineInstr::setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
484 // Do nothing if old and new symbols are the same.
485 if (Symbol == getPostInstrSymbol())
486 return;
487
488 // If there was only one symbol and we're removing it, just clear info.
489 if (!Symbol && Info.is<EIIK_PostInstrSymbol>()) {
490 Info.clear();
491 return;
492 }
493
494 setExtraInfo(MF, memoperands(), getPreInstrSymbol(), Symbol,
495 getHeapAllocMarker());
496}
497
498void MachineInstr::setHeapAllocMarker(MachineFunction &MF, MDNode *Marker) {
499 // Do nothing if old and new symbols are the same.
500 if (Marker == getHeapAllocMarker())
501 return;
502
503 setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(),
504 Marker);
505}
506
507void MachineInstr::cloneInstrSymbols(MachineFunction &MF,
508 const MachineInstr &MI) {
509 if (this == &MI)
510 // Nothing to do for a self-clone!
511 return;
512
513 assert(&MF == MI.getMF() &&((&MF == MI.getMF() && "Invalid machine functions when cloning instruction symbols!"
) ? static_cast<void> (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning instruction symbols!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 514, __PRETTY_FUNCTION__))
514 "Invalid machine functions when cloning instruction symbols!")((&MF == MI.getMF() && "Invalid machine functions when cloning instruction symbols!"
) ? static_cast<void> (0) : __assert_fail ("&MF == MI.getMF() && \"Invalid machine functions when cloning instruction symbols!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 514, __PRETTY_FUNCTION__))
;
515
516 setPreInstrSymbol(MF, MI.getPreInstrSymbol());
517 setPostInstrSymbol(MF, MI.getPostInstrSymbol());
518 setHeapAllocMarker(MF, MI.getHeapAllocMarker());
519}
520
521uint16_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
522 // For now, the just return the union of the flags. If the flags get more
523 // complicated over time, we might need more logic here.
524 return getFlags() | Other.getFlags();
525}
526
527uint16_t MachineInstr::copyFlagsFromInstruction(const Instruction &I) {
528 uint16_t MIFlags = 0;
529 // Copy the wrapping flags.
530 if (const OverflowingBinaryOperator *OB =
531 dyn_cast<OverflowingBinaryOperator>(&I)) {
532 if (OB->hasNoSignedWrap())
533 MIFlags |= MachineInstr::MIFlag::NoSWrap;
534 if (OB->hasNoUnsignedWrap())
535 MIFlags |= MachineInstr::MIFlag::NoUWrap;
536 }
537
538 // Copy the exact flag.
539 if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I))
540 if (PE->isExact())
541 MIFlags |= MachineInstr::MIFlag::IsExact;
542
543 // Copy the fast-math flags.
544 if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) {
545 const FastMathFlags Flags = FP->getFastMathFlags();
546 if (Flags.noNaNs())
547 MIFlags |= MachineInstr::MIFlag::FmNoNans;
548 if (Flags.noInfs())
549 MIFlags |= MachineInstr::MIFlag::FmNoInfs;
550 if (Flags.noSignedZeros())
551 MIFlags |= MachineInstr::MIFlag::FmNsz;
552 if (Flags.allowReciprocal())
553 MIFlags |= MachineInstr::MIFlag::FmArcp;
554 if (Flags.allowContract())
555 MIFlags |= MachineInstr::MIFlag::FmContract;
556 if (Flags.approxFunc())
557 MIFlags |= MachineInstr::MIFlag::FmAfn;
558 if (Flags.allowReassoc())
559 MIFlags |= MachineInstr::MIFlag::FmReassoc;
560 }
561
562 return MIFlags;
563}
564
565void MachineInstr::copyIRFlags(const Instruction &I) {
566 Flags = copyFlagsFromInstruction(I);
567}
568
569bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const {
570 assert(!isBundledWithPred() && "Must be called on bundle header")((!isBundledWithPred() && "Must be called on bundle header"
) ? static_cast<void> (0) : __assert_fail ("!isBundledWithPred() && \"Must be called on bundle header\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 570, __PRETTY_FUNCTION__))
;
571 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
572 if (MII->getDesc().getFlags() & Mask) {
573 if (Type == AnyInBundle)
574 return true;
575 } else {
576 if (Type == AllInBundle && !MII->isBundle())
577 return false;
578 }
579 // This was the last instruction in the bundle.
580 if (!MII->isBundledWithSucc())
581 return Type == AllInBundle;
582 }
583}
584
585bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
586 MICheckType Check) const {
587 // If opcodes or number of operands are not the same then the two
588 // instructions are obviously not identical.
589 if (Other.getOpcode() != getOpcode() ||
590 Other.getNumOperands() != getNumOperands())
591 return false;
592
593 if (isBundle()) {
594 // We have passed the test above that both instructions have the same
595 // opcode, so we know that both instructions are bundles here. Let's compare
596 // MIs inside the bundle.
597 assert(Other.isBundle() && "Expected that both instructions are bundles.")((Other.isBundle() && "Expected that both instructions are bundles."
) ? static_cast<void> (0) : __assert_fail ("Other.isBundle() && \"Expected that both instructions are bundles.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 597, __PRETTY_FUNCTION__))
;
598 MachineBasicBlock::const_instr_iterator I1 = getIterator();
599 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
600 // Loop until we analysed the last intruction inside at least one of the
601 // bundles.
602 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
603 ++I1;
604 ++I2;
605 if (!I1->isIdenticalTo(*I2, Check))
606 return false;
607 }
608 // If we've reached the end of just one of the two bundles, but not both,
609 // the instructions are not identical.
610 if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
611 return false;
612 }
613
614 // Check operands to make sure they match.
615 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
616 const MachineOperand &MO = getOperand(i);
617 const MachineOperand &OMO = Other.getOperand(i);
618 if (!MO.isReg()) {
619 if (!MO.isIdenticalTo(OMO))
620 return false;
621 continue;
622 }
623
624 // Clients may or may not want to ignore defs when testing for equality.
625 // For example, machine CSE pass only cares about finding common
626 // subexpressions, so it's safe to ignore virtual register defs.
627 if (MO.isDef()) {
628 if (Check == IgnoreDefs)
629 continue;
630 else if (Check == IgnoreVRegDefs) {
631 if (!Register::isVirtualRegister(MO.getReg()) ||
632 !Register::isVirtualRegister(OMO.getReg()))
633 if (!MO.isIdenticalTo(OMO))
634 return false;
635 } else {
636 if (!MO.isIdenticalTo(OMO))
637 return false;
638 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
639 return false;
640 }
641 } else {
642 if (!MO.isIdenticalTo(OMO))
643 return false;
644 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
645 return false;
646 }
647 }
648 // If DebugLoc does not match then two debug instructions are not identical.
649 if (isDebugInstr())
650 if (getDebugLoc() && Other.getDebugLoc() &&
651 getDebugLoc() != Other.getDebugLoc())
652 return false;
653 return true;
654}
655
656const MachineFunction *MachineInstr::getMF() const {
657 return getParent()->getParent();
658}
659
660MachineInstr *MachineInstr::removeFromParent() {
661 assert(getParent() && "Not embedded in a basic block!")((getParent() && "Not embedded in a basic block!") ? static_cast
<void> (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 661, __PRETTY_FUNCTION__))
;
662 return getParent()->remove(this);
663}
664
665MachineInstr *MachineInstr::removeFromBundle() {
666 assert(getParent() && "Not embedded in a basic block!")((getParent() && "Not embedded in a basic block!") ? static_cast
<void> (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 666, __PRETTY_FUNCTION__))
;
667 return getParent()->remove_instr(this);
668}
669
670void MachineInstr::eraseFromParent() {
671 assert(getParent() && "Not embedded in a basic block!")((getParent() && "Not embedded in a basic block!") ? static_cast
<void> (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 671, __PRETTY_FUNCTION__))
;
672 getParent()->erase(this);
673}
674
675void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
676 assert(getParent() && "Not embedded in a basic block!")((getParent() && "Not embedded in a basic block!") ? static_cast
<void> (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 676, __PRETTY_FUNCTION__))
;
677 MachineBasicBlock *MBB = getParent();
678 MachineFunction *MF = MBB->getParent();
679 assert(MF && "Not embedded in a function!")((MF && "Not embedded in a function!") ? static_cast<
void> (0) : __assert_fail ("MF && \"Not embedded in a function!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 679, __PRETTY_FUNCTION__))
;
680
681 MachineInstr *MI = (MachineInstr *)this;
682 MachineRegisterInfo &MRI = MF->getRegInfo();
683
684 for (const MachineOperand &MO : MI->operands()) {
685 if (!MO.isReg() || !MO.isDef())
686 continue;
687 Register Reg = MO.getReg();
688 if (!Reg.isVirtual())
689 continue;
690 MRI.markUsesInDebugValueAsUndef(Reg);
691 }
692 MI->eraseFromParent();
693}
694
695void MachineInstr::eraseFromBundle() {
696 assert(getParent() && "Not embedded in a basic block!")((getParent() && "Not embedded in a basic block!") ? static_cast
<void> (0) : __assert_fail ("getParent() && \"Not embedded in a basic block!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 696, __PRETTY_FUNCTION__))
;
697 getParent()->erase_instr(this);
698}
699
700bool MachineInstr::isCandidateForCallSiteEntry(QueryType Type) const {
701 if (!isCall(Type))
702 return false;
703 switch (getOpcode()) {
704 case TargetOpcode::PATCHABLE_EVENT_CALL:
705 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
706 case TargetOpcode::PATCHPOINT:
707 case TargetOpcode::STACKMAP:
708 case TargetOpcode::STATEPOINT:
709 return false;
710 }
711 return true;
712}
713
714bool MachineInstr::shouldUpdateCallSiteInfo() const {
715 if (isBundle())
716 return isCandidateForCallSiteEntry(MachineInstr::AnyInBundle);
717 return isCandidateForCallSiteEntry();
718}
719
720unsigned MachineInstr::getNumExplicitOperands() const {
721 unsigned NumOperands = MCID->getNumOperands();
722 if (!MCID->isVariadic())
723 return NumOperands;
724
725 for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) {
726 const MachineOperand &MO = getOperand(I);
727 // The operands must always be in the following order:
728 // - explicit reg defs,
729 // - other explicit operands (reg uses, immediates, etc.),
730 // - implicit reg defs
731 // - implicit reg uses
732 if (MO.isReg() && MO.isImplicit())
733 break;
734 ++NumOperands;
735 }
736 return NumOperands;
737}
738
739unsigned MachineInstr::getNumExplicitDefs() const {
740 unsigned NumDefs = MCID->getNumDefs();
741 if (!MCID->isVariadic())
742 return NumDefs;
743
744 for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) {
745 const MachineOperand &MO = getOperand(I);
746 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
747 break;
748 ++NumDefs;
749 }
750 return NumDefs;
751}
752
753void MachineInstr::bundleWithPred() {
754 assert(!isBundledWithPred() && "MI is already bundled with its predecessor")((!isBundledWithPred() && "MI is already bundled with its predecessor"
) ? static_cast<void> (0) : __assert_fail ("!isBundledWithPred() && \"MI is already bundled with its predecessor\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 754, __PRETTY_FUNCTION__))
;
755 setFlag(BundledPred);
756 MachineBasicBlock::instr_iterator Pred = getIterator();
757 --Pred;
758 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags")((!Pred->isBundledWithSucc() && "Inconsistent bundle flags"
) ? static_cast<void> (0) : __assert_fail ("!Pred->isBundledWithSucc() && \"Inconsistent bundle flags\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 758, __PRETTY_FUNCTION__))
;
759 Pred->setFlag(BundledSucc);
760}
761
762void MachineInstr::bundleWithSucc() {
763 assert(!isBundledWithSucc() && "MI is already bundled with its successor")((!isBundledWithSucc() && "MI is already bundled with its successor"
) ? static_cast<void> (0) : __assert_fail ("!isBundledWithSucc() && \"MI is already bundled with its successor\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 763, __PRETTY_FUNCTION__))
;
764 setFlag(BundledSucc);
765 MachineBasicBlock::instr_iterator Succ = getIterator();
766 ++Succ;
767 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags")((!Succ->isBundledWithPred() && "Inconsistent bundle flags"
) ? static_cast<void> (0) : __assert_fail ("!Succ->isBundledWithPred() && \"Inconsistent bundle flags\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 767, __PRETTY_FUNCTION__))
;
768 Succ->setFlag(BundledPred);
769}
770
771void MachineInstr::unbundleFromPred() {
772 assert(isBundledWithPred() && "MI isn't bundled with its predecessor")((isBundledWithPred() && "MI isn't bundled with its predecessor"
) ? static_cast<void> (0) : __assert_fail ("isBundledWithPred() && \"MI isn't bundled with its predecessor\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 772, __PRETTY_FUNCTION__))
;
773 clearFlag(BundledPred);
774 MachineBasicBlock::instr_iterator Pred = getIterator();
775 --Pred;
776 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags")((Pred->isBundledWithSucc() && "Inconsistent bundle flags"
) ? static_cast<void> (0) : __assert_fail ("Pred->isBundledWithSucc() && \"Inconsistent bundle flags\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 776, __PRETTY_FUNCTION__))
;
777 Pred->clearFlag(BundledSucc);
778}
779
780void MachineInstr::unbundleFromSucc() {
781 assert(isBundledWithSucc() && "MI isn't bundled with its successor")((isBundledWithSucc() && "MI isn't bundled with its successor"
) ? static_cast<void> (0) : __assert_fail ("isBundledWithSucc() && \"MI isn't bundled with its successor\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 781, __PRETTY_FUNCTION__))
;
782 clearFlag(BundledSucc);
783 MachineBasicBlock::instr_iterator Succ = getIterator();
784 ++Succ;
785 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags")((Succ->isBundledWithPred() && "Inconsistent bundle flags"
) ? static_cast<void> (0) : __assert_fail ("Succ->isBundledWithPred() && \"Inconsistent bundle flags\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 785, __PRETTY_FUNCTION__))
;
786 Succ->clearFlag(BundledPred);
787}
788
789bool MachineInstr::isStackAligningInlineAsm() const {
790 if (isInlineAsm()) {
791 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
792 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
793 return true;
794 }
795 return false;
796}
797
798InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
799 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!")((isInlineAsm() && "getInlineAsmDialect() only works for inline asms!"
) ? static_cast<void> (0) : __assert_fail ("isInlineAsm() && \"getInlineAsmDialect() only works for inline asms!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 799, __PRETTY_FUNCTION__))
;
800 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
801 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
802}
803
804int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
805 unsigned *GroupNo) const {
806 assert(isInlineAsm() && "Expected an inline asm instruction")((isInlineAsm() && "Expected an inline asm instruction"
) ? static_cast<void> (0) : __assert_fail ("isInlineAsm() && \"Expected an inline asm instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 806, __PRETTY_FUNCTION__))
;
807 assert(OpIdx < getNumOperands() && "OpIdx out of range")((OpIdx < getNumOperands() && "OpIdx out of range"
) ? static_cast<void> (0) : __assert_fail ("OpIdx < getNumOperands() && \"OpIdx out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 807, __PRETTY_FUNCTION__))
;
808
809 // Ignore queries about the initial operands.
810 if (OpIdx < InlineAsm::MIOp_FirstOperand)
811 return -1;
812
813 unsigned Group = 0;
814 unsigned NumOps;
815 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
816 i += NumOps) {
817 const MachineOperand &FlagMO = getOperand(i);
818 // If we reach the implicit register operands, stop looking.
819 if (!FlagMO.isImm())
820 return -1;
821 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
822 if (i + NumOps > OpIdx) {
823 if (GroupNo)
824 *GroupNo = Group;
825 return i;
826 }
827 ++Group;
828 }
829 return -1;
830}
831
832const DILabel *MachineInstr::getDebugLabel() const {
833 assert(isDebugLabel() && "not a DBG_LABEL")((isDebugLabel() && "not a DBG_LABEL") ? static_cast<
void> (0) : __assert_fail ("isDebugLabel() && \"not a DBG_LABEL\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 833, __PRETTY_FUNCTION__))
;
834 return cast<DILabel>(getOperand(0).getMetadata());
835}
836
837const DILocalVariable *MachineInstr::getDebugVariable() const {
838 assert(isDebugValue() && "not a DBG_VALUE")((isDebugValue() && "not a DBG_VALUE") ? static_cast<
void> (0) : __assert_fail ("isDebugValue() && \"not a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 838, __PRETTY_FUNCTION__))
;
839 return cast<DILocalVariable>(getOperand(2).getMetadata());
840}
841
842const DIExpression *MachineInstr::getDebugExpression() const {
843 assert(isDebugValue() && "not a DBG_VALUE")((isDebugValue() && "not a DBG_VALUE") ? static_cast<
void> (0) : __assert_fail ("isDebugValue() && \"not a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 843, __PRETTY_FUNCTION__))
;
844 return cast<DIExpression>(getOperand(3).getMetadata());
845}
846
847bool MachineInstr::isDebugEntryValue() const {
848 return isDebugValue() && getDebugExpression()->isEntryValue();
849}
850
851const TargetRegisterClass*
852MachineInstr::getRegClassConstraint(unsigned OpIdx,
853 const TargetInstrInfo *TII,
854 const TargetRegisterInfo *TRI) const {
855 assert(getParent() && "Can't have an MBB reference here!")((getParent() && "Can't have an MBB reference here!")
? static_cast<void> (0) : __assert_fail ("getParent() && \"Can't have an MBB reference here!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 855, __PRETTY_FUNCTION__))
;
856 assert(getMF() && "Can't have an MF reference here!")((getMF() && "Can't have an MF reference here!") ? static_cast
<void> (0) : __assert_fail ("getMF() && \"Can't have an MF reference here!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 856, __PRETTY_FUNCTION__))
;
857 const MachineFunction &MF = *getMF();
858
859 // Most opcodes have fixed constraints in their MCInstrDesc.
860 if (!isInlineAsm())
861 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
862
863 if (!getOperand(OpIdx).isReg())
864 return nullptr;
865
866 // For tied uses on inline asm, get the constraint from the def.
867 unsigned DefIdx;
868 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
869 OpIdx = DefIdx;
870
871 // Inline asm stores register class constraints in the flag word.
872 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
873 if (FlagIdx < 0)
874 return nullptr;
875
876 unsigned Flag = getOperand(FlagIdx).getImm();
877 unsigned RCID;
878 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
879 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
880 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
881 InlineAsm::hasRegClassConstraint(Flag, RCID))
882 return TRI->getRegClass(RCID);
883
884 // Assume that all registers in a memory operand are pointers.
885 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
886 return TRI->getPointerRegClass(MF);
887
888 return nullptr;
889}
890
891const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
892 Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
893 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
894 // Check every operands inside the bundle if we have
895 // been asked to.
896 if (ExploreBundle)
897 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
898 ++OpndIt)
899 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
900 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
901 else
902 // Otherwise, just check the current operands.
903 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
904 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
905 return CurRC;
906}
907
908const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
909 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
910 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
911 assert(CurRC && "Invalid initial register class")((CurRC && "Invalid initial register class") ? static_cast
<void> (0) : __assert_fail ("CurRC && \"Invalid initial register class\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 911, __PRETTY_FUNCTION__))
;
912 // Check if Reg is constrained by some of its use/def from MI.
913 const MachineOperand &MO = getOperand(OpIdx);
914 if (!MO.isReg() || MO.getReg() != Reg)
915 return CurRC;
916 // If yes, accumulate the constraints through the operand.
917 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
918}
919
920const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
921 unsigned OpIdx, const TargetRegisterClass *CurRC,
922 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
923 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
924 const MachineOperand &MO = getOperand(OpIdx);
925 assert(MO.isReg() &&((MO.isReg() && "Cannot get register constraints for non-register operand"
) ? static_cast<void> (0) : __assert_fail ("MO.isReg() && \"Cannot get register constraints for non-register operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 926, __PRETTY_FUNCTION__))
926 "Cannot get register constraints for non-register operand")((MO.isReg() && "Cannot get register constraints for non-register operand"
) ? static_cast<void> (0) : __assert_fail ("MO.isReg() && \"Cannot get register constraints for non-register operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 926, __PRETTY_FUNCTION__))
;
927 assert(CurRC && "Invalid initial register class")((CurRC && "Invalid initial register class") ? static_cast
<void> (0) : __assert_fail ("CurRC && \"Invalid initial register class\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 927, __PRETTY_FUNCTION__))
;
928 if (unsigned SubIdx = MO.getSubReg()) {
929 if (OpRC)
930 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
931 else
932 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
933 } else if (OpRC)
934 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
935 return CurRC;
936}
937
938/// Return the number of instructions inside the MI bundle, not counting the
939/// header instruction.
940unsigned MachineInstr::getBundleSize() const {
941 MachineBasicBlock::const_instr_iterator I = getIterator();
942 unsigned Size = 0;
943 while (I->isBundledWithSucc()) {
944 ++Size;
945 ++I;
946 }
947 return Size;
948}
949
950/// Returns true if the MachineInstr has an implicit-use operand of exactly
951/// the given register (not considering sub/super-registers).
952bool MachineInstr::hasRegisterImplicitUseOperand(Register Reg) const {
953 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
954 const MachineOperand &MO = getOperand(i);
955 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
956 return true;
957 }
958 return false;
959}
960
961/// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
962/// the specific register or -1 if it is not found. It further tightens
963/// the search criteria to a use that kills the register if isKill is true.
964int MachineInstr::findRegisterUseOperandIdx(
965 Register Reg, bool isKill, const TargetRegisterInfo *TRI) const {
966 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
967 const MachineOperand &MO = getOperand(i);
968 if (!MO.isReg() || !MO.isUse())
969 continue;
970 Register MOReg = MO.getReg();
971 if (!MOReg)
972 continue;
973 if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg)))
974 if (!isKill || MO.isKill())
975 return i;
976 }
977 return -1;
978}
979
980/// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
981/// indicating if this instruction reads or writes Reg. This also considers
982/// partial defines.
983std::pair<bool,bool>
984MachineInstr::readsWritesVirtualRegister(Register Reg,
985 SmallVectorImpl<unsigned> *Ops) const {
986 bool PartDef = false; // Partial redefine.
987 bool FullDef = false; // Full define.
988 bool Use = false;
989
990 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
991 const MachineOperand &MO = getOperand(i);
992 if (!MO.isReg() || MO.getReg() != Reg)
993 continue;
994 if (Ops)
995 Ops->push_back(i);
996 if (MO.isUse())
997 Use |= !MO.isUndef();
998 else if (MO.getSubReg() && !MO.isUndef())
999 // A partial def undef doesn't count as reading the register.
1000 PartDef = true;
1001 else
1002 FullDef = true;
1003 }
1004 // A partial redefine uses Reg unless there is also a full define.
1005 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1006}
1007
1008/// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1009/// the specified register or -1 if it is not found. If isDead is true, defs
1010/// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1011/// also checks if there is a def of a super-register.
1012int
1013MachineInstr::findRegisterDefOperandIdx(Register Reg, bool isDead, bool Overlap,
1014 const TargetRegisterInfo *TRI) const {
1015 bool isPhys = Register::isPhysicalRegister(Reg);
1016 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1017 const MachineOperand &MO = getOperand(i);
1018 // Accept regmask operands when Overlap is set.
1019 // Ignore them when looking for a specific def operand (Overlap == false).
1020 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1021 return i;
1022 if (!MO.isReg() || !MO.isDef())
1023 continue;
1024 Register MOReg = MO.getReg();
1025 bool Found = (MOReg == Reg);
1026 if (!Found && TRI && isPhys && Register::isPhysicalRegister(MOReg)) {
1027 if (Overlap)
1028 Found = TRI->regsOverlap(MOReg, Reg);
1029 else
1030 Found = TRI->isSubRegister(MOReg, Reg);
1031 }
1032 if (Found && (!isDead || MO.isDead()))
1033 return i;
1034 }
1035 return -1;
1036}
1037
1038/// findFirstPredOperandIdx() - Find the index of the first operand in the
1039/// operand list that is used to represent the predicate. It returns -1 if
1040/// none is found.
1041int MachineInstr::findFirstPredOperandIdx() const {
1042 // Don't call MCID.findFirstPredOperandIdx() because this variant
1043 // is sometimes called on an instruction that's not yet complete, and
1044 // so the number of operands is less than the MCID indicates. In
1045 // particular, the PTX target does this.
1046 const MCInstrDesc &MCID = getDesc();
1047 if (MCID.isPredicable()) {
1048 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1049 if (MCID.OpInfo[i].isPredicate())
1050 return i;
1051 }
1052
1053 return -1;
1054}
1055
1056// MachineOperand::TiedTo is 4 bits wide.
1057const unsigned TiedMax = 15;
1058
1059/// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1060///
1061/// Use and def operands can be tied together, indicated by a non-zero TiedTo
1062/// field. TiedTo can have these values:
1063///
1064/// 0: Operand is not tied to anything.
1065/// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1066/// TiedMax: Tied to an operand >= TiedMax-1.
1067///
1068/// The tied def must be one of the first TiedMax operands on a normal
1069/// instruction. INLINEASM instructions allow more tied defs.
1070///
1071void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1072 MachineOperand &DefMO = getOperand(DefIdx);
1073 MachineOperand &UseMO = getOperand(UseIdx);
1074 assert(DefMO.isDef() && "DefIdx must be a def operand")((DefMO.isDef() && "DefIdx must be a def operand") ? static_cast
<void> (0) : __assert_fail ("DefMO.isDef() && \"DefIdx must be a def operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1074, __PRETTY_FUNCTION__))
;
1075 assert(UseMO.isUse() && "UseIdx must be a use operand")((UseMO.isUse() && "UseIdx must be a use operand") ? static_cast
<void> (0) : __assert_fail ("UseMO.isUse() && \"UseIdx must be a use operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1075, __PRETTY_FUNCTION__))
;
1076 assert(!DefMO.isTied() && "Def is already tied to another use")((!DefMO.isTied() && "Def is already tied to another use"
) ? static_cast<void> (0) : __assert_fail ("!DefMO.isTied() && \"Def is already tied to another use\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1076, __PRETTY_FUNCTION__))
;
1077 assert(!UseMO.isTied() && "Use is already tied to another def")((!UseMO.isTied() && "Use is already tied to another def"
) ? static_cast<void> (0) : __assert_fail ("!UseMO.isTied() && \"Use is already tied to another def\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1077, __PRETTY_FUNCTION__))
;
1078
1079 if (DefIdx < TiedMax)
1080 UseMO.TiedTo = DefIdx + 1;
1081 else {
1082 // Inline asm can use the group descriptors to find tied operands, but on
1083 // normal instruction, the tied def must be within the first TiedMax
1084 // operands.
1085 assert(isInlineAsm() && "DefIdx out of range")((isInlineAsm() && "DefIdx out of range") ? static_cast
<void> (0) : __assert_fail ("isInlineAsm() && \"DefIdx out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1085, __PRETTY_FUNCTION__))
;
1086 UseMO.TiedTo = TiedMax;
1087 }
1088
1089 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1090 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1091}
1092
1093/// Given the index of a tied register operand, find the operand it is tied to.
1094/// Defs are tied to uses and vice versa. Returns the index of the tied operand
1095/// which must exist.
1096unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1097 const MachineOperand &MO = getOperand(OpIdx);
1098 assert(MO.isTied() && "Operand isn't tied")((MO.isTied() && "Operand isn't tied") ? static_cast<
void> (0) : __assert_fail ("MO.isTied() && \"Operand isn't tied\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1098, __PRETTY_FUNCTION__))
;
1099
1100 // Normally TiedTo is in range.
1101 if (MO.TiedTo < TiedMax)
1102 return MO.TiedTo - 1;
1103
1104 // Uses on normal instructions can be out of range.
1105 if (!isInlineAsm()) {
1106 // Normal tied defs must be in the 0..TiedMax-1 range.
1107 if (MO.isUse())
1108 return TiedMax - 1;
1109 // MO is a def. Search for the tied use.
1110 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1111 const MachineOperand &UseMO = getOperand(i);
1112 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1113 return i;
1114 }
1115 llvm_unreachable("Can't find tied use")::llvm::llvm_unreachable_internal("Can't find tied use", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1115)
;
1116 }
1117
1118 // Now deal with inline asm by parsing the operand group descriptor flags.
1119 // Find the beginning of each operand group.
1120 SmallVector<unsigned, 8> GroupIdx;
1121 unsigned OpIdxGroup = ~0u;
1122 unsigned NumOps;
1123 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1124 i += NumOps) {
1125 const MachineOperand &FlagMO = getOperand(i);
1126 assert(FlagMO.isImm() && "Invalid tied operand on inline asm")((FlagMO.isImm() && "Invalid tied operand on inline asm"
) ? static_cast<void> (0) : __assert_fail ("FlagMO.isImm() && \"Invalid tied operand on inline asm\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1126, __PRETTY_FUNCTION__))
;
1127 unsigned CurGroup = GroupIdx.size();
1128 GroupIdx.push_back(i);
1129 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1130 // OpIdx belongs to this operand group.
1131 if (OpIdx > i && OpIdx < i + NumOps)
1132 OpIdxGroup = CurGroup;
1133 unsigned TiedGroup;
1134 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1135 continue;
1136 // Operands in this group are tied to operands in TiedGroup which must be
1137 // earlier. Find the number of operands between the two groups.
1138 unsigned Delta = i - GroupIdx[TiedGroup];
1139
1140 // OpIdx is a use tied to TiedGroup.
1141 if (OpIdxGroup == CurGroup)
1142 return OpIdx - Delta;
1143
1144 // OpIdx is a def tied to this use group.
1145 if (OpIdxGroup == TiedGroup)
1146 return OpIdx + Delta;
1147 }
1148 llvm_unreachable("Invalid tied operand on inline asm")::llvm::llvm_unreachable_internal("Invalid tied operand on inline asm"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1148)
;
1149}
1150
1151/// clearKillInfo - Clears kill flags on all operands.
1152///
1153void MachineInstr::clearKillInfo() {
1154 for (MachineOperand &MO : operands()) {
1155 if (MO.isReg() && MO.isUse())
1156 MO.setIsKill(false);
1157 }
1158}
1159
1160void MachineInstr::substituteRegister(Register FromReg, Register ToReg,
1161 unsigned SubIdx,
1162 const TargetRegisterInfo &RegInfo) {
1163 if (Register::isPhysicalRegister(ToReg)) {
1164 if (SubIdx)
1165 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1166 for (MachineOperand &MO : operands()) {
1167 if (!MO.isReg() || MO.getReg() != FromReg)
1168 continue;
1169 MO.substPhysReg(ToReg, RegInfo);
1170 }
1171 } else {
1172 for (MachineOperand &MO : operands()) {
1173 if (!MO.isReg() || MO.getReg() != FromReg)
1174 continue;
1175 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1176 }
1177 }
1178}
1179
1180/// isSafeToMove - Return true if it is safe to move this instruction. If
1181/// SawStore is set to true, it means that there is a store (or call) between
1182/// the instruction's location and its intended destination.
1183bool MachineInstr::isSafeToMove(AAResults *AA, bool &SawStore) const {
1184 // Ignore stuff that we obviously can't move.
1185 //
1186 // Treat volatile loads as stores. This is not strictly necessary for
1187 // volatiles, but it is required for atomic loads. It is not allowed to move
1188 // a load across an atomic load with Ordering > Monotonic.
1189 if (mayStore() || isCall() || isPHI() ||
1190 (mayLoad() && hasOrderedMemoryRef())) {
1191 SawStore = true;
1192 return false;
1193 }
1194
1195 if (isPosition() || isDebugInstr() || isTerminator() ||
1196 mayRaiseFPException() || hasUnmodeledSideEffects())
1197 return false;
1198
1199 // See if this instruction does a load. If so, we have to guarantee that the
1200 // loaded value doesn't change between the load and the its intended
1201 // destination. The check for isInvariantLoad gives the targe the chance to
1202 // classify the load as always returning a constant, e.g. a constant pool
1203 // load.
1204 if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1205 // Otherwise, this is a real load. If there is a store between the load and
1206 // end of block, we can't move it.
1207 return !SawStore;
1208
1209 return true;
1210}
1211
1212bool MachineInstr::mayAlias(AAResults *AA, const MachineInstr &Other,
1213 bool UseTBAA) const {
1214 const MachineFunction *MF = getMF();
1215 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1216 const MachineFrameInfo &MFI = MF->getFrameInfo();
1217
1218 // If neither instruction stores to memory, they can't alias in any
1219 // meaningful way, even if they read from the same address.
1220 if (!mayStore() && !Other.mayStore())
1221 return false;
1222
1223 // Let the target decide if memory accesses cannot possibly overlap.
1224 if (TII->areMemAccessesTriviallyDisjoint(*this, Other))
1225 return false;
1226
1227 // FIXME: Need to handle multiple memory operands to support all targets.
1228 if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1229 return true;
1230
1231 MachineMemOperand *MMOa = *memoperands_begin();
1232 MachineMemOperand *MMOb = *Other.memoperands_begin();
1233
1234 // The following interface to AA is fashioned after DAGCombiner::isAlias
1235 // and operates with MachineMemOperand offset with some important
1236 // assumptions:
1237 // - LLVM fundamentally assumes flat address spaces.
1238 // - MachineOperand offset can *only* result from legalization and
1239 // cannot affect queries other than the trivial case of overlap
1240 // checking.
1241 // - These offsets never wrap and never step outside
1242 // of allocated objects.
1243 // - There should never be any negative offsets here.
1244 //
1245 // FIXME: Modify API to hide this math from "user"
1246 // Even before we go to AA we can reason locally about some
1247 // memory objects. It can save compile time, and possibly catch some
1248 // corner cases not currently covered.
1249
1250 int64_t OffsetA = MMOa->getOffset();
1251 int64_t OffsetB = MMOb->getOffset();
1252 int64_t MinOffset = std::min(OffsetA, OffsetB);
1253
1254 uint64_t WidthA = MMOa->getSize();
1255 uint64_t WidthB = MMOb->getSize();
1256 bool KnownWidthA = WidthA != MemoryLocation::UnknownSize;
1257 bool KnownWidthB = WidthB != MemoryLocation::UnknownSize;
1258
1259 const Value *ValA = MMOa->getValue();
1260 const Value *ValB = MMOb->getValue();
1261 bool SameVal = (ValA && ValB && (ValA == ValB));
1262 if (!SameVal) {
1263 const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
1264 const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
1265 if (PSVa && ValB && !PSVa->mayAlias(&MFI))
1266 return false;
1267 if (PSVb && ValA && !PSVb->mayAlias(&MFI))
1268 return false;
1269 if (PSVa && PSVb && (PSVa == PSVb))
1270 SameVal = true;
1271 }
1272
1273 if (SameVal) {
1274 if (!KnownWidthA || !KnownWidthB)
1275 return true;
1276 int64_t MaxOffset = std::max(OffsetA, OffsetB);
1277 int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
1278 return (MinOffset + LowWidth > MaxOffset);
1279 }
1280
1281 if (!AA)
1282 return true;
1283
1284 if (!ValA || !ValB)
1285 return true;
1286
1287 assert((OffsetA >= 0) && "Negative MachineMemOperand offset")(((OffsetA >= 0) && "Negative MachineMemOperand offset"
) ? static_cast<void> (0) : __assert_fail ("(OffsetA >= 0) && \"Negative MachineMemOperand offset\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1287, __PRETTY_FUNCTION__))
;
1288 assert((OffsetB >= 0) && "Negative MachineMemOperand offset")(((OffsetB >= 0) && "Negative MachineMemOperand offset"
) ? static_cast<void> (0) : __assert_fail ("(OffsetB >= 0) && \"Negative MachineMemOperand offset\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1288, __PRETTY_FUNCTION__))
;
1289
1290 int64_t OverlapA = KnownWidthA ? WidthA + OffsetA - MinOffset
1291 : MemoryLocation::UnknownSize;
1292 int64_t OverlapB = KnownWidthB ? WidthB + OffsetB - MinOffset
1293 : MemoryLocation::UnknownSize;
1294
1295 AliasResult AAResult = AA->alias(
1296 MemoryLocation(ValA, OverlapA,
1297 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1298 MemoryLocation(ValB, OverlapB,
1299 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1300
1301 return (AAResult != NoAlias);
1302}
1303
1304/// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1305/// or volatile memory reference, or if the information describing the memory
1306/// reference is not available. Return false if it is known to have no ordered
1307/// memory references.
1308bool MachineInstr::hasOrderedMemoryRef() const {
1309 // An instruction known never to access memory won't have a volatile access.
1310 if (!mayStore() &&
1311 !mayLoad() &&
1312 !isCall() &&
1313 !hasUnmodeledSideEffects())
1314 return false;
1315
1316 // Otherwise, if the instruction has no memory reference information,
1317 // conservatively assume it wasn't preserved.
1318 if (memoperands_empty())
1319 return true;
1320
1321 // Check if any of our memory operands are ordered.
1322 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1323 return !MMO->isUnordered();
1324 });
1325}
1326
1327/// isDereferenceableInvariantLoad - Return true if this instruction will never
1328/// trap and is loading from a location whose value is invariant across a run of
1329/// this function.
1330bool MachineInstr::isDereferenceableInvariantLoad(AAResults *AA) const {
1331 // If the instruction doesn't load at all, it isn't an invariant load.
1332 if (!mayLoad())
1333 return false;
1334
1335 // If the instruction has lost its memoperands, conservatively assume that
1336 // it may not be an invariant load.
1337 if (memoperands_empty())
1338 return false;
1339
1340 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1341
1342 for (MachineMemOperand *MMO : memoperands()) {
1343 if (!MMO->isUnordered())
1344 // If the memory operand has ordering side effects, we can't move the
1345 // instruction. Such an instruction is technically an invariant load,
1346 // but the caller code would need updated to expect that.
1347 return false;
1348 if (MMO->isStore()) return false;
1349 if (MMO->isInvariant() && MMO->isDereferenceable())
1350 continue;
1351
1352 // A load from a constant PseudoSourceValue is invariant.
1353 if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1354 if (PSV->isConstant(&MFI))
1355 continue;
1356
1357 if (const Value *V = MMO->getValue()) {
1358 // If we have an AliasAnalysis, ask it whether the memory is constant.
1359 if (AA &&
1360 AA->pointsToConstantMemory(
1361 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1362 continue;
1363 }
1364
1365 // Otherwise assume conservatively.
1366 return false;
1367 }
1368
1369 // Everything checks out.
1370 return true;
1371}
1372
1373/// isConstantValuePHI - If the specified instruction is a PHI that always
1374/// merges together the same virtual register, return the register, otherwise
1375/// return 0.
1376unsigned MachineInstr::isConstantValuePHI() const {
1377 if (!isPHI())
1378 return 0;
1379 assert(getNumOperands() >= 3 &&((getNumOperands() >= 3 && "It's illegal to have a PHI without source operands"
) ? static_cast<void> (0) : __assert_fail ("getNumOperands() >= 3 && \"It's illegal to have a PHI without source operands\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1380, __PRETTY_FUNCTION__))
1380 "It's illegal to have a PHI without source operands")((getNumOperands() >= 3 && "It's illegal to have a PHI without source operands"
) ? static_cast<void> (0) : __assert_fail ("getNumOperands() >= 3 && \"It's illegal to have a PHI without source operands\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1380, __PRETTY_FUNCTION__))
;
1381
1382 Register Reg = getOperand(1).getReg();
1383 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1384 if (getOperand(i).getReg() != Reg)
1385 return 0;
1386 return Reg;
1387}
1388
1389bool MachineInstr::hasUnmodeledSideEffects() const {
1390 if (hasProperty(MCID::UnmodeledSideEffects))
1391 return true;
1392 if (isInlineAsm()) {
1393 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1394 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1395 return true;
1396 }
1397
1398 return false;
1399}
1400
1401bool MachineInstr::isLoadFoldBarrier() const {
1402 return mayStore() || isCall() || hasUnmodeledSideEffects();
1403}
1404
1405/// allDefsAreDead - Return true if all the defs of this instruction are dead.
1406///
1407bool MachineInstr::allDefsAreDead() const {
1408 for (const MachineOperand &MO : operands()) {
1409 if (!MO.isReg() || MO.isUse())
1410 continue;
1411 if (!MO.isDead())
1412 return false;
1413 }
1414 return true;
1415}
1416
1417/// copyImplicitOps - Copy implicit register operands from specified
1418/// instruction to this instruction.
1419void MachineInstr::copyImplicitOps(MachineFunction &MF,
1420 const MachineInstr &MI) {
1421 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1422 i != e; ++i) {
1423 const MachineOperand &MO = MI.getOperand(i);
1424 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1425 addOperand(MF, MO);
1426 }
1427}
1428
1429bool MachineInstr::hasComplexRegisterTies() const {
1430 const MCInstrDesc &MCID = getDesc();
1431 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1432 const auto &Operand = getOperand(I);
1433 if (!Operand.isReg() || Operand.isDef())
1434 // Ignore the defined registers as MCID marks only the uses as tied.
1435 continue;
1436 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
1437 int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
1438 if (ExpectedTiedIdx != TiedIdx)
1439 return true;
1440 }
1441 return false;
1442}
1443
1444LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1445 const MachineRegisterInfo &MRI) const {
1446 const MachineOperand &Op = getOperand(OpIdx);
1447 if (!Op.isReg())
1448 return LLT{};
1449
1450 if (isVariadic() || OpIdx >= getNumExplicitOperands())
1451 return MRI.getType(Op.getReg());
1452
1453 auto &OpInfo = getDesc().OpInfo[OpIdx];
1454 if (!OpInfo.isGenericType())
1455 return MRI.getType(Op.getReg());
1456
1457 if (PrintedTypes[OpInfo.getGenericTypeIndex()])
1458 return LLT{};
1459
1460 LLT TypeToPrint = MRI.getType(Op.getReg());
1461 // Don't mark the type index printed if it wasn't actually printed: maybe
1462 // another operand with the same type index has an actual type attached:
1463 if (TypeToPrint.isValid())
1464 PrintedTypes.set(OpInfo.getGenericTypeIndex());
1465 return TypeToPrint;
1466}
1467
1468#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1469LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MachineInstr::dump() const {
1470 dbgs() << " ";
1471 print(dbgs());
1472}
1473
1474LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MachineInstr::dumprImpl(
1475 const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
1476 SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const {
1477 if (Depth >= MaxDepth)
1478 return;
1479 if (!AlreadySeenInstrs.insert(this).second)
1480 return;
1481 // PadToColumn always inserts at least one space.
1482 // Don't mess up the alignment if we don't want any space.
1483 if (Depth)
1484 fdbgs().PadToColumn(Depth * 2);
1485 print(fdbgs());
1486 for (const MachineOperand &MO : operands()) {
1487 if (!MO.isReg() || MO.isDef())
1488 continue;
1489 Register Reg = MO.getReg();
1490 if (Reg.isPhysical())
1491 continue;
1492 const MachineInstr *NewMI = MRI.getUniqueVRegDef(Reg);
1493 if (NewMI == nullptr)
1494 continue;
1495 NewMI->dumprImpl(MRI, Depth + 1, MaxDepth, AlreadySeenInstrs);
1496 }
1497}
1498
1499LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MachineInstr::dumpr(const MachineRegisterInfo &MRI,
1500 unsigned MaxDepth) const {
1501 SmallPtrSet<const MachineInstr *, 16> AlreadySeenInstrs;
1502 dumprImpl(MRI, 0, MaxDepth, AlreadySeenInstrs);
1503}
1504#endif
1505
1506void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
1507 bool SkipDebugLoc, bool AddNewLine,
1508 const TargetInstrInfo *TII) const {
1509 const Module *M = nullptr;
1510 const Function *F = nullptr;
1511 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1512 F = &MF->getFunction();
1513 M = F->getParent();
1514 if (!TII)
1515 TII = MF->getSubtarget().getInstrInfo();
1516 }
1517
1518 ModuleSlotTracker MST(M);
1519 if (F)
1520 MST.incorporateFunction(*F);
1521 print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, AddNewLine, TII);
1522}
1523
1524void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1525 bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
1526 bool AddNewLine, const TargetInstrInfo *TII) const {
1527 // We can be a bit tidier if we know the MachineFunction.
1528 const TargetRegisterInfo *TRI = nullptr;
1529 const MachineRegisterInfo *MRI = nullptr;
1530 const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1531 tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
1532
1533 if (isCFIInstruction())
1534 assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction")((getNumOperands() == 1 && "Expected 1 operand in CFI instruction"
) ? static_cast<void> (0) : __assert_fail ("getNumOperands() == 1 && \"Expected 1 operand in CFI instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 1534, __PRETTY_FUNCTION__))
;
1535
1536 SmallBitVector PrintedTypes(8);
1537 bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
1538 auto getTiedOperandIdx = [&](unsigned OpIdx) {
1539 if (!ShouldPrintRegisterTies)
1540 return 0U;
1541 const MachineOperand &MO = getOperand(OpIdx);
1542 if (MO.isReg() && MO.isTied() && !MO.isDef())
1543 return findTiedOperandIdx(OpIdx);
1544 return 0U;
1545 };
1546 unsigned StartOp = 0;
1547 unsigned e = getNumOperands();
1548
1549 // Print explicitly defined operands on the left of an assignment syntax.
1550 while (StartOp < e) {
1551 const MachineOperand &MO = getOperand(StartOp);
1552 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
1553 break;
1554
1555 if (StartOp != 0)
1556 OS << ", ";
1557
1558 LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
1559 unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
1560 MO.print(OS, MST, TypeToPrint, StartOp, /*PrintDef=*/false, IsStandalone,
1561 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1562 ++StartOp;
1563 }
1564
1565 if (StartOp != 0)
1566 OS << " = ";
1567
1568 if (getFlag(MachineInstr::FrameSetup))
1569 OS << "frame-setup ";
1570 if (getFlag(MachineInstr::FrameDestroy))
1571 OS << "frame-destroy ";
1572 if (getFlag(MachineInstr::FmNoNans))
1573 OS << "nnan ";
1574 if (getFlag(MachineInstr::FmNoInfs))
1575 OS << "ninf ";
1576 if (getFlag(MachineInstr::FmNsz))
1577 OS << "nsz ";
1578 if (getFlag(MachineInstr::FmArcp))
1579 OS << "arcp ";
1580 if (getFlag(MachineInstr::FmContract))
1581 OS << "contract ";
1582 if (getFlag(MachineInstr::FmAfn))
1583 OS << "afn ";
1584 if (getFlag(MachineInstr::FmReassoc))
1585 OS << "reassoc ";
1586 if (getFlag(MachineInstr::NoUWrap))
1587 OS << "nuw ";
1588 if (getFlag(MachineInstr::NoSWrap))
1589 OS << "nsw ";
1590 if (getFlag(MachineInstr::IsExact))
1591 OS << "exact ";
1592 if (getFlag(MachineInstr::NoFPExcept))
1593 OS << "nofpexcept ";
1594
1595 // Print the opcode name.
1596 if (TII)
1597 OS << TII->getName(getOpcode());
1598 else
1599 OS << "UNKNOWN";
1600
1601 if (SkipOpers)
1602 return;
1603
1604 // Print the rest of the operands.
1605 bool FirstOp = true;
1606 unsigned AsmDescOp = ~0u;
1607 unsigned AsmOpCount = 0;
1608
1609 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1610 // Print asm string.
1611 OS << " ";
1612 const unsigned OpIdx = InlineAsm::MIOp_AsmString;
1613 LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
1614 unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
1615 getOperand(OpIdx).print(OS, MST, TypeToPrint, OpIdx, /*PrintDef=*/true, IsStandalone,
1616 ShouldPrintRegisterTies, TiedOperandIdx, TRI,
1617 IntrinsicInfo);
1618
1619 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1620 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1621 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1622 OS << " [sideeffect]";
1623 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1624 OS << " [mayload]";
1625 if (ExtraInfo & InlineAsm::Extra_MayStore)
1626 OS << " [maystore]";
1627 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1628 OS << " [isconvergent]";
1629 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1630 OS << " [alignstack]";
1631 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1632 OS << " [attdialect]";
1633 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1634 OS << " [inteldialect]";
1635
1636 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1637 FirstOp = false;
1638 }
1639
1640 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1641 const MachineOperand &MO = getOperand(i);
1642
1643 if (FirstOp) FirstOp = false; else OS << ",";
1644 OS << " ";
1645
1646 if (isDebugValue() && MO.isMetadata()) {
1647 // Pretty print DBG_VALUE instructions.
1648 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1649 if (DIV && !DIV->getName().empty())
1650 OS << "!\"" << DIV->getName() << '\"';
1651 else {
1652 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1653 unsigned TiedOperandIdx = getTiedOperandIdx(i);
1654 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1655 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1656 }
1657 } else if (isDebugLabel() && MO.isMetadata()) {
1658 // Pretty print DBG_LABEL instructions.
1659 auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
1660 if (DIL && !DIL->getName().empty())
1661 OS << "\"" << DIL->getName() << '\"';
1662 else {
1663 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1664 unsigned TiedOperandIdx = getTiedOperandIdx(i);
1665 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1666 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1667 }
1668 } else if (i == AsmDescOp && MO.isImm()) {
1669 // Pretty print the inline asm operand descriptor.
1670 OS << '$' << AsmOpCount++;
1671 unsigned Flag = MO.getImm();
1672 switch (InlineAsm::getKind(Flag)) {
1673 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1674 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1675 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1676 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1677 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1678 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1679 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1680 }
1681
1682 unsigned RCID = 0;
1683 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1684 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1685 if (TRI) {
1686 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1687 } else
1688 OS << ":RC" << RCID;
1689 }
1690
1691 if (InlineAsm::isMemKind(Flag)) {
1692 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1693 switch (MCID) {
1694 case InlineAsm::Constraint_es: OS << ":es"; break;
1695 case InlineAsm::Constraint_i: OS << ":i"; break;
1696 case InlineAsm::Constraint_m: OS << ":m"; break;
1697 case InlineAsm::Constraint_o: OS << ":o"; break;
1698 case InlineAsm::Constraint_v: OS << ":v"; break;
1699 case InlineAsm::Constraint_Q: OS << ":Q"; break;
1700 case InlineAsm::Constraint_R: OS << ":R"; break;
1701 case InlineAsm::Constraint_S: OS << ":S"; break;
1702 case InlineAsm::Constraint_T: OS << ":T"; break;
1703 case InlineAsm::Constraint_Um: OS << ":Um"; break;
1704 case InlineAsm::Constraint_Un: OS << ":Un"; break;
1705 case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1706 case InlineAsm::Constraint_Us: OS << ":Us"; break;
1707 case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1708 case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1709 case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1710 case InlineAsm::Constraint_X: OS << ":X"; break;
1711 case InlineAsm::Constraint_Z: OS << ":Z"; break;
1712 case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1713 case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1714 default: OS << ":?"; break;
1715 }
1716 }
1717
1718 unsigned TiedTo = 0;
1719 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1720 OS << " tiedto:$" << TiedTo;
1721
1722 OS << ']';
1723
1724 // Compute the index of the next operand descriptor.
1725 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1726 } else {
1727 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1728 unsigned TiedOperandIdx = getTiedOperandIdx(i);
1729 if (MO.isImm() && isOperandSubregIdx(i))
1730 MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
1731 else
1732 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1733 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1734 }
1735 }
1736
1737 // Print any optional symbols attached to this instruction as-if they were
1738 // operands.
1739 if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
1740 if (!FirstOp) {
1741 FirstOp = false;
1742 OS << ',';
1743 }
1744 OS << " pre-instr-symbol ";
1745 MachineOperand::printSymbol(OS, *PreInstrSymbol);
1746 }
1747 if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
1748 if (!FirstOp) {
1749 FirstOp = false;
1750 OS << ',';
1751 }
1752 OS << " post-instr-symbol ";
1753 MachineOperand::printSymbol(OS, *PostInstrSymbol);
1754 }
1755 if (MDNode *HeapAllocMarker = getHeapAllocMarker()) {
1756 if (!FirstOp) {
1757 FirstOp = false;
1758 OS << ',';
1759 }
1760 OS << " heap-alloc-marker ";
1761 HeapAllocMarker->printAsOperand(OS, MST);
1762 }
1763
1764 if (!SkipDebugLoc) {
1765 if (const DebugLoc &DL = getDebugLoc()) {
1766 if (!FirstOp)
1767 OS << ',';
1768 OS << " debug-location ";
1769 DL->printAsOperand(OS, MST);
1770 }
1771 }
1772
1773 if (!memoperands_empty()) {
1774 SmallVector<StringRef, 0> SSNs;
1775 const LLVMContext *Context = nullptr;
1776 std::unique_ptr<LLVMContext> CtxPtr;
1777 const MachineFrameInfo *MFI = nullptr;
1778 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1779 MFI = &MF->getFrameInfo();
1780 Context = &MF->getFunction().getContext();
1781 } else {
1782 CtxPtr = std::make_unique<LLVMContext>();
1783 Context = CtxPtr.get();
1784 }
1785
1786 OS << " :: ";
1787 bool NeedComma = false;
1788 for (const MachineMemOperand *Op : memoperands()) {
1789 if (NeedComma)
1790 OS << ", ";
1791 Op->print(OS, MST, SSNs, *Context, MFI, TII);
1792 NeedComma = true;
1793 }
1794 }
1795
1796 if (SkipDebugLoc)
1797 return;
1798
1799 bool HaveSemi = false;
1800
1801 // Print debug location information.
1802 if (const DebugLoc &DL = getDebugLoc()) {
1803 if (!HaveSemi) {
1804 OS << ';';
1805 HaveSemi = true;
1806 }
1807 OS << ' ';
1808 DL.print(OS);
1809 }
1810
1811 // Print extra comments for DEBUG_VALUE.
1812 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
1813 if (!HaveSemi) {
1814 OS << ";";
1815 HaveSemi = true;
Value stored to 'HaveSemi' is never read
1816 }
1817 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
1818 OS << " line no:" << DV->getLine();
1819 if (isIndirectDebugValue())
1820 OS << " indirect";
1821 }
1822 // TODO: DBG_LABEL
1823
1824 if (AddNewLine)
1825 OS << '\n';
1826}
1827
1828bool MachineInstr::addRegisterKilled(Register IncomingReg,
1829 const TargetRegisterInfo *RegInfo,
1830 bool AddIfNotFound) {
1831 bool isPhysReg = Register::isPhysicalRegister(IncomingReg);
1832 bool hasAliases = isPhysReg &&
1833 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1834 bool Found = false;
1835 SmallVector<unsigned,4> DeadOps;
1836 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1837 MachineOperand &MO = getOperand(i);
1838 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1839 continue;
1840
1841 // DEBUG_VALUE nodes do not contribute to code generation and should
1842 // always be ignored. Failure to do so may result in trying to modify
1843 // KILL flags on DEBUG_VALUE nodes.
1844 if (MO.isDebug())
1845 continue;
1846
1847 Register Reg = MO.getReg();
1848 if (!Reg)
1849 continue;
1850
1851 if (Reg == IncomingReg) {
1852 if (!Found) {
1853 if (MO.isKill())
1854 // The register is already marked kill.
1855 return true;
1856 if (isPhysReg && isRegTiedToDefOperand(i))
1857 // Two-address uses of physregs must not be marked kill.
1858 return true;
1859 MO.setIsKill();
1860 Found = true;
1861 }
1862 } else if (hasAliases && MO.isKill() && Register::isPhysicalRegister(Reg)) {
1863 // A super-register kill already exists.
1864 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1865 return true;
1866 if (RegInfo->isSubRegister(IncomingReg, Reg))
1867 DeadOps.push_back(i);
1868 }
1869 }
1870
1871 // Trim unneeded kill operands.
1872 while (!DeadOps.empty()) {
1873 unsigned OpIdx = DeadOps.back();
1874 if (getOperand(OpIdx).isImplicit() &&
1875 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
1876 RemoveOperand(OpIdx);
1877 else
1878 getOperand(OpIdx).setIsKill(false);
1879 DeadOps.pop_back();
1880 }
1881
1882 // If not found, this means an alias of one of the operands is killed. Add a
1883 // new implicit operand if required.
1884 if (!Found && AddIfNotFound) {
1885 addOperand(MachineOperand::CreateReg(IncomingReg,
1886 false /*IsDef*/,
1887 true /*IsImp*/,
1888 true /*IsKill*/));
1889 return true;
1890 }
1891 return Found;
1892}
1893
1894void MachineInstr::clearRegisterKills(Register Reg,
1895 const TargetRegisterInfo *RegInfo) {
1896 if (!Register::isPhysicalRegister(Reg))
1897 RegInfo = nullptr;
1898 for (MachineOperand &MO : operands()) {
1899 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1900 continue;
1901 Register OpReg = MO.getReg();
1902 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
1903 MO.setIsKill(false);
1904 }
1905}
1906
1907bool MachineInstr::addRegisterDead(Register Reg,
1908 const TargetRegisterInfo *RegInfo,
1909 bool AddIfNotFound) {
1910 bool isPhysReg = Register::isPhysicalRegister(Reg);
1911 bool hasAliases = isPhysReg &&
1912 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1913 bool Found = false;
1914 SmallVector<unsigned,4> DeadOps;
1915 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1916 MachineOperand &MO = getOperand(i);
1917 if (!MO.isReg() || !MO.isDef())
1918 continue;
1919 Register MOReg = MO.getReg();
1920 if (!MOReg)
1921 continue;
1922
1923 if (MOReg == Reg) {
1924 MO.setIsDead();
1925 Found = true;
1926 } else if (hasAliases && MO.isDead() &&
1927 Register::isPhysicalRegister(MOReg)) {
1928 // There exists a super-register that's marked dead.
1929 if (RegInfo->isSuperRegister(Reg, MOReg))
1930 return true;
1931 if (RegInfo->isSubRegister(Reg, MOReg))
1932 DeadOps.push_back(i);
1933 }
1934 }
1935
1936 // Trim unneeded dead operands.
1937 while (!DeadOps.empty()) {
1938 unsigned OpIdx = DeadOps.back();
1939 if (getOperand(OpIdx).isImplicit() &&
1940 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
1941 RemoveOperand(OpIdx);
1942 else
1943 getOperand(OpIdx).setIsDead(false);
1944 DeadOps.pop_back();
1945 }
1946
1947 // If not found, this means an alias of one of the operands is dead. Add a
1948 // new implicit operand if required.
1949 if (Found || !AddIfNotFound)
1950 return Found;
1951
1952 addOperand(MachineOperand::CreateReg(Reg,
1953 true /*IsDef*/,
1954 true /*IsImp*/,
1955 false /*IsKill*/,
1956 true /*IsDead*/));
1957 return true;
1958}
1959
1960void MachineInstr::clearRegisterDeads(Register Reg) {
1961 for (MachineOperand &MO : operands()) {
1962 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
1963 continue;
1964 MO.setIsDead(false);
1965 }
1966}
1967
1968void MachineInstr::setRegisterDefReadUndef(Register Reg, bool IsUndef) {
1969 for (MachineOperand &MO : operands()) {
1970 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
1971 continue;
1972 MO.setIsUndef(IsUndef);
1973 }
1974}
1975
1976void MachineInstr::addRegisterDefined(Register Reg,
1977 const TargetRegisterInfo *RegInfo) {
1978 if (Register::isPhysicalRegister(Reg)) {
1979 MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo);
1980 if (MO)
1981 return;
1982 } else {
1983 for (const MachineOperand &MO : operands()) {
1984 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1985 MO.getSubReg() == 0)
1986 return;
1987 }
1988 }
1989 addOperand(MachineOperand::CreateReg(Reg,
1990 true /*IsDef*/,
1991 true /*IsImp*/));
1992}
1993
1994void MachineInstr::setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
1995 const TargetRegisterInfo &TRI) {
1996 bool HasRegMask = false;
1997 for (MachineOperand &MO : operands()) {
1998 if (MO.isRegMask()) {
1999 HasRegMask = true;
2000 continue;
2001 }
2002 if (!MO.isReg() || !MO.isDef()) continue;
2003 Register Reg = MO.getReg();
2004 if (!Reg.isPhysical())
2005 continue;
2006 // If there are no uses, including partial uses, the def is dead.
2007 if (llvm::none_of(UsedRegs,
2008 [&](MCRegister Use) { return TRI.regsOverlap(Use, Reg); }))
2009 MO.setIsDead();
2010 }
2011
2012 // This is a call with a register mask operand.
2013 // Mask clobbers are always dead, so add defs for the non-dead defines.
2014 if (HasRegMask)
2015 for (ArrayRef<Register>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2016 I != E; ++I)
2017 addRegisterDefined(*I, &TRI);
2018}
2019
2020unsigned
2021MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2022 // Build up a buffer of hash code components.
2023 SmallVector<size_t, 16> HashComponents;
2024 HashComponents.reserve(MI->getNumOperands() + 1);
2025 HashComponents.push_back(MI->getOpcode());
2026 for (const MachineOperand &MO : MI->operands()) {
2027 if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg()))
2028 continue; // Skip virtual register defs.
2029
2030 HashComponents.push_back(hash_value(MO));
2031 }
2032 return hash_combine_range(HashComponents.begin(), HashComponents.end());
2033}
2034
2035void MachineInstr::emitError(StringRef Msg) const {
2036 // Find the source location cookie.
2037 unsigned LocCookie = 0;
2038 const MDNode *LocMD = nullptr;
2039 for (unsigned i = getNumOperands(); i != 0; --i) {
2040 if (getOperand(i-1).isMetadata() &&
2041 (LocMD = getOperand(i-1).getMetadata()) &&
2042 LocMD->getNumOperands() != 0) {
2043 if (const ConstantInt *CI =
2044 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2045 LocCookie = CI->getZExtValue();
2046 break;
2047 }
2048 }
2049 }
2050
2051 if (const MachineBasicBlock *MBB = getParent())
2052 if (const MachineFunction *MF = MBB->getParent())
2053 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2054 report_fatal_error(Msg);
2055}
2056
2057MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2058 const MCInstrDesc &MCID, bool IsIndirect,
2059 Register Reg, const MDNode *Variable,
2060 const MDNode *Expr) {
2061 assert(isa<DILocalVariable>(Variable) && "not a variable")((isa<DILocalVariable>(Variable) && "not a variable"
) ? static_cast<void> (0) : __assert_fail ("isa<DILocalVariable>(Variable) && \"not a variable\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2061, __PRETTY_FUNCTION__))
;
2062 assert(cast<DIExpression>(Expr)->isValid() && "not an expression")((cast<DIExpression>(Expr)->isValid() && "not an expression"
) ? static_cast<void> (0) : __assert_fail ("cast<DIExpression>(Expr)->isValid() && \"not an expression\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2062, __PRETTY_FUNCTION__))
;
2063 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&((cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic
(DL) && "Expected inlined-at fields to agree") ? static_cast
<void> (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2064, __PRETTY_FUNCTION__))
2064 "Expected inlined-at fields to agree")((cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic
(DL) && "Expected inlined-at fields to agree") ? static_cast
<void> (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2064, __PRETTY_FUNCTION__))
;
2065 auto MIB = BuildMI(MF, DL, MCID).addReg(Reg, RegState::Debug);
2066 if (IsIndirect)
2067 MIB.addImm(0U);
2068 else
2069 MIB.addReg(0U, RegState::Debug);
2070 return MIB.addMetadata(Variable).addMetadata(Expr);
2071}
2072
2073MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2074 const MCInstrDesc &MCID, bool IsIndirect,
2075 MachineOperand &MO, const MDNode *Variable,
2076 const MDNode *Expr) {
2077 assert(isa<DILocalVariable>(Variable) && "not a variable")((isa<DILocalVariable>(Variable) && "not a variable"
) ? static_cast<void> (0) : __assert_fail ("isa<DILocalVariable>(Variable) && \"not a variable\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2077, __PRETTY_FUNCTION__))
;
2078 assert(cast<DIExpression>(Expr)->isValid() && "not an expression")((cast<DIExpression>(Expr)->isValid() && "not an expression"
) ? static_cast<void> (0) : __assert_fail ("cast<DIExpression>(Expr)->isValid() && \"not an expression\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2078, __PRETTY_FUNCTION__))
;
2079 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&((cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic
(DL) && "Expected inlined-at fields to agree") ? static_cast
<void> (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2080, __PRETTY_FUNCTION__))
2080 "Expected inlined-at fields to agree")((cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic
(DL) && "Expected inlined-at fields to agree") ? static_cast
<void> (0) : __assert_fail ("cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2080, __PRETTY_FUNCTION__))
;
2081 if (MO.isReg())
2082 return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr);
2083
2084 auto MIB = BuildMI(MF, DL, MCID).add(MO);
2085 if (IsIndirect)
2086 MIB.addImm(0U);
2087 else
2088 MIB.addReg(0U, RegState::Debug);
2089 return MIB.addMetadata(Variable).addMetadata(Expr);
2090 }
2091
2092MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2093 MachineBasicBlock::iterator I,
2094 const DebugLoc &DL, const MCInstrDesc &MCID,
2095 bool IsIndirect, Register Reg,
2096 const MDNode *Variable, const MDNode *Expr) {
2097 MachineFunction &MF = *BB.getParent();
2098 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
2099 BB.insert(I, MI);
2100 return MachineInstrBuilder(MF, MI);
2101}
2102
2103MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2104 MachineBasicBlock::iterator I,
2105 const DebugLoc &DL, const MCInstrDesc &MCID,
2106 bool IsIndirect, MachineOperand &MO,
2107 const MDNode *Variable, const MDNode *Expr) {
2108 MachineFunction &MF = *BB.getParent();
2109 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr);
2110 BB.insert(I, MI);
2111 return MachineInstrBuilder(MF, *MI);
2112}
2113
2114/// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
2115/// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
2116static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
2117 assert(MI.getOperand(0).isReg() && "can't spill non-register")((MI.getOperand(0).isReg() && "can't spill non-register"
) ? static_cast<void> (0) : __assert_fail ("MI.getOperand(0).isReg() && \"can't spill non-register\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2117, __PRETTY_FUNCTION__))
;
2118 assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&((MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc
()) && "Expected inlined-at fields to agree") ? static_cast
<void> (0) : __assert_fail ("MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2119, __PRETTY_FUNCTION__))
2119 "Expected inlined-at fields to agree")((MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc
()) && "Expected inlined-at fields to agree") ? static_cast
<void> (0) : __assert_fail ("MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2119, __PRETTY_FUNCTION__))
;
2120
2121 const DIExpression *Expr = MI.getDebugExpression();
2122 if (MI.isIndirectDebugValue()) {
2123 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset")((MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset"
) ? static_cast<void> (0) : __assert_fail ("MI.getOperand(1).getImm() == 0 && \"DBG_VALUE with nonzero offset\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/MachineInstr.cpp"
, 2123, __PRETTY_FUNCTION__))
;
2124 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
2125 }
2126 return Expr;
2127}
2128
2129MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2130 MachineBasicBlock::iterator I,
2131 const MachineInstr &Orig,
2132 int FrameIndex) {
2133 const DIExpression *Expr = computeExprForSpill(Orig);
2134 return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
2135 .addFrameIndex(FrameIndex)
2136 .addImm(0U)
2137 .addMetadata(Orig.getDebugVariable())
2138 .addMetadata(Expr);
2139}
2140
2141void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
2142 const DIExpression *Expr = computeExprForSpill(Orig);
2143 Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
2144 Orig.getOperand(1).ChangeToImmediate(0U);
2145 Orig.getOperand(3).setMetadata(Expr);
2146}
2147
2148void MachineInstr::collectDebugValues(
2149 SmallVectorImpl<MachineInstr *> &DbgValues) {
2150 MachineInstr &MI = *this;
2151 if (!MI.getOperand(0).isReg())
2152 return;
2153
2154 MachineBasicBlock::iterator DI = MI; ++DI;
2155 for (MachineBasicBlock::iterator DE = MI.getParent()->end();
2156 DI != DE; ++DI) {
2157 if (!DI->isDebugValue())
2158 return;
2159 if (DI->getOperand(0).isReg() &&
2160 DI->getOperand(0).getReg() == MI.getOperand(0).getReg())
2161 DbgValues.push_back(&*DI);
2162 }
2163}
2164
2165void MachineInstr::changeDebugValuesDefReg(Register Reg) {
2166 // Collect matching debug values.
2167 SmallVector<MachineInstr *, 2> DbgValues;
2168
2169 if (!getOperand(0).isReg())
2170 return;
2171
2172 unsigned DefReg = getOperand(0).getReg();
2173 auto *MRI = getRegInfo();
2174 for (auto &MO : MRI->use_operands(DefReg)) {
2175 auto *DI = MO.getParent();
2176 if (!DI->isDebugValue())
2177 continue;
2178 if (DI->getOperand(0).isReg() &&
2179 DI->getOperand(0).getReg() == DefReg){
2180 DbgValues.push_back(DI);
2181 }
2182 }
2183
2184 // Propagate Reg to debug value instructions.
2185 for (auto *DBI : DbgValues)
2186 DBI->getOperand(0).setReg(Reg);
2187}
2188
2189using MMOList = SmallVector<const MachineMemOperand *, 2>;
2190
2191static unsigned getSpillSlotSize(const MMOList &Accesses,
2192 const MachineFrameInfo &MFI) {
2193 unsigned Size = 0;
2194 for (auto A : Accesses)
2195 if (MFI.isSpillSlotObjectIndex(
2196 cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
2197 ->getFrameIndex()))
2198 Size += A->getSize();
2199 return Size;
2200}
2201
2202Optional<unsigned>
2203MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
2204 int FI;
2205 if (TII->isStoreToStackSlotPostFE(*this, FI)) {
2206 const MachineFrameInfo &MFI = getMF()->getFrameInfo();
2207 if (MFI.isSpillSlotObjectIndex(FI))
2208 return (*memoperands_begin())->getSize();
2209 }
2210 return None;
2211}
2212
2213Optional<unsigned>
2214MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
2215 MMOList Accesses;
2216 if (TII->hasStoreToStackSlot(*this, Accesses))
2217 return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
2218 return None;
2219}
2220
2221Optional<unsigned>
2222MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
2223 int FI;
2224 if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
2225 const MachineFrameInfo &MFI = getMF()->getFrameInfo();
2226 if (MFI.isSpillSlotObjectIndex(FI))
2227 return (*memoperands_begin())->getSize();
2228 }
2229 return None;
2230}
2231
2232Optional<unsigned>
2233MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
2234 MMOList Accesses;
2235 if (TII->hasLoadFromStackSlot(*this, Accesses))
2236 return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
2237 return None;
2238}