Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220821100726+abce7acebd4c/llvm/lib/CodeGen/MachineInstr.cpp
Warning:line 1814, column 7
Value stored to 'HaveSemi' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

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