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/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/MC/MCInstrDesc.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetIntrinsicInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
50 static cl::opt<bool> PrintWholeRegMask(
51 "print-whole-regmask",
52 cl::desc("Print the full contents of regmask operands in IR dumps"),
53 cl::init(true), cl::Hidden);
55 //===----------------------------------------------------------------------===//
56 // MachineOperand Implementation
57 //===----------------------------------------------------------------------===//
59 void MachineOperand::setReg(unsigned Reg) {
60 if (getReg() == Reg) return; // No change.
62 // Otherwise, we have to change the register. If this operand is embedded
63 // into a machine function, we need to update the old and new register's
65 if (MachineInstr *MI = getParent())
66 if (MachineBasicBlock *MBB = MI->getParent())
67 if (MachineFunction *MF = MBB->getParent()) {
68 MachineRegisterInfo &MRI = MF->getRegInfo();
69 MRI.removeRegOperandFromUseList(this);
70 SmallContents.RegNo = Reg;
71 MRI.addRegOperandToUseList(this);
75 // Otherwise, just change the register, no problem. :)
76 SmallContents.RegNo = Reg;
79 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
80 const TargetRegisterInfo &TRI) {
81 assert(TargetRegisterInfo::isVirtualRegister(Reg));
82 if (SubIdx && getSubReg())
83 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
89 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
90 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
92 Reg = TRI.getSubReg(Reg, getSubReg());
93 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
94 // That won't happen in legal code.
102 /// Change a def to a use, or a use to a def.
103 void MachineOperand::setIsDef(bool Val) {
104 assert(isReg() && "Wrong MachineOperand accessor");
105 assert((!Val || !isDebug()) && "Marking a debug operation as def");
108 // MRI may keep uses and defs in different list positions.
109 if (MachineInstr *MI = getParent())
110 if (MachineBasicBlock *MBB = MI->getParent())
111 if (MachineFunction *MF = MBB->getParent()) {
112 MachineRegisterInfo &MRI = MF->getRegInfo();
113 MRI.removeRegOperandFromUseList(this);
115 MRI.addRegOperandToUseList(this);
121 // If this operand is currently a register operand, and if this is in a
122 // function, deregister the operand from the register's use/def list.
123 void MachineOperand::removeRegFromUses() {
124 if (!isReg() || !isOnRegUseList())
127 if (MachineInstr *MI = getParent()) {
128 if (MachineBasicBlock *MBB = MI->getParent()) {
129 if (MachineFunction *MF = MBB->getParent())
130 MF->getRegInfo().removeRegOperandFromUseList(this);
135 /// ChangeToImmediate - Replace this operand with a new immediate operand of
136 /// the specified value. If an operand is known to be an immediate already,
137 /// the setImm method should be used.
138 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
139 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
143 OpKind = MO_Immediate;
144 Contents.ImmVal = ImmVal;
147 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
148 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
152 OpKind = MO_FPImmediate;
153 Contents.CFP = FPImm;
156 void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
157 assert((!isReg() || !isTied()) &&
158 "Cannot change a tied operand into an external symbol");
162 OpKind = MO_ExternalSymbol;
163 Contents.OffsetedInfo.Val.SymbolName = SymName;
164 setOffset(0); // Offset is always 0.
165 setTargetFlags(TargetFlags);
168 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
169 assert((!isReg() || !isTied()) &&
170 "Cannot change a tied operand into an MCSymbol");
174 OpKind = MO_MCSymbol;
178 void MachineOperand::ChangeToFrameIndex(int Idx) {
179 assert((!isReg() || !isTied()) &&
180 "Cannot change a tied operand into a FrameIndex");
184 OpKind = MO_FrameIndex;
188 /// ChangeToRegister - Replace this operand with a new register operand of
189 /// the specified value. If an operand is known to be an register already,
190 /// the setReg method should be used.
191 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
192 bool isKill, bool isDead, bool isUndef,
194 MachineRegisterInfo *RegInfo = nullptr;
195 if (MachineInstr *MI = getParent())
196 if (MachineBasicBlock *MBB = MI->getParent())
197 if (MachineFunction *MF = MBB->getParent())
198 RegInfo = &MF->getRegInfo();
199 // If this operand is already a register operand, remove it from the
200 // register's use/def lists.
201 bool WasReg = isReg();
202 if (RegInfo && WasReg)
203 RegInfo->removeRegOperandFromUseList(this);
205 // Change this to a register and set the reg#.
206 OpKind = MO_Register;
207 SmallContents.RegNo = Reg;
208 SubReg_TargetFlags = 0;
214 IsInternalRead = false;
215 IsEarlyClobber = false;
217 // Ensure isOnRegUseList() returns false.
218 Contents.Reg.Prev = nullptr;
219 // Preserve the tie when the operand was already a register.
223 // If this operand is embedded in a function, add the operand to the
224 // register's use/def list.
226 RegInfo->addRegOperandToUseList(this);
229 /// isIdenticalTo - Return true if this operand is identical to the specified
230 /// operand. Note that this should stay in sync with the hash_value overload
232 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
233 if (getType() != Other.getType() ||
234 getTargetFlags() != Other.getTargetFlags())
238 case MachineOperand::MO_Register:
239 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
240 getSubReg() == Other.getSubReg();
241 case MachineOperand::MO_Immediate:
242 return getImm() == Other.getImm();
243 case MachineOperand::MO_CImmediate:
244 return getCImm() == Other.getCImm();
245 case MachineOperand::MO_FPImmediate:
246 return getFPImm() == Other.getFPImm();
247 case MachineOperand::MO_MachineBasicBlock:
248 return getMBB() == Other.getMBB();
249 case MachineOperand::MO_FrameIndex:
250 return getIndex() == Other.getIndex();
251 case MachineOperand::MO_ConstantPoolIndex:
252 case MachineOperand::MO_TargetIndex:
253 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
254 case MachineOperand::MO_JumpTableIndex:
255 return getIndex() == Other.getIndex();
256 case MachineOperand::MO_GlobalAddress:
257 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
258 case MachineOperand::MO_ExternalSymbol:
259 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
260 getOffset() == Other.getOffset();
261 case MachineOperand::MO_BlockAddress:
262 return getBlockAddress() == Other.getBlockAddress() &&
263 getOffset() == Other.getOffset();
264 case MachineOperand::MO_RegisterMask:
265 case MachineOperand::MO_RegisterLiveOut: {
266 // Shallow compare of the two RegMasks
267 const uint32_t *RegMask = getRegMask();
268 const uint32_t *OtherRegMask = Other.getRegMask();
269 if (RegMask == OtherRegMask)
272 // Calculate the size of the RegMask
273 const MachineFunction *MF = getParent()->getParent()->getParent();
274 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
275 unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
277 // Deep compare of the two RegMasks
278 return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
280 case MachineOperand::MO_MCSymbol:
281 return getMCSymbol() == Other.getMCSymbol();
282 case MachineOperand::MO_CFIIndex:
283 return getCFIIndex() == Other.getCFIIndex();
284 case MachineOperand::MO_Metadata:
285 return getMetadata() == Other.getMetadata();
286 case MachineOperand::MO_IntrinsicID:
287 return getIntrinsicID() == Other.getIntrinsicID();
288 case MachineOperand::MO_Predicate:
289 return getPredicate() == Other.getPredicate();
291 llvm_unreachable("Invalid machine operand type");
294 // Note: this must stay exactly in sync with isIdenticalTo above.
295 hash_code llvm::hash_value(const MachineOperand &MO) {
296 switch (MO.getType()) {
297 case MachineOperand::MO_Register:
298 // Register operands don't have target flags.
299 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
300 case MachineOperand::MO_Immediate:
301 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
302 case MachineOperand::MO_CImmediate:
303 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
304 case MachineOperand::MO_FPImmediate:
305 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
306 case MachineOperand::MO_MachineBasicBlock:
307 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
308 case MachineOperand::MO_FrameIndex:
309 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
310 case MachineOperand::MO_ConstantPoolIndex:
311 case MachineOperand::MO_TargetIndex:
312 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
314 case MachineOperand::MO_JumpTableIndex:
315 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
316 case MachineOperand::MO_ExternalSymbol:
317 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
319 case MachineOperand::MO_GlobalAddress:
320 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
322 case MachineOperand::MO_BlockAddress:
323 return hash_combine(MO.getType(), MO.getTargetFlags(),
324 MO.getBlockAddress(), MO.getOffset());
325 case MachineOperand::MO_RegisterMask:
326 case MachineOperand::MO_RegisterLiveOut:
327 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
328 case MachineOperand::MO_Metadata:
329 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
330 case MachineOperand::MO_MCSymbol:
331 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
332 case MachineOperand::MO_CFIIndex:
333 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
334 case MachineOperand::MO_IntrinsicID:
335 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
336 case MachineOperand::MO_Predicate:
337 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
339 llvm_unreachable("Invalid machine operand type");
342 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
343 const TargetIntrinsicInfo *IntrinsicInfo) const {
344 ModuleSlotTracker DummyMST(nullptr);
345 print(OS, DummyMST, TRI, IntrinsicInfo);
348 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
349 const TargetRegisterInfo *TRI,
350 const TargetIntrinsicInfo *IntrinsicInfo) const {
352 case MachineOperand::MO_Register:
353 OS << PrintReg(getReg(), TRI, getSubReg());
355 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
356 isInternalRead() || isEarlyClobber() || isTied()) {
358 bool NeedComma = false;
360 if (NeedComma) OS << ',';
361 if (isEarlyClobber())
362 OS << "earlyclobber,";
367 // <def,read-undef> only makes sense when getSubReg() is set.
368 // Don't clutter the output otherwise.
369 if (isUndef() && getSubReg())
371 } else if (isImplicit()) {
377 if (NeedComma) OS << ',';
382 if (NeedComma) OS << ',';
386 if (isUndef() && isUse()) {
387 if (NeedComma) OS << ',';
391 if (isInternalRead()) {
392 if (NeedComma) OS << ',';
397 if (NeedComma) OS << ',';
400 OS << unsigned(TiedTo - 1);
405 case MachineOperand::MO_Immediate:
408 case MachineOperand::MO_CImmediate:
409 getCImm()->getValue().print(OS, false);
411 case MachineOperand::MO_FPImmediate:
412 if (getFPImm()->getType()->isFloatTy()) {
413 OS << getFPImm()->getValueAPF().convertToFloat();
414 } else if (getFPImm()->getType()->isHalfTy()) {
415 APFloat APF = getFPImm()->getValueAPF();
417 APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &Unused);
418 OS << "half " << APF.convertToFloat();
419 } else if (getFPImm()->getType()->isFP128Ty()) {
420 APFloat APF = getFPImm()->getValueAPF();
422 getFPImm()->getValueAPF().toString(Str);
423 OS << "quad " << Str;
425 OS << getFPImm()->getValueAPF().convertToDouble();
428 case MachineOperand::MO_MachineBasicBlock:
429 OS << "<BB#" << getMBB()->getNumber() << ">";
431 case MachineOperand::MO_FrameIndex:
432 OS << "<fi#" << getIndex() << '>';
434 case MachineOperand::MO_ConstantPoolIndex:
435 OS << "<cp#" << getIndex();
436 if (getOffset()) OS << "+" << getOffset();
439 case MachineOperand::MO_TargetIndex:
440 OS << "<ti#" << getIndex();
441 if (getOffset()) OS << "+" << getOffset();
444 case MachineOperand::MO_JumpTableIndex:
445 OS << "<jt#" << getIndex() << '>';
447 case MachineOperand::MO_GlobalAddress:
449 getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
450 if (getOffset()) OS << "+" << getOffset();
453 case MachineOperand::MO_ExternalSymbol:
454 OS << "<es:" << getSymbolName();
455 if (getOffset()) OS << "+" << getOffset();
458 case MachineOperand::MO_BlockAddress:
460 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
461 if (getOffset()) OS << "+" << getOffset();
464 case MachineOperand::MO_RegisterMask: {
465 unsigned NumRegsInMask = 0;
466 unsigned NumRegsEmitted = 0;
468 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
469 unsigned MaskWord = i / 32;
470 unsigned MaskBit = i % 32;
471 if (getRegMask()[MaskWord] & (1 << MaskBit)) {
472 if (PrintWholeRegMask || NumRegsEmitted <= 10) {
473 OS << " " << PrintReg(i, TRI);
479 if (NumRegsEmitted != NumRegsInMask)
480 OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
484 case MachineOperand::MO_RegisterLiveOut:
485 OS << "<regliveout>";
487 case MachineOperand::MO_Metadata:
489 getMetadata()->printAsOperand(OS, MST);
492 case MachineOperand::MO_MCSymbol:
493 OS << "<MCSym=" << *getMCSymbol() << '>';
495 case MachineOperand::MO_CFIIndex:
496 OS << "<call frame instruction>";
498 case MachineOperand::MO_IntrinsicID: {
499 Intrinsic::ID ID = getIntrinsicID();
500 if (ID < Intrinsic::num_intrinsics)
501 OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << '>';
502 else if (IntrinsicInfo)
503 OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << '>';
505 OS << "<intrinsic:" << ID << '>';
508 case MachineOperand::MO_Predicate: {
509 auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
510 OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
511 << CmpInst::getPredicateName(Pred) << '>';
515 if (unsigned TF = getTargetFlags())
516 OS << "[TF=" << TF << ']';
519 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
520 LLVM_DUMP_METHOD void MachineOperand::dump() const {
521 dbgs() << *this << '\n';
525 //===----------------------------------------------------------------------===//
526 // MachineMemOperand Implementation
527 //===----------------------------------------------------------------------===//
529 /// getAddrSpace - Return the LLVM IR address space number that this pointer
531 unsigned MachinePointerInfo::getAddrSpace() const {
532 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
533 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
536 /// getConstantPool - Return a MachinePointerInfo record that refers to the
538 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
539 return MachinePointerInfo(MF.getPSVManager().getConstantPool());
542 /// getFixedStack - Return a MachinePointerInfo record that refers to the
543 /// the specified FrameIndex.
544 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
545 int FI, int64_t Offset) {
546 return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
549 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
550 return MachinePointerInfo(MF.getPSVManager().getJumpTable());
553 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
554 return MachinePointerInfo(MF.getPSVManager().getGOT());
557 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
559 return MachinePointerInfo(MF.getPSVManager().getStack(), Offset);
562 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
563 uint64_t s, unsigned int a,
564 const AAMDNodes &AAInfo,
565 const MDNode *Ranges,
566 SynchronizationScope SynchScope,
567 AtomicOrdering Ordering,
568 AtomicOrdering FailureOrdering)
569 : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
570 AAInfo(AAInfo), Ranges(Ranges) {
571 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
572 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
573 "invalid pointer value");
574 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
575 assert((isLoad() || isStore()) && "Not a load/store!");
577 AtomicInfo.SynchScope = static_cast<unsigned>(SynchScope);
578 assert(getSynchScope() == SynchScope && "Value truncated");
579 AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
580 assert(getOrdering() == Ordering && "Value truncated");
581 AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
582 assert(getFailureOrdering() == FailureOrdering && "Value truncated");
585 /// Profile - Gather unique data for the object.
587 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
588 ID.AddInteger(getOffset());
590 ID.AddPointer(getOpaqueValue());
591 ID.AddInteger(getFlags());
592 ID.AddInteger(getBaseAlignment());
595 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
596 // The Value and Offset may differ due to CSE. But the flags and size
597 // should be the same.
598 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
599 assert(MMO->getSize() == getSize() && "Size mismatch!");
601 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
602 // Update the alignment value.
603 BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
604 // Also update the base and offset, because the new alignment may
605 // not be applicable with the old ones.
606 PtrInfo = MMO->PtrInfo;
610 /// getAlignment - Return the minimum known alignment in bytes of the
611 /// actual memory reference.
612 uint64_t MachineMemOperand::getAlignment() const {
613 return MinAlign(getBaseAlignment(), getOffset());
616 void MachineMemOperand::print(raw_ostream &OS) const {
617 ModuleSlotTracker DummyMST(nullptr);
620 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
621 assert((isLoad() || isStore()) &&
622 "SV has to be a load, store or both.");
633 // Print the address information.
635 if (const Value *V = getValue())
636 V->printAsOperand(OS, /*PrintType=*/false, MST);
637 else if (const PseudoSourceValue *PSV = getPseudoValue())
638 PSV->printCustom(OS);
642 unsigned AS = getAddrSpace();
644 OS << "(addrspace=" << AS << ')';
646 // If the alignment of the memory reference itself differs from the alignment
647 // of the base pointer, print the base alignment explicitly, next to the base
649 if (getBaseAlignment() != getAlignment())
650 OS << "(align=" << getBaseAlignment() << ")";
652 if (getOffset() != 0)
653 OS << "+" << getOffset();
656 // Print the alignment of the reference.
657 if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
658 OS << "(align=" << getAlignment() << ")";
661 if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
663 if (TBAAInfo->getNumOperands() > 0)
664 TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
670 // Print AA scope info.
671 if (const MDNode *ScopeInfo = getAAInfo().Scope) {
672 OS << "(alias.scope=";
673 if (ScopeInfo->getNumOperands() > 0)
674 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
675 ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
684 // Print AA noalias scope info.
685 if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
687 if (NoAliasInfo->getNumOperands() > 0)
688 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
689 NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
699 OS << "(nontemporal)";
700 if (isDereferenceable())
701 OS << "(dereferenceable)";
706 //===----------------------------------------------------------------------===//
707 // MachineInstr Implementation
708 //===----------------------------------------------------------------------===//
710 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
711 if (MCID->ImplicitDefs)
712 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
714 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
715 if (MCID->ImplicitUses)
716 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
718 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
721 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
722 /// implicit operands. It reserves space for the number of operands specified by
724 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
725 DebugLoc dl, bool NoImp)
726 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0), Flags(0),
727 AsmPrinterFlags(0), NumMemRefs(0), MemRefs(nullptr),
728 debugLoc(std::move(dl)) {
729 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
731 // Reserve space for the expected number of operands.
732 if (unsigned NumOps = MCID->getNumOperands() +
733 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
734 CapOperands = OperandCapacity::get(NumOps);
735 Operands = MF.allocateOperandArray(CapOperands);
739 addImplicitDefUseOperands(MF);
742 /// MachineInstr ctor - Copies MachineInstr arg exactly
744 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
745 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
746 Flags(0), AsmPrinterFlags(0), NumMemRefs(MI.NumMemRefs),
747 MemRefs(MI.MemRefs), debugLoc(MI.getDebugLoc()) {
748 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
750 CapOperands = OperandCapacity::get(MI.getNumOperands());
751 Operands = MF.allocateOperandArray(CapOperands);
754 for (const MachineOperand &MO : MI.operands())
757 // Copy all the sensible flags.
761 /// getRegInfo - If this instruction is embedded into a MachineFunction,
762 /// return the MachineRegisterInfo object for the current function, otherwise
764 MachineRegisterInfo *MachineInstr::getRegInfo() {
765 if (MachineBasicBlock *MBB = getParent())
766 return &MBB->getParent()->getRegInfo();
770 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
771 /// this instruction from their respective use lists. This requires that the
772 /// operands already be on their use lists.
773 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
774 for (MachineOperand &MO : operands())
776 MRI.removeRegOperandFromUseList(&MO);
779 /// AddRegOperandsToUseLists - Add all of the register operands in
780 /// this instruction from their respective use lists. This requires that the
781 /// operands not be on their use lists yet.
782 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
783 for (MachineOperand &MO : operands())
785 MRI.addRegOperandToUseList(&MO);
788 void MachineInstr::addOperand(const MachineOperand &Op) {
789 MachineBasicBlock *MBB = getParent();
790 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
791 MachineFunction *MF = MBB->getParent();
792 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
796 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
797 /// ranges. If MRI is non-null also update use-def chains.
798 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
799 unsigned NumOps, MachineRegisterInfo *MRI) {
801 return MRI->moveOperands(Dst, Src, NumOps);
803 // MachineOperand is a trivially copyable type so we can just use memmove.
804 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
807 /// addOperand - Add the specified operand to the instruction. If it is an
808 /// implicit operand, it is added to the end of the operand list. If it is
809 /// an explicit operand it is added at the end of the explicit operand list
810 /// (before the first implicit operand).
811 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
812 assert(MCID && "Cannot add operands before providing an instr descriptor");
814 // Check if we're adding one of our existing operands.
815 if (&Op >= Operands && &Op < Operands + NumOperands) {
816 // This is unusual: MI->addOperand(MI->getOperand(i)).
817 // If adding Op requires reallocating or moving existing operands around,
818 // the Op reference could go stale. Support it by copying Op.
819 MachineOperand CopyOp(Op);
820 return addOperand(MF, CopyOp);
823 // Find the insert location for the new operand. Implicit registers go at
824 // the end, everything else goes before the implicit regs.
826 // FIXME: Allow mixed explicit and implicit operands on inline asm.
827 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
828 // implicit-defs, but they must not be moved around. See the FIXME in
830 unsigned OpNo = getNumOperands();
831 bool isImpReg = Op.isReg() && Op.isImplicit();
832 if (!isImpReg && !isInlineAsm()) {
833 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
835 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
840 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
841 // OpNo now points as the desired insertion point. Unless this is a variadic
842 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
843 // RegMask operands go between the explicit and implicit operands.
844 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
845 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
846 "Trying to add an operand to a machine instr that is already done!");
849 MachineRegisterInfo *MRI = getRegInfo();
851 // Determine if the Operands array needs to be reallocated.
852 // Save the old capacity and operand array.
853 OperandCapacity OldCap = CapOperands;
854 MachineOperand *OldOperands = Operands;
855 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
856 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
857 Operands = MF.allocateOperandArray(CapOperands);
858 // Move the operands before the insertion point.
860 moveOperands(Operands, OldOperands, OpNo, MRI);
863 // Move the operands following the insertion point.
864 if (OpNo != NumOperands)
865 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
869 // Deallocate the old operand array.
870 if (OldOperands != Operands && OldOperands)
871 MF.deallocateOperandArray(OldCap, OldOperands);
873 // Copy Op into place. It still needs to be inserted into the MRI use lists.
874 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
875 NewMO->ParentMI = this;
877 // When adding a register operand, tell MRI about it.
878 if (NewMO->isReg()) {
879 // Ensure isOnRegUseList() returns false, regardless of Op's status.
880 NewMO->Contents.Reg.Prev = nullptr;
881 // Ignore existing ties. This is not a property that can be copied.
883 // Add the new operand to MRI, but only for instructions in an MBB.
885 MRI->addRegOperandToUseList(NewMO);
886 // The MCID operand information isn't accurate until we start adding
887 // explicit operands. The implicit operands are added first, then the
888 // explicits are inserted before them.
890 // Tie uses to defs as indicated in MCInstrDesc.
891 if (NewMO->isUse()) {
892 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
894 tieOperands(DefIdx, OpNo);
896 // If the register operand is flagged as early, mark the operand as such.
897 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
898 NewMO->setIsEarlyClobber(true);
903 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
904 /// fewer operand than it started with.
906 void MachineInstr::RemoveOperand(unsigned OpNo) {
907 assert(OpNo < getNumOperands() && "Invalid operand number");
908 untieRegOperand(OpNo);
911 // Moving tied operands would break the ties.
912 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
913 if (Operands[i].isReg())
914 assert(!Operands[i].isTied() && "Cannot move tied operands");
917 MachineRegisterInfo *MRI = getRegInfo();
918 if (MRI && Operands[OpNo].isReg())
919 MRI->removeRegOperandFromUseList(Operands + OpNo);
921 // Don't call the MachineOperand destructor. A lot of this code depends on
922 // MachineOperand having a trivial destructor anyway, and adding a call here
923 // wouldn't make it 'destructor-correct'.
925 if (unsigned N = NumOperands - 1 - OpNo)
926 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
930 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
931 /// This function should be used only occasionally. The setMemRefs function
932 /// is the primary method for setting up a MachineInstr's MemRefs list.
933 void MachineInstr::addMemOperand(MachineFunction &MF,
934 MachineMemOperand *MO) {
935 mmo_iterator OldMemRefs = MemRefs;
936 unsigned OldNumMemRefs = NumMemRefs;
938 unsigned NewNum = NumMemRefs + 1;
939 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
941 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
942 NewMemRefs[NewNum - 1] = MO;
943 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
946 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
948 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
949 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
950 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
951 if ((E1 - I1) != (E2 - I2))
953 for (; I1 != E1; ++I1, ++I2) {
960 std::pair<MachineInstr::mmo_iterator, unsigned>
961 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
963 // If either of the incoming memrefs are empty, we must be conservative and
964 // treat this as if we've exhausted our space for memrefs and dropped them.
965 if (memoperands_empty() || Other.memoperands_empty())
966 return std::make_pair(nullptr, 0);
968 // If both instructions have identical memrefs, we don't need to merge them.
969 // Since many instructions have a single memref, and we tend to merge things
970 // like pairs of loads from the same location, this catches a large number of
971 // cases in practice.
972 if (hasIdenticalMMOs(*this, Other))
973 return std::make_pair(MemRefs, NumMemRefs);
975 // TODO: consider uniquing elements within the operand lists to reduce
976 // space usage and fall back to conservative information less often.
977 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
979 // If we don't have enough room to store this many memrefs, be conservative
980 // and drop them. Otherwise, we'd fail asserts when trying to add them to
981 // the new instruction.
982 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
983 return std::make_pair(nullptr, 0);
985 MachineFunction *MF = getParent()->getParent();
986 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
987 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
989 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
991 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
994 return std::make_pair(MemBegin, CombinedNumMemRefs);
997 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
998 assert(!isBundledWithPred() && "Must be called on bundle header");
999 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
1000 if (MII->getDesc().getFlags() & Mask) {
1001 if (Type == AnyInBundle)
1004 if (Type == AllInBundle && !MII->isBundle())
1007 // This was the last instruction in the bundle.
1008 if (!MII->isBundledWithSucc())
1009 return Type == AllInBundle;
1013 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
1014 MICheckType Check) const {
1015 // If opcodes or number of operands are not the same then the two
1016 // instructions are obviously not identical.
1017 if (Other.getOpcode() != getOpcode() ||
1018 Other.getNumOperands() != getNumOperands())
1022 // We have passed the test above that both instructions have the same
1023 // opcode, so we know that both instructions are bundles here. Let's compare
1024 // MIs inside the bundle.
1025 assert(Other.isBundle() && "Expected that both instructions are bundles.");
1026 MachineBasicBlock::const_instr_iterator I1 = getIterator();
1027 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
1028 // Loop until we analysed the last intruction inside at least one of the
1030 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
1033 if (!I1->isIdenticalTo(*I2, Check))
1036 // If we've reached the end of just one of the two bundles, but not both,
1037 // the instructions are not identical.
1038 if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
1042 // Check operands to make sure they match.
1043 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1044 const MachineOperand &MO = getOperand(i);
1045 const MachineOperand &OMO = Other.getOperand(i);
1047 if (!MO.isIdenticalTo(OMO))
1052 // Clients may or may not want to ignore defs when testing for equality.
1053 // For example, machine CSE pass only cares about finding common
1054 // subexpressions, so it's safe to ignore virtual register defs.
1056 if (Check == IgnoreDefs)
1058 else if (Check == IgnoreVRegDefs) {
1059 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1060 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
1061 if (MO.getReg() != OMO.getReg())
1064 if (!MO.isIdenticalTo(OMO))
1066 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
1070 if (!MO.isIdenticalTo(OMO))
1072 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
1076 // If DebugLoc does not match then two dbg.values are not identical.
1078 if (getDebugLoc() && Other.getDebugLoc() &&
1079 getDebugLoc() != Other.getDebugLoc())
1084 MachineInstr *MachineInstr::removeFromParent() {
1085 assert(getParent() && "Not embedded in a basic block!");
1086 return getParent()->remove(this);
1089 MachineInstr *MachineInstr::removeFromBundle() {
1090 assert(getParent() && "Not embedded in a basic block!");
1091 return getParent()->remove_instr(this);
1094 void MachineInstr::eraseFromParent() {
1095 assert(getParent() && "Not embedded in a basic block!");
1096 getParent()->erase(this);
1099 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1100 assert(getParent() && "Not embedded in a basic block!");
1101 MachineBasicBlock *MBB = getParent();
1102 MachineFunction *MF = MBB->getParent();
1103 assert(MF && "Not embedded in a function!");
1105 MachineInstr *MI = (MachineInstr *)this;
1106 MachineRegisterInfo &MRI = MF->getRegInfo();
1108 for (const MachineOperand &MO : MI->operands()) {
1109 if (!MO.isReg() || !MO.isDef())
1111 unsigned Reg = MO.getReg();
1112 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1114 MRI.markUsesInDebugValueAsUndef(Reg);
1116 MI->eraseFromParent();
1119 void MachineInstr::eraseFromBundle() {
1120 assert(getParent() && "Not embedded in a basic block!");
1121 getParent()->erase_instr(this);
1124 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1126 unsigned MachineInstr::getNumExplicitOperands() const {
1127 unsigned NumOperands = MCID->getNumOperands();
1128 if (!MCID->isVariadic())
1131 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1132 const MachineOperand &MO = getOperand(i);
1133 if (!MO.isReg() || !MO.isImplicit())
1139 void MachineInstr::bundleWithPred() {
1140 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1141 setFlag(BundledPred);
1142 MachineBasicBlock::instr_iterator Pred = getIterator();
1144 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1145 Pred->setFlag(BundledSucc);
1148 void MachineInstr::bundleWithSucc() {
1149 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1150 setFlag(BundledSucc);
1151 MachineBasicBlock::instr_iterator Succ = getIterator();
1153 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1154 Succ->setFlag(BundledPred);
1157 void MachineInstr::unbundleFromPred() {
1158 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1159 clearFlag(BundledPred);
1160 MachineBasicBlock::instr_iterator Pred = getIterator();
1162 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1163 Pred->clearFlag(BundledSucc);
1166 void MachineInstr::unbundleFromSucc() {
1167 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1168 clearFlag(BundledSucc);
1169 MachineBasicBlock::instr_iterator Succ = getIterator();
1171 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1172 Succ->clearFlag(BundledPred);
1175 bool MachineInstr::isStackAligningInlineAsm() const {
1176 if (isInlineAsm()) {
1177 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1178 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1184 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1185 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1186 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1187 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1190 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1191 unsigned *GroupNo) const {
1192 assert(isInlineAsm() && "Expected an inline asm instruction");
1193 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1195 // Ignore queries about the initial operands.
1196 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1201 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1203 const MachineOperand &FlagMO = getOperand(i);
1204 // If we reach the implicit register operands, stop looking.
1205 if (!FlagMO.isImm())
1207 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1208 if (i + NumOps > OpIdx) {
1218 const DILocalVariable *MachineInstr::getDebugVariable() const {
1219 assert(isDebugValue() && "not a DBG_VALUE");
1220 return cast<DILocalVariable>(getOperand(2).getMetadata());
1223 const DIExpression *MachineInstr::getDebugExpression() const {
1224 assert(isDebugValue() && "not a DBG_VALUE");
1225 return cast<DIExpression>(getOperand(3).getMetadata());
1228 const TargetRegisterClass*
1229 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1230 const TargetInstrInfo *TII,
1231 const TargetRegisterInfo *TRI) const {
1232 assert(getParent() && "Can't have an MBB reference here!");
1233 assert(getParent()->getParent() && "Can't have an MF reference here!");
1234 const MachineFunction &MF = *getParent()->getParent();
1236 // Most opcodes have fixed constraints in their MCInstrDesc.
1238 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1240 if (!getOperand(OpIdx).isReg())
1243 // For tied uses on inline asm, get the constraint from the def.
1245 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1248 // Inline asm stores register class constraints in the flag word.
1249 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1253 unsigned Flag = getOperand(FlagIdx).getImm();
1255 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1256 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1257 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1258 InlineAsm::hasRegClassConstraint(Flag, RCID))
1259 return TRI->getRegClass(RCID);
1261 // Assume that all registers in a memory operand are pointers.
1262 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1263 return TRI->getPointerRegClass(MF);
1268 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1269 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1270 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1271 // Check every operands inside the bundle if we have
1274 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1276 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1277 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1279 // Otherwise, just check the current operands.
1280 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1281 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1285 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1286 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1287 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1288 assert(CurRC && "Invalid initial register class");
1289 // Check if Reg is constrained by some of its use/def from MI.
1290 const MachineOperand &MO = getOperand(OpIdx);
1291 if (!MO.isReg() || MO.getReg() != Reg)
1293 // If yes, accumulate the constraints through the operand.
1294 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1297 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1298 unsigned OpIdx, const TargetRegisterClass *CurRC,
1299 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1300 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1301 const MachineOperand &MO = getOperand(OpIdx);
1302 assert(MO.isReg() &&
1303 "Cannot get register constraints for non-register operand");
1304 assert(CurRC && "Invalid initial register class");
1305 if (unsigned SubIdx = MO.getSubReg()) {
1307 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1309 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1311 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1315 /// Return the number of instructions inside the MI bundle, not counting the
1316 /// header instruction.
1317 unsigned MachineInstr::getBundleSize() const {
1318 MachineBasicBlock::const_instr_iterator I = getIterator();
1320 while (I->isBundledWithSucc()) {
1327 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1328 /// the given register (not considering sub/super-registers).
1329 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1330 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1331 const MachineOperand &MO = getOperand(i);
1332 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1338 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1339 /// the specific register or -1 if it is not found. It further tightens
1340 /// the search criteria to a use that kills the register if isKill is true.
1341 int MachineInstr::findRegisterUseOperandIdx(
1342 unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
1343 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1344 const MachineOperand &MO = getOperand(i);
1345 if (!MO.isReg() || !MO.isUse())
1347 unsigned MOReg = MO.getReg();
1350 if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1351 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1352 TRI->isSubRegister(MOReg, Reg)))
1353 if (!isKill || MO.isKill())
1359 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1360 /// indicating if this instruction reads or writes Reg. This also considers
1361 /// partial defines.
1362 std::pair<bool,bool>
1363 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1364 SmallVectorImpl<unsigned> *Ops) const {
1365 bool PartDef = false; // Partial redefine.
1366 bool FullDef = false; // Full define.
1369 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1370 const MachineOperand &MO = getOperand(i);
1371 if (!MO.isReg() || MO.getReg() != Reg)
1376 Use |= !MO.isUndef();
1377 else if (MO.getSubReg() && !MO.isUndef())
1378 // A partial <def,undef> doesn't count as reading the register.
1383 // A partial redefine uses Reg unless there is also a full define.
1384 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1387 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1388 /// the specified register or -1 if it is not found. If isDead is true, defs
1389 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1390 /// also checks if there is a def of a super-register.
1392 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1393 const TargetRegisterInfo *TRI) const {
1394 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1395 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1396 const MachineOperand &MO = getOperand(i);
1397 // Accept regmask operands when Overlap is set.
1398 // Ignore them when looking for a specific def operand (Overlap == false).
1399 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1401 if (!MO.isReg() || !MO.isDef())
1403 unsigned MOReg = MO.getReg();
1404 bool Found = (MOReg == Reg);
1405 if (!Found && TRI && isPhys &&
1406 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1408 Found = TRI->regsOverlap(MOReg, Reg);
1410 Found = TRI->isSubRegister(MOReg, Reg);
1412 if (Found && (!isDead || MO.isDead()))
1418 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1419 /// operand list that is used to represent the predicate. It returns -1 if
1421 int MachineInstr::findFirstPredOperandIdx() const {
1422 // Don't call MCID.findFirstPredOperandIdx() because this variant
1423 // is sometimes called on an instruction that's not yet complete, and
1424 // so the number of operands is less than the MCID indicates. In
1425 // particular, the PTX target does this.
1426 const MCInstrDesc &MCID = getDesc();
1427 if (MCID.isPredicable()) {
1428 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1429 if (MCID.OpInfo[i].isPredicate())
1436 // MachineOperand::TiedTo is 4 bits wide.
1437 const unsigned TiedMax = 15;
1439 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1441 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1442 /// field. TiedTo can have these values:
1444 /// 0: Operand is not tied to anything.
1445 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1446 /// TiedMax: Tied to an operand >= TiedMax-1.
1448 /// The tied def must be one of the first TiedMax operands on a normal
1449 /// instruction. INLINEASM instructions allow more tied defs.
1451 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1452 MachineOperand &DefMO = getOperand(DefIdx);
1453 MachineOperand &UseMO = getOperand(UseIdx);
1454 assert(DefMO.isDef() && "DefIdx must be a def operand");
1455 assert(UseMO.isUse() && "UseIdx must be a use operand");
1456 assert(!DefMO.isTied() && "Def is already tied to another use");
1457 assert(!UseMO.isTied() && "Use is already tied to another def");
1459 if (DefIdx < TiedMax)
1460 UseMO.TiedTo = DefIdx + 1;
1462 // Inline asm can use the group descriptors to find tied operands, but on
1463 // normal instruction, the tied def must be within the first TiedMax
1465 assert(isInlineAsm() && "DefIdx out of range");
1466 UseMO.TiedTo = TiedMax;
1469 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1470 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1473 /// Given the index of a tied register operand, find the operand it is tied to.
1474 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1475 /// which must exist.
1476 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1477 const MachineOperand &MO = getOperand(OpIdx);
1478 assert(MO.isTied() && "Operand isn't tied");
1480 // Normally TiedTo is in range.
1481 if (MO.TiedTo < TiedMax)
1482 return MO.TiedTo - 1;
1484 // Uses on normal instructions can be out of range.
1485 if (!isInlineAsm()) {
1486 // Normal tied defs must be in the 0..TiedMax-1 range.
1489 // MO is a def. Search for the tied use.
1490 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1491 const MachineOperand &UseMO = getOperand(i);
1492 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1495 llvm_unreachable("Can't find tied use");
1498 // Now deal with inline asm by parsing the operand group descriptor flags.
1499 // Find the beginning of each operand group.
1500 SmallVector<unsigned, 8> GroupIdx;
1501 unsigned OpIdxGroup = ~0u;
1503 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1505 const MachineOperand &FlagMO = getOperand(i);
1506 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1507 unsigned CurGroup = GroupIdx.size();
1508 GroupIdx.push_back(i);
1509 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1510 // OpIdx belongs to this operand group.
1511 if (OpIdx > i && OpIdx < i + NumOps)
1512 OpIdxGroup = CurGroup;
1514 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1516 // Operands in this group are tied to operands in TiedGroup which must be
1517 // earlier. Find the number of operands between the two groups.
1518 unsigned Delta = i - GroupIdx[TiedGroup];
1520 // OpIdx is a use tied to TiedGroup.
1521 if (OpIdxGroup == CurGroup)
1522 return OpIdx - Delta;
1524 // OpIdx is a def tied to this use group.
1525 if (OpIdxGroup == TiedGroup)
1526 return OpIdx + Delta;
1528 llvm_unreachable("Invalid tied operand on inline asm");
1531 /// clearKillInfo - Clears kill flags on all operands.
1533 void MachineInstr::clearKillInfo() {
1534 for (MachineOperand &MO : operands()) {
1535 if (MO.isReg() && MO.isUse())
1536 MO.setIsKill(false);
1540 void MachineInstr::substituteRegister(unsigned FromReg,
1543 const TargetRegisterInfo &RegInfo) {
1544 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1546 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1547 for (MachineOperand &MO : operands()) {
1548 if (!MO.isReg() || MO.getReg() != FromReg)
1550 MO.substPhysReg(ToReg, RegInfo);
1553 for (MachineOperand &MO : operands()) {
1554 if (!MO.isReg() || MO.getReg() != FromReg)
1556 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1561 /// isSafeToMove - Return true if it is safe to move this instruction. If
1562 /// SawStore is set to true, it means that there is a store (or call) between
1563 /// the instruction's location and its intended destination.
1564 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1565 // Ignore stuff that we obviously can't move.
1567 // Treat volatile loads as stores. This is not strictly necessary for
1568 // volatiles, but it is required for atomic loads. It is not allowed to move
1569 // a load across an atomic load with Ordering > Monotonic.
1570 if (mayStore() || isCall() ||
1571 (mayLoad() && hasOrderedMemoryRef())) {
1576 if (isPosition() || isDebugValue() || isTerminator() ||
1577 hasUnmodeledSideEffects())
1580 // See if this instruction does a load. If so, we have to guarantee that the
1581 // loaded value doesn't change between the load and the its intended
1582 // destination. The check for isInvariantLoad gives the targe the chance to
1583 // classify the load as always returning a constant, e.g. a constant pool
1585 if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1586 // Otherwise, this is a real load. If there is a store between the load and
1587 // end of block, we can't move it.
1593 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
1595 const MachineFunction *MF = getParent()->getParent();
1596 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1598 // If neither instruction stores to memory, they can't alias in any
1599 // meaningful way, even if they read from the same address.
1600 if (!mayStore() && !Other.mayStore())
1603 // Let the target decide if memory accesses cannot possibly overlap.
1604 if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
1610 // FIXME: Need to handle multiple memory operands to support all targets.
1611 if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1614 MachineMemOperand *MMOa = *memoperands_begin();
1615 MachineMemOperand *MMOb = *Other.memoperands_begin();
1617 if (!MMOa->getValue() || !MMOb->getValue())
1620 // The following interface to AA is fashioned after DAGCombiner::isAlias
1621 // and operates with MachineMemOperand offset with some important
1623 // - LLVM fundamentally assumes flat address spaces.
1624 // - MachineOperand offset can *only* result from legalization and
1625 // cannot affect queries other than the trivial case of overlap
1627 // - These offsets never wrap and never step outside
1628 // of allocated objects.
1629 // - There should never be any negative offsets here.
1631 // FIXME: Modify API to hide this math from "user"
1632 // FIXME: Even before we go to AA we can reason locally about some
1633 // memory objects. It can save compile time, and possibly catch some
1634 // corner cases not currently covered.
1636 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
1637 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
1639 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
1640 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
1641 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
1643 AliasResult AAResult =
1644 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
1645 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1646 MemoryLocation(MMOb->getValue(), Overlapb,
1647 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1649 return (AAResult != NoAlias);
1652 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1653 /// or volatile memory reference, or if the information describing the memory
1654 /// reference is not available. Return false if it is known to have no ordered
1655 /// memory references.
1656 bool MachineInstr::hasOrderedMemoryRef() const {
1657 // An instruction known never to access memory won't have a volatile access.
1661 !hasUnmodeledSideEffects())
1664 // Otherwise, if the instruction has no memory reference information,
1665 // conservatively assume it wasn't preserved.
1666 if (memoperands_empty())
1669 // Check if any of our memory operands are ordered.
1670 return any_of(memoperands(), [](const MachineMemOperand *MMO) {
1671 return !MMO->isUnordered();
1675 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1676 /// trap and is loading from a location whose value is invariant across a run of
1678 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
1679 // If the instruction doesn't load at all, it isn't an invariant load.
1683 // If the instruction has lost its memoperands, conservatively assume that
1684 // it may not be an invariant load.
1685 if (memoperands_empty())
1688 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1690 for (MachineMemOperand *MMO : memoperands()) {
1691 if (MMO->isVolatile()) return false;
1692 if (MMO->isStore()) return false;
1693 if (MMO->isInvariant() && MMO->isDereferenceable())
1696 // A load from a constant PseudoSourceValue is invariant.
1697 if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1698 if (PSV->isConstant(&MFI))
1701 if (const Value *V = MMO->getValue()) {
1702 // If we have an AliasAnalysis, ask it whether the memory is constant.
1704 AA->pointsToConstantMemory(
1705 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1709 // Otherwise assume conservatively.
1713 // Everything checks out.
1717 /// isConstantValuePHI - If the specified instruction is a PHI that always
1718 /// merges together the same virtual register, return the register, otherwise
1720 unsigned MachineInstr::isConstantValuePHI() const {
1723 assert(getNumOperands() >= 3 &&
1724 "It's illegal to have a PHI without source operands");
1726 unsigned Reg = getOperand(1).getReg();
1727 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1728 if (getOperand(i).getReg() != Reg)
1733 bool MachineInstr::hasUnmodeledSideEffects() const {
1734 if (hasProperty(MCID::UnmodeledSideEffects))
1736 if (isInlineAsm()) {
1737 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1738 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1745 bool MachineInstr::isLoadFoldBarrier() const {
1746 return mayStore() || isCall() || hasUnmodeledSideEffects();
1749 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1751 bool MachineInstr::allDefsAreDead() const {
1752 for (const MachineOperand &MO : operands()) {
1753 if (!MO.isReg() || MO.isUse())
1761 /// copyImplicitOps - Copy implicit register operands from specified
1762 /// instruction to this instruction.
1763 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1764 const MachineInstr &MI) {
1765 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1767 const MachineOperand &MO = MI.getOperand(i);
1768 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1773 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1774 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1780 void MachineInstr::print(raw_ostream &OS, bool SkipOpers, bool SkipDebugLoc,
1781 const TargetInstrInfo *TII) const {
1782 const Module *M = nullptr;
1783 if (const MachineBasicBlock *MBB = getParent())
1784 if (const MachineFunction *MF = MBB->getParent())
1785 M = MF->getFunction()->getParent();
1787 ModuleSlotTracker MST(M);
1788 print(OS, MST, SkipOpers, SkipDebugLoc, TII);
1791 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1792 bool SkipOpers, bool SkipDebugLoc,
1793 const TargetInstrInfo *TII) const {
1794 // We can be a bit tidier if we know the MachineFunction.
1795 const MachineFunction *MF = nullptr;
1796 const TargetRegisterInfo *TRI = nullptr;
1797 const MachineRegisterInfo *MRI = nullptr;
1798 const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1800 if (const MachineBasicBlock *MBB = getParent()) {
1801 MF = MBB->getParent();
1803 MRI = &MF->getRegInfo();
1804 TRI = MF->getSubtarget().getRegisterInfo();
1806 TII = MF->getSubtarget().getInstrInfo();
1807 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
1811 // Save a list of virtual registers.
1812 SmallVector<unsigned, 8> VirtRegs;
1814 // Print explicitly defined operands on the left of an assignment syntax.
1815 unsigned StartOp = 0, e = getNumOperands();
1816 for (; StartOp < e && getOperand(StartOp).isReg() &&
1817 getOperand(StartOp).isDef() &&
1818 !getOperand(StartOp).isImplicit();
1820 if (StartOp != 0) OS << ", ";
1821 getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
1822 unsigned Reg = getOperand(StartOp).getReg();
1823 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1824 VirtRegs.push_back(Reg);
1825 LLT Ty = MRI ? MRI->getType(Reg) : LLT{};
1827 OS << '(' << Ty << ')';
1834 // Print the opcode name.
1836 OS << TII->getName(getOpcode());
1843 // Print the rest of the operands.
1844 bool OmittedAnyCallClobbers = false;
1845 bool FirstOp = true;
1846 unsigned AsmDescOp = ~0u;
1847 unsigned AsmOpCount = 0;
1849 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1850 // Print asm string.
1852 getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1854 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1855 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1856 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1857 OS << " [sideeffect]";
1858 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1860 if (ExtraInfo & InlineAsm::Extra_MayStore)
1861 OS << " [maystore]";
1862 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1863 OS << " [isconvergent]";
1864 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1865 OS << " [alignstack]";
1866 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1867 OS << " [attdialect]";
1868 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1869 OS << " [inteldialect]";
1871 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1875 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1876 const MachineOperand &MO = getOperand(i);
1878 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1879 VirtRegs.push_back(MO.getReg());
1881 // Omit call-clobbered registers which aren't used anywhere. This makes
1882 // call instructions much less noisy on targets where calls clobber lots
1883 // of registers. Don't rely on MO.isDead() because we may be called before
1884 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1885 if (MRI && isCall() &&
1886 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1887 unsigned Reg = MO.getReg();
1888 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1889 if (MRI->use_empty(Reg)) {
1890 bool HasAliasLive = false;
1891 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
1892 unsigned AliasReg = *AI;
1893 if (!MRI->use_empty(AliasReg)) {
1894 HasAliasLive = true;
1898 if (!HasAliasLive) {
1899 OmittedAnyCallClobbers = true;
1906 if (FirstOp) FirstOp = false; else OS << ",";
1908 if (i < getDesc().NumOperands) {
1909 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1910 if (MCOI.isPredicate())
1912 if (MCOI.isOptionalDef())
1915 if (isDebugValue() && MO.isMetadata()) {
1916 // Pretty print DBG_VALUE instructions.
1917 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1918 if (DIV && !DIV->getName().empty())
1919 OS << "!\"" << DIV->getName() << '\"';
1921 MO.print(OS, MST, TRI);
1922 } else if (TRI && (isInsertSubreg() || isRegSequence() ||
1923 (isSubregToReg() && i == 3)) && MO.isImm()) {
1924 OS << TRI->getSubRegIndexName(MO.getImm());
1925 } else if (i == AsmDescOp && MO.isImm()) {
1926 // Pretty print the inline asm operand descriptor.
1927 OS << '$' << AsmOpCount++;
1928 unsigned Flag = MO.getImm();
1929 switch (InlineAsm::getKind(Flag)) {
1930 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1931 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1932 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1933 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1934 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1935 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1936 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1940 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1941 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1943 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1945 OS << ":RC" << RCID;
1948 if (InlineAsm::isMemKind(Flag)) {
1949 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1951 case InlineAsm::Constraint_es: OS << ":es"; break;
1952 case InlineAsm::Constraint_i: OS << ":i"; break;
1953 case InlineAsm::Constraint_m: OS << ":m"; break;
1954 case InlineAsm::Constraint_o: OS << ":o"; break;
1955 case InlineAsm::Constraint_v: OS << ":v"; break;
1956 case InlineAsm::Constraint_Q: OS << ":Q"; break;
1957 case InlineAsm::Constraint_R: OS << ":R"; break;
1958 case InlineAsm::Constraint_S: OS << ":S"; break;
1959 case InlineAsm::Constraint_T: OS << ":T"; break;
1960 case InlineAsm::Constraint_Um: OS << ":Um"; break;
1961 case InlineAsm::Constraint_Un: OS << ":Un"; break;
1962 case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1963 case InlineAsm::Constraint_Us: OS << ":Us"; break;
1964 case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1965 case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1966 case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1967 case InlineAsm::Constraint_X: OS << ":X"; break;
1968 case InlineAsm::Constraint_Z: OS << ":Z"; break;
1969 case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1970 case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1971 default: OS << ":?"; break;
1975 unsigned TiedTo = 0;
1976 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1977 OS << " tiedto:$" << TiedTo;
1981 // Compute the index of the next operand descriptor.
1982 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1984 MO.print(OS, MST, TRI);
1987 // Briefly indicate whether any call clobbers were omitted.
1988 if (OmittedAnyCallClobbers) {
1989 if (!FirstOp) OS << ",";
1993 bool HaveSemi = false;
1994 const unsigned PrintableFlags = FrameSetup | FrameDestroy;
1995 if (Flags & PrintableFlags) {
2002 if (Flags & FrameSetup)
2005 if (Flags & FrameDestroy)
2006 OS << "FrameDestroy";
2009 if (!memoperands_empty()) {
2016 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
2018 (*i)->print(OS, MST);
2019 if (std::next(i) != e)
2024 // Print the regclass of any virtual registers encountered.
2025 if (MRI && !VirtRegs.empty()) {
2030 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
2031 const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
2034 // Generic virtual registers do not have register classes.
2035 if (RC.is<const RegisterBank *>())
2036 OS << " " << RC.get<const RegisterBank *>()->getName();
2039 << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
2040 OS << ':' << PrintReg(VirtRegs[i]);
2041 for (unsigned j = i+1; j != VirtRegs.size();) {
2042 if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
2046 if (VirtRegs[i] != VirtRegs[j])
2047 OS << "," << PrintReg(VirtRegs[j]);
2048 VirtRegs.erase(VirtRegs.begin()+j);
2053 // Print debug location information.
2054 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
2057 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
2058 OS << " line no:" << DV->getLine();
2059 if (auto *InlinedAt = debugLoc->getInlinedAt()) {
2060 DebugLoc InlinedAtDL(InlinedAt);
2061 if (InlinedAtDL && MF) {
2062 OS << " inlined @[ ";
2063 InlinedAtDL.print(OS);
2067 if (isIndirectDebugValue())
2069 } else if (SkipDebugLoc) {
2071 } else if (debugLoc && MF) {
2081 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
2082 const TargetRegisterInfo *RegInfo,
2083 bool AddIfNotFound) {
2084 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
2085 bool hasAliases = isPhysReg &&
2086 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
2088 SmallVector<unsigned,4> DeadOps;
2089 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2090 MachineOperand &MO = getOperand(i);
2091 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
2094 // DEBUG_VALUE nodes do not contribute to code generation and should
2095 // always be ignored. Failure to do so may result in trying to modify
2096 // KILL flags on DEBUG_VALUE nodes.
2100 unsigned Reg = MO.getReg();
2104 if (Reg == IncomingReg) {
2107 // The register is already marked kill.
2109 if (isPhysReg && isRegTiedToDefOperand(i))
2110 // Two-address uses of physregs must not be marked kill.
2115 } else if (hasAliases && MO.isKill() &&
2116 TargetRegisterInfo::isPhysicalRegister(Reg)) {
2117 // A super-register kill already exists.
2118 if (RegInfo->isSuperRegister(IncomingReg, Reg))
2120 if (RegInfo->isSubRegister(IncomingReg, Reg))
2121 DeadOps.push_back(i);
2125 // Trim unneeded kill operands.
2126 while (!DeadOps.empty()) {
2127 unsigned OpIdx = DeadOps.back();
2128 if (getOperand(OpIdx).isImplicit())
2129 RemoveOperand(OpIdx);
2131 getOperand(OpIdx).setIsKill(false);
2135 // If not found, this means an alias of one of the operands is killed. Add a
2136 // new implicit operand if required.
2137 if (!Found && AddIfNotFound) {
2138 addOperand(MachineOperand::CreateReg(IncomingReg,
2147 void MachineInstr::clearRegisterKills(unsigned Reg,
2148 const TargetRegisterInfo *RegInfo) {
2149 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2151 for (MachineOperand &MO : operands()) {
2152 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2154 unsigned OpReg = MO.getReg();
2155 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2156 MO.setIsKill(false);
2160 bool MachineInstr::addRegisterDead(unsigned Reg,
2161 const TargetRegisterInfo *RegInfo,
2162 bool AddIfNotFound) {
2163 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2164 bool hasAliases = isPhysReg &&
2165 MCRegAliasIterator(Reg, RegInfo, false).isValid();
2167 SmallVector<unsigned,4> DeadOps;
2168 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2169 MachineOperand &MO = getOperand(i);
2170 if (!MO.isReg() || !MO.isDef())
2172 unsigned MOReg = MO.getReg();
2179 } else if (hasAliases && MO.isDead() &&
2180 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2181 // There exists a super-register that's marked dead.
2182 if (RegInfo->isSuperRegister(Reg, MOReg))
2184 if (RegInfo->isSubRegister(Reg, MOReg))
2185 DeadOps.push_back(i);
2189 // Trim unneeded dead operands.
2190 while (!DeadOps.empty()) {
2191 unsigned OpIdx = DeadOps.back();
2192 if (getOperand(OpIdx).isImplicit())
2193 RemoveOperand(OpIdx);
2195 getOperand(OpIdx).setIsDead(false);
2199 // If not found, this means an alias of one of the operands is dead. Add a
2200 // new implicit operand if required.
2201 if (Found || !AddIfNotFound)
2204 addOperand(MachineOperand::CreateReg(Reg,
2212 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2213 for (MachineOperand &MO : operands()) {
2214 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2216 MO.setIsDead(false);
2220 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2221 for (MachineOperand &MO : operands()) {
2222 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2224 MO.setIsUndef(IsUndef);
2228 void MachineInstr::addRegisterDefined(unsigned Reg,
2229 const TargetRegisterInfo *RegInfo) {
2230 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2231 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2235 for (const MachineOperand &MO : operands()) {
2236 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2237 MO.getSubReg() == 0)
2241 addOperand(MachineOperand::CreateReg(Reg,
2246 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2247 const TargetRegisterInfo &TRI) {
2248 bool HasRegMask = false;
2249 for (MachineOperand &MO : operands()) {
2250 if (MO.isRegMask()) {
2254 if (!MO.isReg() || !MO.isDef()) continue;
2255 unsigned Reg = MO.getReg();
2256 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2257 // If there are no uses, including partial uses, the def is dead.
2258 if (none_of(UsedRegs,
2259 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2263 // This is a call with a register mask operand.
2264 // Mask clobbers are always dead, so add defs for the non-dead defines.
2266 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2268 addRegisterDefined(*I, &TRI);
2272 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2273 // Build up a buffer of hash code components.
2274 SmallVector<size_t, 8> HashComponents;
2275 HashComponents.reserve(MI->getNumOperands() + 1);
2276 HashComponents.push_back(MI->getOpcode());
2277 for (const MachineOperand &MO : MI->operands()) {
2278 if (MO.isReg() && MO.isDef() &&
2279 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2280 continue; // Skip virtual register defs.
2282 HashComponents.push_back(hash_value(MO));
2284 return hash_combine_range(HashComponents.begin(), HashComponents.end());
2287 void MachineInstr::emitError(StringRef Msg) const {
2288 // Find the source location cookie.
2289 unsigned LocCookie = 0;
2290 const MDNode *LocMD = nullptr;
2291 for (unsigned i = getNumOperands(); i != 0; --i) {
2292 if (getOperand(i-1).isMetadata() &&
2293 (LocMD = getOperand(i-1).getMetadata()) &&
2294 LocMD->getNumOperands() != 0) {
2295 if (const ConstantInt *CI =
2296 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2297 LocCookie = CI->getZExtValue();
2303 if (const MachineBasicBlock *MBB = getParent())
2304 if (const MachineFunction *MF = MBB->getParent())
2305 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2306 report_fatal_error(Msg);
2309 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2310 const MCInstrDesc &MCID, bool IsIndirect,
2311 unsigned Reg, unsigned Offset,
2312 const MDNode *Variable, const MDNode *Expr) {
2313 assert(isa<DILocalVariable>(Variable) && "not a variable");
2314 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2315 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2316 "Expected inlined-at fields to agree");
2318 return BuildMI(MF, DL, MCID)
2319 .addReg(Reg, RegState::Debug)
2321 .addMetadata(Variable)
2324 assert(Offset == 0 && "A direct address cannot have an offset.");
2325 return BuildMI(MF, DL, MCID)
2326 .addReg(Reg, RegState::Debug)
2327 .addReg(0U, RegState::Debug)
2328 .addMetadata(Variable)
2333 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2334 MachineBasicBlock::iterator I,
2335 const DebugLoc &DL, const MCInstrDesc &MCID,
2336 bool IsIndirect, unsigned Reg,
2337 unsigned Offset, const MDNode *Variable,
2338 const MDNode *Expr) {
2339 assert(isa<DILocalVariable>(Variable) && "not a variable");
2340 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2341 MachineFunction &MF = *BB.getParent();
2343 BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr);
2345 return MachineInstrBuilder(MF, MI);
2348 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2349 MachineBasicBlock::iterator I,
2350 const MachineInstr &Orig,
2352 const MDNode *Var = Orig.getDebugVariable();
2353 auto *Expr = cast_or_null<DIExpression>(Orig.getDebugExpression());
2354 bool IsIndirect = Orig.isIndirectDebugValue();
2355 uint64_t Offset = IsIndirect ? Orig.getOperand(1).getImm() : 0;
2356 DebugLoc DL = Orig.getDebugLoc();
2357 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
2358 "Expected inlined-at fields to agree");
2359 // If the DBG_VALUE already was a memory location, add an extra
2360 // DW_OP_deref. Otherwise just turning this from a register into a
2361 // memory/indirect location is sufficient.
2363 SmallVector<uint64_t, 8> Ops;
2364 Ops.push_back(dwarf::DW_OP_deref);
2366 Ops.append(Expr->elements_begin(), Expr->elements_end());
2367 Expr = DIExpression::get(Expr->getContext(), Ops);
2369 return BuildMI(BB, I, DL, Orig.getDesc())
2370 .addFrameIndex(FrameIndex)