Bug Summary

File:lib/CodeGen/MachineInstr.cpp
Warning:line 191, column 3
Null pointer passed as an argument to a 'nonnull' parameter

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MachineInstr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp

/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp

1//===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Methods common to all machine instructions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/MachineInstr.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/FoldingSet.h"
18#include "llvm/ADT/Hashing.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallBitVector.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/Loads.h"
26#include "llvm/Analysis/MemoryLocation.h"
27#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
28#include "llvm/CodeGen/MachineBasicBlock.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/MachineInstrBundle.h"
32#include "llvm/CodeGen/MachineMemOperand.h"
33#include "llvm/CodeGen/MachineModuleInfo.h"
34#include "llvm/CodeGen/MachineOperand.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/PseudoSourceValue.h"
37#include "llvm/CodeGen/TargetInstrInfo.h"
38#include "llvm/CodeGen/TargetRegisterInfo.h"
39#include "llvm/CodeGen/TargetSubtargetInfo.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DebugInfoMetadata.h"
42#include "llvm/IR/DebugLoc.h"
43#include "llvm/IR/DerivedTypes.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/InlineAsm.h"
46#include "llvm/IR/InstrTypes.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/Metadata.h"
50#include "llvm/IR/Module.h"
51#include "llvm/IR/ModuleSlotTracker.h"
52#include "llvm/IR/Type.h"
53#include "llvm/IR/Value.h"
54#include "llvm/MC/MCInstrDesc.h"
55#include "llvm/MC/MCRegisterInfo.h"
56#include "llvm/MC/MCSymbol.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/CommandLine.h"
59#include "llvm/Support/Compiler.h"
60#include "llvm/Support/Debug.h"
61#include "llvm/Support/ErrorHandling.h"
62#include "llvm/Support/LowLevelTypeImpl.h"
63#include "llvm/Support/MathExtras.h"
64#include "llvm/Support/raw_ostream.h"
65#include "llvm/Target/TargetIntrinsicInfo.h"
66#include "llvm/Target/TargetMachine.h"
67#include <algorithm>
68#include <cassert>
69#include <cstddef>
70#include <cstdint>
71#include <cstring>
72#include <iterator>
73#include <utility>
74
75using namespace llvm;
76
77static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
78 if (const MachineBasicBlock *MBB = MI.getParent())
79 if (const MachineFunction *MF = MBB->getParent())
80 return MF;
81 return nullptr;
82}
83
84// Try to crawl up to the machine function and get TRI and IntrinsicInfo from
85// it.
86static void tryToGetTargetInfo(const MachineInstr &MI,
87 const TargetRegisterInfo *&TRI,
88 const MachineRegisterInfo *&MRI,
89 const TargetIntrinsicInfo *&IntrinsicInfo,
90 const TargetInstrInfo *&TII) {
91
92 if (const MachineFunction *MF = getMFIfAvailable(MI)) {
93 TRI = MF->getSubtarget().getRegisterInfo();
94 MRI = &MF->getRegInfo();
95 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
96 TII = MF->getSubtarget().getInstrInfo();
97 }
98}
99
100void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
101 if (MCID->ImplicitDefs)
102 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
103 ++ImpDefs)
104 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
105 if (MCID->ImplicitUses)
106 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
107 ++ImpUses)
108 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
109}
110
111/// MachineInstr ctor - This constructor creates a MachineInstr and adds the
112/// implicit operands. It reserves space for the number of operands specified by
113/// the MCInstrDesc.
114MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
115 DebugLoc dl, bool NoImp)
116 : MCID(&tid), debugLoc(std::move(dl)) {
117 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")(static_cast <bool> (debugLoc.hasTrivialDestructor() &&
"Expected trivial destructor") ? void (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 117, __extension__ __PRETTY_FUNCTION__))
;
118
119 // Reserve space for the expected number of operands.
120 if (unsigned NumOps = MCID->getNumOperands() +
121 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
122 CapOperands = OperandCapacity::get(NumOps);
123 Operands = MF.allocateOperandArray(CapOperands);
124 }
125
126 if (!NoImp)
127 addImplicitDefUseOperands(MF);
128}
129
130/// MachineInstr ctor - Copies MachineInstr arg exactly
131///
132MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
133 : MCID(&MI.getDesc()), NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
134 debugLoc(MI.getDebugLoc()) {
135 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")(static_cast <bool> (debugLoc.hasTrivialDestructor() &&
"Expected trivial destructor") ? void (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 135, __extension__ __PRETTY_FUNCTION__))
;
136
137 CapOperands = OperandCapacity::get(MI.getNumOperands());
138 Operands = MF.allocateOperandArray(CapOperands);
139
140 // Copy operands.
141 for (const MachineOperand &MO : MI.operands())
142 addOperand(MF, MO);
143
144 // Copy all the sensible flags.
145 setFlags(MI.Flags);
146}
147
148/// getRegInfo - If this instruction is embedded into a MachineFunction,
149/// return the MachineRegisterInfo object for the current function, otherwise
150/// return null.
151MachineRegisterInfo *MachineInstr::getRegInfo() {
152 if (MachineBasicBlock *MBB = getParent())
153 return &MBB->getParent()->getRegInfo();
154 return nullptr;
155}
156
157/// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
158/// this instruction from their respective use lists. This requires that the
159/// operands already be on their use lists.
160void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
161 for (MachineOperand &MO : operands())
162 if (MO.isReg())
163 MRI.removeRegOperandFromUseList(&MO);
164}
165
166/// AddRegOperandsToUseLists - Add all of the register operands in
167/// this instruction from their respective use lists. This requires that the
168/// operands not be on their use lists yet.
169void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
170 for (MachineOperand &MO : operands())
171 if (MO.isReg())
172 MRI.addRegOperandToUseList(&MO);
173}
174
175void MachineInstr::addOperand(const MachineOperand &Op) {
176 MachineBasicBlock *MBB = getParent();
177 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 177, __extension__ __PRETTY_FUNCTION__))
;
178 MachineFunction *MF = MBB->getParent();
179 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 179, __extension__ __PRETTY_FUNCTION__))
;
180 addOperand(*MF, Op);
181}
182
183/// Move NumOps MachineOperands from Src to Dst, with support for overlapping
184/// ranges. If MRI is non-null also update use-def chains.
185static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
186 unsigned NumOps, MachineRegisterInfo *MRI) {
187 if (MRI)
12
Taking false branch
188 return MRI->moveOperands(Dst, Src, NumOps);
189
190 // MachineOperand is a trivially copyable type so we can just use memmove.
191 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
13
Null pointer passed as an argument to a 'nonnull' parameter
192}
193
194/// addOperand - Add the specified operand to the instruction. If it is an
195/// implicit operand, it is added to the end of the operand list. If it is
196/// an explicit operand it is added at the end of the explicit operand list
197/// (before the first implicit operand).
198void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
199 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 199, __extension__ __PRETTY_FUNCTION__))
;
200
201 // Check if we're adding one of our existing operands.
202 if (&Op >= Operands && &Op < Operands + NumOperands) {
203 // This is unusual: MI->addOperand(MI->getOperand(i)).
204 // If adding Op requires reallocating or moving existing operands around,
205 // the Op reference could go stale. Support it by copying Op.
206 MachineOperand CopyOp(Op);
207 return addOperand(MF, CopyOp);
208 }
209
210 // Find the insert location for the new operand. Implicit registers go at
211 // the end, everything else goes before the implicit regs.
212 //
213 // FIXME: Allow mixed explicit and implicit operands on inline asm.
214 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
215 // implicit-defs, but they must not be moved around. See the FIXME in
216 // InstrEmitter.cpp.
217 unsigned OpNo = getNumOperands();
218 bool isImpReg = Op.isReg() && Op.isImplicit();
219 if (!isImpReg && !isInlineAsm()) {
3
Taking false branch
220 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
221 --OpNo;
222 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 222, __extension__ __PRETTY_FUNCTION__))
;
223 }
224 }
225
226#ifndef NDEBUG
227 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
228 // OpNo now points as the desired insertion point. Unless this is a variadic
229 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
230 // RegMask operands go between the explicit and implicit operands.
231 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||(static_cast <bool> ((isImpReg || Op.isRegMask() || MCID
->isVariadic() || OpNo < MCID->getNumOperands() || isMetaDataOp
) && "Trying to add an operand to a machine instr that is already done!"
) ? void (0) : __assert_fail ("(isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo < MCID->getNumOperands() || isMetaDataOp) && \"Trying to add an operand to a machine instr that is already done!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 233, __extension__ __PRETTY_FUNCTION__))
232 OpNo < MCID->getNumOperands() || isMetaDataOp) &&(static_cast <bool> ((isImpReg || Op.isRegMask() || MCID
->isVariadic() || OpNo < MCID->getNumOperands() || isMetaDataOp
) && "Trying to add an operand to a machine instr that is already done!"
) ? void (0) : __assert_fail ("(isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo < MCID->getNumOperands() || isMetaDataOp) && \"Trying to add an operand to a machine instr that is already done!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 233, __extension__ __PRETTY_FUNCTION__))
233 "Trying to add an operand to a machine instr that is already done!")(static_cast <bool> ((isImpReg || Op.isRegMask() || MCID
->isVariadic() || OpNo < MCID->getNumOperands() || isMetaDataOp
) && "Trying to add an operand to a machine instr that is already done!"
) ? void (0) : __assert_fail ("(isImpReg || Op.isRegMask() || MCID->isVariadic() || OpNo < MCID->getNumOperands() || isMetaDataOp) && \"Trying to add an operand to a machine instr that is already done!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 233, __extension__ __PRETTY_FUNCTION__))
;
234#endif
235
236 MachineRegisterInfo *MRI = getRegInfo();
237
238 // Determine if the Operands array needs to be reallocated.
239 // Save the old capacity and operand array.
240 OperandCapacity OldCap = CapOperands;
241 MachineOperand *OldOperands = Operands;
4
'OldOperands' initialized here
242 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
5
Assuming pointer value is null
6
Assuming 'OldOperands' is null
243 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
7
'?' condition is false
244 Operands = MF.allocateOperandArray(CapOperands);
245 // Move the operands before the insertion point.
246 if (OpNo)
8
Assuming 'OpNo' is not equal to 0
9
Taking true branch
247 moveOperands(Operands, OldOperands, OpNo, MRI);
10
Passing null pointer value via 2nd parameter 'Src'
11
Calling 'moveOperands'
248 }
249
250 // Move the operands following the insertion point.
251 if (OpNo != NumOperands)
252 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
253 MRI);
254 ++NumOperands;
255
256 // Deallocate the old operand array.
257 if (OldOperands != Operands && OldOperands)
258 MF.deallocateOperandArray(OldCap, OldOperands);
259
260 // Copy Op into place. It still needs to be inserted into the MRI use lists.
261 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
262 NewMO->ParentMI = this;
263
264 // When adding a register operand, tell MRI about it.
265 if (NewMO->isReg()) {
266 // Ensure isOnRegUseList() returns false, regardless of Op's status.
267 NewMO->Contents.Reg.Prev = nullptr;
268 // Ignore existing ties. This is not a property that can be copied.
269 NewMO->TiedTo = 0;
270 // Add the new operand to MRI, but only for instructions in an MBB.
271 if (MRI)
272 MRI->addRegOperandToUseList(NewMO);
273 // The MCID operand information isn't accurate until we start adding
274 // explicit operands. The implicit operands are added first, then the
275 // explicits are inserted before them.
276 if (!isImpReg) {
277 // Tie uses to defs as indicated in MCInstrDesc.
278 if (NewMO->isUse()) {
279 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
280 if (DefIdx != -1)
281 tieOperands(DefIdx, OpNo);
282 }
283 // If the register operand is flagged as early, mark the operand as such.
284 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
285 NewMO->setIsEarlyClobber(true);
286 }
287 }
288}
289
290/// RemoveOperand - Erase an operand from an instruction, leaving it with one
291/// fewer operand than it started with.
292///
293void MachineInstr::RemoveOperand(unsigned OpNo) {
294 assert(OpNo < getNumOperands() && "Invalid operand number")(static_cast <bool> (OpNo < getNumOperands() &&
"Invalid operand number") ? void (0) : __assert_fail ("OpNo < getNumOperands() && \"Invalid operand number\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 294, __extension__ __PRETTY_FUNCTION__))
;
295 untieRegOperand(OpNo);
296
297#ifndef NDEBUG
298 // Moving tied operands would break the ties.
299 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
300 if (Operands[i].isReg())
301 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 301, __extension__ __PRETTY_FUNCTION__))
;
302#endif
303
304 MachineRegisterInfo *MRI = getRegInfo();
305 if (MRI && Operands[OpNo].isReg())
306 MRI->removeRegOperandFromUseList(Operands + OpNo);
307
308 // Don't call the MachineOperand destructor. A lot of this code depends on
309 // MachineOperand having a trivial destructor anyway, and adding a call here
310 // wouldn't make it 'destructor-correct'.
311
312 if (unsigned N = NumOperands - 1 - OpNo)
313 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
314 --NumOperands;
315}
316
317/// addMemOperand - Add a MachineMemOperand to the machine instruction.
318/// This function should be used only occasionally. The setMemRefs function
319/// is the primary method for setting up a MachineInstr's MemRefs list.
320void MachineInstr::addMemOperand(MachineFunction &MF,
321 MachineMemOperand *MO) {
322 mmo_iterator OldMemRefs = MemRefs;
323 unsigned OldNumMemRefs = NumMemRefs;
324
325 unsigned NewNum = NumMemRefs + 1;
326 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
327
328 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
329 NewMemRefs[NewNum - 1] = MO;
330 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
331}
332
333/// Check to see if the MMOs pointed to by the two MemRefs arrays are
334/// identical.
335static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
336 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
337 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
338 if ((E1 - I1) != (E2 - I2))
339 return false;
340 for (; I1 != E1; ++I1, ++I2) {
341 if (**I1 != **I2)
342 return false;
343 }
344 return true;
345}
346
347std::pair<MachineInstr::mmo_iterator, unsigned>
348MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
349
350 // If either of the incoming memrefs are empty, we must be conservative and
351 // treat this as if we've exhausted our space for memrefs and dropped them.
352 if (memoperands_empty() || Other.memoperands_empty())
353 return std::make_pair(nullptr, 0);
354
355 // If both instructions have identical memrefs, we don't need to merge them.
356 // Since many instructions have a single memref, and we tend to merge things
357 // like pairs of loads from the same location, this catches a large number of
358 // cases in practice.
359 if (hasIdenticalMMOs(*this, Other))
360 return std::make_pair(MemRefs, NumMemRefs);
361
362 // TODO: consider uniquing elements within the operand lists to reduce
363 // space usage and fall back to conservative information less often.
364 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
365
366 // If we don't have enough room to store this many memrefs, be conservative
367 // and drop them. Otherwise, we'd fail asserts when trying to add them to
368 // the new instruction.
369 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
370 return std::make_pair(nullptr, 0);
371
372 MachineFunction *MF = getMF();
373 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
374 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
375 MemBegin);
376 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
377 MemEnd);
378 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&(static_cast <bool> (MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs
&& "missing memrefs") ? void (0) : __assert_fail ("MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs && \"missing memrefs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 379, __extension__ __PRETTY_FUNCTION__))
379 "missing memrefs")(static_cast <bool> (MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs
&& "missing memrefs") ? void (0) : __assert_fail ("MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs && \"missing memrefs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 379, __extension__ __PRETTY_FUNCTION__))
;
380
381 return std::make_pair(MemBegin, CombinedNumMemRefs);
382}
383
384uint8_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
385 // For now, the just return the union of the flags. If the flags get more
386 // complicated over time, we might need more logic here.
387 return getFlags() | Other.getFlags();
388}
389
390bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
391 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 391, __extension__ __PRETTY_FUNCTION__))
;
392 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
393 if (MII->getDesc().getFlags() & Mask) {
394 if (Type == AnyInBundle)
395 return true;
396 } else {
397 if (Type == AllInBundle && !MII->isBundle())
398 return false;
399 }
400 // This was the last instruction in the bundle.
401 if (!MII->isBundledWithSucc())
402 return Type == AllInBundle;
403 }
404}
405
406bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
407 MICheckType Check) const {
408 // If opcodes or number of operands are not the same then the two
409 // instructions are obviously not identical.
410 if (Other.getOpcode() != getOpcode() ||
411 Other.getNumOperands() != getNumOperands())
412 return false;
413
414 if (isBundle()) {
415 // We have passed the test above that both instructions have the same
416 // opcode, so we know that both instructions are bundles here. Let's compare
417 // MIs inside the bundle.
418 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.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 418, __extension__ __PRETTY_FUNCTION__))
;
419 MachineBasicBlock::const_instr_iterator I1 = getIterator();
420 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
421 // Loop until we analysed the last intruction inside at least one of the
422 // bundles.
423 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
424 ++I1;
425 ++I2;
426 if (!I1->isIdenticalTo(*I2, Check))
427 return false;
428 }
429 // If we've reached the end of just one of the two bundles, but not both,
430 // the instructions are not identical.
431 if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
432 return false;
433 }
434
435 // Check operands to make sure they match.
436 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
437 const MachineOperand &MO = getOperand(i);
438 const MachineOperand &OMO = Other.getOperand(i);
439 if (!MO.isReg()) {
440 if (!MO.isIdenticalTo(OMO))
441 return false;
442 continue;
443 }
444
445 // Clients may or may not want to ignore defs when testing for equality.
446 // For example, machine CSE pass only cares about finding common
447 // subexpressions, so it's safe to ignore virtual register defs.
448 if (MO.isDef()) {
449 if (Check == IgnoreDefs)
450 continue;
451 else if (Check == IgnoreVRegDefs) {
452 if (!TargetRegisterInfo::isVirtualRegister(MO.getReg()) ||
453 !TargetRegisterInfo::isVirtualRegister(OMO.getReg()))
454 if (!MO.isIdenticalTo(OMO))
455 return false;
456 } else {
457 if (!MO.isIdenticalTo(OMO))
458 return false;
459 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
460 return false;
461 }
462 } else {
463 if (!MO.isIdenticalTo(OMO))
464 return false;
465 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
466 return false;
467 }
468 }
469 // If DebugLoc does not match then two dbg.values are not identical.
470 if (isDebugValue())
471 if (getDebugLoc() && Other.getDebugLoc() &&
472 getDebugLoc() != Other.getDebugLoc())
473 return false;
474 return true;
475}
476
477const MachineFunction *MachineInstr::getMF() const {
478 return getParent()->getParent();
479}
480
481MachineInstr *MachineInstr::removeFromParent() {
482 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 482, __extension__ __PRETTY_FUNCTION__))
;
483 return getParent()->remove(this);
484}
485
486MachineInstr *MachineInstr::removeFromBundle() {
487 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 487, __extension__ __PRETTY_FUNCTION__))
;
488 return getParent()->remove_instr(this);
489}
490
491void MachineInstr::eraseFromParent() {
492 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 492, __extension__ __PRETTY_FUNCTION__))
;
493 getParent()->erase(this);
494}
495
496void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
497 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 497, __extension__ __PRETTY_FUNCTION__))
;
498 MachineBasicBlock *MBB = getParent();
499 MachineFunction *MF = MBB->getParent();
500 assert(MF && "Not embedded in a function!")(static_cast <bool> (MF && "Not embedded in a function!"
) ? void (0) : __assert_fail ("MF && \"Not embedded in a function!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 500, __extension__ __PRETTY_FUNCTION__))
;
501
502 MachineInstr *MI = (MachineInstr *)this;
503 MachineRegisterInfo &MRI = MF->getRegInfo();
504
505 for (const MachineOperand &MO : MI->operands()) {
506 if (!MO.isReg() || !MO.isDef())
507 continue;
508 unsigned Reg = MO.getReg();
509 if (!TargetRegisterInfo::isVirtualRegister(Reg))
510 continue;
511 MRI.markUsesInDebugValueAsUndef(Reg);
512 }
513 MI->eraseFromParent();
514}
515
516void MachineInstr::eraseFromBundle() {
517 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 517, __extension__ __PRETTY_FUNCTION__))
;
518 getParent()->erase_instr(this);
519}
520
521/// getNumExplicitOperands - Returns the number of non-implicit operands.
522///
523unsigned MachineInstr::getNumExplicitOperands() const {
524 unsigned NumOperands = MCID->getNumOperands();
525 if (!MCID->isVariadic())
526 return NumOperands;
527
528 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
529 const MachineOperand &MO = getOperand(i);
530 if (!MO.isReg() || !MO.isImplicit())
531 NumOperands++;
532 }
533 return NumOperands;
534}
535
536void MachineInstr::bundleWithPred() {
537 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 537, __extension__ __PRETTY_FUNCTION__))
;
538 setFlag(BundledPred);
539 MachineBasicBlock::instr_iterator Pred = getIterator();
540 --Pred;
541 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags")(static_cast <bool> (!Pred->isBundledWithSucc() &&
"Inconsistent bundle flags") ? void (0) : __assert_fail ("!Pred->isBundledWithSucc() && \"Inconsistent bundle flags\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 541, __extension__ __PRETTY_FUNCTION__))
;
542 Pred->setFlag(BundledSucc);
543}
544
545void MachineInstr::bundleWithSucc() {
546 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 546, __extension__ __PRETTY_FUNCTION__))
;
547 setFlag(BundledSucc);
548 MachineBasicBlock::instr_iterator Succ = getIterator();
549 ++Succ;
550 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags")(static_cast <bool> (!Succ->isBundledWithPred() &&
"Inconsistent bundle flags") ? void (0) : __assert_fail ("!Succ->isBundledWithPred() && \"Inconsistent bundle flags\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 550, __extension__ __PRETTY_FUNCTION__))
;
551 Succ->setFlag(BundledPred);
552}
553
554void MachineInstr::unbundleFromPred() {
555 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 555, __extension__ __PRETTY_FUNCTION__))
;
556 clearFlag(BundledPred);
557 MachineBasicBlock::instr_iterator Pred = getIterator();
558 --Pred;
559 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags")(static_cast <bool> (Pred->isBundledWithSucc() &&
"Inconsistent bundle flags") ? void (0) : __assert_fail ("Pred->isBundledWithSucc() && \"Inconsistent bundle flags\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 559, __extension__ __PRETTY_FUNCTION__))
;
560 Pred->clearFlag(BundledSucc);
561}
562
563void MachineInstr::unbundleFromSucc() {
564 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 564, __extension__ __PRETTY_FUNCTION__))
;
565 clearFlag(BundledSucc);
566 MachineBasicBlock::instr_iterator Succ = getIterator();
567 ++Succ;
568 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags")(static_cast <bool> (Succ->isBundledWithPred() &&
"Inconsistent bundle flags") ? void (0) : __assert_fail ("Succ->isBundledWithPred() && \"Inconsistent bundle flags\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 568, __extension__ __PRETTY_FUNCTION__))
;
569 Succ->clearFlag(BundledPred);
570}
571
572bool MachineInstr::isStackAligningInlineAsm() const {
573 if (isInlineAsm()) {
574 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
575 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
576 return true;
577 }
578 return false;
579}
580
581InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
582 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 582, __extension__ __PRETTY_FUNCTION__))
;
583 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
584 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
585}
586
587int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
588 unsigned *GroupNo) const {
589 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 589, __extension__ __PRETTY_FUNCTION__))
;
590 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 590, __extension__ __PRETTY_FUNCTION__))
;
591
592 // Ignore queries about the initial operands.
593 if (OpIdx < InlineAsm::MIOp_FirstOperand)
594 return -1;
595
596 unsigned Group = 0;
597 unsigned NumOps;
598 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
599 i += NumOps) {
600 const MachineOperand &FlagMO = getOperand(i);
601 // If we reach the implicit register operands, stop looking.
602 if (!FlagMO.isImm())
603 return -1;
604 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
605 if (i + NumOps > OpIdx) {
606 if (GroupNo)
607 *GroupNo = Group;
608 return i;
609 }
610 ++Group;
611 }
612 return -1;
613}
614
615const DILocalVariable *MachineInstr::getDebugVariable() const {
616 assert(isDebugValue() && "not a DBG_VALUE")(static_cast <bool> (isDebugValue() && "not a DBG_VALUE"
) ? void (0) : __assert_fail ("isDebugValue() && \"not a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 616, __extension__ __PRETTY_FUNCTION__))
;
617 return cast<DILocalVariable>(getOperand(2).getMetadata());
618}
619
620const DIExpression *MachineInstr::getDebugExpression() const {
621 assert(isDebugValue() && "not a DBG_VALUE")(static_cast <bool> (isDebugValue() && "not a DBG_VALUE"
) ? void (0) : __assert_fail ("isDebugValue() && \"not a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 621, __extension__ __PRETTY_FUNCTION__))
;
622 return cast<DIExpression>(getOperand(3).getMetadata());
623}
624
625const TargetRegisterClass*
626MachineInstr::getRegClassConstraint(unsigned OpIdx,
627 const TargetInstrInfo *TII,
628 const TargetRegisterInfo *TRI) const {
629 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 629, __extension__ __PRETTY_FUNCTION__))
;
630 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!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 630, __extension__ __PRETTY_FUNCTION__))
;
631 const MachineFunction &MF = *getMF();
632
633 // Most opcodes have fixed constraints in their MCInstrDesc.
634 if (!isInlineAsm())
635 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
636
637 if (!getOperand(OpIdx).isReg())
638 return nullptr;
639
640 // For tied uses on inline asm, get the constraint from the def.
641 unsigned DefIdx;
642 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
643 OpIdx = DefIdx;
644
645 // Inline asm stores register class constraints in the flag word.
646 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
647 if (FlagIdx < 0)
648 return nullptr;
649
650 unsigned Flag = getOperand(FlagIdx).getImm();
651 unsigned RCID;
652 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
653 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
654 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
655 InlineAsm::hasRegClassConstraint(Flag, RCID))
656 return TRI->getRegClass(RCID);
657
658 // Assume that all registers in a memory operand are pointers.
659 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
660 return TRI->getPointerRegClass(MF);
661
662 return nullptr;
663}
664
665const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
666 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
667 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
668 // Check every operands inside the bundle if we have
669 // been asked to.
670 if (ExploreBundle)
671 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
672 ++OpndIt)
673 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
674 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
675 else
676 // Otherwise, just check the current operands.
677 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
678 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
679 return CurRC;
680}
681
682const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
683 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
684 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
685 assert(CurRC && "Invalid initial register class")(static_cast <bool> (CurRC && "Invalid initial register class"
) ? void (0) : __assert_fail ("CurRC && \"Invalid initial register class\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 685, __extension__ __PRETTY_FUNCTION__))
;
686 // Check if Reg is constrained by some of its use/def from MI.
687 const MachineOperand &MO = getOperand(OpIdx);
688 if (!MO.isReg() || MO.getReg() != Reg)
689 return CurRC;
690 // If yes, accumulate the constraints through the operand.
691 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
692}
693
694const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
695 unsigned OpIdx, const TargetRegisterClass *CurRC,
696 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
697 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
698 const MachineOperand &MO = getOperand(OpIdx);
699 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 700, __extension__ __PRETTY_FUNCTION__))
700 "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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 700, __extension__ __PRETTY_FUNCTION__))
;
701 assert(CurRC && "Invalid initial register class")(static_cast <bool> (CurRC && "Invalid initial register class"
) ? void (0) : __assert_fail ("CurRC && \"Invalid initial register class\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 701, __extension__ __PRETTY_FUNCTION__))
;
702 if (unsigned SubIdx = MO.getSubReg()) {
703 if (OpRC)
704 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
705 else
706 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
707 } else if (OpRC)
708 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
709 return CurRC;
710}
711
712/// Return the number of instructions inside the MI bundle, not counting the
713/// header instruction.
714unsigned MachineInstr::getBundleSize() const {
715 MachineBasicBlock::const_instr_iterator I = getIterator();
716 unsigned Size = 0;
717 while (I->isBundledWithSucc()) {
718 ++Size;
719 ++I;
720 }
721 return Size;
722}
723
724/// Returns true if the MachineInstr has an implicit-use operand of exactly
725/// the given register (not considering sub/super-registers).
726bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
727 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
728 const MachineOperand &MO = getOperand(i);
729 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
730 return true;
731 }
732 return false;
733}
734
735/// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
736/// the specific register or -1 if it is not found. It further tightens
737/// the search criteria to a use that kills the register if isKill is true.
738int MachineInstr::findRegisterUseOperandIdx(
739 unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
740 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
741 const MachineOperand &MO = getOperand(i);
742 if (!MO.isReg() || !MO.isUse())
743 continue;
744 unsigned MOReg = MO.getReg();
745 if (!MOReg)
746 continue;
747 if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
748 TargetRegisterInfo::isPhysicalRegister(Reg) &&
749 TRI->isSubRegister(MOReg, Reg)))
750 if (!isKill || MO.isKill())
751 return i;
752 }
753 return -1;
754}
755
756/// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
757/// indicating if this instruction reads or writes Reg. This also considers
758/// partial defines.
759std::pair<bool,bool>
760MachineInstr::readsWritesVirtualRegister(unsigned Reg,
761 SmallVectorImpl<unsigned> *Ops) const {
762 bool PartDef = false; // Partial redefine.
763 bool FullDef = false; // Full define.
764 bool Use = false;
765
766 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
767 const MachineOperand &MO = getOperand(i);
768 if (!MO.isReg() || MO.getReg() != Reg)
769 continue;
770 if (Ops)
771 Ops->push_back(i);
772 if (MO.isUse())
773 Use |= !MO.isUndef();
774 else if (MO.getSubReg() && !MO.isUndef())
775 // A partial def undef doesn't count as reading the register.
776 PartDef = true;
777 else
778 FullDef = true;
779 }
780 // A partial redefine uses Reg unless there is also a full define.
781 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
782}
783
784/// findRegisterDefOperandIdx() - Returns the operand index that is a def of
785/// the specified register or -1 if it is not found. If isDead is true, defs
786/// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
787/// also checks if there is a def of a super-register.
788int
789MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
790 const TargetRegisterInfo *TRI) const {
791 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
792 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
793 const MachineOperand &MO = getOperand(i);
794 // Accept regmask operands when Overlap is set.
795 // Ignore them when looking for a specific def operand (Overlap == false).
796 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
797 return i;
798 if (!MO.isReg() || !MO.isDef())
799 continue;
800 unsigned MOReg = MO.getReg();
801 bool Found = (MOReg == Reg);
802 if (!Found && TRI && isPhys &&
803 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
804 if (Overlap)
805 Found = TRI->regsOverlap(MOReg, Reg);
806 else
807 Found = TRI->isSubRegister(MOReg, Reg);
808 }
809 if (Found && (!isDead || MO.isDead()))
810 return i;
811 }
812 return -1;
813}
814
815/// findFirstPredOperandIdx() - Find the index of the first operand in the
816/// operand list that is used to represent the predicate. It returns -1 if
817/// none is found.
818int MachineInstr::findFirstPredOperandIdx() const {
819 // Don't call MCID.findFirstPredOperandIdx() because this variant
820 // is sometimes called on an instruction that's not yet complete, and
821 // so the number of operands is less than the MCID indicates. In
822 // particular, the PTX target does this.
823 const MCInstrDesc &MCID = getDesc();
824 if (MCID.isPredicable()) {
825 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
826 if (MCID.OpInfo[i].isPredicate())
827 return i;
828 }
829
830 return -1;
831}
832
833// MachineOperand::TiedTo is 4 bits wide.
834const unsigned TiedMax = 15;
835
836/// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
837///
838/// Use and def operands can be tied together, indicated by a non-zero TiedTo
839/// field. TiedTo can have these values:
840///
841/// 0: Operand is not tied to anything.
842/// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
843/// TiedMax: Tied to an operand >= TiedMax-1.
844///
845/// The tied def must be one of the first TiedMax operands on a normal
846/// instruction. INLINEASM instructions allow more tied defs.
847///
848void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
849 MachineOperand &DefMO = getOperand(DefIdx);
850 MachineOperand &UseMO = getOperand(UseIdx);
851 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 851, __extension__ __PRETTY_FUNCTION__))
;
852 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 852, __extension__ __PRETTY_FUNCTION__))
;
853 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 853, __extension__ __PRETTY_FUNCTION__))
;
854 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 854, __extension__ __PRETTY_FUNCTION__))
;
855
856 if (DefIdx < TiedMax)
857 UseMO.TiedTo = DefIdx + 1;
858 else {
859 // Inline asm can use the group descriptors to find tied operands, but on
860 // normal instruction, the tied def must be within the first TiedMax
861 // operands.
862 assert(isInlineAsm() && "DefIdx out of range")(static_cast <bool> (isInlineAsm() && "DefIdx out of range"
) ? void (0) : __assert_fail ("isInlineAsm() && \"DefIdx out of range\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 862, __extension__ __PRETTY_FUNCTION__))
;
863 UseMO.TiedTo = TiedMax;
864 }
865
866 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
867 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
868}
869
870/// Given the index of a tied register operand, find the operand it is tied to.
871/// Defs are tied to uses and vice versa. Returns the index of the tied operand
872/// which must exist.
873unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
874 const MachineOperand &MO = getOperand(OpIdx);
875 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 875, __extension__ __PRETTY_FUNCTION__))
;
876
877 // Normally TiedTo is in range.
878 if (MO.TiedTo < TiedMax)
879 return MO.TiedTo - 1;
880
881 // Uses on normal instructions can be out of range.
882 if (!isInlineAsm()) {
883 // Normal tied defs must be in the 0..TiedMax-1 range.
884 if (MO.isUse())
885 return TiedMax - 1;
886 // MO is a def. Search for the tied use.
887 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
888 const MachineOperand &UseMO = getOperand(i);
889 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
890 return i;
891 }
892 llvm_unreachable("Can't find tied use")::llvm::llvm_unreachable_internal("Can't find tied use", "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 892)
;
893 }
894
895 // Now deal with inline asm by parsing the operand group descriptor flags.
896 // Find the beginning of each operand group.
897 SmallVector<unsigned, 8> GroupIdx;
898 unsigned OpIdxGroup = ~0u;
899 unsigned NumOps;
900 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
901 i += NumOps) {
902 const MachineOperand &FlagMO = getOperand(i);
903 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 903, __extension__ __PRETTY_FUNCTION__))
;
904 unsigned CurGroup = GroupIdx.size();
905 GroupIdx.push_back(i);
906 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
907 // OpIdx belongs to this operand group.
908 if (OpIdx > i && OpIdx < i + NumOps)
909 OpIdxGroup = CurGroup;
910 unsigned TiedGroup;
911 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
912 continue;
913 // Operands in this group are tied to operands in TiedGroup which must be
914 // earlier. Find the number of operands between the two groups.
915 unsigned Delta = i - GroupIdx[TiedGroup];
916
917 // OpIdx is a use tied to TiedGroup.
918 if (OpIdxGroup == CurGroup)
919 return OpIdx - Delta;
920
921 // OpIdx is a def tied to this use group.
922 if (OpIdxGroup == TiedGroup)
923 return OpIdx + Delta;
924 }
925 llvm_unreachable("Invalid tied operand on inline asm")::llvm::llvm_unreachable_internal("Invalid tied operand on inline asm"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 925)
;
926}
927
928/// clearKillInfo - Clears kill flags on all operands.
929///
930void MachineInstr::clearKillInfo() {
931 for (MachineOperand &MO : operands()) {
932 if (MO.isReg() && MO.isUse())
933 MO.setIsKill(false);
934 }
935}
936
937void MachineInstr::substituteRegister(unsigned FromReg, unsigned ToReg,
938 unsigned SubIdx,
939 const TargetRegisterInfo &RegInfo) {
940 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
941 if (SubIdx)
942 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
943 for (MachineOperand &MO : operands()) {
944 if (!MO.isReg() || MO.getReg() != FromReg)
945 continue;
946 MO.substPhysReg(ToReg, RegInfo);
947 }
948 } else {
949 for (MachineOperand &MO : operands()) {
950 if (!MO.isReg() || MO.getReg() != FromReg)
951 continue;
952 MO.substVirtReg(ToReg, SubIdx, RegInfo);
953 }
954 }
955}
956
957/// isSafeToMove - Return true if it is safe to move this instruction. If
958/// SawStore is set to true, it means that there is a store (or call) between
959/// the instruction's location and its intended destination.
960bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
961 // Ignore stuff that we obviously can't move.
962 //
963 // Treat volatile loads as stores. This is not strictly necessary for
964 // volatiles, but it is required for atomic loads. It is not allowed to move
965 // a load across an atomic load with Ordering > Monotonic.
966 if (mayStore() || isCall() || isPHI() ||
967 (mayLoad() && hasOrderedMemoryRef())) {
968 SawStore = true;
969 return false;
970 }
971
972 if (isPosition() || isDebugValue() || isTerminator() ||
973 hasUnmodeledSideEffects())
974 return false;
975
976 // See if this instruction does a load. If so, we have to guarantee that the
977 // loaded value doesn't change between the load and the its intended
978 // destination. The check for isInvariantLoad gives the targe the chance to
979 // classify the load as always returning a constant, e.g. a constant pool
980 // load.
981 if (mayLoad() && !isDereferenceableInvariantLoad(AA))
982 // Otherwise, this is a real load. If there is a store between the load and
983 // end of block, we can't move it.
984 return !SawStore;
985
986 return true;
987}
988
989bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
990 bool UseTBAA) {
991 const MachineFunction *MF = getMF();
992 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
993 const MachineFrameInfo &MFI = MF->getFrameInfo();
994
995 // If neither instruction stores to memory, they can't alias in any
996 // meaningful way, even if they read from the same address.
997 if (!mayStore() && !Other.mayStore())
998 return false;
999
1000 // Let the target decide if memory accesses cannot possibly overlap.
1001 if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
1002 return false;
1003
1004 // FIXME: Need to handle multiple memory operands to support all targets.
1005 if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1006 return true;
1007
1008 MachineMemOperand *MMOa = *memoperands_begin();
1009 MachineMemOperand *MMOb = *Other.memoperands_begin();
1010
1011 // The following interface to AA is fashioned after DAGCombiner::isAlias
1012 // and operates with MachineMemOperand offset with some important
1013 // assumptions:
1014 // - LLVM fundamentally assumes flat address spaces.
1015 // - MachineOperand offset can *only* result from legalization and
1016 // cannot affect queries other than the trivial case of overlap
1017 // checking.
1018 // - These offsets never wrap and never step outside
1019 // of allocated objects.
1020 // - There should never be any negative offsets here.
1021 //
1022 // FIXME: Modify API to hide this math from "user"
1023 // Even before we go to AA we can reason locally about some
1024 // memory objects. It can save compile time, and possibly catch some
1025 // corner cases not currently covered.
1026
1027 int64_t OffsetA = MMOa->getOffset();
1028 int64_t OffsetB = MMOb->getOffset();
1029
1030 int64_t MinOffset = std::min(OffsetA, OffsetB);
1031 int64_t WidthA = MMOa->getSize();
1032 int64_t WidthB = MMOb->getSize();
1033 const Value *ValA = MMOa->getValue();
1034 const Value *ValB = MMOb->getValue();
1035 bool SameVal = (ValA && ValB && (ValA == ValB));
1036 if (!SameVal) {
1037 const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
1038 const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
1039 if (PSVa && ValB && !PSVa->mayAlias(&MFI))
1040 return false;
1041 if (PSVb && ValA && !PSVb->mayAlias(&MFI))
1042 return false;
1043 if (PSVa && PSVb && (PSVa == PSVb))
1044 SameVal = true;
1045 }
1046
1047 if (SameVal) {
1048 int64_t MaxOffset = std::max(OffsetA, OffsetB);
1049 int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
1050 return (MinOffset + LowWidth > MaxOffset);
1051 }
1052
1053 if (!AA)
1054 return true;
1055
1056 if (!ValA || !ValB)
1057 return true;
1058
1059 assert((OffsetA >= 0) && "Negative MachineMemOperand offset")(static_cast <bool> ((OffsetA >= 0) && "Negative MachineMemOperand offset"
) ? void (0) : __assert_fail ("(OffsetA >= 0) && \"Negative MachineMemOperand offset\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1059, __extension__ __PRETTY_FUNCTION__))
;
1060 assert((OffsetB >= 0) && "Negative MachineMemOperand offset")(static_cast <bool> ((OffsetB >= 0) && "Negative MachineMemOperand offset"
) ? void (0) : __assert_fail ("(OffsetB >= 0) && \"Negative MachineMemOperand offset\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1060, __extension__ __PRETTY_FUNCTION__))
;
1061
1062 int64_t Overlapa = WidthA + OffsetA - MinOffset;
1063 int64_t Overlapb = WidthB + OffsetB - MinOffset;
1064
1065 AliasResult AAResult = AA->alias(
1066 MemoryLocation(ValA, Overlapa,
1067 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1068 MemoryLocation(ValB, Overlapb,
1069 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1070
1071 return (AAResult != NoAlias);
1072}
1073
1074/// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1075/// or volatile memory reference, or if the information describing the memory
1076/// reference is not available. Return false if it is known to have no ordered
1077/// memory references.
1078bool MachineInstr::hasOrderedMemoryRef() const {
1079 // An instruction known never to access memory won't have a volatile access.
1080 if (!mayStore() &&
1081 !mayLoad() &&
1082 !isCall() &&
1083 !hasUnmodeledSideEffects())
1084 return false;
1085
1086 // Otherwise, if the instruction has no memory reference information,
1087 // conservatively assume it wasn't preserved.
1088 if (memoperands_empty())
1089 return true;
1090
1091 // Check if any of our memory operands are ordered.
1092 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1093 return !MMO->isUnordered();
1094 });
1095}
1096
1097/// isDereferenceableInvariantLoad - Return true if this instruction will never
1098/// trap and is loading from a location whose value is invariant across a run of
1099/// this function.
1100bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
1101 // If the instruction doesn't load at all, it isn't an invariant load.
1102 if (!mayLoad())
1103 return false;
1104
1105 // If the instruction has lost its memoperands, conservatively assume that
1106 // it may not be an invariant load.
1107 if (memoperands_empty())
1108 return false;
1109
1110 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1111
1112 for (MachineMemOperand *MMO : memoperands()) {
1113 if (MMO->isVolatile()) return false;
1114 if (MMO->isStore()) return false;
1115 if (MMO->isInvariant() && MMO->isDereferenceable())
1116 continue;
1117
1118 // A load from a constant PseudoSourceValue is invariant.
1119 if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1120 if (PSV->isConstant(&MFI))
1121 continue;
1122
1123 if (const Value *V = MMO->getValue()) {
1124 // If we have an AliasAnalysis, ask it whether the memory is constant.
1125 if (AA &&
1126 AA->pointsToConstantMemory(
1127 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1128 continue;
1129 }
1130
1131 // Otherwise assume conservatively.
1132 return false;
1133 }
1134
1135 // Everything checks out.
1136 return true;
1137}
1138
1139/// isConstantValuePHI - If the specified instruction is a PHI that always
1140/// merges together the same virtual register, return the register, otherwise
1141/// return 0.
1142unsigned MachineInstr::isConstantValuePHI() const {
1143 if (!isPHI())
1144 return 0;
1145 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1146, __extension__ __PRETTY_FUNCTION__))
1146 "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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1146, __extension__ __PRETTY_FUNCTION__))
;
1147
1148 unsigned Reg = getOperand(1).getReg();
1149 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1150 if (getOperand(i).getReg() != Reg)
1151 return 0;
1152 return Reg;
1153}
1154
1155bool MachineInstr::hasUnmodeledSideEffects() const {
1156 if (hasProperty(MCID::UnmodeledSideEffects))
1157 return true;
1158 if (isInlineAsm()) {
1159 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1160 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1161 return true;
1162 }
1163
1164 return false;
1165}
1166
1167bool MachineInstr::isLoadFoldBarrier() const {
1168 return mayStore() || isCall() || hasUnmodeledSideEffects();
1169}
1170
1171/// allDefsAreDead - Return true if all the defs of this instruction are dead.
1172///
1173bool MachineInstr::allDefsAreDead() const {
1174 for (const MachineOperand &MO : operands()) {
1175 if (!MO.isReg() || MO.isUse())
1176 continue;
1177 if (!MO.isDead())
1178 return false;
1179 }
1180 return true;
1181}
1182
1183/// copyImplicitOps - Copy implicit register operands from specified
1184/// instruction to this instruction.
1185void MachineInstr::copyImplicitOps(MachineFunction &MF,
1186 const MachineInstr &MI) {
1187 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1188 i != e; ++i) {
1189 const MachineOperand &MO = MI.getOperand(i);
1190 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1191 addOperand(MF, MO);
1192 }
1193}
1194
1195bool MachineInstr::hasComplexRegisterTies() const {
1196 const MCInstrDesc &MCID = getDesc();
1197 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1198 const auto &Operand = getOperand(I);
1199 if (!Operand.isReg() || Operand.isDef())
1200 // Ignore the defined registers as MCID marks only the uses as tied.
1201 continue;
1202 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
1203 int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
1204 if (ExpectedTiedIdx != TiedIdx)
1205 return true;
1206 }
1207 return false;
1208}
1209
1210LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1211 const MachineRegisterInfo &MRI) const {
1212 const MachineOperand &Op = getOperand(OpIdx);
1213 if (!Op.isReg())
1214 return LLT{};
1215
1216 if (isVariadic() || OpIdx >= getNumExplicitOperands())
1217 return MRI.getType(Op.getReg());
1218
1219 auto &OpInfo = getDesc().OpInfo[OpIdx];
1220 if (!OpInfo.isGenericType())
1221 return MRI.getType(Op.getReg());
1222
1223 if (PrintedTypes[OpInfo.getGenericTypeIndex()])
1224 return LLT{};
1225
1226 PrintedTypes.set(OpInfo.getGenericTypeIndex());
1227 return MRI.getType(Op.getReg());
1228}
1229
1230#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1231LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MachineInstr::dump() const {
1232 dbgs() << " ";
1233 print(dbgs());
1234}
1235#endif
1236
1237void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
1238 bool SkipDebugLoc, const TargetInstrInfo *TII) const {
1239 const Module *M = nullptr;
1240 const Function *F = nullptr;
1241 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1242 F = &MF->getFunction();
1243 M = F->getParent();
1244 if (!TII)
1245 TII = MF->getSubtarget().getInstrInfo();
1246 }
1247
1248 ModuleSlotTracker MST(M);
1249 if (F)
1250 MST.incorporateFunction(*F);
1251 print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, TII);
1252}
1253
1254void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1255 bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
1256 const TargetInstrInfo *TII) const {
1257 // We can be a bit tidier if we know the MachineFunction.
1258 const MachineFunction *MF = nullptr;
1259 const TargetRegisterInfo *TRI = nullptr;
1260 const MachineRegisterInfo *MRI = nullptr;
1261 const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1262 tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
1263
1264 if (isCFIInstruction())
1265 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1265, __extension__ __PRETTY_FUNCTION__))
;
1266
1267 SmallBitVector PrintedTypes(8);
1268 bool ShouldPrintRegisterTies = hasComplexRegisterTies();
1269 auto getTiedOperandIdx = [&](unsigned OpIdx) {
1270 if (!ShouldPrintRegisterTies)
1271 return 0U;
1272 const MachineOperand &MO = getOperand(OpIdx);
1273 if (MO.isReg() && MO.isTied() && !MO.isDef())
1274 return findTiedOperandIdx(OpIdx);
1275 return 0U;
1276 };
1277 unsigned StartOp = 0;
1278 unsigned e = getNumOperands();
1279
1280 // Print explicitly defined operands on the left of an assignment syntax.
1281 while (StartOp < e) {
1282 const MachineOperand &MO = getOperand(StartOp);
1283 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
1284 break;
1285
1286 if (StartOp != 0)
1287 OS << ", ";
1288
1289 LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
1290 unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
1291 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/false, IsStandalone,
1292 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1293 ++StartOp;
1294 }
1295
1296 if (StartOp != 0)
1297 OS << " = ";
1298
1299 if (getFlag(MachineInstr::FrameSetup))
1300 OS << "frame-setup ";
1301 if (getFlag(MachineInstr::FrameDestroy))
1302 OS << "frame-destroy ";
1303
1304 // Print the opcode name.
1305 if (TII)
1306 OS << TII->getName(getOpcode());
1307 else
1308 OS << "UNKNOWN";
1309
1310 if (SkipOpers)
1311 return;
1312
1313 // Print the rest of the operands.
1314 bool FirstOp = true;
1315 unsigned AsmDescOp = ~0u;
1316 unsigned AsmOpCount = 0;
1317
1318 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1319 // Print asm string.
1320 OS << " ";
1321 const unsigned OpIdx = InlineAsm::MIOp_AsmString;
1322 LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
1323 unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
1324 getOperand(OpIdx).print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
1325 ShouldPrintRegisterTies, TiedOperandIdx, TRI,
1326 IntrinsicInfo);
1327
1328 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1329 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1330 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1331 OS << " [sideeffect]";
1332 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1333 OS << " [mayload]";
1334 if (ExtraInfo & InlineAsm::Extra_MayStore)
1335 OS << " [maystore]";
1336 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1337 OS << " [isconvergent]";
1338 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1339 OS << " [alignstack]";
1340 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1341 OS << " [attdialect]";
1342 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1343 OS << " [inteldialect]";
1344
1345 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1346 FirstOp = false;
1347 }
1348
1349 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1350 const MachineOperand &MO = getOperand(i);
1351
1352 if (FirstOp) FirstOp = false; else OS << ",";
1353 OS << " ";
1354
1355 if (isDebugValue() && MO.isMetadata()) {
1356 // Pretty print DBG_VALUE instructions.
1357 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1358 if (DIV && !DIV->getName().empty())
1359 OS << "!\"" << DIV->getName() << '\"';
1360 else {
1361 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1362 unsigned TiedOperandIdx = getTiedOperandIdx(i);
1363 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
1364 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1365 }
1366 } else if (i == AsmDescOp && MO.isImm()) {
1367 // Pretty print the inline asm operand descriptor.
1368 OS << '$' << AsmOpCount++;
1369 unsigned Flag = MO.getImm();
1370 switch (InlineAsm::getKind(Flag)) {
1371 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1372 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1373 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1374 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1375 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1376 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1377 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1378 }
1379
1380 unsigned RCID = 0;
1381 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1382 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1383 if (TRI) {
1384 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1385 } else
1386 OS << ":RC" << RCID;
1387 }
1388
1389 if (InlineAsm::isMemKind(Flag)) {
1390 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1391 switch (MCID) {
1392 case InlineAsm::Constraint_es: OS << ":es"; break;
1393 case InlineAsm::Constraint_i: OS << ":i"; break;
1394 case InlineAsm::Constraint_m: OS << ":m"; break;
1395 case InlineAsm::Constraint_o: OS << ":o"; break;
1396 case InlineAsm::Constraint_v: OS << ":v"; break;
1397 case InlineAsm::Constraint_Q: OS << ":Q"; break;
1398 case InlineAsm::Constraint_R: OS << ":R"; break;
1399 case InlineAsm::Constraint_S: OS << ":S"; break;
1400 case InlineAsm::Constraint_T: OS << ":T"; break;
1401 case InlineAsm::Constraint_Um: OS << ":Um"; break;
1402 case InlineAsm::Constraint_Un: OS << ":Un"; break;
1403 case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1404 case InlineAsm::Constraint_Us: OS << ":Us"; break;
1405 case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1406 case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1407 case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1408 case InlineAsm::Constraint_X: OS << ":X"; break;
1409 case InlineAsm::Constraint_Z: OS << ":Z"; break;
1410 case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1411 case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1412 default: OS << ":?"; break;
1413 }
1414 }
1415
1416 unsigned TiedTo = 0;
1417 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1418 OS << " tiedto:$" << TiedTo;
1419
1420 OS << ']';
1421
1422 // Compute the index of the next operand descriptor.
1423 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1424 } else {
1425 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1426 unsigned TiedOperandIdx = getTiedOperandIdx(i);
1427 if (MO.isImm() && isOperandSubregIdx(i))
1428 MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
1429 else
1430 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
1431 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1432 }
1433 }
1434
1435 if (!SkipDebugLoc) {
1436 if (const DebugLoc &DL = getDebugLoc()) {
1437 if (!FirstOp)
1438 OS << ',';
1439 OS << " debug-location ";
1440 DL->printAsOperand(OS, MST);
1441 }
1442 }
1443
1444 if (!memoperands_empty()) {
1445 SmallVector<StringRef, 0> SSNs;
1446 const LLVMContext *Context = nullptr;
1447 std::unique_ptr<LLVMContext> CtxPtr;
1448 const MachineFrameInfo *MFI = nullptr;
1449 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1450 MFI = &MF->getFrameInfo();
1451 Context = &MF->getFunction().getContext();
1452 } else {
1453 CtxPtr = llvm::make_unique<LLVMContext>();
1454 Context = CtxPtr.get();
1455 }
1456
1457 OS << " :: ";
1458 bool NeedComma = false;
1459 for (const MachineMemOperand *Op : memoperands()) {
1460 if (NeedComma)
1461 OS << ", ";
1462 Op->print(OS, MST, SSNs, *Context, MFI, TII);
1463 NeedComma = true;
1464 }
1465 }
1466
1467 if (SkipDebugLoc)
1468 return;
1469
1470 bool HaveSemi = false;
1471 // Print debug location information.
1472 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
1473 if (!HaveSemi)
1474 OS << ";";
1475 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
1476 OS << " line no:" << DV->getLine();
1477 if (auto *InlinedAt = debugLoc->getInlinedAt()) {
1478 DebugLoc InlinedAtDL(InlinedAt);
1479 if (InlinedAtDL && MF) {
1480 OS << " inlined @[ ";
1481 InlinedAtDL.print(OS);
1482 OS << " ]";
1483 }
1484 }
1485 if (isIndirectDebugValue())
1486 OS << " indirect";
1487 }
1488
1489 OS << '\n';
1490}
1491
1492bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1493 const TargetRegisterInfo *RegInfo,
1494 bool AddIfNotFound) {
1495 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1496 bool hasAliases = isPhysReg &&
1497 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1498 bool Found = false;
1499 SmallVector<unsigned,4> DeadOps;
1500 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1501 MachineOperand &MO = getOperand(i);
1502 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1503 continue;
1504
1505 // DEBUG_VALUE nodes do not contribute to code generation and should
1506 // always be ignored. Failure to do so may result in trying to modify
1507 // KILL flags on DEBUG_VALUE nodes.
1508 if (MO.isDebug())
1509 continue;
1510
1511 unsigned Reg = MO.getReg();
1512 if (!Reg)
1513 continue;
1514
1515 if (Reg == IncomingReg) {
1516 if (!Found) {
1517 if (MO.isKill())
1518 // The register is already marked kill.
1519 return true;
1520 if (isPhysReg && isRegTiedToDefOperand(i))
1521 // Two-address uses of physregs must not be marked kill.
1522 return true;
1523 MO.setIsKill();
1524 Found = true;
1525 }
1526 } else if (hasAliases && MO.isKill() &&
1527 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1528 // A super-register kill already exists.
1529 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1530 return true;
1531 if (RegInfo->isSubRegister(IncomingReg, Reg))
1532 DeadOps.push_back(i);
1533 }
1534 }
1535
1536 // Trim unneeded kill operands.
1537 while (!DeadOps.empty()) {
1538 unsigned OpIdx = DeadOps.back();
1539 if (getOperand(OpIdx).isImplicit())
1540 RemoveOperand(OpIdx);
1541 else
1542 getOperand(OpIdx).setIsKill(false);
1543 DeadOps.pop_back();
1544 }
1545
1546 // If not found, this means an alias of one of the operands is killed. Add a
1547 // new implicit operand if required.
1548 if (!Found && AddIfNotFound) {
1549 addOperand(MachineOperand::CreateReg(IncomingReg,
1550 false /*IsDef*/,
1551 true /*IsImp*/,
1552 true /*IsKill*/));
1553 return true;
1554 }
1555 return Found;
1556}
1557
1558void MachineInstr::clearRegisterKills(unsigned Reg,
1559 const TargetRegisterInfo *RegInfo) {
1560 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1561 RegInfo = nullptr;
1562 for (MachineOperand &MO : operands()) {
1563 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1564 continue;
1565 unsigned OpReg = MO.getReg();
1566 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
1567 MO.setIsKill(false);
1568 }
1569}
1570
1571bool MachineInstr::addRegisterDead(unsigned Reg,
1572 const TargetRegisterInfo *RegInfo,
1573 bool AddIfNotFound) {
1574 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1575 bool hasAliases = isPhysReg &&
1576 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1577 bool Found = false;
1578 SmallVector<unsigned,4> DeadOps;
1579 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1580 MachineOperand &MO = getOperand(i);
1581 if (!MO.isReg() || !MO.isDef())
1582 continue;
1583 unsigned MOReg = MO.getReg();
1584 if (!MOReg)
1585 continue;
1586
1587 if (MOReg == Reg) {
1588 MO.setIsDead();
1589 Found = true;
1590 } else if (hasAliases && MO.isDead() &&
1591 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1592 // There exists a super-register that's marked dead.
1593 if (RegInfo->isSuperRegister(Reg, MOReg))
1594 return true;
1595 if (RegInfo->isSubRegister(Reg, MOReg))
1596 DeadOps.push_back(i);
1597 }
1598 }
1599
1600 // Trim unneeded dead operands.
1601 while (!DeadOps.empty()) {
1602 unsigned OpIdx = DeadOps.back();
1603 if (getOperand(OpIdx).isImplicit())
1604 RemoveOperand(OpIdx);
1605 else
1606 getOperand(OpIdx).setIsDead(false);
1607 DeadOps.pop_back();
1608 }
1609
1610 // If not found, this means an alias of one of the operands is dead. Add a
1611 // new implicit operand if required.
1612 if (Found || !AddIfNotFound)
1613 return Found;
1614
1615 addOperand(MachineOperand::CreateReg(Reg,
1616 true /*IsDef*/,
1617 true /*IsImp*/,
1618 false /*IsKill*/,
1619 true /*IsDead*/));
1620 return true;
1621}
1622
1623void MachineInstr::clearRegisterDeads(unsigned Reg) {
1624 for (MachineOperand &MO : operands()) {
1625 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
1626 continue;
1627 MO.setIsDead(false);
1628 }
1629}
1630
1631void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
1632 for (MachineOperand &MO : operands()) {
1633 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
1634 continue;
1635 MO.setIsUndef(IsUndef);
1636 }
1637}
1638
1639void MachineInstr::addRegisterDefined(unsigned Reg,
1640 const TargetRegisterInfo *RegInfo) {
1641 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1642 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1643 if (MO)
1644 return;
1645 } else {
1646 for (const MachineOperand &MO : operands()) {
1647 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1648 MO.getSubReg() == 0)
1649 return;
1650 }
1651 }
1652 addOperand(MachineOperand::CreateReg(Reg,
1653 true /*IsDef*/,
1654 true /*IsImp*/));
1655}
1656
1657void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1658 const TargetRegisterInfo &TRI) {
1659 bool HasRegMask = false;
1660 for (MachineOperand &MO : operands()) {
1661 if (MO.isRegMask()) {
1662 HasRegMask = true;
1663 continue;
1664 }
1665 if (!MO.isReg() || !MO.isDef()) continue;
1666 unsigned Reg = MO.getReg();
1667 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1668 // If there are no uses, including partial uses, the def is dead.
1669 if (llvm::none_of(UsedRegs,
1670 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
1671 MO.setIsDead();
1672 }
1673
1674 // This is a call with a register mask operand.
1675 // Mask clobbers are always dead, so add defs for the non-dead defines.
1676 if (HasRegMask)
1677 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1678 I != E; ++I)
1679 addRegisterDefined(*I, &TRI);
1680}
1681
1682unsigned
1683MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1684 // Build up a buffer of hash code components.
1685 SmallVector<size_t, 8> HashComponents;
1686 HashComponents.reserve(MI->getNumOperands() + 1);
1687 HashComponents.push_back(MI->getOpcode());
1688 for (const MachineOperand &MO : MI->operands()) {
1689 if (MO.isReg() && MO.isDef() &&
1690 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1691 continue; // Skip virtual register defs.
1692
1693 HashComponents.push_back(hash_value(MO));
1694 }
1695 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1696}
1697
1698void MachineInstr::emitError(StringRef Msg) const {
1699 // Find the source location cookie.
1700 unsigned LocCookie = 0;
1701 const MDNode *LocMD = nullptr;
1702 for (unsigned i = getNumOperands(); i != 0; --i) {
1703 if (getOperand(i-1).isMetadata() &&
1704 (LocMD = getOperand(i-1).getMetadata()) &&
1705 LocMD->getNumOperands() != 0) {
1706 if (const ConstantInt *CI =
1707 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
1708 LocCookie = CI->getZExtValue();
1709 break;
1710 }
1711 }
1712 }
1713
1714 if (const MachineBasicBlock *MBB = getParent())
1715 if (const MachineFunction *MF = MBB->getParent())
1716 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1717 report_fatal_error(Msg);
1718}
1719
1720MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
1721 const MCInstrDesc &MCID, bool IsIndirect,
1722 unsigned Reg, const MDNode *Variable,
1723 const MDNode *Expr) {
1724 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1724, __extension__ __PRETTY_FUNCTION__))
;
1725 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1725, __extension__ __PRETTY_FUNCTION__))
;
1726 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1727, __extension__ __PRETTY_FUNCTION__))
1727 "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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1727, __extension__ __PRETTY_FUNCTION__))
;
1728 if (IsIndirect)
1729 return BuildMI(MF, DL, MCID)
1730 .addReg(Reg, RegState::Debug)
1731 .addImm(0U)
1732 .addMetadata(Variable)
1733 .addMetadata(Expr);
1734 else
1735 return BuildMI(MF, DL, MCID)
1736 .addReg(Reg, RegState::Debug)
1737 .addReg(0U, RegState::Debug)
1738 .addMetadata(Variable)
1739 .addMetadata(Expr);
1740}
1741
1742MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
1743 MachineBasicBlock::iterator I,
1744 const DebugLoc &DL, const MCInstrDesc &MCID,
1745 bool IsIndirect, unsigned Reg,
1746 const MDNode *Variable, const MDNode *Expr) {
1747 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1747, __extension__ __PRETTY_FUNCTION__))
;
1748 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1748, __extension__ __PRETTY_FUNCTION__))
;
1749 MachineFunction &MF = *BB.getParent();
1750 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
1751 BB.insert(I, MI);
1752 return MachineInstrBuilder(MF, MI);
1753}
1754
1755/// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
1756/// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
1757static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
1758 assert(MI.getOperand(0).isReg() && "can't spill non-register")(static_cast <bool> (MI.getOperand(0).isReg() &&
"can't spill non-register") ? void (0) : __assert_fail ("MI.getOperand(0).isReg() && \"can't spill non-register\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1758, __extension__ __PRETTY_FUNCTION__))
;
1759 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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1760, __extension__ __PRETTY_FUNCTION__))
1760 "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\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1760, __extension__ __PRETTY_FUNCTION__))
;
1761
1762 const DIExpression *Expr = MI.getDebugExpression();
1763 if (MI.isIndirectDebugValue()) {
1764 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset")(static_cast <bool> (MI.getOperand(1).getImm() == 0 &&
"DBG_VALUE with nonzero offset") ? void (0) : __assert_fail (
"MI.getOperand(1).getImm() == 0 && \"DBG_VALUE with nonzero offset\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/CodeGen/MachineInstr.cpp"
, 1764, __extension__ __PRETTY_FUNCTION__))
;
1765 Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
1766 }
1767 return Expr;
1768}
1769
1770MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
1771 MachineBasicBlock::iterator I,
1772 const MachineInstr &Orig,
1773 int FrameIndex) {
1774 const DIExpression *Expr = computeExprForSpill(Orig);
1775 return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
1
Calling 'MachineInstrBuilder::addFrameIndex'
1776 .addFrameIndex(FrameIndex)
1777 .addImm(0U)
1778 .addMetadata(Orig.getDebugVariable())
1779 .addMetadata(Expr);
1780}
1781
1782void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
1783 const DIExpression *Expr = computeExprForSpill(Orig);
1784 Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
1785 Orig.getOperand(1).ChangeToImmediate(0U);
1786 Orig.getOperand(3).setMetadata(Expr);
1787}

/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h

1//===- CodeGen/MachineInstrBuilder.h - Simplify creation of MIs --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file exposes a function named BuildMI, which is useful for dramatically
11// simplifying how MachineInstr's are created. It allows use of code like this:
12//
13// M = BuildMI(MBB, MI, DL, TII.get(X86::ADD8rr), Dst)
14// .addReg(argVal1)
15// .addReg(argVal2);
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_CODEGEN_MACHINEINSTRBUILDER_H
20#define LLVM_CODEGEN_MACHINEINSTRBUILDER_H
21
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/CodeGen/GlobalISel/Utils.h"
24#include "llvm/CodeGen/MachineBasicBlock.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineInstr.h"
27#include "llvm/CodeGen/MachineInstrBundle.h"
28#include "llvm/CodeGen/MachineOperand.h"
29#include "llvm/CodeGen/TargetRegisterInfo.h"
30#include "llvm/IR/InstrTypes.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/Support/ErrorHandling.h"
33#include <cassert>
34#include <cstdint>
35#include <utility>
36
37namespace llvm {
38
39class MCInstrDesc;
40class MDNode;
41
42namespace RegState {
43
44 enum {
45 Define = 0x2,
46 Implicit = 0x4,
47 Kill = 0x8,
48 Dead = 0x10,
49 Undef = 0x20,
50 EarlyClobber = 0x40,
51 Debug = 0x80,
52 InternalRead = 0x100,
53 Renamable = 0x200,
54 DefineNoRead = Define | Undef,
55 ImplicitDefine = Implicit | Define,
56 ImplicitKill = Implicit | Kill
57 };
58
59} // end namespace RegState
60
61class MachineInstrBuilder {
62 MachineFunction *MF = nullptr;
63 MachineInstr *MI = nullptr;
64
65public:
66 MachineInstrBuilder() = default;
67
68 /// Create a MachineInstrBuilder for manipulating an existing instruction.
69 /// F must be the machine function that was used to allocate I.
70 MachineInstrBuilder(MachineFunction &F, MachineInstr *I) : MF(&F), MI(I) {}
71 MachineInstrBuilder(MachineFunction &F, MachineBasicBlock::iterator I)
72 : MF(&F), MI(&*I) {}
73
74 /// Allow automatic conversion to the machine instruction we are working on.
75 operator MachineInstr*() const { return MI; }
76 MachineInstr *operator->() const { return MI; }
77 operator MachineBasicBlock::iterator() const { return MI; }
78
79 /// If conversion operators fail, use this method to get the MachineInstr
80 /// explicitly.
81 MachineInstr *getInstr() const { return MI; }
82
83 /// Add a new virtual register operand.
84 const MachineInstrBuilder &addReg(unsigned RegNo, unsigned flags = 0,
85 unsigned SubReg = 0) const {
86 assert((flags & 0x1) == 0 &&(static_cast <bool> ((flags & 0x1) == 0 && "Passing in 'true' to addReg is forbidden! Use enums instead."
) ? void (0) : __assert_fail ("(flags & 0x1) == 0 && \"Passing in 'true' to addReg is forbidden! Use enums instead.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 87, __extension__ __PRETTY_FUNCTION__))
87 "Passing in 'true' to addReg is forbidden! Use enums instead.")(static_cast <bool> ((flags & 0x1) == 0 && "Passing in 'true' to addReg is forbidden! Use enums instead."
) ? void (0) : __assert_fail ("(flags & 0x1) == 0 && \"Passing in 'true' to addReg is forbidden! Use enums instead.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 87, __extension__ __PRETTY_FUNCTION__))
;
88 MI->addOperand(*MF, MachineOperand::CreateReg(RegNo,
89 flags & RegState::Define,
90 flags & RegState::Implicit,
91 flags & RegState::Kill,
92 flags & RegState::Dead,
93 flags & RegState::Undef,
94 flags & RegState::EarlyClobber,
95 SubReg,
96 flags & RegState::Debug,
97 flags & RegState::InternalRead,
98 flags & RegState::Renamable));
99 return *this;
100 }
101
102 /// Add a virtual register definition operand.
103 const MachineInstrBuilder &addDef(unsigned RegNo, unsigned Flags = 0,
104 unsigned SubReg = 0) const {
105 return addReg(RegNo, Flags | RegState::Define, SubReg);
106 }
107
108 /// Add a virtual register use operand. It is an error for Flags to contain
109 /// `RegState::Define` when calling this function.
110 const MachineInstrBuilder &addUse(unsigned RegNo, unsigned Flags = 0,
111 unsigned SubReg = 0) const {
112 assert(!(Flags & RegState::Define) &&(static_cast <bool> (!(Flags & RegState::Define) &&
"Misleading addUse defines register, use addReg instead.") ?
void (0) : __assert_fail ("!(Flags & RegState::Define) && \"Misleading addUse defines register, use addReg instead.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 113, __extension__ __PRETTY_FUNCTION__))
113 "Misleading addUse defines register, use addReg instead.")(static_cast <bool> (!(Flags & RegState::Define) &&
"Misleading addUse defines register, use addReg instead.") ?
void (0) : __assert_fail ("!(Flags & RegState::Define) && \"Misleading addUse defines register, use addReg instead.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return addReg(RegNo, Flags, SubReg);
115 }
116
117 /// Add a new immediate operand.
118 const MachineInstrBuilder &addImm(int64_t Val) const {
119 MI->addOperand(*MF, MachineOperand::CreateImm(Val));
120 return *this;
121 }
122
123 const MachineInstrBuilder &addCImm(const ConstantInt *Val) const {
124 MI->addOperand(*MF, MachineOperand::CreateCImm(Val));
125 return *this;
126 }
127
128 const MachineInstrBuilder &addFPImm(const ConstantFP *Val) const {
129 MI->addOperand(*MF, MachineOperand::CreateFPImm(Val));
130 return *this;
131 }
132
133 const MachineInstrBuilder &addMBB(MachineBasicBlock *MBB,
134 unsigned char TargetFlags = 0) const {
135 MI->addOperand(*MF, MachineOperand::CreateMBB(MBB, TargetFlags));
136 return *this;
137 }
138
139 const MachineInstrBuilder &addFrameIndex(int Idx) const {
140 MI->addOperand(*MF, MachineOperand::CreateFI(Idx));
2
Calling 'MachineInstr::addOperand'
141 return *this;
142 }
143
144 const MachineInstrBuilder &addConstantPoolIndex(unsigned Idx,
145 int Offset = 0,
146 unsigned char TargetFlags = 0) const {
147 MI->addOperand(*MF, MachineOperand::CreateCPI(Idx, Offset, TargetFlags));
148 return *this;
149 }
150
151 const MachineInstrBuilder &addTargetIndex(unsigned Idx, int64_t Offset = 0,
152 unsigned char TargetFlags = 0) const {
153 MI->addOperand(*MF, MachineOperand::CreateTargetIndex(Idx, Offset,
154 TargetFlags));
155 return *this;
156 }
157
158 const MachineInstrBuilder &addJumpTableIndex(unsigned Idx,
159 unsigned char TargetFlags = 0) const {
160 MI->addOperand(*MF, MachineOperand::CreateJTI(Idx, TargetFlags));
161 return *this;
162 }
163
164 const MachineInstrBuilder &addGlobalAddress(const GlobalValue *GV,
165 int64_t Offset = 0,
166 unsigned char TargetFlags = 0) const {
167 MI->addOperand(*MF, MachineOperand::CreateGA(GV, Offset, TargetFlags));
168 return *this;
169 }
170
171 const MachineInstrBuilder &addExternalSymbol(const char *FnName,
172 unsigned char TargetFlags = 0) const {
173 MI->addOperand(*MF, MachineOperand::CreateES(FnName, TargetFlags));
174 return *this;
175 }
176
177 const MachineInstrBuilder &addBlockAddress(const BlockAddress *BA,
178 int64_t Offset = 0,
179 unsigned char TargetFlags = 0) const {
180 MI->addOperand(*MF, MachineOperand::CreateBA(BA, Offset, TargetFlags));
181 return *this;
182 }
183
184 const MachineInstrBuilder &addRegMask(const uint32_t *Mask) const {
185 MI->addOperand(*MF, MachineOperand::CreateRegMask(Mask));
186 return *this;
187 }
188
189 const MachineInstrBuilder &addMemOperand(MachineMemOperand *MMO) const {
190 MI->addMemOperand(*MF, MMO);
191 return *this;
192 }
193
194 const MachineInstrBuilder &setMemRefs(MachineInstr::mmo_iterator b,
195 MachineInstr::mmo_iterator e) const {
196 MI->setMemRefs(b, e);
197 return *this;
198 }
199
200 const MachineInstrBuilder &setMemRefs(std::pair<MachineInstr::mmo_iterator,
201 unsigned> MemOperandsRef) const {
202 MI->setMemRefs(MemOperandsRef);
203 return *this;
204 }
205
206 const MachineInstrBuilder &add(const MachineOperand &MO) const {
207 MI->addOperand(*MF, MO);
208 return *this;
209 }
210
211 const MachineInstrBuilder &add(ArrayRef<MachineOperand> MOs) const {
212 for (const MachineOperand &MO : MOs) {
213 MI->addOperand(*MF, MO);
214 }
215 return *this;
216 }
217
218 const MachineInstrBuilder &addMetadata(const MDNode *MD) const {
219 MI->addOperand(*MF, MachineOperand::CreateMetadata(MD));
220 assert((MI->isDebugValue() ? static_cast<bool>(MI->getDebugVariable())(static_cast <bool> ((MI->isDebugValue() ? static_cast
<bool>(MI->getDebugVariable()) : true) && "first MDNode argument of a DBG_VALUE not a variable"
) ? void (0) : __assert_fail ("(MI->isDebugValue() ? static_cast<bool>(MI->getDebugVariable()) : true) && \"first MDNode argument of a DBG_VALUE not a variable\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 222, __extension__ __PRETTY_FUNCTION__))
221 : true) &&(static_cast <bool> ((MI->isDebugValue() ? static_cast
<bool>(MI->getDebugVariable()) : true) && "first MDNode argument of a DBG_VALUE not a variable"
) ? void (0) : __assert_fail ("(MI->isDebugValue() ? static_cast<bool>(MI->getDebugVariable()) : true) && \"first MDNode argument of a DBG_VALUE not a variable\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 222, __extension__ __PRETTY_FUNCTION__))
222 "first MDNode argument of a DBG_VALUE not a variable")(static_cast <bool> ((MI->isDebugValue() ? static_cast
<bool>(MI->getDebugVariable()) : true) && "first MDNode argument of a DBG_VALUE not a variable"
) ? void (0) : __assert_fail ("(MI->isDebugValue() ? static_cast<bool>(MI->getDebugVariable()) : true) && \"first MDNode argument of a DBG_VALUE not a variable\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 222, __extension__ __PRETTY_FUNCTION__))
;
223 return *this;
224 }
225
226 const MachineInstrBuilder &addCFIIndex(unsigned CFIIndex) const {
227 MI->addOperand(*MF, MachineOperand::CreateCFIIndex(CFIIndex));
228 return *this;
229 }
230
231 const MachineInstrBuilder &addIntrinsicID(Intrinsic::ID ID) const {
232 MI->addOperand(*MF, MachineOperand::CreateIntrinsicID(ID));
233 return *this;
234 }
235
236 const MachineInstrBuilder &addPredicate(CmpInst::Predicate Pred) const {
237 MI->addOperand(*MF, MachineOperand::CreatePredicate(Pred));
238 return *this;
239 }
240
241 const MachineInstrBuilder &addSym(MCSymbol *Sym,
242 unsigned char TargetFlags = 0) const {
243 MI->addOperand(*MF, MachineOperand::CreateMCSymbol(Sym, TargetFlags));
244 return *this;
245 }
246
247 const MachineInstrBuilder &setMIFlags(unsigned Flags) const {
248 MI->setFlags(Flags);
249 return *this;
250 }
251
252 const MachineInstrBuilder &setMIFlag(MachineInstr::MIFlag Flag) const {
253 MI->setFlag(Flag);
254 return *this;
255 }
256
257 // Add a displacement from an existing MachineOperand with an added offset.
258 const MachineInstrBuilder &addDisp(const MachineOperand &Disp, int64_t off,
259 unsigned char TargetFlags = 0) const {
260 // If caller specifies new TargetFlags then use it, otherwise the
261 // default behavior is to copy the target flags from the existing
262 // MachineOperand. This means if the caller wants to clear the
263 // target flags it needs to do so explicitly.
264 if (0 == TargetFlags)
265 TargetFlags = Disp.getTargetFlags();
266
267 switch (Disp.getType()) {
268 default:
269 llvm_unreachable("Unhandled operand type in addDisp()")::llvm::llvm_unreachable_internal("Unhandled operand type in addDisp()"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 269)
;
270 case MachineOperand::MO_Immediate:
271 return addImm(Disp.getImm() + off);
272 case MachineOperand::MO_ConstantPoolIndex:
273 return addConstantPoolIndex(Disp.getIndex(), Disp.getOffset() + off,
274 TargetFlags);
275 case MachineOperand::MO_GlobalAddress:
276 return addGlobalAddress(Disp.getGlobal(), Disp.getOffset() + off,
277 TargetFlags);
278 }
279 }
280
281 /// Copy all the implicit operands from OtherMI onto this one.
282 const MachineInstrBuilder &
283 copyImplicitOps(const MachineInstr &OtherMI) const {
284 MI->copyImplicitOps(*MF, OtherMI);
285 return *this;
286 }
287
288 bool constrainAllUses(const TargetInstrInfo &TII,
289 const TargetRegisterInfo &TRI,
290 const RegisterBankInfo &RBI) const {
291 return constrainSelectedInstRegOperands(*MI, TII, TRI, RBI);
292 }
293};
294
295/// Builder interface. Specify how to create the initial instruction itself.
296inline MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL,
297 const MCInstrDesc &MCID) {
298 return MachineInstrBuilder(MF, MF.CreateMachineInstr(MCID, DL));
299}
300
301/// This version of the builder sets up the first operand as a
302/// destination virtual register.
303inline MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL,
304 const MCInstrDesc &MCID, unsigned DestReg) {
305 return MachineInstrBuilder(MF, MF.CreateMachineInstr(MCID, DL))
306 .addReg(DestReg, RegState::Define);
307}
308
309/// This version of the builder inserts the newly-built instruction before
310/// the given position in the given MachineBasicBlock, and sets up the first
311/// operand as a destination virtual register.
312inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
313 MachineBasicBlock::iterator I,
314 const DebugLoc &DL, const MCInstrDesc &MCID,
315 unsigned DestReg) {
316 MachineFunction &MF = *BB.getParent();
317 MachineInstr *MI = MF.CreateMachineInstr(MCID, DL);
318 BB.insert(I, MI);
319 return MachineInstrBuilder(MF, MI).addReg(DestReg, RegState::Define);
320}
321
322/// This version of the builder inserts the newly-built instruction before
323/// the given position in the given MachineBasicBlock, and sets up the first
324/// operand as a destination virtual register.
325///
326/// If \c I is inside a bundle, then the newly inserted \a MachineInstr is
327/// added to the same bundle.
328inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
329 MachineBasicBlock::instr_iterator I,
330 const DebugLoc &DL, const MCInstrDesc &MCID,
331 unsigned DestReg) {
332 MachineFunction &MF = *BB.getParent();
333 MachineInstr *MI = MF.CreateMachineInstr(MCID, DL);
334 BB.insert(I, MI);
335 return MachineInstrBuilder(MF, MI).addReg(DestReg, RegState::Define);
336}
337
338inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB, MachineInstr &I,
339 const DebugLoc &DL, const MCInstrDesc &MCID,
340 unsigned DestReg) {
341 // Calling the overload for instr_iterator is always correct. However, the
342 // definition is not available in headers, so inline the check.
343 if (I.isInsideBundle())
344 return BuildMI(BB, MachineBasicBlock::instr_iterator(I), DL, MCID, DestReg);
345 return BuildMI(BB, MachineBasicBlock::iterator(I), DL, MCID, DestReg);
346}
347
348inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB, MachineInstr *I,
349 const DebugLoc &DL, const MCInstrDesc &MCID,
350 unsigned DestReg) {
351 return BuildMI(BB, *I, DL, MCID, DestReg);
352}
353
354/// This version of the builder inserts the newly-built instruction before the
355/// given position in the given MachineBasicBlock, and does NOT take a
356/// destination register.
357inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
358 MachineBasicBlock::iterator I,
359 const DebugLoc &DL,
360 const MCInstrDesc &MCID) {
361 MachineFunction &MF = *BB.getParent();
362 MachineInstr *MI = MF.CreateMachineInstr(MCID, DL);
363 BB.insert(I, MI);
364 return MachineInstrBuilder(MF, MI);
365}
366
367inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
368 MachineBasicBlock::instr_iterator I,
369 const DebugLoc &DL,
370 const MCInstrDesc &MCID) {
371 MachineFunction &MF = *BB.getParent();
372 MachineInstr *MI = MF.CreateMachineInstr(MCID, DL);
373 BB.insert(I, MI);
374 return MachineInstrBuilder(MF, MI);
375}
376
377inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB, MachineInstr &I,
378 const DebugLoc &DL,
379 const MCInstrDesc &MCID) {
380 // Calling the overload for instr_iterator is always correct. However, the
381 // definition is not available in headers, so inline the check.
382 if (I.isInsideBundle())
383 return BuildMI(BB, MachineBasicBlock::instr_iterator(I), DL, MCID);
384 return BuildMI(BB, MachineBasicBlock::iterator(I), DL, MCID);
385}
386
387inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB, MachineInstr *I,
388 const DebugLoc &DL,
389 const MCInstrDesc &MCID) {
390 return BuildMI(BB, *I, DL, MCID);
391}
392
393/// This version of the builder inserts the newly-built instruction at the end
394/// of the given MachineBasicBlock, and does NOT take a destination register.
395inline MachineInstrBuilder BuildMI(MachineBasicBlock *BB, const DebugLoc &DL,
396 const MCInstrDesc &MCID) {
397 return BuildMI(*BB, BB->end(), DL, MCID);
398}
399
400/// This version of the builder inserts the newly-built instruction at the
401/// end of the given MachineBasicBlock, and sets up the first operand as a
402/// destination virtual register.
403inline MachineInstrBuilder BuildMI(MachineBasicBlock *BB, const DebugLoc &DL,
404 const MCInstrDesc &MCID, unsigned DestReg) {
405 return BuildMI(*BB, BB->end(), DL, MCID, DestReg);
406}
407
408/// This version of the builder builds a DBG_VALUE intrinsic
409/// for either a value in a register or a register-indirect
410/// address. The convention is that a DBG_VALUE is indirect iff the
411/// second operand is an immediate.
412MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL,
413 const MCInstrDesc &MCID, bool IsIndirect,
414 unsigned Reg, const MDNode *Variable,
415 const MDNode *Expr);
416
417/// This version of the builder builds a DBG_VALUE intrinsic
418/// for either a value in a register or a register-indirect
419/// address and inserts it at position I.
420MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
421 MachineBasicBlock::iterator I, const DebugLoc &DL,
422 const MCInstrDesc &MCID, bool IsIndirect,
423 unsigned Reg, const MDNode *Variable,
424 const MDNode *Expr);
425
426/// Clone a DBG_VALUE whose value has been spilled to FrameIndex.
427MachineInstr *buildDbgValueForSpill(MachineBasicBlock &BB,
428 MachineBasicBlock::iterator I,
429 const MachineInstr &Orig, int FrameIndex);
430
431/// Update a DBG_VALUE whose value has been spilled to FrameIndex. Useful when
432/// modifying an instruction in place while iterating over a basic block.
433void updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex);
434
435inline unsigned getDefRegState(bool B) {
436 return B ? RegState::Define : 0;
437}
438inline unsigned getImplRegState(bool B) {
439 return B ? RegState::Implicit : 0;
440}
441inline unsigned getKillRegState(bool B) {
442 return B ? RegState::Kill : 0;
443}
444inline unsigned getDeadRegState(bool B) {
445 return B ? RegState::Dead : 0;
446}
447inline unsigned getUndefRegState(bool B) {
448 return B ? RegState::Undef : 0;
449}
450inline unsigned getInternalReadRegState(bool B) {
451 return B ? RegState::InternalRead : 0;
452}
453inline unsigned getDebugRegState(bool B) {
454 return B ? RegState::Debug : 0;
455}
456inline unsigned getRenamableRegState(bool B) {
457 return B ? RegState::Renamable : 0;
458}
459
460/// Get all register state flags from machine operand \p RegOp.
461inline unsigned getRegState(const MachineOperand &RegOp) {
462 assert(RegOp.isReg() && "Not a register operand")(static_cast <bool> (RegOp.isReg() && "Not a register operand"
) ? void (0) : __assert_fail ("RegOp.isReg() && \"Not a register operand\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 462, __extension__ __PRETTY_FUNCTION__))
;
463 return getDefRegState(RegOp.isDef()) |
464 getImplRegState(RegOp.isImplicit()) |
465 getKillRegState(RegOp.isKill()) |
466 getDeadRegState(RegOp.isDead()) |
467 getUndefRegState(RegOp.isUndef()) |
468 getInternalReadRegState(RegOp.isInternalRead()) |
469 getDebugRegState(RegOp.isDebug()) |
470 getRenamableRegState(
471 TargetRegisterInfo::isPhysicalRegister(RegOp.getReg()) &&
472 RegOp.isRenamable());
473}
474
475/// Helper class for constructing bundles of MachineInstrs.
476///
477/// MIBundleBuilder can create a bundle from scratch by inserting new
478/// MachineInstrs one at a time, or it can create a bundle from a sequence of
479/// existing MachineInstrs in a basic block.
480class MIBundleBuilder {
481 MachineBasicBlock &MBB;
482 MachineBasicBlock::instr_iterator Begin;
483 MachineBasicBlock::instr_iterator End;
484
485public:
486 /// Create an MIBundleBuilder that inserts instructions into a new bundle in
487 /// BB above the bundle or instruction at Pos.
488 MIBundleBuilder(MachineBasicBlock &BB, MachineBasicBlock::iterator Pos)
489 : MBB(BB), Begin(Pos.getInstrIterator()), End(Begin) {}
490
491 /// Create a bundle from the sequence of instructions between B and E.
492 MIBundleBuilder(MachineBasicBlock &BB, MachineBasicBlock::iterator B,
493 MachineBasicBlock::iterator E)
494 : MBB(BB), Begin(B.getInstrIterator()), End(E.getInstrIterator()) {
495 assert(B != E && "No instructions to bundle")(static_cast <bool> (B != E && "No instructions to bundle"
) ? void (0) : __assert_fail ("B != E && \"No instructions to bundle\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/CodeGen/MachineInstrBuilder.h"
, 495, __extension__ __PRETTY_FUNCTION__))
;
496 ++B;
497 while (B != E) {
498 MachineInstr &MI = *B;
499 ++B;
500 MI.bundleWithPred();
501 }
502 }
503
504 /// Create an MIBundleBuilder representing an existing instruction or bundle
505 /// that has MI as its head.
506 explicit MIBundleBuilder(MachineInstr *MI)
507 : MBB(*MI->getParent()), Begin(MI),
508 End(getBundleEnd(MI->getIterator())) {}
509
510 /// Return a reference to the basic block containing this bundle.
511 MachineBasicBlock &getMBB() const { return MBB; }
512
513 /// Return true if no instructions have been inserted in this bundle yet.
514 /// Empty bundles aren't representable in a MachineBasicBlock.
515 bool empty() const { return Begin == End; }
516
517 /// Return an iterator to the first bundled instruction.
518 MachineBasicBlock::instr_iterator begin() const { return Begin; }
519
520 /// Return an iterator beyond the last bundled instruction.
521 MachineBasicBlock::instr_iterator end() const { return End; }
522
523 /// Insert MI into this bundle before I which must point to an instruction in
524 /// the bundle, or end().
525 MIBundleBuilder &insert(MachineBasicBlock::instr_iterator I,
526 MachineInstr *MI) {
527 MBB.insert(I, MI);
528 if (I == Begin) {
529 if (!empty())
530 MI->bundleWithSucc();
531 Begin = MI->getIterator();
532 return *this;
533 }
534 if (I == End) {
535 MI->bundleWithPred();
536 return *this;
537 }
538 // MI was inserted in the middle of the bundle, so its neighbors' flags are
539 // already fine. Update MI's bundle flags manually.
540 MI->setFlag(MachineInstr::BundledPred);
541 MI->setFlag(MachineInstr::BundledSucc);
542 return *this;
543 }
544
545 /// Insert MI into MBB by prepending it to the instructions in the bundle.
546 /// MI will become the first instruction in the bundle.
547 MIBundleBuilder &prepend(MachineInstr *MI) {
548 return insert(begin(), MI);
549 }
550
551 /// Insert MI into MBB by appending it to the instructions in the bundle.
552 /// MI will become the last instruction in the bundle.
553 MIBundleBuilder &append(MachineInstr *MI) {
554 return insert(end(), MI);
555 }
556};
557
558} // end namespace llvm
559
560#endif // LLVM_CODEGEN_MACHINEINSTRBUILDER_H