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/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/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/Loads.h"
25 #include "llvm/Analysis/MemoryLocation.h"
26 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineInstrBundle.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/InstrTypes.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Metadata.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/ModuleSlotTracker.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/Value.h"
50 #include "llvm/MC/MCInstrDesc.h"
51 #include "llvm/MC/MCRegisterInfo.h"
52 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/LowLevelTypeImpl.h"
59 #include "llvm/Support/MathExtras.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Target/TargetInstrInfo.h"
62 #include "llvm/Target/TargetIntrinsicInfo.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Target/TargetRegisterInfo.h"
65 #include "llvm/Target/TargetSubtargetInfo.h"
76 static cl::opt<bool> PrintWholeRegMask(
77 "print-whole-regmask",
78 cl::desc("Print the full contents of regmask operands in IR dumps"),
79 cl::init(true), cl::Hidden);
81 //===----------------------------------------------------------------------===//
82 // MachineOperand Implementation
83 //===----------------------------------------------------------------------===//
85 void MachineOperand::setReg(unsigned Reg) {
86 if (getReg() == Reg) return; // No change.
88 // Otherwise, we have to change the register. If this operand is embedded
89 // into a machine function, we need to update the old and new register's
91 if (MachineInstr *MI = getParent())
92 if (MachineBasicBlock *MBB = MI->getParent())
93 if (MachineFunction *MF = MBB->getParent()) {
94 MachineRegisterInfo &MRI = MF->getRegInfo();
95 MRI.removeRegOperandFromUseList(this);
96 SmallContents.RegNo = Reg;
97 MRI.addRegOperandToUseList(this);
101 // Otherwise, just change the register, no problem. :)
102 SmallContents.RegNo = Reg;
105 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
106 const TargetRegisterInfo &TRI) {
107 assert(TargetRegisterInfo::isVirtualRegister(Reg));
108 if (SubIdx && getSubReg())
109 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
115 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
116 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
118 Reg = TRI.getSubReg(Reg, getSubReg());
119 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
120 // That won't happen in legal code.
128 /// Change a def to a use, or a use to a def.
129 void MachineOperand::setIsDef(bool Val) {
130 assert(isReg() && "Wrong MachineOperand accessor");
131 assert((!Val || !isDebug()) && "Marking a debug operation as def");
134 // MRI may keep uses and defs in different list positions.
135 if (MachineInstr *MI = getParent())
136 if (MachineBasicBlock *MBB = MI->getParent())
137 if (MachineFunction *MF = MBB->getParent()) {
138 MachineRegisterInfo &MRI = MF->getRegInfo();
139 MRI.removeRegOperandFromUseList(this);
141 MRI.addRegOperandToUseList(this);
147 // If this operand is currently a register operand, and if this is in a
148 // function, deregister the operand from the register's use/def list.
149 void MachineOperand::removeRegFromUses() {
150 if (!isReg() || !isOnRegUseList())
153 if (MachineInstr *MI = getParent()) {
154 if (MachineBasicBlock *MBB = MI->getParent()) {
155 if (MachineFunction *MF = MBB->getParent())
156 MF->getRegInfo().removeRegOperandFromUseList(this);
161 /// ChangeToImmediate - Replace this operand with a new immediate operand of
162 /// the specified value. If an operand is known to be an immediate already,
163 /// the setImm method should be used.
164 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
165 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
169 OpKind = MO_Immediate;
170 Contents.ImmVal = ImmVal;
173 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
174 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
178 OpKind = MO_FPImmediate;
179 Contents.CFP = FPImm;
182 void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
183 assert((!isReg() || !isTied()) &&
184 "Cannot change a tied operand into an external symbol");
188 OpKind = MO_ExternalSymbol;
189 Contents.OffsetedInfo.Val.SymbolName = SymName;
190 setOffset(0); // Offset is always 0.
191 setTargetFlags(TargetFlags);
194 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
195 assert((!isReg() || !isTied()) &&
196 "Cannot change a tied operand into an MCSymbol");
200 OpKind = MO_MCSymbol;
204 void MachineOperand::ChangeToFrameIndex(int Idx) {
205 assert((!isReg() || !isTied()) &&
206 "Cannot change a tied operand into a FrameIndex");
210 OpKind = MO_FrameIndex;
214 /// ChangeToRegister - Replace this operand with a new register operand of
215 /// the specified value. If an operand is known to be an register already,
216 /// the setReg method should be used.
217 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
218 bool isKill, bool isDead, bool isUndef,
220 MachineRegisterInfo *RegInfo = nullptr;
221 if (MachineInstr *MI = getParent())
222 if (MachineBasicBlock *MBB = MI->getParent())
223 if (MachineFunction *MF = MBB->getParent())
224 RegInfo = &MF->getRegInfo();
225 // If this operand is already a register operand, remove it from the
226 // register's use/def lists.
227 bool WasReg = isReg();
228 if (RegInfo && WasReg)
229 RegInfo->removeRegOperandFromUseList(this);
231 // Change this to a register and set the reg#.
232 OpKind = MO_Register;
233 SmallContents.RegNo = Reg;
234 SubReg_TargetFlags = 0;
240 IsInternalRead = false;
241 IsEarlyClobber = false;
243 // Ensure isOnRegUseList() returns false.
244 Contents.Reg.Prev = nullptr;
245 // Preserve the tie when the operand was already a register.
249 // If this operand is embedded in a function, add the operand to the
250 // register's use/def list.
252 RegInfo->addRegOperandToUseList(this);
255 /// isIdenticalTo - Return true if this operand is identical to the specified
256 /// operand. Note that this should stay in sync with the hash_value overload
258 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
259 if (getType() != Other.getType() ||
260 getTargetFlags() != Other.getTargetFlags())
264 case MachineOperand::MO_Register:
265 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
266 getSubReg() == Other.getSubReg();
267 case MachineOperand::MO_Immediate:
268 return getImm() == Other.getImm();
269 case MachineOperand::MO_CImmediate:
270 return getCImm() == Other.getCImm();
271 case MachineOperand::MO_FPImmediate:
272 return getFPImm() == Other.getFPImm();
273 case MachineOperand::MO_MachineBasicBlock:
274 return getMBB() == Other.getMBB();
275 case MachineOperand::MO_FrameIndex:
276 return getIndex() == Other.getIndex();
277 case MachineOperand::MO_ConstantPoolIndex:
278 case MachineOperand::MO_TargetIndex:
279 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
280 case MachineOperand::MO_JumpTableIndex:
281 return getIndex() == Other.getIndex();
282 case MachineOperand::MO_GlobalAddress:
283 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
284 case MachineOperand::MO_ExternalSymbol:
285 return strcmp(getSymbolName(), Other.getSymbolName()) == 0 &&
286 getOffset() == Other.getOffset();
287 case MachineOperand::MO_BlockAddress:
288 return getBlockAddress() == Other.getBlockAddress() &&
289 getOffset() == Other.getOffset();
290 case MachineOperand::MO_RegisterMask:
291 case MachineOperand::MO_RegisterLiveOut: {
292 // Shallow compare of the two RegMasks
293 const uint32_t *RegMask = getRegMask();
294 const uint32_t *OtherRegMask = Other.getRegMask();
295 if (RegMask == OtherRegMask)
298 // Calculate the size of the RegMask
299 const MachineFunction *MF = getParent()->getParent()->getParent();
300 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
301 unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
303 // Deep compare of the two RegMasks
304 return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
306 case MachineOperand::MO_MCSymbol:
307 return getMCSymbol() == Other.getMCSymbol();
308 case MachineOperand::MO_CFIIndex:
309 return getCFIIndex() == Other.getCFIIndex();
310 case MachineOperand::MO_Metadata:
311 return getMetadata() == Other.getMetadata();
312 case MachineOperand::MO_IntrinsicID:
313 return getIntrinsicID() == Other.getIntrinsicID();
314 case MachineOperand::MO_Predicate:
315 return getPredicate() == Other.getPredicate();
317 llvm_unreachable("Invalid machine operand type");
320 // Note: this must stay exactly in sync with isIdenticalTo above.
321 hash_code llvm::hash_value(const MachineOperand &MO) {
322 switch (MO.getType()) {
323 case MachineOperand::MO_Register:
324 // Register operands don't have target flags.
325 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
326 case MachineOperand::MO_Immediate:
327 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
328 case MachineOperand::MO_CImmediate:
329 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
330 case MachineOperand::MO_FPImmediate:
331 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
332 case MachineOperand::MO_MachineBasicBlock:
333 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
334 case MachineOperand::MO_FrameIndex:
335 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
336 case MachineOperand::MO_ConstantPoolIndex:
337 case MachineOperand::MO_TargetIndex:
338 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
340 case MachineOperand::MO_JumpTableIndex:
341 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
342 case MachineOperand::MO_ExternalSymbol:
343 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
345 case MachineOperand::MO_GlobalAddress:
346 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
348 case MachineOperand::MO_BlockAddress:
349 return hash_combine(MO.getType(), MO.getTargetFlags(),
350 MO.getBlockAddress(), MO.getOffset());
351 case MachineOperand::MO_RegisterMask:
352 case MachineOperand::MO_RegisterLiveOut:
353 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
354 case MachineOperand::MO_Metadata:
355 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
356 case MachineOperand::MO_MCSymbol:
357 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
358 case MachineOperand::MO_CFIIndex:
359 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
360 case MachineOperand::MO_IntrinsicID:
361 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
362 case MachineOperand::MO_Predicate:
363 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
365 llvm_unreachable("Invalid machine operand type");
368 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
369 const TargetIntrinsicInfo *IntrinsicInfo) const {
370 ModuleSlotTracker DummyMST(nullptr);
371 print(OS, DummyMST, TRI, IntrinsicInfo);
374 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
375 const TargetRegisterInfo *TRI,
376 const TargetIntrinsicInfo *IntrinsicInfo) const {
378 case MachineOperand::MO_Register:
379 OS << PrintReg(getReg(), TRI, getSubReg());
381 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
382 isInternalRead() || isEarlyClobber() || isTied()) {
384 bool NeedComma = false;
386 if (NeedComma) OS << ',';
387 if (isEarlyClobber())
388 OS << "earlyclobber,";
393 // <def,read-undef> only makes sense when getSubReg() is set.
394 // Don't clutter the output otherwise.
395 if (isUndef() && getSubReg())
397 } else if (isImplicit()) {
403 if (NeedComma) OS << ',';
408 if (NeedComma) OS << ',';
412 if (isUndef() && isUse()) {
413 if (NeedComma) OS << ',';
417 if (isInternalRead()) {
418 if (NeedComma) OS << ',';
423 if (NeedComma) OS << ',';
426 OS << unsigned(TiedTo - 1);
431 case MachineOperand::MO_Immediate:
434 case MachineOperand::MO_CImmediate:
435 getCImm()->getValue().print(OS, false);
437 case MachineOperand::MO_FPImmediate:
438 if (getFPImm()->getType()->isFloatTy()) {
439 OS << getFPImm()->getValueAPF().convertToFloat();
440 } else if (getFPImm()->getType()->isHalfTy()) {
441 APFloat APF = getFPImm()->getValueAPF();
443 APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &Unused);
444 OS << "half " << APF.convertToFloat();
445 } else if (getFPImm()->getType()->isFP128Ty()) {
446 APFloat APF = getFPImm()->getValueAPF();
448 getFPImm()->getValueAPF().toString(Str);
449 OS << "quad " << Str;
451 OS << getFPImm()->getValueAPF().convertToDouble();
454 case MachineOperand::MO_MachineBasicBlock:
455 OS << "<BB#" << getMBB()->getNumber() << ">";
457 case MachineOperand::MO_FrameIndex:
458 OS << "<fi#" << getIndex() << '>';
460 case MachineOperand::MO_ConstantPoolIndex:
461 OS << "<cp#" << getIndex();
462 if (getOffset()) OS << "+" << getOffset();
465 case MachineOperand::MO_TargetIndex:
466 OS << "<ti#" << getIndex();
467 if (getOffset()) OS << "+" << getOffset();
470 case MachineOperand::MO_JumpTableIndex:
471 OS << "<jt#" << getIndex() << '>';
473 case MachineOperand::MO_GlobalAddress:
475 getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
476 if (getOffset()) OS << "+" << getOffset();
479 case MachineOperand::MO_ExternalSymbol:
480 OS << "<es:" << getSymbolName();
481 if (getOffset()) OS << "+" << getOffset();
484 case MachineOperand::MO_BlockAddress:
486 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
487 if (getOffset()) OS << "+" << getOffset();
490 case MachineOperand::MO_RegisterMask: {
491 unsigned NumRegsInMask = 0;
492 unsigned NumRegsEmitted = 0;
494 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
495 unsigned MaskWord = i / 32;
496 unsigned MaskBit = i % 32;
497 if (getRegMask()[MaskWord] & (1 << MaskBit)) {
498 if (PrintWholeRegMask || NumRegsEmitted <= 10) {
499 OS << " " << PrintReg(i, TRI);
505 if (NumRegsEmitted != NumRegsInMask)
506 OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
510 case MachineOperand::MO_RegisterLiveOut:
511 OS << "<regliveout>";
513 case MachineOperand::MO_Metadata:
515 getMetadata()->printAsOperand(OS, MST);
518 case MachineOperand::MO_MCSymbol:
519 OS << "<MCSym=" << *getMCSymbol() << '>';
521 case MachineOperand::MO_CFIIndex:
522 OS << "<call frame instruction>";
524 case MachineOperand::MO_IntrinsicID: {
525 Intrinsic::ID ID = getIntrinsicID();
526 if (ID < Intrinsic::num_intrinsics)
527 OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << '>';
528 else if (IntrinsicInfo)
529 OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << '>';
531 OS << "<intrinsic:" << ID << '>';
534 case MachineOperand::MO_Predicate: {
535 auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
536 OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
537 << CmpInst::getPredicateName(Pred) << '>';
541 if (unsigned TF = getTargetFlags())
542 OS << "[TF=" << TF << ']';
545 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
546 LLVM_DUMP_METHOD void MachineOperand::dump() const {
547 dbgs() << *this << '\n';
551 //===----------------------------------------------------------------------===//
552 // MachineMemOperand Implementation
553 //===----------------------------------------------------------------------===//
555 /// getAddrSpace - Return the LLVM IR address space number that this pointer
557 unsigned MachinePointerInfo::getAddrSpace() const {
558 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
559 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
562 /// isDereferenceable - Return true if V is always dereferenceable for
563 /// Offset + Size byte.
564 bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
565 const DataLayout &DL) const {
566 if (!V.is<const Value*>())
569 const Value *BasePtr = V.get<const Value*>();
570 if (BasePtr == nullptr)
573 return isDereferenceableAndAlignedPointer(BasePtr, 1,
574 APInt(DL.getPointerSize(),
579 /// getConstantPool - Return a MachinePointerInfo record that refers to the
581 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
582 return MachinePointerInfo(MF.getPSVManager().getConstantPool());
585 /// getFixedStack - Return a MachinePointerInfo record that refers to the
586 /// the specified FrameIndex.
587 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
588 int FI, int64_t Offset) {
589 return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
592 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
593 return MachinePointerInfo(MF.getPSVManager().getJumpTable());
596 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
597 return MachinePointerInfo(MF.getPSVManager().getGOT());
600 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
602 return MachinePointerInfo(MF.getPSVManager().getStack(), Offset);
605 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
606 uint64_t s, unsigned int a,
607 const AAMDNodes &AAInfo,
608 const MDNode *Ranges,
609 SynchronizationScope SynchScope,
610 AtomicOrdering Ordering,
611 AtomicOrdering FailureOrdering)
612 : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
613 AAInfo(AAInfo), Ranges(Ranges) {
614 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
615 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
616 "invalid pointer value");
617 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
618 assert((isLoad() || isStore()) && "Not a load/store!");
620 AtomicInfo.SynchScope = static_cast<unsigned>(SynchScope);
621 assert(getSynchScope() == SynchScope && "Value truncated");
622 AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
623 assert(getOrdering() == Ordering && "Value truncated");
624 AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
625 assert(getFailureOrdering() == FailureOrdering && "Value truncated");
628 /// Profile - Gather unique data for the object.
630 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
631 ID.AddInteger(getOffset());
633 ID.AddPointer(getOpaqueValue());
634 ID.AddInteger(getFlags());
635 ID.AddInteger(getBaseAlignment());
638 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
639 // The Value and Offset may differ due to CSE. But the flags and size
640 // should be the same.
641 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
642 assert(MMO->getSize() == getSize() && "Size mismatch!");
644 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
645 // Update the alignment value.
646 BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
647 // Also update the base and offset, because the new alignment may
648 // not be applicable with the old ones.
649 PtrInfo = MMO->PtrInfo;
653 /// getAlignment - Return the minimum known alignment in bytes of the
654 /// actual memory reference.
655 uint64_t MachineMemOperand::getAlignment() const {
656 return MinAlign(getBaseAlignment(), getOffset());
659 void MachineMemOperand::print(raw_ostream &OS) const {
660 ModuleSlotTracker DummyMST(nullptr);
663 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
664 assert((isLoad() || isStore()) &&
665 "SV has to be a load, store or both.");
676 // Print the address information.
678 if (const Value *V = getValue())
679 V->printAsOperand(OS, /*PrintType=*/false, MST);
680 else if (const PseudoSourceValue *PSV = getPseudoValue())
681 PSV->printCustom(OS);
685 unsigned AS = getAddrSpace();
687 OS << "(addrspace=" << AS << ')';
689 // If the alignment of the memory reference itself differs from the alignment
690 // of the base pointer, print the base alignment explicitly, next to the base
692 if (getBaseAlignment() != getAlignment())
693 OS << "(align=" << getBaseAlignment() << ")";
695 if (getOffset() != 0)
696 OS << "+" << getOffset();
699 // Print the alignment of the reference.
700 if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
701 OS << "(align=" << getAlignment() << ")";
704 if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
706 if (TBAAInfo->getNumOperands() > 0)
707 TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
713 // Print AA scope info.
714 if (const MDNode *ScopeInfo = getAAInfo().Scope) {
715 OS << "(alias.scope=";
716 if (ScopeInfo->getNumOperands() > 0)
717 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
718 ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
727 // Print AA noalias scope info.
728 if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
730 if (NoAliasInfo->getNumOperands() > 0)
731 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
732 NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
742 OS << "(nontemporal)";
743 if (isDereferenceable())
744 OS << "(dereferenceable)";
749 //===----------------------------------------------------------------------===//
750 // MachineInstr Implementation
751 //===----------------------------------------------------------------------===//
753 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
754 if (MCID->ImplicitDefs)
755 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
757 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
758 if (MCID->ImplicitUses)
759 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
761 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
764 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
765 /// implicit operands. It reserves space for the number of operands specified by
767 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
768 DebugLoc dl, bool NoImp)
769 : MCID(&tid), debugLoc(std::move(dl)) {
770 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
772 // Reserve space for the expected number of operands.
773 if (unsigned NumOps = MCID->getNumOperands() +
774 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
775 CapOperands = OperandCapacity::get(NumOps);
776 Operands = MF.allocateOperandArray(CapOperands);
780 addImplicitDefUseOperands(MF);
783 /// MachineInstr ctor - Copies MachineInstr arg exactly
785 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
786 : MCID(&MI.getDesc()), NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
787 debugLoc(MI.getDebugLoc()) {
788 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
790 CapOperands = OperandCapacity::get(MI.getNumOperands());
791 Operands = MF.allocateOperandArray(CapOperands);
794 for (const MachineOperand &MO : MI.operands())
797 // Copy all the sensible flags.
801 /// getRegInfo - If this instruction is embedded into a MachineFunction,
802 /// return the MachineRegisterInfo object for the current function, otherwise
804 MachineRegisterInfo *MachineInstr::getRegInfo() {
805 if (MachineBasicBlock *MBB = getParent())
806 return &MBB->getParent()->getRegInfo();
810 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
811 /// this instruction from their respective use lists. This requires that the
812 /// operands already be on their use lists.
813 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
814 for (MachineOperand &MO : operands())
816 MRI.removeRegOperandFromUseList(&MO);
819 /// AddRegOperandsToUseLists - Add all of the register operands in
820 /// this instruction from their respective use lists. This requires that the
821 /// operands not be on their use lists yet.
822 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
823 for (MachineOperand &MO : operands())
825 MRI.addRegOperandToUseList(&MO);
828 void MachineInstr::addOperand(const MachineOperand &Op) {
829 MachineBasicBlock *MBB = getParent();
830 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
831 MachineFunction *MF = MBB->getParent();
832 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
836 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
837 /// ranges. If MRI is non-null also update use-def chains.
838 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
839 unsigned NumOps, MachineRegisterInfo *MRI) {
841 return MRI->moveOperands(Dst, Src, NumOps);
843 // MachineOperand is a trivially copyable type so we can just use memmove.
844 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
847 /// addOperand - Add the specified operand to the instruction. If it is an
848 /// implicit operand, it is added to the end of the operand list. If it is
849 /// an explicit operand it is added at the end of the explicit operand list
850 /// (before the first implicit operand).
851 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
852 assert(MCID && "Cannot add operands before providing an instr descriptor");
854 // Check if we're adding one of our existing operands.
855 if (&Op >= Operands && &Op < Operands + NumOperands) {
856 // This is unusual: MI->addOperand(MI->getOperand(i)).
857 // If adding Op requires reallocating or moving existing operands around,
858 // the Op reference could go stale. Support it by copying Op.
859 MachineOperand CopyOp(Op);
860 return addOperand(MF, CopyOp);
863 // Find the insert location for the new operand. Implicit registers go at
864 // the end, everything else goes before the implicit regs.
866 // FIXME: Allow mixed explicit and implicit operands on inline asm.
867 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
868 // implicit-defs, but they must not be moved around. See the FIXME in
870 unsigned OpNo = getNumOperands();
871 bool isImpReg = Op.isReg() && Op.isImplicit();
872 if (!isImpReg && !isInlineAsm()) {
873 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
875 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
880 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
881 // OpNo now points as the desired insertion point. Unless this is a variadic
882 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
883 // RegMask operands go between the explicit and implicit operands.
884 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
885 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
886 "Trying to add an operand to a machine instr that is already done!");
889 MachineRegisterInfo *MRI = getRegInfo();
891 // Determine if the Operands array needs to be reallocated.
892 // Save the old capacity and operand array.
893 OperandCapacity OldCap = CapOperands;
894 MachineOperand *OldOperands = Operands;
895 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
896 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
897 Operands = MF.allocateOperandArray(CapOperands);
898 // Move the operands before the insertion point.
900 moveOperands(Operands, OldOperands, OpNo, MRI);
903 // Move the operands following the insertion point.
904 if (OpNo != NumOperands)
905 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
909 // Deallocate the old operand array.
910 if (OldOperands != Operands && OldOperands)
911 MF.deallocateOperandArray(OldCap, OldOperands);
913 // Copy Op into place. It still needs to be inserted into the MRI use lists.
914 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
915 NewMO->ParentMI = this;
917 // When adding a register operand, tell MRI about it.
918 if (NewMO->isReg()) {
919 // Ensure isOnRegUseList() returns false, regardless of Op's status.
920 NewMO->Contents.Reg.Prev = nullptr;
921 // Ignore existing ties. This is not a property that can be copied.
923 // Add the new operand to MRI, but only for instructions in an MBB.
925 MRI->addRegOperandToUseList(NewMO);
926 // The MCID operand information isn't accurate until we start adding
927 // explicit operands. The implicit operands are added first, then the
928 // explicits are inserted before them.
930 // Tie uses to defs as indicated in MCInstrDesc.
931 if (NewMO->isUse()) {
932 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
934 tieOperands(DefIdx, OpNo);
936 // If the register operand is flagged as early, mark the operand as such.
937 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
938 NewMO->setIsEarlyClobber(true);
943 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
944 /// fewer operand than it started with.
946 void MachineInstr::RemoveOperand(unsigned OpNo) {
947 assert(OpNo < getNumOperands() && "Invalid operand number");
948 untieRegOperand(OpNo);
951 // Moving tied operands would break the ties.
952 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
953 if (Operands[i].isReg())
954 assert(!Operands[i].isTied() && "Cannot move tied operands");
957 MachineRegisterInfo *MRI = getRegInfo();
958 if (MRI && Operands[OpNo].isReg())
959 MRI->removeRegOperandFromUseList(Operands + OpNo);
961 // Don't call the MachineOperand destructor. A lot of this code depends on
962 // MachineOperand having a trivial destructor anyway, and adding a call here
963 // wouldn't make it 'destructor-correct'.
965 if (unsigned N = NumOperands - 1 - OpNo)
966 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
970 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
971 /// This function should be used only occasionally. The setMemRefs function
972 /// is the primary method for setting up a MachineInstr's MemRefs list.
973 void MachineInstr::addMemOperand(MachineFunction &MF,
974 MachineMemOperand *MO) {
975 mmo_iterator OldMemRefs = MemRefs;
976 unsigned OldNumMemRefs = NumMemRefs;
978 unsigned NewNum = NumMemRefs + 1;
979 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
981 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
982 NewMemRefs[NewNum - 1] = MO;
983 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
986 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
988 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
989 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
990 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
991 if ((E1 - I1) != (E2 - I2))
993 for (; I1 != E1; ++I1, ++I2) {
1000 std::pair<MachineInstr::mmo_iterator, unsigned>
1001 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
1003 // If either of the incoming memrefs are empty, we must be conservative and
1004 // treat this as if we've exhausted our space for memrefs and dropped them.
1005 if (memoperands_empty() || Other.memoperands_empty())
1006 return std::make_pair(nullptr, 0);
1008 // If both instructions have identical memrefs, we don't need to merge them.
1009 // Since many instructions have a single memref, and we tend to merge things
1010 // like pairs of loads from the same location, this catches a large number of
1011 // cases in practice.
1012 if (hasIdenticalMMOs(*this, Other))
1013 return std::make_pair(MemRefs, NumMemRefs);
1015 // TODO: consider uniquing elements within the operand lists to reduce
1016 // space usage and fall back to conservative information less often.
1017 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
1019 // If we don't have enough room to store this many memrefs, be conservative
1020 // and drop them. Otherwise, we'd fail asserts when trying to add them to
1021 // the new instruction.
1022 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
1023 return std::make_pair(nullptr, 0);
1025 MachineFunction *MF = getParent()->getParent();
1026 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
1027 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
1029 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
1031 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
1034 return std::make_pair(MemBegin, CombinedNumMemRefs);
1037 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
1038 assert(!isBundledWithPred() && "Must be called on bundle header");
1039 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
1040 if (MII->getDesc().getFlags() & Mask) {
1041 if (Type == AnyInBundle)
1044 if (Type == AllInBundle && !MII->isBundle())
1047 // This was the last instruction in the bundle.
1048 if (!MII->isBundledWithSucc())
1049 return Type == AllInBundle;
1053 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
1054 MICheckType Check) const {
1055 // If opcodes or number of operands are not the same then the two
1056 // instructions are obviously not identical.
1057 if (Other.getOpcode() != getOpcode() ||
1058 Other.getNumOperands() != getNumOperands())
1062 // We have passed the test above that both instructions have the same
1063 // opcode, so we know that both instructions are bundles here. Let's compare
1064 // MIs inside the bundle.
1065 assert(Other.isBundle() && "Expected that both instructions are bundles.");
1066 MachineBasicBlock::const_instr_iterator I1 = getIterator();
1067 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
1068 // Loop until we analysed the last intruction inside at least one of the
1070 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
1073 if (!I1->isIdenticalTo(*I2, Check))
1076 // If we've reached the end of just one of the two bundles, but not both,
1077 // the instructions are not identical.
1078 if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
1082 // Check operands to make sure they match.
1083 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1084 const MachineOperand &MO = getOperand(i);
1085 const MachineOperand &OMO = Other.getOperand(i);
1087 if (!MO.isIdenticalTo(OMO))
1092 // Clients may or may not want to ignore defs when testing for equality.
1093 // For example, machine CSE pass only cares about finding common
1094 // subexpressions, so it's safe to ignore virtual register defs.
1096 if (Check == IgnoreDefs)
1098 else if (Check == IgnoreVRegDefs) {
1099 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1100 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
1101 if (MO.getReg() != OMO.getReg())
1104 if (!MO.isIdenticalTo(OMO))
1106 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
1110 if (!MO.isIdenticalTo(OMO))
1112 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
1116 // If DebugLoc does not match then two dbg.values are not identical.
1118 if (getDebugLoc() && Other.getDebugLoc() &&
1119 getDebugLoc() != Other.getDebugLoc())
1124 MachineInstr *MachineInstr::removeFromParent() {
1125 assert(getParent() && "Not embedded in a basic block!");
1126 return getParent()->remove(this);
1129 MachineInstr *MachineInstr::removeFromBundle() {
1130 assert(getParent() && "Not embedded in a basic block!");
1131 return getParent()->remove_instr(this);
1134 void MachineInstr::eraseFromParent() {
1135 assert(getParent() && "Not embedded in a basic block!");
1136 getParent()->erase(this);
1139 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1140 assert(getParent() && "Not embedded in a basic block!");
1141 MachineBasicBlock *MBB = getParent();
1142 MachineFunction *MF = MBB->getParent();
1143 assert(MF && "Not embedded in a function!");
1145 MachineInstr *MI = (MachineInstr *)this;
1146 MachineRegisterInfo &MRI = MF->getRegInfo();
1148 for (const MachineOperand &MO : MI->operands()) {
1149 if (!MO.isReg() || !MO.isDef())
1151 unsigned Reg = MO.getReg();
1152 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1154 MRI.markUsesInDebugValueAsUndef(Reg);
1156 MI->eraseFromParent();
1159 void MachineInstr::eraseFromBundle() {
1160 assert(getParent() && "Not embedded in a basic block!");
1161 getParent()->erase_instr(this);
1164 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1166 unsigned MachineInstr::getNumExplicitOperands() const {
1167 unsigned NumOperands = MCID->getNumOperands();
1168 if (!MCID->isVariadic())
1171 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1172 const MachineOperand &MO = getOperand(i);
1173 if (!MO.isReg() || !MO.isImplicit())
1179 void MachineInstr::bundleWithPred() {
1180 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1181 setFlag(BundledPred);
1182 MachineBasicBlock::instr_iterator Pred = getIterator();
1184 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1185 Pred->setFlag(BundledSucc);
1188 void MachineInstr::bundleWithSucc() {
1189 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1190 setFlag(BundledSucc);
1191 MachineBasicBlock::instr_iterator Succ = getIterator();
1193 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1194 Succ->setFlag(BundledPred);
1197 void MachineInstr::unbundleFromPred() {
1198 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1199 clearFlag(BundledPred);
1200 MachineBasicBlock::instr_iterator Pred = getIterator();
1202 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1203 Pred->clearFlag(BundledSucc);
1206 void MachineInstr::unbundleFromSucc() {
1207 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1208 clearFlag(BundledSucc);
1209 MachineBasicBlock::instr_iterator Succ = getIterator();
1211 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1212 Succ->clearFlag(BundledPred);
1215 bool MachineInstr::isStackAligningInlineAsm() const {
1216 if (isInlineAsm()) {
1217 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1218 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1224 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1225 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1226 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1227 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1230 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1231 unsigned *GroupNo) const {
1232 assert(isInlineAsm() && "Expected an inline asm instruction");
1233 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1235 // Ignore queries about the initial operands.
1236 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1241 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1243 const MachineOperand &FlagMO = getOperand(i);
1244 // If we reach the implicit register operands, stop looking.
1245 if (!FlagMO.isImm())
1247 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1248 if (i + NumOps > OpIdx) {
1258 const DILocalVariable *MachineInstr::getDebugVariable() const {
1259 assert(isDebugValue() && "not a DBG_VALUE");
1260 return cast<DILocalVariable>(getOperand(2).getMetadata());
1263 const DIExpression *MachineInstr::getDebugExpression() const {
1264 assert(isDebugValue() && "not a DBG_VALUE");
1265 return cast<DIExpression>(getOperand(3).getMetadata());
1268 const TargetRegisterClass*
1269 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1270 const TargetInstrInfo *TII,
1271 const TargetRegisterInfo *TRI) const {
1272 assert(getParent() && "Can't have an MBB reference here!");
1273 assert(getParent()->getParent() && "Can't have an MF reference here!");
1274 const MachineFunction &MF = *getParent()->getParent();
1276 // Most opcodes have fixed constraints in their MCInstrDesc.
1278 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1280 if (!getOperand(OpIdx).isReg())
1283 // For tied uses on inline asm, get the constraint from the def.
1285 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1288 // Inline asm stores register class constraints in the flag word.
1289 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1293 unsigned Flag = getOperand(FlagIdx).getImm();
1295 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1296 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1297 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1298 InlineAsm::hasRegClassConstraint(Flag, RCID))
1299 return TRI->getRegClass(RCID);
1301 // Assume that all registers in a memory operand are pointers.
1302 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1303 return TRI->getPointerRegClass(MF);
1308 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1309 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1310 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1311 // Check every operands inside the bundle if we have
1314 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1316 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1317 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1319 // Otherwise, just check the current operands.
1320 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1321 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1325 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1326 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1327 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1328 assert(CurRC && "Invalid initial register class");
1329 // Check if Reg is constrained by some of its use/def from MI.
1330 const MachineOperand &MO = getOperand(OpIdx);
1331 if (!MO.isReg() || MO.getReg() != Reg)
1333 // If yes, accumulate the constraints through the operand.
1334 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1337 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1338 unsigned OpIdx, const TargetRegisterClass *CurRC,
1339 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1340 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1341 const MachineOperand &MO = getOperand(OpIdx);
1342 assert(MO.isReg() &&
1343 "Cannot get register constraints for non-register operand");
1344 assert(CurRC && "Invalid initial register class");
1345 if (unsigned SubIdx = MO.getSubReg()) {
1347 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1349 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1351 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1355 /// Return the number of instructions inside the MI bundle, not counting the
1356 /// header instruction.
1357 unsigned MachineInstr::getBundleSize() const {
1358 MachineBasicBlock::const_instr_iterator I = getIterator();
1360 while (I->isBundledWithSucc()) {
1367 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1368 /// the given register (not considering sub/super-registers).
1369 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1370 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1371 const MachineOperand &MO = getOperand(i);
1372 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1378 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1379 /// the specific register or -1 if it is not found. It further tightens
1380 /// the search criteria to a use that kills the register if isKill is true.
1381 int MachineInstr::findRegisterUseOperandIdx(
1382 unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
1383 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1384 const MachineOperand &MO = getOperand(i);
1385 if (!MO.isReg() || !MO.isUse())
1387 unsigned MOReg = MO.getReg();
1390 if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1391 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1392 TRI->isSubRegister(MOReg, Reg)))
1393 if (!isKill || MO.isKill())
1399 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1400 /// indicating if this instruction reads or writes Reg. This also considers
1401 /// partial defines.
1402 std::pair<bool,bool>
1403 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1404 SmallVectorImpl<unsigned> *Ops) const {
1405 bool PartDef = false; // Partial redefine.
1406 bool FullDef = false; // Full define.
1409 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1410 const MachineOperand &MO = getOperand(i);
1411 if (!MO.isReg() || MO.getReg() != Reg)
1416 Use |= !MO.isUndef();
1417 else if (MO.getSubReg() && !MO.isUndef())
1418 // A partial <def,undef> doesn't count as reading the register.
1423 // A partial redefine uses Reg unless there is also a full define.
1424 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1427 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1428 /// the specified register or -1 if it is not found. If isDead is true, defs
1429 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1430 /// also checks if there is a def of a super-register.
1432 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1433 const TargetRegisterInfo *TRI) const {
1434 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1435 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1436 const MachineOperand &MO = getOperand(i);
1437 // Accept regmask operands when Overlap is set.
1438 // Ignore them when looking for a specific def operand (Overlap == false).
1439 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1441 if (!MO.isReg() || !MO.isDef())
1443 unsigned MOReg = MO.getReg();
1444 bool Found = (MOReg == Reg);
1445 if (!Found && TRI && isPhys &&
1446 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1448 Found = TRI->regsOverlap(MOReg, Reg);
1450 Found = TRI->isSubRegister(MOReg, Reg);
1452 if (Found && (!isDead || MO.isDead()))
1458 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1459 /// operand list that is used to represent the predicate. It returns -1 if
1461 int MachineInstr::findFirstPredOperandIdx() const {
1462 // Don't call MCID.findFirstPredOperandIdx() because this variant
1463 // is sometimes called on an instruction that's not yet complete, and
1464 // so the number of operands is less than the MCID indicates. In
1465 // particular, the PTX target does this.
1466 const MCInstrDesc &MCID = getDesc();
1467 if (MCID.isPredicable()) {
1468 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1469 if (MCID.OpInfo[i].isPredicate())
1476 // MachineOperand::TiedTo is 4 bits wide.
1477 const unsigned TiedMax = 15;
1479 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1481 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1482 /// field. TiedTo can have these values:
1484 /// 0: Operand is not tied to anything.
1485 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1486 /// TiedMax: Tied to an operand >= TiedMax-1.
1488 /// The tied def must be one of the first TiedMax operands on a normal
1489 /// instruction. INLINEASM instructions allow more tied defs.
1491 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1492 MachineOperand &DefMO = getOperand(DefIdx);
1493 MachineOperand &UseMO = getOperand(UseIdx);
1494 assert(DefMO.isDef() && "DefIdx must be a def operand");
1495 assert(UseMO.isUse() && "UseIdx must be a use operand");
1496 assert(!DefMO.isTied() && "Def is already tied to another use");
1497 assert(!UseMO.isTied() && "Use is already tied to another def");
1499 if (DefIdx < TiedMax)
1500 UseMO.TiedTo = DefIdx + 1;
1502 // Inline asm can use the group descriptors to find tied operands, but on
1503 // normal instruction, the tied def must be within the first TiedMax
1505 assert(isInlineAsm() && "DefIdx out of range");
1506 UseMO.TiedTo = TiedMax;
1509 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1510 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1513 /// Given the index of a tied register operand, find the operand it is tied to.
1514 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1515 /// which must exist.
1516 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1517 const MachineOperand &MO = getOperand(OpIdx);
1518 assert(MO.isTied() && "Operand isn't tied");
1520 // Normally TiedTo is in range.
1521 if (MO.TiedTo < TiedMax)
1522 return MO.TiedTo - 1;
1524 // Uses on normal instructions can be out of range.
1525 if (!isInlineAsm()) {
1526 // Normal tied defs must be in the 0..TiedMax-1 range.
1529 // MO is a def. Search for the tied use.
1530 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1531 const MachineOperand &UseMO = getOperand(i);
1532 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1535 llvm_unreachable("Can't find tied use");
1538 // Now deal with inline asm by parsing the operand group descriptor flags.
1539 // Find the beginning of each operand group.
1540 SmallVector<unsigned, 8> GroupIdx;
1541 unsigned OpIdxGroup = ~0u;
1543 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1545 const MachineOperand &FlagMO = getOperand(i);
1546 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1547 unsigned CurGroup = GroupIdx.size();
1548 GroupIdx.push_back(i);
1549 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1550 // OpIdx belongs to this operand group.
1551 if (OpIdx > i && OpIdx < i + NumOps)
1552 OpIdxGroup = CurGroup;
1554 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1556 // Operands in this group are tied to operands in TiedGroup which must be
1557 // earlier. Find the number of operands between the two groups.
1558 unsigned Delta = i - GroupIdx[TiedGroup];
1560 // OpIdx is a use tied to TiedGroup.
1561 if (OpIdxGroup == CurGroup)
1562 return OpIdx - Delta;
1564 // OpIdx is a def tied to this use group.
1565 if (OpIdxGroup == TiedGroup)
1566 return OpIdx + Delta;
1568 llvm_unreachable("Invalid tied operand on inline asm");
1571 /// clearKillInfo - Clears kill flags on all operands.
1573 void MachineInstr::clearKillInfo() {
1574 for (MachineOperand &MO : operands()) {
1575 if (MO.isReg() && MO.isUse())
1576 MO.setIsKill(false);
1580 void MachineInstr::substituteRegister(unsigned FromReg,
1583 const TargetRegisterInfo &RegInfo) {
1584 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1586 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1587 for (MachineOperand &MO : operands()) {
1588 if (!MO.isReg() || MO.getReg() != FromReg)
1590 MO.substPhysReg(ToReg, RegInfo);
1593 for (MachineOperand &MO : operands()) {
1594 if (!MO.isReg() || MO.getReg() != FromReg)
1596 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1601 /// isSafeToMove - Return true if it is safe to move this instruction. If
1602 /// SawStore is set to true, it means that there is a store (or call) between
1603 /// the instruction's location and its intended destination.
1604 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1605 // Ignore stuff that we obviously can't move.
1607 // Treat volatile loads as stores. This is not strictly necessary for
1608 // volatiles, but it is required for atomic loads. It is not allowed to move
1609 // a load across an atomic load with Ordering > Monotonic.
1610 if (mayStore() || isCall() ||
1611 (mayLoad() && hasOrderedMemoryRef())) {
1616 if (isPosition() || isDebugValue() || isTerminator() ||
1617 hasUnmodeledSideEffects())
1620 // See if this instruction does a load. If so, we have to guarantee that the
1621 // loaded value doesn't change between the load and the its intended
1622 // destination. The check for isInvariantLoad gives the targe the chance to
1623 // classify the load as always returning a constant, e.g. a constant pool
1625 if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1626 // Otherwise, this is a real load. If there is a store between the load and
1627 // end of block, we can't move it.
1633 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
1635 const MachineFunction *MF = getParent()->getParent();
1636 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1638 // If neither instruction stores to memory, they can't alias in any
1639 // meaningful way, even if they read from the same address.
1640 if (!mayStore() && !Other.mayStore())
1643 // Let the target decide if memory accesses cannot possibly overlap.
1644 if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
1650 // FIXME: Need to handle multiple memory operands to support all targets.
1651 if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1654 MachineMemOperand *MMOa = *memoperands_begin();
1655 MachineMemOperand *MMOb = *Other.memoperands_begin();
1657 if (!MMOa->getValue() || !MMOb->getValue())
1660 // The following interface to AA is fashioned after DAGCombiner::isAlias
1661 // and operates with MachineMemOperand offset with some important
1663 // - LLVM fundamentally assumes flat address spaces.
1664 // - MachineOperand offset can *only* result from legalization and
1665 // cannot affect queries other than the trivial case of overlap
1667 // - These offsets never wrap and never step outside
1668 // of allocated objects.
1669 // - There should never be any negative offsets here.
1671 // FIXME: Modify API to hide this math from "user"
1672 // FIXME: Even before we go to AA we can reason locally about some
1673 // memory objects. It can save compile time, and possibly catch some
1674 // corner cases not currently covered.
1676 assert((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
1677 assert((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
1679 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
1680 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
1681 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
1683 AliasResult AAResult =
1684 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
1685 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1686 MemoryLocation(MMOb->getValue(), Overlapb,
1687 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1689 return (AAResult != NoAlias);
1692 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1693 /// or volatile memory reference, or if the information describing the memory
1694 /// reference is not available. Return false if it is known to have no ordered
1695 /// memory references.
1696 bool MachineInstr::hasOrderedMemoryRef() const {
1697 // An instruction known never to access memory won't have a volatile access.
1701 !hasUnmodeledSideEffects())
1704 // Otherwise, if the instruction has no memory reference information,
1705 // conservatively assume it wasn't preserved.
1706 if (memoperands_empty())
1709 // Check if any of our memory operands are ordered.
1710 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1711 return !MMO->isUnordered();
1715 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1716 /// trap and is loading from a location whose value is invariant across a run of
1718 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
1719 // If the instruction doesn't load at all, it isn't an invariant load.
1723 // If the instruction has lost its memoperands, conservatively assume that
1724 // it may not be an invariant load.
1725 if (memoperands_empty())
1728 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1730 for (MachineMemOperand *MMO : memoperands()) {
1731 if (MMO->isVolatile()) return false;
1732 if (MMO->isStore()) return false;
1733 if (MMO->isInvariant() && MMO->isDereferenceable())
1736 // A load from a constant PseudoSourceValue is invariant.
1737 if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1738 if (PSV->isConstant(&MFI))
1741 if (const Value *V = MMO->getValue()) {
1742 // If we have an AliasAnalysis, ask it whether the memory is constant.
1744 AA->pointsToConstantMemory(
1745 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1749 // Otherwise assume conservatively.
1753 // Everything checks out.
1757 /// isConstantValuePHI - If the specified instruction is a PHI that always
1758 /// merges together the same virtual register, return the register, otherwise
1760 unsigned MachineInstr::isConstantValuePHI() const {
1763 assert(getNumOperands() >= 3 &&
1764 "It's illegal to have a PHI without source operands");
1766 unsigned Reg = getOperand(1).getReg();
1767 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1768 if (getOperand(i).getReg() != Reg)
1773 bool MachineInstr::hasUnmodeledSideEffects() const {
1774 if (hasProperty(MCID::UnmodeledSideEffects))
1776 if (isInlineAsm()) {
1777 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1778 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1785 bool MachineInstr::isLoadFoldBarrier() const {
1786 return mayStore() || isCall() || hasUnmodeledSideEffects();
1789 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1791 bool MachineInstr::allDefsAreDead() const {
1792 for (const MachineOperand &MO : operands()) {
1793 if (!MO.isReg() || MO.isUse())
1801 /// copyImplicitOps - Copy implicit register operands from specified
1802 /// instruction to this instruction.
1803 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1804 const MachineInstr &MI) {
1805 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1807 const MachineOperand &MO = MI.getOperand(i);
1808 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1813 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1814 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1820 void MachineInstr::print(raw_ostream &OS, bool SkipOpers, bool SkipDebugLoc,
1821 const TargetInstrInfo *TII) const {
1822 const Module *M = nullptr;
1823 if (const MachineBasicBlock *MBB = getParent())
1824 if (const MachineFunction *MF = MBB->getParent())
1825 M = MF->getFunction()->getParent();
1827 ModuleSlotTracker MST(M);
1828 print(OS, MST, SkipOpers, SkipDebugLoc, TII);
1831 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1832 bool SkipOpers, bool SkipDebugLoc,
1833 const TargetInstrInfo *TII) const {
1834 // We can be a bit tidier if we know the MachineFunction.
1835 const MachineFunction *MF = nullptr;
1836 const TargetRegisterInfo *TRI = nullptr;
1837 const MachineRegisterInfo *MRI = nullptr;
1838 const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1840 if (const MachineBasicBlock *MBB = getParent()) {
1841 MF = MBB->getParent();
1843 MRI = &MF->getRegInfo();
1844 TRI = MF->getSubtarget().getRegisterInfo();
1846 TII = MF->getSubtarget().getInstrInfo();
1847 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
1851 // Save a list of virtual registers.
1852 SmallVector<unsigned, 8> VirtRegs;
1854 // Print explicitly defined operands on the left of an assignment syntax.
1855 unsigned StartOp = 0, e = getNumOperands();
1856 for (; StartOp < e && getOperand(StartOp).isReg() &&
1857 getOperand(StartOp).isDef() &&
1858 !getOperand(StartOp).isImplicit();
1860 if (StartOp != 0) OS << ", ";
1861 getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
1862 unsigned Reg = getOperand(StartOp).getReg();
1863 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1864 VirtRegs.push_back(Reg);
1865 LLT Ty = MRI ? MRI->getType(Reg) : LLT{};
1867 OS << '(' << Ty << ')';
1874 // Print the opcode name.
1876 OS << TII->getName(getOpcode());
1883 // Print the rest of the operands.
1884 bool FirstOp = true;
1885 unsigned AsmDescOp = ~0u;
1886 unsigned AsmOpCount = 0;
1888 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1889 // Print asm string.
1891 getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1893 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1894 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1895 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1896 OS << " [sideeffect]";
1897 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1899 if (ExtraInfo & InlineAsm::Extra_MayStore)
1900 OS << " [maystore]";
1901 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1902 OS << " [isconvergent]";
1903 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1904 OS << " [alignstack]";
1905 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1906 OS << " [attdialect]";
1907 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1908 OS << " [inteldialect]";
1910 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1914 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1915 const MachineOperand &MO = getOperand(i);
1917 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1918 VirtRegs.push_back(MO.getReg());
1920 if (FirstOp) FirstOp = false; else OS << ",";
1922 if (i < getDesc().NumOperands) {
1923 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1924 if (MCOI.isPredicate())
1926 if (MCOI.isOptionalDef())
1929 if (isDebugValue() && MO.isMetadata()) {
1930 // Pretty print DBG_VALUE instructions.
1931 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1932 if (DIV && !DIV->getName().empty())
1933 OS << "!\"" << DIV->getName() << '\"';
1935 MO.print(OS, MST, TRI);
1936 } else if (TRI && (isInsertSubreg() || isRegSequence() ||
1937 (isSubregToReg() && i == 3)) && MO.isImm()) {
1938 OS << TRI->getSubRegIndexName(MO.getImm());
1939 } else if (i == AsmDescOp && MO.isImm()) {
1940 // Pretty print the inline asm operand descriptor.
1941 OS << '$' << AsmOpCount++;
1942 unsigned Flag = MO.getImm();
1943 switch (InlineAsm::getKind(Flag)) {
1944 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1945 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1946 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1947 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1948 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1949 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1950 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1954 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1955 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1957 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1959 OS << ":RC" << RCID;
1962 if (InlineAsm::isMemKind(Flag)) {
1963 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1965 case InlineAsm::Constraint_es: OS << ":es"; break;
1966 case InlineAsm::Constraint_i: OS << ":i"; break;
1967 case InlineAsm::Constraint_m: OS << ":m"; break;
1968 case InlineAsm::Constraint_o: OS << ":o"; break;
1969 case InlineAsm::Constraint_v: OS << ":v"; break;
1970 case InlineAsm::Constraint_Q: OS << ":Q"; break;
1971 case InlineAsm::Constraint_R: OS << ":R"; break;
1972 case InlineAsm::Constraint_S: OS << ":S"; break;
1973 case InlineAsm::Constraint_T: OS << ":T"; break;
1974 case InlineAsm::Constraint_Um: OS << ":Um"; break;
1975 case InlineAsm::Constraint_Un: OS << ":Un"; break;
1976 case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1977 case InlineAsm::Constraint_Us: OS << ":Us"; break;
1978 case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1979 case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1980 case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1981 case InlineAsm::Constraint_X: OS << ":X"; break;
1982 case InlineAsm::Constraint_Z: OS << ":Z"; break;
1983 case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1984 case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1985 default: OS << ":?"; break;
1989 unsigned TiedTo = 0;
1990 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1991 OS << " tiedto:$" << TiedTo;
1995 // Compute the index of the next operand descriptor.
1996 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1998 MO.print(OS, MST, TRI);
2001 bool HaveSemi = false;
2002 const unsigned PrintableFlags = FrameSetup | FrameDestroy;
2003 if (Flags & PrintableFlags) {
2010 if (Flags & FrameSetup)
2013 if (Flags & FrameDestroy)
2014 OS << "FrameDestroy";
2017 if (!memoperands_empty()) {
2024 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
2026 (*i)->print(OS, MST);
2027 if (std::next(i) != e)
2032 // Print the regclass of any virtual registers encountered.
2033 if (MRI && !VirtRegs.empty()) {
2038 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
2039 const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
2042 // Generic virtual registers do not have register classes.
2043 if (RC.is<const RegisterBank *>())
2044 OS << " " << RC.get<const RegisterBank *>()->getName();
2047 << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
2048 OS << ':' << PrintReg(VirtRegs[i]);
2049 for (unsigned j = i+1; j != VirtRegs.size();) {
2050 if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
2054 if (VirtRegs[i] != VirtRegs[j])
2055 OS << "," << PrintReg(VirtRegs[j]);
2056 VirtRegs.erase(VirtRegs.begin()+j);
2061 // Print debug location information.
2062 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
2065 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
2066 OS << " line no:" << DV->getLine();
2067 if (auto *InlinedAt = debugLoc->getInlinedAt()) {
2068 DebugLoc InlinedAtDL(InlinedAt);
2069 if (InlinedAtDL && MF) {
2070 OS << " inlined @[ ";
2071 InlinedAtDL.print(OS);
2075 if (isIndirectDebugValue())
2077 } else if (SkipDebugLoc) {
2079 } else if (debugLoc && MF) {
2089 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
2090 const TargetRegisterInfo *RegInfo,
2091 bool AddIfNotFound) {
2092 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
2093 bool hasAliases = isPhysReg &&
2094 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
2096 SmallVector<unsigned,4> DeadOps;
2097 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2098 MachineOperand &MO = getOperand(i);
2099 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
2102 // DEBUG_VALUE nodes do not contribute to code generation and should
2103 // always be ignored. Failure to do so may result in trying to modify
2104 // KILL flags on DEBUG_VALUE nodes.
2108 unsigned Reg = MO.getReg();
2112 if (Reg == IncomingReg) {
2115 // The register is already marked kill.
2117 if (isPhysReg && isRegTiedToDefOperand(i))
2118 // Two-address uses of physregs must not be marked kill.
2123 } else if (hasAliases && MO.isKill() &&
2124 TargetRegisterInfo::isPhysicalRegister(Reg)) {
2125 // A super-register kill already exists.
2126 if (RegInfo->isSuperRegister(IncomingReg, Reg))
2128 if (RegInfo->isSubRegister(IncomingReg, Reg))
2129 DeadOps.push_back(i);
2133 // Trim unneeded kill operands.
2134 while (!DeadOps.empty()) {
2135 unsigned OpIdx = DeadOps.back();
2136 if (getOperand(OpIdx).isImplicit())
2137 RemoveOperand(OpIdx);
2139 getOperand(OpIdx).setIsKill(false);
2143 // If not found, this means an alias of one of the operands is killed. Add a
2144 // new implicit operand if required.
2145 if (!Found && AddIfNotFound) {
2146 addOperand(MachineOperand::CreateReg(IncomingReg,
2155 void MachineInstr::clearRegisterKills(unsigned Reg,
2156 const TargetRegisterInfo *RegInfo) {
2157 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2159 for (MachineOperand &MO : operands()) {
2160 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2162 unsigned OpReg = MO.getReg();
2163 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2164 MO.setIsKill(false);
2168 bool MachineInstr::addRegisterDead(unsigned Reg,
2169 const TargetRegisterInfo *RegInfo,
2170 bool AddIfNotFound) {
2171 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2172 bool hasAliases = isPhysReg &&
2173 MCRegAliasIterator(Reg, RegInfo, false).isValid();
2175 SmallVector<unsigned,4> DeadOps;
2176 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2177 MachineOperand &MO = getOperand(i);
2178 if (!MO.isReg() || !MO.isDef())
2180 unsigned MOReg = MO.getReg();
2187 } else if (hasAliases && MO.isDead() &&
2188 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2189 // There exists a super-register that's marked dead.
2190 if (RegInfo->isSuperRegister(Reg, MOReg))
2192 if (RegInfo->isSubRegister(Reg, MOReg))
2193 DeadOps.push_back(i);
2197 // Trim unneeded dead operands.
2198 while (!DeadOps.empty()) {
2199 unsigned OpIdx = DeadOps.back();
2200 if (getOperand(OpIdx).isImplicit())
2201 RemoveOperand(OpIdx);
2203 getOperand(OpIdx).setIsDead(false);
2207 // If not found, this means an alias of one of the operands is dead. Add a
2208 // new implicit operand if required.
2209 if (Found || !AddIfNotFound)
2212 addOperand(MachineOperand::CreateReg(Reg,
2220 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2221 for (MachineOperand &MO : operands()) {
2222 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2224 MO.setIsDead(false);
2228 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2229 for (MachineOperand &MO : operands()) {
2230 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2232 MO.setIsUndef(IsUndef);
2236 void MachineInstr::addRegisterDefined(unsigned Reg,
2237 const TargetRegisterInfo *RegInfo) {
2238 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2239 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2243 for (const MachineOperand &MO : operands()) {
2244 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2245 MO.getSubReg() == 0)
2249 addOperand(MachineOperand::CreateReg(Reg,
2254 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2255 const TargetRegisterInfo &TRI) {
2256 bool HasRegMask = false;
2257 for (MachineOperand &MO : operands()) {
2258 if (MO.isRegMask()) {
2262 if (!MO.isReg() || !MO.isDef()) continue;
2263 unsigned Reg = MO.getReg();
2264 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2265 // If there are no uses, including partial uses, the def is dead.
2266 if (llvm::none_of(UsedRegs,
2267 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2271 // This is a call with a register mask operand.
2272 // Mask clobbers are always dead, so add defs for the non-dead defines.
2274 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2276 addRegisterDefined(*I, &TRI);
2280 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2281 // Build up a buffer of hash code components.
2282 SmallVector<size_t, 8> HashComponents;
2283 HashComponents.reserve(MI->getNumOperands() + 1);
2284 HashComponents.push_back(MI->getOpcode());
2285 for (const MachineOperand &MO : MI->operands()) {
2286 if (MO.isReg() && MO.isDef() &&
2287 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2288 continue; // Skip virtual register defs.
2290 HashComponents.push_back(hash_value(MO));
2292 return hash_combine_range(HashComponents.begin(), HashComponents.end());
2295 void MachineInstr::emitError(StringRef Msg) const {
2296 // Find the source location cookie.
2297 unsigned LocCookie = 0;
2298 const MDNode *LocMD = nullptr;
2299 for (unsigned i = getNumOperands(); i != 0; --i) {
2300 if (getOperand(i-1).isMetadata() &&
2301 (LocMD = getOperand(i-1).getMetadata()) &&
2302 LocMD->getNumOperands() != 0) {
2303 if (const ConstantInt *CI =
2304 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2305 LocCookie = CI->getZExtValue();
2311 if (const MachineBasicBlock *MBB = getParent())
2312 if (const MachineFunction *MF = MBB->getParent())
2313 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2314 report_fatal_error(Msg);
2317 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2318 const MCInstrDesc &MCID, bool IsIndirect,
2319 unsigned Reg, unsigned Offset,
2320 const MDNode *Variable, const MDNode *Expr) {
2321 assert(isa<DILocalVariable>(Variable) && "not a variable");
2322 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2323 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2324 "Expected inlined-at fields to agree");
2326 return BuildMI(MF, DL, MCID)
2327 .addReg(Reg, RegState::Debug)
2329 .addMetadata(Variable)
2332 assert(Offset == 0 && "A direct address cannot have an offset.");
2333 return BuildMI(MF, DL, MCID)
2334 .addReg(Reg, RegState::Debug)
2335 .addReg(0U, RegState::Debug)
2336 .addMetadata(Variable)
2341 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2342 MachineBasicBlock::iterator I,
2343 const DebugLoc &DL, const MCInstrDesc &MCID,
2344 bool IsIndirect, unsigned Reg,
2345 unsigned Offset, const MDNode *Variable,
2346 const MDNode *Expr) {
2347 assert(isa<DILocalVariable>(Variable) && "not a variable");
2348 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2349 MachineFunction &MF = *BB.getParent();
2351 BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr);
2353 return MachineInstrBuilder(MF, MI);
2356 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2357 MachineBasicBlock::iterator I,
2358 const MachineInstr &Orig,
2360 const MDNode *Var = Orig.getDebugVariable();
2361 const auto *Expr = cast_or_null<DIExpression>(Orig.getDebugExpression());
2362 bool IsIndirect = Orig.isIndirectDebugValue();
2363 uint64_t Offset = IsIndirect ? Orig.getOperand(1).getImm() : 0;
2364 DebugLoc DL = Orig.getDebugLoc();
2365 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
2366 "Expected inlined-at fields to agree");
2367 // If the DBG_VALUE already was a memory location, add an extra
2368 // DW_OP_deref. Otherwise just turning this from a register into a
2369 // memory/indirect location is sufficient.
2371 Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
2372 return BuildMI(BB, I, DL, Orig.getDesc())
2373 .addFrameIndex(FrameIndex)