1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Methods common to all machine instructions.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/ADT/FoldingSet.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineMemOperand.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/InlineAsm.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ModuleSlotTracker.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/MC/MCInstrDesc.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
48 static cl::opt<bool> PrintWholeRegMask(
49 "print-whole-regmask",
50 cl::desc("Print the full contents of regmask operands in IR dumps"),
51 cl::init(true), cl::Hidden);
53 //===----------------------------------------------------------------------===//
54 // MachineOperand Implementation
55 //===----------------------------------------------------------------------===//
57 void MachineOperand::setReg(unsigned Reg) {
58 if (getReg() == Reg) return; // No change.
60 // Otherwise, we have to change the register. If this operand is embedded
61 // into a machine function, we need to update the old and new register's
63 if (MachineInstr *MI = getParent())
64 if (MachineBasicBlock *MBB = MI->getParent())
65 if (MachineFunction *MF = MBB->getParent()) {
66 MachineRegisterInfo &MRI = MF->getRegInfo();
67 MRI.removeRegOperandFromUseList(this);
68 SmallContents.RegNo = Reg;
69 MRI.addRegOperandToUseList(this);
73 // Otherwise, just change the register, no problem. :)
74 SmallContents.RegNo = Reg;
77 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
78 const TargetRegisterInfo &TRI) {
79 assert(TargetRegisterInfo::isVirtualRegister(Reg));
80 if (SubIdx && getSubReg())
81 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
87 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
88 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
90 Reg = TRI.getSubReg(Reg, getSubReg());
91 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
92 // That won't happen in legal code.
98 /// Change a def to a use, or a use to a def.
99 void MachineOperand::setIsDef(bool Val) {
100 assert(isReg() && "Wrong MachineOperand accessor");
101 assert((!Val || !isDebug()) && "Marking a debug operation as def");
104 // MRI may keep uses and defs in different list positions.
105 if (MachineInstr *MI = getParent())
106 if (MachineBasicBlock *MBB = MI->getParent())
107 if (MachineFunction *MF = MBB->getParent()) {
108 MachineRegisterInfo &MRI = MF->getRegInfo();
109 MRI.removeRegOperandFromUseList(this);
111 MRI.addRegOperandToUseList(this);
117 // If this operand is currently a register operand, and if this is in a
118 // function, deregister the operand from the register's use/def list.
119 void MachineOperand::removeRegFromUses() {
120 if (!isReg() || !isOnRegUseList())
123 if (MachineInstr *MI = getParent()) {
124 if (MachineBasicBlock *MBB = MI->getParent()) {
125 if (MachineFunction *MF = MBB->getParent())
126 MF->getRegInfo().removeRegOperandFromUseList(this);
131 /// ChangeToImmediate - Replace this operand with a new immediate operand of
132 /// the specified value. If an operand is known to be an immediate already,
133 /// the setImm method should be used.
134 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
135 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
139 OpKind = MO_Immediate;
140 Contents.ImmVal = ImmVal;
143 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
144 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
148 OpKind = MO_FPImmediate;
149 Contents.CFP = FPImm;
152 void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
153 assert((!isReg() || !isTied()) &&
154 "Cannot change a tied operand into an external symbol");
158 OpKind = MO_ExternalSymbol;
159 Contents.OffsetedInfo.Val.SymbolName = SymName;
160 setOffset(0); // Offset is always 0.
161 setTargetFlags(TargetFlags);
164 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
165 assert((!isReg() || !isTied()) &&
166 "Cannot change a tied operand into an MCSymbol");
170 OpKind = MO_MCSymbol;
174 /// ChangeToRegister - Replace this operand with a new register operand of
175 /// the specified value. If an operand is known to be an register already,
176 /// the setReg method should be used.
177 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
178 bool isKill, bool isDead, bool isUndef,
180 MachineRegisterInfo *RegInfo = nullptr;
181 if (MachineInstr *MI = getParent())
182 if (MachineBasicBlock *MBB = MI->getParent())
183 if (MachineFunction *MF = MBB->getParent())
184 RegInfo = &MF->getRegInfo();
185 // If this operand is already a register operand, remove it from the
186 // register's use/def lists.
187 bool WasReg = isReg();
188 if (RegInfo && WasReg)
189 RegInfo->removeRegOperandFromUseList(this);
191 // Change this to a register and set the reg#.
192 OpKind = MO_Register;
193 SmallContents.RegNo = Reg;
194 SubReg_TargetFlags = 0;
200 IsInternalRead = false;
201 IsEarlyClobber = false;
203 // Ensure isOnRegUseList() returns false.
204 Contents.Reg.Prev = nullptr;
205 // Preserve the tie when the operand was already a register.
209 // If this operand is embedded in a function, add the operand to the
210 // register's use/def list.
212 RegInfo->addRegOperandToUseList(this);
215 /// isIdenticalTo - Return true if this operand is identical to the specified
216 /// operand. Note that this should stay in sync with the hash_value overload
218 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
219 if (getType() != Other.getType() ||
220 getTargetFlags() != Other.getTargetFlags())
224 case MachineOperand::MO_Register:
225 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
226 getSubReg() == Other.getSubReg();
227 case MachineOperand::MO_Immediate:
228 return getImm() == Other.getImm();
229 case MachineOperand::MO_CImmediate:
230 return getCImm() == Other.getCImm();
231 case MachineOperand::MO_FPImmediate:
232 return getFPImm() == Other.getFPImm();
233 case MachineOperand::MO_MachineBasicBlock:
234 return getMBB() == Other.getMBB();
235 case MachineOperand::MO_FrameIndex:
236 return getIndex() == Other.getIndex();
237 case MachineOperand::MO_ConstantPoolIndex:
238 case MachineOperand::MO_TargetIndex:
239 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
240 case MachineOperand::MO_JumpTableIndex:
241 return getIndex() == Other.getIndex();
242 case MachineOperand::MO_GlobalAddress:
243 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
244 case MachineOperand::MO_ExternalSymbol:
245 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
246 getOffset() == Other.getOffset();
247 case MachineOperand::MO_BlockAddress:
248 return getBlockAddress() == Other.getBlockAddress() &&
249 getOffset() == Other.getOffset();
250 case MachineOperand::MO_RegisterMask:
251 case MachineOperand::MO_RegisterLiveOut:
252 return getRegMask() == Other.getRegMask();
253 case MachineOperand::MO_MCSymbol:
254 return getMCSymbol() == Other.getMCSymbol();
255 case MachineOperand::MO_CFIIndex:
256 return getCFIIndex() == Other.getCFIIndex();
257 case MachineOperand::MO_Metadata:
258 return getMetadata() == Other.getMetadata();
260 llvm_unreachable("Invalid machine operand type");
263 // Note: this must stay exactly in sync with isIdenticalTo above.
264 hash_code llvm::hash_value(const MachineOperand &MO) {
265 switch (MO.getType()) {
266 case MachineOperand::MO_Register:
267 // Register operands don't have target flags.
268 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
269 case MachineOperand::MO_Immediate:
270 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
271 case MachineOperand::MO_CImmediate:
272 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
273 case MachineOperand::MO_FPImmediate:
274 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
275 case MachineOperand::MO_MachineBasicBlock:
276 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
277 case MachineOperand::MO_FrameIndex:
278 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
279 case MachineOperand::MO_ConstantPoolIndex:
280 case MachineOperand::MO_TargetIndex:
281 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
283 case MachineOperand::MO_JumpTableIndex:
284 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
285 case MachineOperand::MO_ExternalSymbol:
286 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
288 case MachineOperand::MO_GlobalAddress:
289 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
291 case MachineOperand::MO_BlockAddress:
292 return hash_combine(MO.getType(), MO.getTargetFlags(),
293 MO.getBlockAddress(), MO.getOffset());
294 case MachineOperand::MO_RegisterMask:
295 case MachineOperand::MO_RegisterLiveOut:
296 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
297 case MachineOperand::MO_Metadata:
298 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
299 case MachineOperand::MO_MCSymbol:
300 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
301 case MachineOperand::MO_CFIIndex:
302 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
304 llvm_unreachable("Invalid machine operand type");
307 void MachineOperand::print(raw_ostream &OS,
308 const TargetRegisterInfo *TRI) const {
309 ModuleSlotTracker DummyMST(nullptr);
310 print(OS, DummyMST, TRI);
313 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
314 const TargetRegisterInfo *TRI) const {
316 case MachineOperand::MO_Register:
317 OS << PrintReg(getReg(), TRI, getSubReg());
319 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
320 isInternalRead() || isEarlyClobber() || isTied()) {
322 bool NeedComma = false;
324 if (NeedComma) OS << ',';
325 if (isEarlyClobber())
326 OS << "earlyclobber,";
331 // <def,read-undef> only makes sense when getSubReg() is set.
332 // Don't clutter the output otherwise.
333 if (isUndef() && getSubReg())
335 } else if (isImplicit()) {
341 if (NeedComma) OS << ',';
346 if (NeedComma) OS << ',';
350 if (isUndef() && isUse()) {
351 if (NeedComma) OS << ',';
355 if (isInternalRead()) {
356 if (NeedComma) OS << ',';
361 if (NeedComma) OS << ',';
364 OS << unsigned(TiedTo - 1);
369 case MachineOperand::MO_Immediate:
372 case MachineOperand::MO_CImmediate:
373 getCImm()->getValue().print(OS, false);
375 case MachineOperand::MO_FPImmediate:
376 if (getFPImm()->getType()->isFloatTy()) {
377 OS << getFPImm()->getValueAPF().convertToFloat();
378 } else if (getFPImm()->getType()->isHalfTy()) {
379 APFloat APF = getFPImm()->getValueAPF();
381 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &Unused);
382 OS << "half " << APF.convertToFloat();
384 OS << getFPImm()->getValueAPF().convertToDouble();
387 case MachineOperand::MO_MachineBasicBlock:
388 OS << "<BB#" << getMBB()->getNumber() << ">";
390 case MachineOperand::MO_FrameIndex:
391 OS << "<fi#" << getIndex() << '>';
393 case MachineOperand::MO_ConstantPoolIndex:
394 OS << "<cp#" << getIndex();
395 if (getOffset()) OS << "+" << getOffset();
398 case MachineOperand::MO_TargetIndex:
399 OS << "<ti#" << getIndex();
400 if (getOffset()) OS << "+" << getOffset();
403 case MachineOperand::MO_JumpTableIndex:
404 OS << "<jt#" << getIndex() << '>';
406 case MachineOperand::MO_GlobalAddress:
408 getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
409 if (getOffset()) OS << "+" << getOffset();
412 case MachineOperand::MO_ExternalSymbol:
413 OS << "<es:" << getSymbolName();
414 if (getOffset()) OS << "+" << getOffset();
417 case MachineOperand::MO_BlockAddress:
419 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
420 if (getOffset()) OS << "+" << getOffset();
423 case MachineOperand::MO_RegisterMask: {
424 unsigned NumRegsInMask = 0;
425 unsigned NumRegsEmitted = 0;
427 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
428 unsigned MaskWord = i / 32;
429 unsigned MaskBit = i % 32;
430 if (getRegMask()[MaskWord] & (1 << MaskBit)) {
431 if (PrintWholeRegMask || NumRegsEmitted <= 10) {
432 OS << " " << PrintReg(i, TRI);
438 if (NumRegsEmitted != NumRegsInMask)
439 OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
443 case MachineOperand::MO_RegisterLiveOut:
444 OS << "<regliveout>";
446 case MachineOperand::MO_Metadata:
448 getMetadata()->printAsOperand(OS, MST);
451 case MachineOperand::MO_MCSymbol:
452 OS << "<MCSym=" << *getMCSymbol() << '>';
454 case MachineOperand::MO_CFIIndex:
455 OS << "<call frame instruction>";
459 if (unsigned TF = getTargetFlags())
460 OS << "[TF=" << TF << ']';
463 //===----------------------------------------------------------------------===//
464 // MachineMemOperand Implementation
465 //===----------------------------------------------------------------------===//
467 /// getAddrSpace - Return the LLVM IR address space number that this pointer
469 unsigned MachinePointerInfo::getAddrSpace() const {
470 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
471 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
474 /// getConstantPool - Return a MachinePointerInfo record that refers to the
476 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
477 return MachinePointerInfo(MF.getPSVManager().getConstantPool());
480 /// getFixedStack - Return a MachinePointerInfo record that refers to the
481 /// the specified FrameIndex.
482 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
483 int FI, int64_t Offset) {
484 return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
487 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
488 return MachinePointerInfo(MF.getPSVManager().getJumpTable());
491 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
492 return MachinePointerInfo(MF.getPSVManager().getGOT());
495 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
497 return MachinePointerInfo(MF.getPSVManager().getStack(), Offset);
500 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
501 uint64_t s, unsigned int a,
502 const AAMDNodes &AAInfo,
503 const MDNode *Ranges)
504 : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
505 AAInfo(AAInfo), Ranges(Ranges) {
506 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
507 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
508 "invalid pointer value");
509 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
510 assert((isLoad() || isStore()) && "Not a load/store!");
513 /// Profile - Gather unique data for the object.
515 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
516 ID.AddInteger(getOffset());
518 ID.AddPointer(getOpaqueValue());
519 ID.AddInteger(getFlags());
520 ID.AddInteger(getBaseAlignment());
523 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
524 // The Value and Offset may differ due to CSE. But the flags and size
525 // should be the same.
526 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
527 assert(MMO->getSize() == getSize() && "Size mismatch!");
529 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
530 // Update the alignment value.
531 BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
532 // Also update the base and offset, because the new alignment may
533 // not be applicable with the old ones.
534 PtrInfo = MMO->PtrInfo;
538 /// getAlignment - Return the minimum known alignment in bytes of the
539 /// actual memory reference.
540 uint64_t MachineMemOperand::getAlignment() const {
541 return MinAlign(getBaseAlignment(), getOffset());
544 void MachineMemOperand::print(raw_ostream &OS) const {
545 ModuleSlotTracker DummyMST(nullptr);
548 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
549 assert((isLoad() || isStore()) &&
550 "SV has to be a load, store or both.");
561 // Print the address information.
563 if (const Value *V = getValue())
564 V->printAsOperand(OS, /*PrintType=*/false, MST);
565 else if (const PseudoSourceValue *PSV = getPseudoValue())
566 PSV->printCustom(OS);
570 unsigned AS = getAddrSpace();
572 OS << "(addrspace=" << AS << ')';
574 // If the alignment of the memory reference itself differs from the alignment
575 // of the base pointer, print the base alignment explicitly, next to the base
577 if (getBaseAlignment() != getAlignment())
578 OS << "(align=" << getBaseAlignment() << ")";
580 if (getOffset() != 0)
581 OS << "+" << getOffset();
584 // Print the alignment of the reference.
585 if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
586 OS << "(align=" << getAlignment() << ")";
589 if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
591 if (TBAAInfo->getNumOperands() > 0)
592 TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
598 // Print AA scope info.
599 if (const MDNode *ScopeInfo = getAAInfo().Scope) {
600 OS << "(alias.scope=";
601 if (ScopeInfo->getNumOperands() > 0)
602 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
603 ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
612 // Print AA noalias scope info.
613 if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
615 if (NoAliasInfo->getNumOperands() > 0)
616 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
617 NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
626 // Print nontemporal info.
628 OS << "(nontemporal)";
634 //===----------------------------------------------------------------------===//
635 // MachineInstr Implementation
636 //===----------------------------------------------------------------------===//
638 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
639 if (MCID->ImplicitDefs)
640 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
642 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
643 if (MCID->ImplicitUses)
644 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
646 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
649 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
650 /// implicit operands. It reserves space for the number of operands specified by
652 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
653 DebugLoc dl, bool NoImp)
654 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0), Flags(0),
655 AsmPrinterFlags(0), NumMemRefs(0), MemRefs(nullptr),
656 debugLoc(std::move(dl))
657 #ifdef LLVM_BUILD_GLOBAL_ISEL
662 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
664 // Reserve space for the expected number of operands.
665 if (unsigned NumOps = MCID->getNumOperands() +
666 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
667 CapOperands = OperandCapacity::get(NumOps);
668 Operands = MF.allocateOperandArray(CapOperands);
672 addImplicitDefUseOperands(MF);
675 /// MachineInstr ctor - Copies MachineInstr arg exactly
677 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
678 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
679 Flags(0), AsmPrinterFlags(0), NumMemRefs(MI.NumMemRefs),
680 MemRefs(MI.MemRefs), debugLoc(MI.getDebugLoc())
681 #ifdef LLVM_BUILD_GLOBAL_ISEL
686 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
688 CapOperands = OperandCapacity::get(MI.getNumOperands());
689 Operands = MF.allocateOperandArray(CapOperands);
692 for (const MachineOperand &MO : MI.operands())
695 // Copy all the sensible flags.
699 /// getRegInfo - If this instruction is embedded into a MachineFunction,
700 /// return the MachineRegisterInfo object for the current function, otherwise
702 MachineRegisterInfo *MachineInstr::getRegInfo() {
703 if (MachineBasicBlock *MBB = getParent())
704 return &MBB->getParent()->getRegInfo();
708 // Implement dummy setter and getter for type when
709 // global-isel is not built.
710 // The proper implementation is WIP and is tracked here:
712 #ifndef LLVM_BUILD_GLOBAL_ISEL
713 void MachineInstr::setType(Type *Ty) {}
715 Type *MachineInstr::getType() const { return nullptr; }
718 void MachineInstr::setType(Type *Ty) {
719 assert((!Ty || isPreISelGenericOpcode(getOpcode())) &&
720 "Non generic instructions are not supposed to be typed");
724 Type *MachineInstr::getType() const { return Ty; }
725 #endif // LLVM_BUILD_GLOBAL_ISEL
727 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
728 /// this instruction from their respective use lists. This requires that the
729 /// operands already be on their use lists.
730 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
731 for (MachineOperand &MO : operands())
733 MRI.removeRegOperandFromUseList(&MO);
736 /// AddRegOperandsToUseLists - Add all of the register operands in
737 /// this instruction from their respective use lists. This requires that the
738 /// operands not be on their use lists yet.
739 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
740 for (MachineOperand &MO : operands())
742 MRI.addRegOperandToUseList(&MO);
745 void MachineInstr::addOperand(const MachineOperand &Op) {
746 MachineBasicBlock *MBB = getParent();
747 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
748 MachineFunction *MF = MBB->getParent();
749 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
753 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
754 /// ranges. If MRI is non-null also update use-def chains.
755 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
756 unsigned NumOps, MachineRegisterInfo *MRI) {
758 return MRI->moveOperands(Dst, Src, NumOps);
760 // MachineOperand is a trivially copyable type so we can just use memmove.
761 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
764 /// addOperand - Add the specified operand to the instruction. If it is an
765 /// implicit operand, it is added to the end of the operand list. If it is
766 /// an explicit operand it is added at the end of the explicit operand list
767 /// (before the first implicit operand).
768 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
769 assert(MCID && "Cannot add operands before providing an instr descriptor");
771 // Check if we're adding one of our existing operands.
772 if (&Op >= Operands && &Op < Operands + NumOperands) {
773 // This is unusual: MI->addOperand(MI->getOperand(i)).
774 // If adding Op requires reallocating or moving existing operands around,
775 // the Op reference could go stale. Support it by copying Op.
776 MachineOperand CopyOp(Op);
777 return addOperand(MF, CopyOp);
780 // Find the insert location for the new operand. Implicit registers go at
781 // the end, everything else goes before the implicit regs.
783 // FIXME: Allow mixed explicit and implicit operands on inline asm.
784 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
785 // implicit-defs, but they must not be moved around. See the FIXME in
787 unsigned OpNo = getNumOperands();
788 bool isImpReg = Op.isReg() && Op.isImplicit();
789 if (!isImpReg && !isInlineAsm()) {
790 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
792 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
797 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
798 // OpNo now points as the desired insertion point. Unless this is a variadic
799 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
800 // RegMask operands go between the explicit and implicit operands.
801 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
802 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
803 "Trying to add an operand to a machine instr that is already done!");
806 MachineRegisterInfo *MRI = getRegInfo();
808 // Determine if the Operands array needs to be reallocated.
809 // Save the old capacity and operand array.
810 OperandCapacity OldCap = CapOperands;
811 MachineOperand *OldOperands = Operands;
812 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
813 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
814 Operands = MF.allocateOperandArray(CapOperands);
815 // Move the operands before the insertion point.
817 moveOperands(Operands, OldOperands, OpNo, MRI);
820 // Move the operands following the insertion point.
821 if (OpNo != NumOperands)
822 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
826 // Deallocate the old operand array.
827 if (OldOperands != Operands && OldOperands)
828 MF.deallocateOperandArray(OldCap, OldOperands);
830 // Copy Op into place. It still needs to be inserted into the MRI use lists.
831 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
832 NewMO->ParentMI = this;
834 // When adding a register operand, tell MRI about it.
835 if (NewMO->isReg()) {
836 // Ensure isOnRegUseList() returns false, regardless of Op's status.
837 NewMO->Contents.Reg.Prev = nullptr;
838 // Ignore existing ties. This is not a property that can be copied.
840 // Add the new operand to MRI, but only for instructions in an MBB.
842 MRI->addRegOperandToUseList(NewMO);
843 // The MCID operand information isn't accurate until we start adding
844 // explicit operands. The implicit operands are added first, then the
845 // explicits are inserted before them.
847 // Tie uses to defs as indicated in MCInstrDesc.
848 if (NewMO->isUse()) {
849 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
851 tieOperands(DefIdx, OpNo);
853 // If the register operand is flagged as early, mark the operand as such.
854 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
855 NewMO->setIsEarlyClobber(true);
860 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
861 /// fewer operand than it started with.
863 void MachineInstr::RemoveOperand(unsigned OpNo) {
864 assert(OpNo < getNumOperands() && "Invalid operand number");
865 untieRegOperand(OpNo);
868 // Moving tied operands would break the ties.
869 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
870 if (Operands[i].isReg())
871 assert(!Operands[i].isTied() && "Cannot move tied operands");
874 MachineRegisterInfo *MRI = getRegInfo();
875 if (MRI && Operands[OpNo].isReg())
876 MRI->removeRegOperandFromUseList(Operands + OpNo);
878 // Don't call the MachineOperand destructor. A lot of this code depends on
879 // MachineOperand having a trivial destructor anyway, and adding a call here
880 // wouldn't make it 'destructor-correct'.
882 if (unsigned N = NumOperands - 1 - OpNo)
883 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
887 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
888 /// This function should be used only occasionally. The setMemRefs function
889 /// is the primary method for setting up a MachineInstr's MemRefs list.
890 void MachineInstr::addMemOperand(MachineFunction &MF,
891 MachineMemOperand *MO) {
892 mmo_iterator OldMemRefs = MemRefs;
893 unsigned OldNumMemRefs = NumMemRefs;
895 unsigned NewNum = NumMemRefs + 1;
896 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
898 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
899 NewMemRefs[NewNum - 1] = MO;
900 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
903 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
905 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
906 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
907 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
908 if ((E1 - I1) != (E2 - I2))
910 for (; I1 != E1; ++I1, ++I2) {
917 std::pair<MachineInstr::mmo_iterator, unsigned>
918 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
920 // If either of the incoming memrefs are empty, we must be conservative and
921 // treat this as if we've exhausted our space for memrefs and dropped them.
922 if (memoperands_empty() || Other.memoperands_empty())
923 return std::make_pair(nullptr, 0);
925 // If both instructions have identical memrefs, we don't need to merge them.
926 // Since many instructions have a single memref, and we tend to merge things
927 // like pairs of loads from the same location, this catches a large number of
928 // cases in practice.
929 if (hasIdenticalMMOs(*this, Other))
930 return std::make_pair(MemRefs, NumMemRefs);
932 // TODO: consider uniquing elements within the operand lists to reduce
933 // space usage and fall back to conservative information less often.
934 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
936 // If we don't have enough room to store this many memrefs, be conservative
937 // and drop them. Otherwise, we'd fail asserts when trying to add them to
938 // the new instruction.
939 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
940 return std::make_pair(nullptr, 0);
942 MachineFunction *MF = getParent()->getParent();
943 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
944 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
946 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
948 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
951 return std::make_pair(MemBegin, CombinedNumMemRefs);
954 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
955 assert(!isBundledWithPred() && "Must be called on bundle header");
956 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
957 if (MII->getDesc().getFlags() & Mask) {
958 if (Type == AnyInBundle)
961 if (Type == AllInBundle && !MII->isBundle())
964 // This was the last instruction in the bundle.
965 if (!MII->isBundledWithSucc())
966 return Type == AllInBundle;
970 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
971 MICheckType Check) const {
972 // If opcodes or number of operands are not the same then the two
973 // instructions are obviously not identical.
974 if (Other.getOpcode() != getOpcode() ||
975 Other.getNumOperands() != getNumOperands())
979 // Both instructions are bundles, compare MIs inside the bundle.
980 MachineBasicBlock::const_instr_iterator I1 = getIterator();
981 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
982 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
983 MachineBasicBlock::const_instr_iterator E2 = Other.getParent()->instr_end();
984 while (++I1 != E1 && I1->isInsideBundle()) {
986 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(*I2, Check))
991 // Check operands to make sure they match.
992 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
993 const MachineOperand &MO = getOperand(i);
994 const MachineOperand &OMO = Other.getOperand(i);
996 if (!MO.isIdenticalTo(OMO))
1001 // Clients may or may not want to ignore defs when testing for equality.
1002 // For example, machine CSE pass only cares about finding common
1003 // subexpressions, so it's safe to ignore virtual register defs.
1005 if (Check == IgnoreDefs)
1007 else if (Check == IgnoreVRegDefs) {
1008 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1009 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
1010 if (MO.getReg() != OMO.getReg())
1013 if (!MO.isIdenticalTo(OMO))
1015 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
1019 if (!MO.isIdenticalTo(OMO))
1021 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
1025 // If DebugLoc does not match then two dbg.values are not identical.
1027 if (getDebugLoc() && Other.getDebugLoc() &&
1028 getDebugLoc() != Other.getDebugLoc())
1033 MachineInstr *MachineInstr::removeFromParent() {
1034 assert(getParent() && "Not embedded in a basic block!");
1035 return getParent()->remove(this);
1038 MachineInstr *MachineInstr::removeFromBundle() {
1039 assert(getParent() && "Not embedded in a basic block!");
1040 return getParent()->remove_instr(this);
1043 void MachineInstr::eraseFromParent() {
1044 assert(getParent() && "Not embedded in a basic block!");
1045 getParent()->erase(this);
1048 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1049 assert(getParent() && "Not embedded in a basic block!");
1050 MachineBasicBlock *MBB = getParent();
1051 MachineFunction *MF = MBB->getParent();
1052 assert(MF && "Not embedded in a function!");
1054 MachineInstr *MI = (MachineInstr *)this;
1055 MachineRegisterInfo &MRI = MF->getRegInfo();
1057 for (const MachineOperand &MO : MI->operands()) {
1058 if (!MO.isReg() || !MO.isDef())
1060 unsigned Reg = MO.getReg();
1061 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1063 MRI.markUsesInDebugValueAsUndef(Reg);
1065 MI->eraseFromParent();
1068 void MachineInstr::eraseFromBundle() {
1069 assert(getParent() && "Not embedded in a basic block!");
1070 getParent()->erase_instr(this);
1073 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1075 unsigned MachineInstr::getNumExplicitOperands() const {
1076 unsigned NumOperands = MCID->getNumOperands();
1077 if (!MCID->isVariadic())
1080 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1081 const MachineOperand &MO = getOperand(i);
1082 if (!MO.isReg() || !MO.isImplicit())
1088 void MachineInstr::bundleWithPred() {
1089 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1090 setFlag(BundledPred);
1091 MachineBasicBlock::instr_iterator Pred = getIterator();
1093 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1094 Pred->setFlag(BundledSucc);
1097 void MachineInstr::bundleWithSucc() {
1098 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1099 setFlag(BundledSucc);
1100 MachineBasicBlock::instr_iterator Succ = getIterator();
1102 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1103 Succ->setFlag(BundledPred);
1106 void MachineInstr::unbundleFromPred() {
1107 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1108 clearFlag(BundledPred);
1109 MachineBasicBlock::instr_iterator Pred = getIterator();
1111 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1112 Pred->clearFlag(BundledSucc);
1115 void MachineInstr::unbundleFromSucc() {
1116 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1117 clearFlag(BundledSucc);
1118 MachineBasicBlock::instr_iterator Succ = getIterator();
1120 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1121 Succ->clearFlag(BundledPred);
1124 bool MachineInstr::isStackAligningInlineAsm() const {
1125 if (isInlineAsm()) {
1126 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1127 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1133 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1134 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1135 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1136 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1139 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1140 unsigned *GroupNo) const {
1141 assert(isInlineAsm() && "Expected an inline asm instruction");
1142 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1144 // Ignore queries about the initial operands.
1145 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1150 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1152 const MachineOperand &FlagMO = getOperand(i);
1153 // If we reach the implicit register operands, stop looking.
1154 if (!FlagMO.isImm())
1156 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1157 if (i + NumOps > OpIdx) {
1167 const DILocalVariable *MachineInstr::getDebugVariable() const {
1168 assert(isDebugValue() && "not a DBG_VALUE");
1169 return cast<DILocalVariable>(getOperand(2).getMetadata());
1172 const DIExpression *MachineInstr::getDebugExpression() const {
1173 assert(isDebugValue() && "not a DBG_VALUE");
1174 return cast<DIExpression>(getOperand(3).getMetadata());
1177 const TargetRegisterClass*
1178 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1179 const TargetInstrInfo *TII,
1180 const TargetRegisterInfo *TRI) const {
1181 assert(getParent() && "Can't have an MBB reference here!");
1182 assert(getParent()->getParent() && "Can't have an MF reference here!");
1183 const MachineFunction &MF = *getParent()->getParent();
1185 // Most opcodes have fixed constraints in their MCInstrDesc.
1187 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1189 if (!getOperand(OpIdx).isReg())
1192 // For tied uses on inline asm, get the constraint from the def.
1194 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1197 // Inline asm stores register class constraints in the flag word.
1198 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1202 unsigned Flag = getOperand(FlagIdx).getImm();
1204 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1205 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1206 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1207 InlineAsm::hasRegClassConstraint(Flag, RCID))
1208 return TRI->getRegClass(RCID);
1210 // Assume that all registers in a memory operand are pointers.
1211 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1212 return TRI->getPointerRegClass(MF);
1217 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1218 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1219 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1220 // Check every operands inside the bundle if we have
1223 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1225 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1226 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1228 // Otherwise, just check the current operands.
1229 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1230 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1234 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1235 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1236 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1237 assert(CurRC && "Invalid initial register class");
1238 // Check if Reg is constrained by some of its use/def from MI.
1239 const MachineOperand &MO = getOperand(OpIdx);
1240 if (!MO.isReg() || MO.getReg() != Reg)
1242 // If yes, accumulate the constraints through the operand.
1243 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1246 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1247 unsigned OpIdx, const TargetRegisterClass *CurRC,
1248 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1249 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1250 const MachineOperand &MO = getOperand(OpIdx);
1251 assert(MO.isReg() &&
1252 "Cannot get register constraints for non-register operand");
1253 assert(CurRC && "Invalid initial register class");
1254 if (unsigned SubIdx = MO.getSubReg()) {
1256 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1258 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1260 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1264 /// Return the number of instructions inside the MI bundle, not counting the
1265 /// header instruction.
1266 unsigned MachineInstr::getBundleSize() const {
1267 MachineBasicBlock::const_instr_iterator I = getIterator();
1269 while (I->isBundledWithSucc()) {
1276 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1277 /// the given register (not considering sub/super-registers).
1278 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1279 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1280 const MachineOperand &MO = getOperand(i);
1281 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1287 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1288 /// the specific register or -1 if it is not found. It further tightens
1289 /// the search criteria to a use that kills the register if isKill is true.
1290 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1291 const TargetRegisterInfo *TRI) const {
1292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1293 const MachineOperand &MO = getOperand(i);
1294 if (!MO.isReg() || !MO.isUse())
1296 unsigned MOReg = MO.getReg();
1301 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1302 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1303 TRI->isSubRegister(MOReg, Reg)))
1304 if (!isKill || MO.isKill())
1310 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1311 /// indicating if this instruction reads or writes Reg. This also considers
1312 /// partial defines.
1313 std::pair<bool,bool>
1314 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1315 SmallVectorImpl<unsigned> *Ops) const {
1316 bool PartDef = false; // Partial redefine.
1317 bool FullDef = false; // Full define.
1320 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1321 const MachineOperand &MO = getOperand(i);
1322 if (!MO.isReg() || MO.getReg() != Reg)
1327 Use |= !MO.isUndef();
1328 else if (MO.getSubReg() && !MO.isUndef())
1329 // A partial <def,undef> doesn't count as reading the register.
1334 // A partial redefine uses Reg unless there is also a full define.
1335 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1338 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1339 /// the specified register or -1 if it is not found. If isDead is true, defs
1340 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1341 /// also checks if there is a def of a super-register.
1343 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1344 const TargetRegisterInfo *TRI) const {
1345 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1346 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1347 const MachineOperand &MO = getOperand(i);
1348 // Accept regmask operands when Overlap is set.
1349 // Ignore them when looking for a specific def operand (Overlap == false).
1350 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1352 if (!MO.isReg() || !MO.isDef())
1354 unsigned MOReg = MO.getReg();
1355 bool Found = (MOReg == Reg);
1356 if (!Found && TRI && isPhys &&
1357 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1359 Found = TRI->regsOverlap(MOReg, Reg);
1361 Found = TRI->isSubRegister(MOReg, Reg);
1363 if (Found && (!isDead || MO.isDead()))
1369 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1370 /// operand list that is used to represent the predicate. It returns -1 if
1372 int MachineInstr::findFirstPredOperandIdx() const {
1373 // Don't call MCID.findFirstPredOperandIdx() because this variant
1374 // is sometimes called on an instruction that's not yet complete, and
1375 // so the number of operands is less than the MCID indicates. In
1376 // particular, the PTX target does this.
1377 const MCInstrDesc &MCID = getDesc();
1378 if (MCID.isPredicable()) {
1379 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1380 if (MCID.OpInfo[i].isPredicate())
1387 // MachineOperand::TiedTo is 4 bits wide.
1388 const unsigned TiedMax = 15;
1390 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1392 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1393 /// field. TiedTo can have these values:
1395 /// 0: Operand is not tied to anything.
1396 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1397 /// TiedMax: Tied to an operand >= TiedMax-1.
1399 /// The tied def must be one of the first TiedMax operands on a normal
1400 /// instruction. INLINEASM instructions allow more tied defs.
1402 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1403 MachineOperand &DefMO = getOperand(DefIdx);
1404 MachineOperand &UseMO = getOperand(UseIdx);
1405 assert(DefMO.isDef() && "DefIdx must be a def operand");
1406 assert(UseMO.isUse() && "UseIdx must be a use operand");
1407 assert(!DefMO.isTied() && "Def is already tied to another use");
1408 assert(!UseMO.isTied() && "Use is already tied to another def");
1410 if (DefIdx < TiedMax)
1411 UseMO.TiedTo = DefIdx + 1;
1413 // Inline asm can use the group descriptors to find tied operands, but on
1414 // normal instruction, the tied def must be within the first TiedMax
1416 assert(isInlineAsm() && "DefIdx out of range");
1417 UseMO.TiedTo = TiedMax;
1420 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1421 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1424 /// Given the index of a tied register operand, find the operand it is tied to.
1425 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1426 /// which must exist.
1427 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1428 const MachineOperand &MO = getOperand(OpIdx);
1429 assert(MO.isTied() && "Operand isn't tied");
1431 // Normally TiedTo is in range.
1432 if (MO.TiedTo < TiedMax)
1433 return MO.TiedTo - 1;
1435 // Uses on normal instructions can be out of range.
1436 if (!isInlineAsm()) {
1437 // Normal tied defs must be in the 0..TiedMax-1 range.
1440 // MO is a def. Search for the tied use.
1441 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1442 const MachineOperand &UseMO = getOperand(i);
1443 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1446 llvm_unreachable("Can't find tied use");
1449 // Now deal with inline asm by parsing the operand group descriptor flags.
1450 // Find the beginning of each operand group.
1451 SmallVector<unsigned, 8> GroupIdx;
1452 unsigned OpIdxGroup = ~0u;
1454 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1456 const MachineOperand &FlagMO = getOperand(i);
1457 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1458 unsigned CurGroup = GroupIdx.size();
1459 GroupIdx.push_back(i);
1460 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1461 // OpIdx belongs to this operand group.
1462 if (OpIdx > i && OpIdx < i + NumOps)
1463 OpIdxGroup = CurGroup;
1465 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1467 // Operands in this group are tied to operands in TiedGroup which must be
1468 // earlier. Find the number of operands between the two groups.
1469 unsigned Delta = i - GroupIdx[TiedGroup];
1471 // OpIdx is a use tied to TiedGroup.
1472 if (OpIdxGroup == CurGroup)
1473 return OpIdx - Delta;
1475 // OpIdx is a def tied to this use group.
1476 if (OpIdxGroup == TiedGroup)
1477 return OpIdx + Delta;
1479 llvm_unreachable("Invalid tied operand on inline asm");
1482 /// clearKillInfo - Clears kill flags on all operands.
1484 void MachineInstr::clearKillInfo() {
1485 for (MachineOperand &MO : operands()) {
1486 if (MO.isReg() && MO.isUse())
1487 MO.setIsKill(false);
1491 void MachineInstr::substituteRegister(unsigned FromReg,
1494 const TargetRegisterInfo &RegInfo) {
1495 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1497 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1498 for (MachineOperand &MO : operands()) {
1499 if (!MO.isReg() || MO.getReg() != FromReg)
1501 MO.substPhysReg(ToReg, RegInfo);
1504 for (MachineOperand &MO : operands()) {
1505 if (!MO.isReg() || MO.getReg() != FromReg)
1507 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1512 /// isSafeToMove - Return true if it is safe to move this instruction. If
1513 /// SawStore is set to true, it means that there is a store (or call) between
1514 /// the instruction's location and its intended destination.
1515 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1516 // Ignore stuff that we obviously can't move.
1518 // Treat volatile loads as stores. This is not strictly necessary for
1519 // volatiles, but it is required for atomic loads. It is not allowed to move
1520 // a load across an atomic load with Ordering > Monotonic.
1521 if (mayStore() || isCall() ||
1522 (mayLoad() && hasOrderedMemoryRef())) {
1527 if (isPosition() || isDebugValue() || isTerminator() ||
1528 hasUnmodeledSideEffects())
1531 // See if this instruction does a load. If so, we have to guarantee that the
1532 // loaded value doesn't change between the load and the its intended
1533 // destination. The check for isInvariantLoad gives the targe the chance to
1534 // classify the load as always returning a constant, e.g. a constant pool
1536 if (mayLoad() && !isInvariantLoad(AA))
1537 // Otherwise, this is a real load. If there is a store between the load and
1538 // end of block, we can't move it.
1544 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1545 /// or volatile memory reference, or if the information describing the memory
1546 /// reference is not available. Return false if it is known to have no ordered
1547 /// memory references.
1548 bool MachineInstr::hasOrderedMemoryRef() const {
1549 // An instruction known never to access memory won't have a volatile access.
1553 !hasUnmodeledSideEffects())
1556 // Otherwise, if the instruction has no memory reference information,
1557 // conservatively assume it wasn't preserved.
1558 if (memoperands_empty())
1561 // Check if any of our memory operands are ordered.
1562 return any_of(memoperands(), [](const MachineMemOperand *MMO) {
1563 return !MMO->isUnordered();
1567 /// isInvariantLoad - Return true if this instruction is loading from a
1568 /// location whose value is invariant across the function. For example,
1569 /// loading a value from the constant pool or from the argument area
1570 /// of a function if it does not change. This should only return true of
1571 /// *all* loads the instruction does are invariant (if it does multiple loads).
1572 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1573 // If the instruction doesn't load at all, it isn't an invariant load.
1577 // If the instruction has lost its memoperands, conservatively assume that
1578 // it may not be an invariant load.
1579 if (memoperands_empty())
1582 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1584 for (MachineMemOperand *MMO : memoperands()) {
1585 if (MMO->isVolatile()) return false;
1586 if (MMO->isStore()) return false;
1587 if (MMO->isInvariant()) continue;
1589 // A load from a constant PseudoSourceValue is invariant.
1590 if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1591 if (PSV->isConstant(MFI))
1594 if (const Value *V = MMO->getValue()) {
1595 // If we have an AliasAnalysis, ask it whether the memory is constant.
1597 AA->pointsToConstantMemory(
1598 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1602 // Otherwise assume conservatively.
1606 // Everything checks out.
1610 /// isConstantValuePHI - If the specified instruction is a PHI that always
1611 /// merges together the same virtual register, return the register, otherwise
1613 unsigned MachineInstr::isConstantValuePHI() const {
1616 assert(getNumOperands() >= 3 &&
1617 "It's illegal to have a PHI without source operands");
1619 unsigned Reg = getOperand(1).getReg();
1620 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1621 if (getOperand(i).getReg() != Reg)
1626 bool MachineInstr::hasUnmodeledSideEffects() const {
1627 if (hasProperty(MCID::UnmodeledSideEffects))
1629 if (isInlineAsm()) {
1630 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1631 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1638 bool MachineInstr::isLoadFoldBarrier() const {
1639 return mayStore() || isCall() || hasUnmodeledSideEffects();
1642 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1644 bool MachineInstr::allDefsAreDead() const {
1645 for (const MachineOperand &MO : operands()) {
1646 if (!MO.isReg() || MO.isUse())
1654 /// copyImplicitOps - Copy implicit register operands from specified
1655 /// instruction to this instruction.
1656 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1657 const MachineInstr &MI) {
1658 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1660 const MachineOperand &MO = MI.getOperand(i);
1661 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1666 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1667 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1668 dbgs() << " " << *this;
1672 void MachineInstr::print(raw_ostream &OS, bool SkipOpers) const {
1673 const Module *M = nullptr;
1674 if (const MachineBasicBlock *MBB = getParent())
1675 if (const MachineFunction *MF = MBB->getParent())
1676 M = MF->getFunction()->getParent();
1678 ModuleSlotTracker MST(M);
1679 print(OS, MST, SkipOpers);
1682 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1683 bool SkipOpers) const {
1684 // We can be a bit tidier if we know the MachineFunction.
1685 const MachineFunction *MF = nullptr;
1686 const TargetRegisterInfo *TRI = nullptr;
1687 const MachineRegisterInfo *MRI = nullptr;
1688 const TargetInstrInfo *TII = nullptr;
1689 if (const MachineBasicBlock *MBB = getParent()) {
1690 MF = MBB->getParent();
1692 MRI = &MF->getRegInfo();
1693 TRI = MF->getSubtarget().getRegisterInfo();
1694 TII = MF->getSubtarget().getInstrInfo();
1698 // Save a list of virtual registers.
1699 SmallVector<unsigned, 8> VirtRegs;
1701 // Print explicitly defined operands on the left of an assignment syntax.
1702 unsigned StartOp = 0, e = getNumOperands();
1703 for (; StartOp < e && getOperand(StartOp).isReg() &&
1704 getOperand(StartOp).isDef() &&
1705 !getOperand(StartOp).isImplicit();
1707 if (StartOp != 0) OS << ", ";
1708 getOperand(StartOp).print(OS, MST, TRI);
1709 unsigned Reg = getOperand(StartOp).getReg();
1710 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1711 VirtRegs.push_back(Reg);
1713 if (MRI && (Size = MRI->getSize(Reg)))
1714 OS << '(' << Size << ')';
1721 // Print the opcode name.
1723 OS << TII->getName(getOpcode());
1729 getType()->print(OS, /*IsForDebug*/ false, /*NoDetails*/ true);
1736 // Print the rest of the operands.
1737 bool OmittedAnyCallClobbers = false;
1738 bool FirstOp = true;
1739 unsigned AsmDescOp = ~0u;
1740 unsigned AsmOpCount = 0;
1742 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1743 // Print asm string.
1745 getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1747 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1748 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1749 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1750 OS << " [sideeffect]";
1751 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1753 if (ExtraInfo & InlineAsm::Extra_MayStore)
1754 OS << " [maystore]";
1755 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1756 OS << " [isconvergent]";
1757 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1758 OS << " [alignstack]";
1759 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1760 OS << " [attdialect]";
1761 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1762 OS << " [inteldialect]";
1764 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1768 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1769 const MachineOperand &MO = getOperand(i);
1771 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1772 VirtRegs.push_back(MO.getReg());
1774 // Omit call-clobbered registers which aren't used anywhere. This makes
1775 // call instructions much less noisy on targets where calls clobber lots
1776 // of registers. Don't rely on MO.isDead() because we may be called before
1777 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1778 if (MRI && isCall() &&
1779 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1780 unsigned Reg = MO.getReg();
1781 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1782 if (MRI->use_empty(Reg)) {
1783 bool HasAliasLive = false;
1784 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
1785 unsigned AliasReg = *AI;
1786 if (!MRI->use_empty(AliasReg)) {
1787 HasAliasLive = true;
1791 if (!HasAliasLive) {
1792 OmittedAnyCallClobbers = true;
1799 if (FirstOp) FirstOp = false; else OS << ",";
1801 if (i < getDesc().NumOperands) {
1802 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1803 if (MCOI.isPredicate())
1805 if (MCOI.isOptionalDef())
1808 if (isDebugValue() && MO.isMetadata()) {
1809 // Pretty print DBG_VALUE instructions.
1810 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1811 if (DIV && !DIV->getName().empty())
1812 OS << "!\"" << DIV->getName() << '\"';
1814 MO.print(OS, MST, TRI);
1815 } else if (TRI && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1816 OS << TRI->getSubRegIndexName(MO.getImm());
1817 } else if (i == AsmDescOp && MO.isImm()) {
1818 // Pretty print the inline asm operand descriptor.
1819 OS << '$' << AsmOpCount++;
1820 unsigned Flag = MO.getImm();
1821 switch (InlineAsm::getKind(Flag)) {
1822 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1823 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1824 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1825 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1826 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1827 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1828 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1832 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1833 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1835 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1837 OS << ":RC" << RCID;
1840 if (InlineAsm::isMemKind(Flag)) {
1841 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1843 case InlineAsm::Constraint_es: OS << ":es"; break;
1844 case InlineAsm::Constraint_i: OS << ":i"; break;
1845 case InlineAsm::Constraint_m: OS << ":m"; break;
1846 case InlineAsm::Constraint_o: OS << ":o"; break;
1847 case InlineAsm::Constraint_v: OS << ":v"; break;
1848 case InlineAsm::Constraint_Q: OS << ":Q"; break;
1849 case InlineAsm::Constraint_R: OS << ":R"; break;
1850 case InlineAsm::Constraint_S: OS << ":S"; break;
1851 case InlineAsm::Constraint_T: OS << ":T"; break;
1852 case InlineAsm::Constraint_Um: OS << ":Um"; break;
1853 case InlineAsm::Constraint_Un: OS << ":Un"; break;
1854 case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1855 case InlineAsm::Constraint_Us: OS << ":Us"; break;
1856 case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1857 case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1858 case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1859 case InlineAsm::Constraint_X: OS << ":X"; break;
1860 case InlineAsm::Constraint_Z: OS << ":Z"; break;
1861 case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1862 case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1863 default: OS << ":?"; break;
1867 unsigned TiedTo = 0;
1868 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1869 OS << " tiedto:$" << TiedTo;
1873 // Compute the index of the next operand descriptor.
1874 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1876 MO.print(OS, MST, TRI);
1879 // Briefly indicate whether any call clobbers were omitted.
1880 if (OmittedAnyCallClobbers) {
1881 if (!FirstOp) OS << ",";
1885 bool HaveSemi = false;
1886 const unsigned PrintableFlags = FrameSetup | FrameDestroy;
1887 if (Flags & PrintableFlags) {
1894 if (Flags & FrameSetup)
1897 if (Flags & FrameDestroy)
1898 OS << "FrameDestroy";
1901 if (!memoperands_empty()) {
1908 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1910 (*i)->print(OS, MST);
1911 if (std::next(i) != e)
1916 // Print the regclass of any virtual registers encountered.
1917 if (MRI && !VirtRegs.empty()) {
1922 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1923 const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
1926 // Generic virtual registers do not have register classes.
1927 if (RC.is<const RegisterBank *>())
1928 OS << " " << RC.get<const RegisterBank *>()->getName();
1931 << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
1932 OS << ':' << PrintReg(VirtRegs[i]);
1933 for (unsigned j = i+1; j != VirtRegs.size();) {
1934 if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
1938 if (VirtRegs[i] != VirtRegs[j])
1939 OS << "," << PrintReg(VirtRegs[j]);
1940 VirtRegs.erase(VirtRegs.begin()+j);
1945 // Print debug location information.
1946 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
1949 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
1950 OS << " line no:" << DV->getLine();
1951 if (auto *InlinedAt = debugLoc->getInlinedAt()) {
1952 DebugLoc InlinedAtDL(InlinedAt);
1953 if (InlinedAtDL && MF) {
1954 OS << " inlined @[ ";
1955 InlinedAtDL.print(OS);
1959 if (isIndirectDebugValue())
1961 } else if (debugLoc && MF) {
1971 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1972 const TargetRegisterInfo *RegInfo,
1973 bool AddIfNotFound) {
1974 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1975 bool hasAliases = isPhysReg &&
1976 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1978 SmallVector<unsigned,4> DeadOps;
1979 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1980 MachineOperand &MO = getOperand(i);
1981 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1984 // DEBUG_VALUE nodes do not contribute to code generation and should
1985 // always be ignored. Failure to do so may result in trying to modify
1986 // KILL flags on DEBUG_VALUE nodes.
1990 unsigned Reg = MO.getReg();
1994 if (Reg == IncomingReg) {
1997 // The register is already marked kill.
1999 if (isPhysReg && isRegTiedToDefOperand(i))
2000 // Two-address uses of physregs must not be marked kill.
2005 } else if (hasAliases && MO.isKill() &&
2006 TargetRegisterInfo::isPhysicalRegister(Reg)) {
2007 // A super-register kill already exists.
2008 if (RegInfo->isSuperRegister(IncomingReg, Reg))
2010 if (RegInfo->isSubRegister(IncomingReg, Reg))
2011 DeadOps.push_back(i);
2015 // Trim unneeded kill operands.
2016 while (!DeadOps.empty()) {
2017 unsigned OpIdx = DeadOps.back();
2018 if (getOperand(OpIdx).isImplicit())
2019 RemoveOperand(OpIdx);
2021 getOperand(OpIdx).setIsKill(false);
2025 // If not found, this means an alias of one of the operands is killed. Add a
2026 // new implicit operand if required.
2027 if (!Found && AddIfNotFound) {
2028 addOperand(MachineOperand::CreateReg(IncomingReg,
2037 void MachineInstr::clearRegisterKills(unsigned Reg,
2038 const TargetRegisterInfo *RegInfo) {
2039 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2041 for (MachineOperand &MO : operands()) {
2042 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2044 unsigned OpReg = MO.getReg();
2045 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2046 MO.setIsKill(false);
2050 bool MachineInstr::addRegisterDead(unsigned Reg,
2051 const TargetRegisterInfo *RegInfo,
2052 bool AddIfNotFound) {
2053 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2054 bool hasAliases = isPhysReg &&
2055 MCRegAliasIterator(Reg, RegInfo, false).isValid();
2057 SmallVector<unsigned,4> DeadOps;
2058 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2059 MachineOperand &MO = getOperand(i);
2060 if (!MO.isReg() || !MO.isDef())
2062 unsigned MOReg = MO.getReg();
2069 } else if (hasAliases && MO.isDead() &&
2070 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2071 // There exists a super-register that's marked dead.
2072 if (RegInfo->isSuperRegister(Reg, MOReg))
2074 if (RegInfo->isSubRegister(Reg, MOReg))
2075 DeadOps.push_back(i);
2079 // Trim unneeded dead operands.
2080 while (!DeadOps.empty()) {
2081 unsigned OpIdx = DeadOps.back();
2082 if (getOperand(OpIdx).isImplicit())
2083 RemoveOperand(OpIdx);
2085 getOperand(OpIdx).setIsDead(false);
2089 // If not found, this means an alias of one of the operands is dead. Add a
2090 // new implicit operand if required.
2091 if (Found || !AddIfNotFound)
2094 addOperand(MachineOperand::CreateReg(Reg,
2102 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2103 for (MachineOperand &MO : operands()) {
2104 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2106 MO.setIsDead(false);
2110 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2111 for (MachineOperand &MO : operands()) {
2112 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2114 MO.setIsUndef(IsUndef);
2118 void MachineInstr::addRegisterDefined(unsigned Reg,
2119 const TargetRegisterInfo *RegInfo) {
2120 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2121 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2125 for (const MachineOperand &MO : operands()) {
2126 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2127 MO.getSubReg() == 0)
2131 addOperand(MachineOperand::CreateReg(Reg,
2136 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2137 const TargetRegisterInfo &TRI) {
2138 bool HasRegMask = false;
2139 for (MachineOperand &MO : operands()) {
2140 if (MO.isRegMask()) {
2144 if (!MO.isReg() || !MO.isDef()) continue;
2145 unsigned Reg = MO.getReg();
2146 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2147 // If there are no uses, including partial uses, the def is dead.
2148 if (std::none_of(UsedRegs.begin(), UsedRegs.end(),
2149 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2153 // This is a call with a register mask operand.
2154 // Mask clobbers are always dead, so add defs for the non-dead defines.
2156 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2158 addRegisterDefined(*I, &TRI);
2162 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2163 // Build up a buffer of hash code components.
2164 SmallVector<size_t, 8> HashComponents;
2165 HashComponents.reserve(MI->getNumOperands() + 1);
2166 HashComponents.push_back(MI->getOpcode());
2167 for (const MachineOperand &MO : MI->operands()) {
2168 if (MO.isReg() && MO.isDef() &&
2169 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2170 continue; // Skip virtual register defs.
2172 HashComponents.push_back(hash_value(MO));
2174 return hash_combine_range(HashComponents.begin(), HashComponents.end());
2177 void MachineInstr::emitError(StringRef Msg) const {
2178 // Find the source location cookie.
2179 unsigned LocCookie = 0;
2180 const MDNode *LocMD = nullptr;
2181 for (unsigned i = getNumOperands(); i != 0; --i) {
2182 if (getOperand(i-1).isMetadata() &&
2183 (LocMD = getOperand(i-1).getMetadata()) &&
2184 LocMD->getNumOperands() != 0) {
2185 if (const ConstantInt *CI =
2186 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2187 LocCookie = CI->getZExtValue();
2193 if (const MachineBasicBlock *MBB = getParent())
2194 if (const MachineFunction *MF = MBB->getParent())
2195 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2196 report_fatal_error(Msg);
2199 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2200 const MCInstrDesc &MCID, bool IsIndirect,
2201 unsigned Reg, unsigned Offset,
2202 const MDNode *Variable, const MDNode *Expr) {
2203 assert(isa<DILocalVariable>(Variable) && "not a variable");
2204 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2205 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2206 "Expected inlined-at fields to agree");
2208 return BuildMI(MF, DL, MCID)
2209 .addReg(Reg, RegState::Debug)
2211 .addMetadata(Variable)
2214 assert(Offset == 0 && "A direct address cannot have an offset.");
2215 return BuildMI(MF, DL, MCID)
2216 .addReg(Reg, RegState::Debug)
2217 .addReg(0U, RegState::Debug)
2218 .addMetadata(Variable)
2223 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2224 MachineBasicBlock::iterator I,
2225 const DebugLoc &DL, const MCInstrDesc &MCID,
2226 bool IsIndirect, unsigned Reg,
2227 unsigned Offset, const MDNode *Variable,
2228 const MDNode *Expr) {
2229 assert(isa<DILocalVariable>(Variable) && "not a variable");
2230 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2231 MachineFunction &MF = *BB.getParent();
2233 BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr);
2235 return MachineInstrBuilder(MF, MI);