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/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
45 //===----------------------------------------------------------------------===//
46 // MachineOperand Implementation
47 //===----------------------------------------------------------------------===//
49 void MachineOperand::setReg(unsigned Reg) {
50 if (getReg() == Reg) return; // No change.
52 // Otherwise, we have to change the register. If this operand is embedded
53 // into a machine function, we need to update the old and new register's
55 if (MachineInstr *MI = getParent())
56 if (MachineBasicBlock *MBB = MI->getParent())
57 if (MachineFunction *MF = MBB->getParent()) {
58 MachineRegisterInfo &MRI = MF->getRegInfo();
59 MRI.removeRegOperandFromUseList(this);
60 SmallContents.RegNo = Reg;
61 MRI.addRegOperandToUseList(this);
65 // Otherwise, just change the register, no problem. :)
66 SmallContents.RegNo = Reg;
69 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
70 const TargetRegisterInfo &TRI) {
71 assert(TargetRegisterInfo::isVirtualRegister(Reg));
72 if (SubIdx && getSubReg())
73 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
79 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
80 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
82 Reg = TRI.getSubReg(Reg, getSubReg());
83 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
84 // That won't happen in legal code.
90 /// Change a def to a use, or a use to a def.
91 void MachineOperand::setIsDef(bool Val) {
92 assert(isReg() && "Wrong MachineOperand accessor");
93 assert((!Val || !isDebug()) && "Marking a debug operation as def");
96 // MRI may keep uses and defs in different list positions.
97 if (MachineInstr *MI = getParent())
98 if (MachineBasicBlock *MBB = MI->getParent())
99 if (MachineFunction *MF = MBB->getParent()) {
100 MachineRegisterInfo &MRI = MF->getRegInfo();
101 MRI.removeRegOperandFromUseList(this);
103 MRI.addRegOperandToUseList(this);
109 // If this operand is currently a register operand, and if this is in a
110 // function, deregister the operand from the register's use/def list.
111 void MachineOperand::removeRegFromUses() {
112 if (!isReg() || !isOnRegUseList())
115 if (MachineInstr *MI = getParent()) {
116 if (MachineBasicBlock *MBB = MI->getParent()) {
117 if (MachineFunction *MF = MBB->getParent())
118 MF->getRegInfo().removeRegOperandFromUseList(this);
123 /// ChangeToImmediate - Replace this operand with a new immediate operand of
124 /// the specified value. If an operand is known to be an immediate already,
125 /// the setImm method should be used.
126 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
127 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
131 OpKind = MO_Immediate;
132 Contents.ImmVal = ImmVal;
135 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
136 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
140 OpKind = MO_FPImmediate;
141 Contents.CFP = FPImm;
144 /// ChangeToRegister - Replace this operand with a new register operand of
145 /// the specified value. If an operand is known to be an register already,
146 /// the setReg method should be used.
147 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
148 bool isKill, bool isDead, bool isUndef,
150 MachineRegisterInfo *RegInfo = nullptr;
151 if (MachineInstr *MI = getParent())
152 if (MachineBasicBlock *MBB = MI->getParent())
153 if (MachineFunction *MF = MBB->getParent())
154 RegInfo = &MF->getRegInfo();
155 // If this operand is already a register operand, remove it from the
156 // register's use/def lists.
157 bool WasReg = isReg();
158 if (RegInfo && WasReg)
159 RegInfo->removeRegOperandFromUseList(this);
161 // Change this to a register and set the reg#.
162 OpKind = MO_Register;
163 SmallContents.RegNo = Reg;
164 SubReg_TargetFlags = 0;
170 IsInternalRead = false;
171 IsEarlyClobber = false;
173 // Ensure isOnRegUseList() returns false.
174 Contents.Reg.Prev = nullptr;
175 // Preserve the tie when the operand was already a register.
179 // If this operand is embedded in a function, add the operand to the
180 // register's use/def list.
182 RegInfo->addRegOperandToUseList(this);
185 /// isIdenticalTo - Return true if this operand is identical to the specified
186 /// operand. Note that this should stay in sync with the hash_value overload
188 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
189 if (getType() != Other.getType() ||
190 getTargetFlags() != Other.getTargetFlags())
194 case MachineOperand::MO_Register:
195 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
196 getSubReg() == Other.getSubReg();
197 case MachineOperand::MO_Immediate:
198 return getImm() == Other.getImm();
199 case MachineOperand::MO_CImmediate:
200 return getCImm() == Other.getCImm();
201 case MachineOperand::MO_FPImmediate:
202 return getFPImm() == Other.getFPImm();
203 case MachineOperand::MO_MachineBasicBlock:
204 return getMBB() == Other.getMBB();
205 case MachineOperand::MO_FrameIndex:
206 return getIndex() == Other.getIndex();
207 case MachineOperand::MO_ConstantPoolIndex:
208 case MachineOperand::MO_TargetIndex:
209 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
210 case MachineOperand::MO_JumpTableIndex:
211 return getIndex() == Other.getIndex();
212 case MachineOperand::MO_GlobalAddress:
213 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
214 case MachineOperand::MO_ExternalSymbol:
215 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
216 getOffset() == Other.getOffset();
217 case MachineOperand::MO_BlockAddress:
218 return getBlockAddress() == Other.getBlockAddress() &&
219 getOffset() == Other.getOffset();
220 case MachineOperand::MO_RegisterMask:
221 case MachineOperand::MO_RegisterLiveOut:
222 return getRegMask() == Other.getRegMask();
223 case MachineOperand::MO_MCSymbol:
224 return getMCSymbol() == Other.getMCSymbol();
225 case MachineOperand::MO_CFIIndex:
226 return getCFIIndex() == Other.getCFIIndex();
227 case MachineOperand::MO_Metadata:
228 return getMetadata() == Other.getMetadata();
230 llvm_unreachable("Invalid machine operand type");
233 // Note: this must stay exactly in sync with isIdenticalTo above.
234 hash_code llvm::hash_value(const MachineOperand &MO) {
235 switch (MO.getType()) {
236 case MachineOperand::MO_Register:
237 // Register operands don't have target flags.
238 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
239 case MachineOperand::MO_Immediate:
240 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
241 case MachineOperand::MO_CImmediate:
242 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
243 case MachineOperand::MO_FPImmediate:
244 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
245 case MachineOperand::MO_MachineBasicBlock:
246 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
247 case MachineOperand::MO_FrameIndex:
248 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
249 case MachineOperand::MO_ConstantPoolIndex:
250 case MachineOperand::MO_TargetIndex:
251 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
253 case MachineOperand::MO_JumpTableIndex:
254 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
255 case MachineOperand::MO_ExternalSymbol:
256 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
258 case MachineOperand::MO_GlobalAddress:
259 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
261 case MachineOperand::MO_BlockAddress:
262 return hash_combine(MO.getType(), MO.getTargetFlags(),
263 MO.getBlockAddress(), MO.getOffset());
264 case MachineOperand::MO_RegisterMask:
265 case MachineOperand::MO_RegisterLiveOut:
266 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
267 case MachineOperand::MO_Metadata:
268 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
269 case MachineOperand::MO_MCSymbol:
270 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
271 case MachineOperand::MO_CFIIndex:
272 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
274 llvm_unreachable("Invalid machine operand type");
277 /// print - Print the specified machine operand.
279 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
280 // If the instruction is embedded into a basic block, we can find the
281 // target info for the instruction.
283 if (const MachineInstr *MI = getParent())
284 if (const MachineBasicBlock *MBB = MI->getParent())
285 if (const MachineFunction *MF = MBB->getParent())
286 TM = &MF->getTarget();
287 const TargetRegisterInfo *TRI =
288 TM ? TM->getSubtargetImpl()->getRegisterInfo() : nullptr;
291 case MachineOperand::MO_Register:
292 OS << PrintReg(getReg(), TRI, getSubReg());
294 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
295 isInternalRead() || isEarlyClobber() || isTied()) {
297 bool NeedComma = false;
299 if (NeedComma) OS << ',';
300 if (isEarlyClobber())
301 OS << "earlyclobber,";
306 // <def,read-undef> only makes sense when getSubReg() is set.
307 // Don't clutter the output otherwise.
308 if (isUndef() && getSubReg())
310 } else if (isImplicit()) {
316 if (NeedComma) OS << ',';
321 if (NeedComma) OS << ',';
325 if (isUndef() && isUse()) {
326 if (NeedComma) OS << ',';
330 if (isInternalRead()) {
331 if (NeedComma) OS << ',';
336 if (NeedComma) OS << ',';
339 OS << unsigned(TiedTo - 1);
344 case MachineOperand::MO_Immediate:
347 case MachineOperand::MO_CImmediate:
348 getCImm()->getValue().print(OS, false);
350 case MachineOperand::MO_FPImmediate:
351 if (getFPImm()->getType()->isFloatTy())
352 OS << getFPImm()->getValueAPF().convertToFloat();
354 OS << getFPImm()->getValueAPF().convertToDouble();
356 case MachineOperand::MO_MachineBasicBlock:
357 OS << "<BB#" << getMBB()->getNumber() << ">";
359 case MachineOperand::MO_FrameIndex:
360 OS << "<fi#" << getIndex() << '>';
362 case MachineOperand::MO_ConstantPoolIndex:
363 OS << "<cp#" << getIndex();
364 if (getOffset()) OS << "+" << getOffset();
367 case MachineOperand::MO_TargetIndex:
368 OS << "<ti#" << getIndex();
369 if (getOffset()) OS << "+" << getOffset();
372 case MachineOperand::MO_JumpTableIndex:
373 OS << "<jt#" << getIndex() << '>';
375 case MachineOperand::MO_GlobalAddress:
377 getGlobal()->printAsOperand(OS, /*PrintType=*/false);
378 if (getOffset()) OS << "+" << getOffset();
381 case MachineOperand::MO_ExternalSymbol:
382 OS << "<es:" << getSymbolName();
383 if (getOffset()) OS << "+" << getOffset();
386 case MachineOperand::MO_BlockAddress:
388 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false);
389 if (getOffset()) OS << "+" << getOffset();
392 case MachineOperand::MO_RegisterMask:
395 case MachineOperand::MO_RegisterLiveOut:
396 OS << "<regliveout>";
398 case MachineOperand::MO_Metadata:
400 getMetadata()->printAsOperand(OS, /*PrintType=*/false);
403 case MachineOperand::MO_MCSymbol:
404 OS << "<MCSym=" << *getMCSymbol() << '>';
406 case MachineOperand::MO_CFIIndex:
407 OS << "<call frame instruction>";
411 if (unsigned TF = getTargetFlags())
412 OS << "[TF=" << TF << ']';
415 //===----------------------------------------------------------------------===//
416 // MachineMemOperand Implementation
417 //===----------------------------------------------------------------------===//
419 /// getAddrSpace - Return the LLVM IR address space number that this pointer
421 unsigned MachinePointerInfo::getAddrSpace() const {
422 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
423 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
426 /// getConstantPool - Return a MachinePointerInfo record that refers to the
428 MachinePointerInfo MachinePointerInfo::getConstantPool() {
429 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
432 /// getFixedStack - Return a MachinePointerInfo record that refers to the
433 /// the specified FrameIndex.
434 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
435 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
438 MachinePointerInfo MachinePointerInfo::getJumpTable() {
439 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
442 MachinePointerInfo MachinePointerInfo::getGOT() {
443 return MachinePointerInfo(PseudoSourceValue::getGOT());
446 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
447 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
450 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
451 uint64_t s, unsigned int a,
452 const AAMDNodes &AAInfo,
453 const MDNode *Ranges)
454 : PtrInfo(ptrinfo), Size(s),
455 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
456 AAInfo(AAInfo), Ranges(Ranges) {
457 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
458 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
459 "invalid pointer value");
460 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
461 assert((isLoad() || isStore()) && "Not a load/store!");
464 /// Profile - Gather unique data for the object.
466 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
467 ID.AddInteger(getOffset());
469 ID.AddPointer(getOpaqueValue());
470 ID.AddInteger(Flags);
473 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
474 // The Value and Offset may differ due to CSE. But the flags and size
475 // should be the same.
476 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
477 assert(MMO->getSize() == getSize() && "Size mismatch!");
479 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
480 // Update the alignment value.
481 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
482 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
483 // Also update the base and offset, because the new alignment may
484 // not be applicable with the old ones.
485 PtrInfo = MMO->PtrInfo;
489 /// getAlignment - Return the minimum known alignment in bytes of the
490 /// actual memory reference.
491 uint64_t MachineMemOperand::getAlignment() const {
492 return MinAlign(getBaseAlignment(), getOffset());
495 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
496 assert((MMO.isLoad() || MMO.isStore()) &&
497 "SV has to be a load, store or both.");
499 if (MMO.isVolatile())
508 // Print the address information.
510 if (const Value *V = MMO.getValue())
511 V->printAsOperand(OS, /*PrintType=*/false);
512 else if (const PseudoSourceValue *PSV = MMO.getPseudoValue())
513 PSV->printCustom(OS);
517 unsigned AS = MMO.getAddrSpace();
519 OS << "(addrspace=" << AS << ')';
521 // If the alignment of the memory reference itself differs from the alignment
522 // of the base pointer, print the base alignment explicitly, next to the base
524 if (MMO.getBaseAlignment() != MMO.getAlignment())
525 OS << "(align=" << MMO.getBaseAlignment() << ")";
527 if (MMO.getOffset() != 0)
528 OS << "+" << MMO.getOffset();
531 // Print the alignment of the reference.
532 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
533 MMO.getBaseAlignment() != MMO.getSize())
534 OS << "(align=" << MMO.getAlignment() << ")";
537 if (const MDNode *TBAAInfo = MMO.getAAInfo().TBAA) {
539 if (TBAAInfo->getNumOperands() > 0)
540 TBAAInfo->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
546 // Print AA scope info.
547 if (const MDNode *ScopeInfo = MMO.getAAInfo().Scope) {
548 OS << "(alias.scope=";
549 if (ScopeInfo->getNumOperands() > 0)
550 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
551 ScopeInfo->getOperand(i)->printAsOperand(OS, /*PrintType=*/false);
560 // Print AA noalias scope info.
561 if (const MDNode *NoAliasInfo = MMO.getAAInfo().NoAlias) {
563 if (NoAliasInfo->getNumOperands() > 0)
564 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
565 NoAliasInfo->getOperand(i)->printAsOperand(OS, /*PrintType=*/false);
574 // Print nontemporal info.
575 if (MMO.isNonTemporal())
576 OS << "(nontemporal)";
581 //===----------------------------------------------------------------------===//
582 // MachineInstr Implementation
583 //===----------------------------------------------------------------------===//
585 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
586 if (MCID->ImplicitDefs)
587 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
588 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
589 if (MCID->ImplicitUses)
590 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
591 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
594 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
595 /// implicit operands. It reserves space for the number of operands specified by
597 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
598 const DebugLoc dl, bool NoImp)
599 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0),
600 Flags(0), AsmPrinterFlags(0),
601 NumMemRefs(0), MemRefs(nullptr), debugLoc(dl) {
602 // Reserve space for the expected number of operands.
603 if (unsigned NumOps = MCID->getNumOperands() +
604 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
605 CapOperands = OperandCapacity::get(NumOps);
606 Operands = MF.allocateOperandArray(CapOperands);
610 addImplicitDefUseOperands(MF);
613 /// MachineInstr ctor - Copies MachineInstr arg exactly
615 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
616 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
617 Flags(0), AsmPrinterFlags(0),
618 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
619 debugLoc(MI.getDebugLoc()) {
620 CapOperands = OperandCapacity::get(MI.getNumOperands());
621 Operands = MF.allocateOperandArray(CapOperands);
624 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
625 addOperand(MF, MI.getOperand(i));
627 // Copy all the sensible flags.
631 /// getRegInfo - If this instruction is embedded into a MachineFunction,
632 /// return the MachineRegisterInfo object for the current function, otherwise
634 MachineRegisterInfo *MachineInstr::getRegInfo() {
635 if (MachineBasicBlock *MBB = getParent())
636 return &MBB->getParent()->getRegInfo();
640 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
641 /// this instruction from their respective use lists. This requires that the
642 /// operands already be on their use lists.
643 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
644 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
645 if (Operands[i].isReg())
646 MRI.removeRegOperandFromUseList(&Operands[i]);
649 /// AddRegOperandsToUseLists - Add all of the register operands in
650 /// this instruction from their respective use lists. This requires that the
651 /// operands not be on their use lists yet.
652 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
653 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
654 if (Operands[i].isReg())
655 MRI.addRegOperandToUseList(&Operands[i]);
658 void MachineInstr::addOperand(const MachineOperand &Op) {
659 MachineBasicBlock *MBB = getParent();
660 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
661 MachineFunction *MF = MBB->getParent();
662 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
666 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
667 /// ranges. If MRI is non-null also update use-def chains.
668 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
669 unsigned NumOps, MachineRegisterInfo *MRI) {
671 return MRI->moveOperands(Dst, Src, NumOps);
673 // Here it would be convenient to call memmove, so that isn't allowed because
674 // MachineOperand has a constructor and so isn't a POD type.
676 for (unsigned i = 0; i != NumOps; ++i)
677 new (Dst + i) MachineOperand(Src[i]);
679 for (unsigned i = NumOps; i ; --i)
680 new (Dst + i - 1) MachineOperand(Src[i - 1]);
683 /// addOperand - Add the specified operand to the instruction. If it is an
684 /// implicit operand, it is added to the end of the operand list. If it is
685 /// an explicit operand it is added at the end of the explicit operand list
686 /// (before the first implicit operand).
687 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
688 assert(MCID && "Cannot add operands before providing an instr descriptor");
690 // Check if we're adding one of our existing operands.
691 if (&Op >= Operands && &Op < Operands + NumOperands) {
692 // This is unusual: MI->addOperand(MI->getOperand(i)).
693 // If adding Op requires reallocating or moving existing operands around,
694 // the Op reference could go stale. Support it by copying Op.
695 MachineOperand CopyOp(Op);
696 return addOperand(MF, CopyOp);
699 // Find the insert location for the new operand. Implicit registers go at
700 // the end, everything else goes before the implicit regs.
702 // FIXME: Allow mixed explicit and implicit operands on inline asm.
703 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
704 // implicit-defs, but they must not be moved around. See the FIXME in
706 unsigned OpNo = getNumOperands();
707 bool isImpReg = Op.isReg() && Op.isImplicit();
708 if (!isImpReg && !isInlineAsm()) {
709 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
711 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
716 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
717 // OpNo now points as the desired insertion point. Unless this is a variadic
718 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
719 // RegMask operands go between the explicit and implicit operands.
720 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
721 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
722 "Trying to add an operand to a machine instr that is already done!");
725 MachineRegisterInfo *MRI = getRegInfo();
727 // Determine if the Operands array needs to be reallocated.
728 // Save the old capacity and operand array.
729 OperandCapacity OldCap = CapOperands;
730 MachineOperand *OldOperands = Operands;
731 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
732 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
733 Operands = MF.allocateOperandArray(CapOperands);
734 // Move the operands before the insertion point.
736 moveOperands(Operands, OldOperands, OpNo, MRI);
739 // Move the operands following the insertion point.
740 if (OpNo != NumOperands)
741 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
745 // Deallocate the old operand array.
746 if (OldOperands != Operands && OldOperands)
747 MF.deallocateOperandArray(OldCap, OldOperands);
749 // Copy Op into place. It still needs to be inserted into the MRI use lists.
750 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
751 NewMO->ParentMI = this;
753 // When adding a register operand, tell MRI about it.
754 if (NewMO->isReg()) {
755 // Ensure isOnRegUseList() returns false, regardless of Op's status.
756 NewMO->Contents.Reg.Prev = nullptr;
757 // Ignore existing ties. This is not a property that can be copied.
759 // Add the new operand to MRI, but only for instructions in an MBB.
761 MRI->addRegOperandToUseList(NewMO);
762 // The MCID operand information isn't accurate until we start adding
763 // explicit operands. The implicit operands are added first, then the
764 // explicits are inserted before them.
766 // Tie uses to defs as indicated in MCInstrDesc.
767 if (NewMO->isUse()) {
768 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
770 tieOperands(DefIdx, OpNo);
772 // If the register operand is flagged as early, mark the operand as such.
773 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
774 NewMO->setIsEarlyClobber(true);
779 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
780 /// fewer operand than it started with.
782 void MachineInstr::RemoveOperand(unsigned OpNo) {
783 assert(OpNo < getNumOperands() && "Invalid operand number");
784 untieRegOperand(OpNo);
787 // Moving tied operands would break the ties.
788 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
789 if (Operands[i].isReg())
790 assert(!Operands[i].isTied() && "Cannot move tied operands");
793 MachineRegisterInfo *MRI = getRegInfo();
794 if (MRI && Operands[OpNo].isReg())
795 MRI->removeRegOperandFromUseList(Operands + OpNo);
797 // Don't call the MachineOperand destructor. A lot of this code depends on
798 // MachineOperand having a trivial destructor anyway, and adding a call here
799 // wouldn't make it 'destructor-correct'.
801 if (unsigned N = NumOperands - 1 - OpNo)
802 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
806 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
807 /// This function should be used only occasionally. The setMemRefs function
808 /// is the primary method for setting up a MachineInstr's MemRefs list.
809 void MachineInstr::addMemOperand(MachineFunction &MF,
810 MachineMemOperand *MO) {
811 mmo_iterator OldMemRefs = MemRefs;
812 unsigned OldNumMemRefs = NumMemRefs;
814 unsigned NewNum = NumMemRefs + 1;
815 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
817 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
818 NewMemRefs[NewNum - 1] = MO;
819 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
822 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
823 assert(!isBundledWithPred() && "Must be called on bundle header");
824 for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
825 if (MII->getDesc().getFlags() & Mask) {
826 if (Type == AnyInBundle)
829 if (Type == AllInBundle && !MII->isBundle())
832 // This was the last instruction in the bundle.
833 if (!MII->isBundledWithSucc())
834 return Type == AllInBundle;
838 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
839 MICheckType Check) const {
840 // If opcodes or number of operands are not the same then the two
841 // instructions are obviously not identical.
842 if (Other->getOpcode() != getOpcode() ||
843 Other->getNumOperands() != getNumOperands())
847 // Both instructions are bundles, compare MIs inside the bundle.
848 MachineBasicBlock::const_instr_iterator I1 = *this;
849 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
850 MachineBasicBlock::const_instr_iterator I2 = *Other;
851 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
852 while (++I1 != E1 && I1->isInsideBundle()) {
854 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
859 // Check operands to make sure they match.
860 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
861 const MachineOperand &MO = getOperand(i);
862 const MachineOperand &OMO = Other->getOperand(i);
864 if (!MO.isIdenticalTo(OMO))
869 // Clients may or may not want to ignore defs when testing for equality.
870 // For example, machine CSE pass only cares about finding common
871 // subexpressions, so it's safe to ignore virtual register defs.
873 if (Check == IgnoreDefs)
875 else if (Check == IgnoreVRegDefs) {
876 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
877 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
878 if (MO.getReg() != OMO.getReg())
881 if (!MO.isIdenticalTo(OMO))
883 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
887 if (!MO.isIdenticalTo(OMO))
889 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
893 // If DebugLoc does not match then two dbg.values are not identical.
895 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
896 && getDebugLoc() != Other->getDebugLoc())
901 MachineInstr *MachineInstr::removeFromParent() {
902 assert(getParent() && "Not embedded in a basic block!");
903 return getParent()->remove(this);
906 MachineInstr *MachineInstr::removeFromBundle() {
907 assert(getParent() && "Not embedded in a basic block!");
908 return getParent()->remove_instr(this);
911 void MachineInstr::eraseFromParent() {
912 assert(getParent() && "Not embedded in a basic block!");
913 getParent()->erase(this);
916 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
917 assert(getParent() && "Not embedded in a basic block!");
918 MachineBasicBlock *MBB = getParent();
919 MachineFunction *MF = MBB->getParent();
920 assert(MF && "Not embedded in a function!");
922 MachineInstr *MI = (MachineInstr *)this;
923 MachineRegisterInfo &MRI = MF->getRegInfo();
925 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
926 const MachineOperand &MO = MI->getOperand(i);
927 if (!MO.isReg() || !MO.isDef())
929 unsigned Reg = MO.getReg();
930 if (!TargetRegisterInfo::isVirtualRegister(Reg))
932 MRI.markUsesInDebugValueAsUndef(Reg);
934 MI->eraseFromParent();
937 void MachineInstr::eraseFromBundle() {
938 assert(getParent() && "Not embedded in a basic block!");
939 getParent()->erase_instr(this);
942 /// getNumExplicitOperands - Returns the number of non-implicit operands.
944 unsigned MachineInstr::getNumExplicitOperands() const {
945 unsigned NumOperands = MCID->getNumOperands();
946 if (!MCID->isVariadic())
949 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
950 const MachineOperand &MO = getOperand(i);
951 if (!MO.isReg() || !MO.isImplicit())
957 void MachineInstr::bundleWithPred() {
958 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
959 setFlag(BundledPred);
960 MachineBasicBlock::instr_iterator Pred = this;
962 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
963 Pred->setFlag(BundledSucc);
966 void MachineInstr::bundleWithSucc() {
967 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
968 setFlag(BundledSucc);
969 MachineBasicBlock::instr_iterator Succ = this;
971 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
972 Succ->setFlag(BundledPred);
975 void MachineInstr::unbundleFromPred() {
976 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
977 clearFlag(BundledPred);
978 MachineBasicBlock::instr_iterator Pred = this;
980 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
981 Pred->clearFlag(BundledSucc);
984 void MachineInstr::unbundleFromSucc() {
985 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
986 clearFlag(BundledSucc);
987 MachineBasicBlock::instr_iterator Succ = this;
989 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
990 Succ->clearFlag(BundledPred);
993 bool MachineInstr::isStackAligningInlineAsm() const {
995 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
996 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1002 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1003 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1004 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1005 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1008 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1009 unsigned *GroupNo) const {
1010 assert(isInlineAsm() && "Expected an inline asm instruction");
1011 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1013 // Ignore queries about the initial operands.
1014 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1019 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1021 const MachineOperand &FlagMO = getOperand(i);
1022 // If we reach the implicit register operands, stop looking.
1023 if (!FlagMO.isImm())
1025 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1026 if (i + NumOps > OpIdx) {
1036 const TargetRegisterClass*
1037 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1038 const TargetInstrInfo *TII,
1039 const TargetRegisterInfo *TRI) const {
1040 assert(getParent() && "Can't have an MBB reference here!");
1041 assert(getParent()->getParent() && "Can't have an MF reference here!");
1042 const MachineFunction &MF = *getParent()->getParent();
1044 // Most opcodes have fixed constraints in their MCInstrDesc.
1046 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1048 if (!getOperand(OpIdx).isReg())
1051 // For tied uses on inline asm, get the constraint from the def.
1053 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1056 // Inline asm stores register class constraints in the flag word.
1057 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1061 unsigned Flag = getOperand(FlagIdx).getImm();
1063 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1064 return TRI->getRegClass(RCID);
1066 // Assume that all registers in a memory operand are pointers.
1067 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1068 return TRI->getPointerRegClass(MF);
1073 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1074 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1075 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1076 // Check every operands inside the bundle if we have
1079 for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
1081 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1082 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1084 // Otherwise, just check the current operands.
1085 for (ConstMIOperands OpndIt(this); OpndIt.isValid() && CurRC; ++OpndIt)
1086 CurRC = getRegClassConstraintEffectForVRegImpl(OpndIt.getOperandNo(), Reg,
1091 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1092 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1093 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1094 assert(CurRC && "Invalid initial register class");
1095 // Check if Reg is constrained by some of its use/def from MI.
1096 const MachineOperand &MO = getOperand(OpIdx);
1097 if (!MO.isReg() || MO.getReg() != Reg)
1099 // If yes, accumulate the constraints through the operand.
1100 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1103 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1104 unsigned OpIdx, const TargetRegisterClass *CurRC,
1105 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1106 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1107 const MachineOperand &MO = getOperand(OpIdx);
1108 assert(MO.isReg() &&
1109 "Cannot get register constraints for non-register operand");
1110 assert(CurRC && "Invalid initial register class");
1111 if (unsigned SubIdx = MO.getSubReg()) {
1113 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1115 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1117 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1121 /// Return the number of instructions inside the MI bundle, not counting the
1122 /// header instruction.
1123 unsigned MachineInstr::getBundleSize() const {
1124 MachineBasicBlock::const_instr_iterator I = this;
1126 while (I->isBundledWithSucc())
1131 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1132 /// the specific register or -1 if it is not found. It further tightens
1133 /// the search criteria to a use that kills the register if isKill is true.
1134 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1135 const TargetRegisterInfo *TRI) const {
1136 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1137 const MachineOperand &MO = getOperand(i);
1138 if (!MO.isReg() || !MO.isUse())
1140 unsigned MOReg = MO.getReg();
1145 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1146 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1147 TRI->isSubRegister(MOReg, Reg)))
1148 if (!isKill || MO.isKill())
1154 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1155 /// indicating if this instruction reads or writes Reg. This also considers
1156 /// partial defines.
1157 std::pair<bool,bool>
1158 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1159 SmallVectorImpl<unsigned> *Ops) const {
1160 bool PartDef = false; // Partial redefine.
1161 bool FullDef = false; // Full define.
1164 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1165 const MachineOperand &MO = getOperand(i);
1166 if (!MO.isReg() || MO.getReg() != Reg)
1171 Use |= !MO.isUndef();
1172 else if (MO.getSubReg() && !MO.isUndef())
1173 // A partial <def,undef> doesn't count as reading the register.
1178 // A partial redefine uses Reg unless there is also a full define.
1179 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1182 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1183 /// the specified register or -1 if it is not found. If isDead is true, defs
1184 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1185 /// also checks if there is a def of a super-register.
1187 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1188 const TargetRegisterInfo *TRI) const {
1189 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1190 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1191 const MachineOperand &MO = getOperand(i);
1192 // Accept regmask operands when Overlap is set.
1193 // Ignore them when looking for a specific def operand (Overlap == false).
1194 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1196 if (!MO.isReg() || !MO.isDef())
1198 unsigned MOReg = MO.getReg();
1199 bool Found = (MOReg == Reg);
1200 if (!Found && TRI && isPhys &&
1201 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1203 Found = TRI->regsOverlap(MOReg, Reg);
1205 Found = TRI->isSubRegister(MOReg, Reg);
1207 if (Found && (!isDead || MO.isDead()))
1213 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1214 /// operand list that is used to represent the predicate. It returns -1 if
1216 int MachineInstr::findFirstPredOperandIdx() const {
1217 // Don't call MCID.findFirstPredOperandIdx() because this variant
1218 // is sometimes called on an instruction that's not yet complete, and
1219 // so the number of operands is less than the MCID indicates. In
1220 // particular, the PTX target does this.
1221 const MCInstrDesc &MCID = getDesc();
1222 if (MCID.isPredicable()) {
1223 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1224 if (MCID.OpInfo[i].isPredicate())
1231 // MachineOperand::TiedTo is 4 bits wide.
1232 const unsigned TiedMax = 15;
1234 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1236 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1237 /// field. TiedTo can have these values:
1239 /// 0: Operand is not tied to anything.
1240 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1241 /// TiedMax: Tied to an operand >= TiedMax-1.
1243 /// The tied def must be one of the first TiedMax operands on a normal
1244 /// instruction. INLINEASM instructions allow more tied defs.
1246 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1247 MachineOperand &DefMO = getOperand(DefIdx);
1248 MachineOperand &UseMO = getOperand(UseIdx);
1249 assert(DefMO.isDef() && "DefIdx must be a def operand");
1250 assert(UseMO.isUse() && "UseIdx must be a use operand");
1251 assert(!DefMO.isTied() && "Def is already tied to another use");
1252 assert(!UseMO.isTied() && "Use is already tied to another def");
1254 if (DefIdx < TiedMax)
1255 UseMO.TiedTo = DefIdx + 1;
1257 // Inline asm can use the group descriptors to find tied operands, but on
1258 // normal instruction, the tied def must be within the first TiedMax
1260 assert(isInlineAsm() && "DefIdx out of range");
1261 UseMO.TiedTo = TiedMax;
1264 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1265 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1268 /// Given the index of a tied register operand, find the operand it is tied to.
1269 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1270 /// which must exist.
1271 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1272 const MachineOperand &MO = getOperand(OpIdx);
1273 assert(MO.isTied() && "Operand isn't tied");
1275 // Normally TiedTo is in range.
1276 if (MO.TiedTo < TiedMax)
1277 return MO.TiedTo - 1;
1279 // Uses on normal instructions can be out of range.
1280 if (!isInlineAsm()) {
1281 // Normal tied defs must be in the 0..TiedMax-1 range.
1284 // MO is a def. Search for the tied use.
1285 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1286 const MachineOperand &UseMO = getOperand(i);
1287 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1290 llvm_unreachable("Can't find tied use");
1293 // Now deal with inline asm by parsing the operand group descriptor flags.
1294 // Find the beginning of each operand group.
1295 SmallVector<unsigned, 8> GroupIdx;
1296 unsigned OpIdxGroup = ~0u;
1298 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1300 const MachineOperand &FlagMO = getOperand(i);
1301 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1302 unsigned CurGroup = GroupIdx.size();
1303 GroupIdx.push_back(i);
1304 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1305 // OpIdx belongs to this operand group.
1306 if (OpIdx > i && OpIdx < i + NumOps)
1307 OpIdxGroup = CurGroup;
1309 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1311 // Operands in this group are tied to operands in TiedGroup which must be
1312 // earlier. Find the number of operands between the two groups.
1313 unsigned Delta = i - GroupIdx[TiedGroup];
1315 // OpIdx is a use tied to TiedGroup.
1316 if (OpIdxGroup == CurGroup)
1317 return OpIdx - Delta;
1319 // OpIdx is a def tied to this use group.
1320 if (OpIdxGroup == TiedGroup)
1321 return OpIdx + Delta;
1323 llvm_unreachable("Invalid tied operand on inline asm");
1326 /// clearKillInfo - Clears kill flags on all operands.
1328 void MachineInstr::clearKillInfo() {
1329 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1330 MachineOperand &MO = getOperand(i);
1331 if (MO.isReg() && MO.isUse())
1332 MO.setIsKill(false);
1336 void MachineInstr::substituteRegister(unsigned FromReg,
1339 const TargetRegisterInfo &RegInfo) {
1340 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1342 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1343 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1344 MachineOperand &MO = getOperand(i);
1345 if (!MO.isReg() || MO.getReg() != FromReg)
1347 MO.substPhysReg(ToReg, RegInfo);
1350 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1351 MachineOperand &MO = getOperand(i);
1352 if (!MO.isReg() || MO.getReg() != FromReg)
1354 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1359 /// isSafeToMove - Return true if it is safe to move this instruction. If
1360 /// SawStore is set to true, it means that there is a store (or call) between
1361 /// the instruction's location and its intended destination.
1362 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1364 bool &SawStore) const {
1365 // Ignore stuff that we obviously can't move.
1367 // Treat volatile loads as stores. This is not strictly necessary for
1368 // volatiles, but it is required for atomic loads. It is not allowed to move
1369 // a load across an atomic load with Ordering > Monotonic.
1370 if (mayStore() || isCall() ||
1371 (mayLoad() && hasOrderedMemoryRef())) {
1376 if (isPosition() || isDebugValue() || isTerminator() ||
1377 hasUnmodeledSideEffects())
1380 // See if this instruction does a load. If so, we have to guarantee that the
1381 // loaded value doesn't change between the load and the its intended
1382 // destination. The check for isInvariantLoad gives the targe the chance to
1383 // classify the load as always returning a constant, e.g. a constant pool
1385 if (mayLoad() && !isInvariantLoad(AA))
1386 // Otherwise, this is a real load. If there is a store between the load and
1387 // end of block, we can't move it.
1393 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1394 /// or volatile memory reference, or if the information describing the memory
1395 /// reference is not available. Return false if it is known to have no ordered
1396 /// memory references.
1397 bool MachineInstr::hasOrderedMemoryRef() const {
1398 // An instruction known never to access memory won't have a volatile access.
1402 !hasUnmodeledSideEffects())
1405 // Otherwise, if the instruction has no memory reference information,
1406 // conservatively assume it wasn't preserved.
1407 if (memoperands_empty())
1410 // Check the memory reference information for ordered references.
1411 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1412 if (!(*I)->isUnordered())
1418 /// isInvariantLoad - Return true if this instruction is loading from a
1419 /// location whose value is invariant across the function. For example,
1420 /// loading a value from the constant pool or from the argument area
1421 /// of a function if it does not change. This should only return true of
1422 /// *all* loads the instruction does are invariant (if it does multiple loads).
1423 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1424 // If the instruction doesn't load at all, it isn't an invariant load.
1428 // If the instruction has lost its memoperands, conservatively assume that
1429 // it may not be an invariant load.
1430 if (memoperands_empty())
1433 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1435 for (mmo_iterator I = memoperands_begin(),
1436 E = memoperands_end(); I != E; ++I) {
1437 if ((*I)->isVolatile()) return false;
1438 if ((*I)->isStore()) return false;
1439 if ((*I)->isInvariant()) return true;
1442 // A load from a constant PseudoSourceValue is invariant.
1443 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue())
1444 if (PSV->isConstant(MFI))
1447 if (const Value *V = (*I)->getValue()) {
1448 // If we have an AliasAnalysis, ask it whether the memory is constant.
1449 if (AA && AA->pointsToConstantMemory(
1450 AliasAnalysis::Location(V, (*I)->getSize(),
1451 (*I)->getAAInfo())))
1455 // Otherwise assume conservatively.
1459 // Everything checks out.
1463 /// isConstantValuePHI - If the specified instruction is a PHI that always
1464 /// merges together the same virtual register, return the register, otherwise
1466 unsigned MachineInstr::isConstantValuePHI() const {
1469 assert(getNumOperands() >= 3 &&
1470 "It's illegal to have a PHI without source operands");
1472 unsigned Reg = getOperand(1).getReg();
1473 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1474 if (getOperand(i).getReg() != Reg)
1479 bool MachineInstr::hasUnmodeledSideEffects() const {
1480 if (hasProperty(MCID::UnmodeledSideEffects))
1482 if (isInlineAsm()) {
1483 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1484 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1491 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1493 bool MachineInstr::allDefsAreDead() const {
1494 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1495 const MachineOperand &MO = getOperand(i);
1496 if (!MO.isReg() || MO.isUse())
1504 /// copyImplicitOps - Copy implicit register operands from specified
1505 /// instruction to this instruction.
1506 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1507 const MachineInstr *MI) {
1508 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1510 const MachineOperand &MO = MI->getOperand(i);
1511 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1516 void MachineInstr::dump() const {
1517 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1518 dbgs() << " " << *this;
1522 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1523 raw_ostream &CommentOS) {
1524 const LLVMContext &Ctx = MF->getFunction()->getContext();
1525 DL.print(Ctx, CommentOS);
1528 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
1529 bool SkipOpers) const {
1530 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1531 const MachineFunction *MF = nullptr;
1532 const MachineRegisterInfo *MRI = nullptr;
1533 if (const MachineBasicBlock *MBB = getParent()) {
1534 MF = MBB->getParent();
1536 TM = &MF->getTarget();
1538 MRI = &MF->getRegInfo();
1541 // Save a list of virtual registers.
1542 SmallVector<unsigned, 8> VirtRegs;
1544 // Print explicitly defined operands on the left of an assignment syntax.
1545 unsigned StartOp = 0, e = getNumOperands();
1546 for (; StartOp < e && getOperand(StartOp).isReg() &&
1547 getOperand(StartOp).isDef() &&
1548 !getOperand(StartOp).isImplicit();
1550 if (StartOp != 0) OS << ", ";
1551 getOperand(StartOp).print(OS, TM);
1552 unsigned Reg = getOperand(StartOp).getReg();
1553 if (TargetRegisterInfo::isVirtualRegister(Reg))
1554 VirtRegs.push_back(Reg);
1560 // Print the opcode name.
1561 if (TM && TM->getSubtargetImpl()->getInstrInfo())
1562 OS << TM->getSubtargetImpl()->getInstrInfo()->getName(getOpcode());
1569 // Print the rest of the operands.
1570 bool OmittedAnyCallClobbers = false;
1571 bool FirstOp = true;
1572 unsigned AsmDescOp = ~0u;
1573 unsigned AsmOpCount = 0;
1575 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1576 // Print asm string.
1578 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1580 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1581 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1582 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1583 OS << " [sideeffect]";
1584 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1586 if (ExtraInfo & InlineAsm::Extra_MayStore)
1587 OS << " [maystore]";
1588 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1589 OS << " [alignstack]";
1590 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1591 OS << " [attdialect]";
1592 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1593 OS << " [inteldialect]";
1595 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1600 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1601 const MachineOperand &MO = getOperand(i);
1603 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1604 VirtRegs.push_back(MO.getReg());
1606 // Omit call-clobbered registers which aren't used anywhere. This makes
1607 // call instructions much less noisy on targets where calls clobber lots
1608 // of registers. Don't rely on MO.isDead() because we may be called before
1609 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1610 if (MF && isCall() &&
1611 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1612 unsigned Reg = MO.getReg();
1613 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1614 const MachineRegisterInfo &MRI = MF->getRegInfo();
1615 if (MRI.use_empty(Reg)) {
1616 bool HasAliasLive = false;
1617 for (MCRegAliasIterator AI(
1618 Reg, TM->getSubtargetImpl()->getRegisterInfo(), true);
1619 AI.isValid(); ++AI) {
1620 unsigned AliasReg = *AI;
1621 if (!MRI.use_empty(AliasReg)) {
1622 HasAliasLive = true;
1626 if (!HasAliasLive) {
1627 OmittedAnyCallClobbers = true;
1634 if (FirstOp) FirstOp = false; else OS << ",";
1636 if (i < getDesc().NumOperands) {
1637 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1638 if (MCOI.isPredicate())
1640 if (MCOI.isOptionalDef())
1643 if (isDebugValue() && MO.isMetadata()) {
1644 // Pretty print DBG_VALUE instructions.
1645 const MDNode *MD = MO.getMetadata();
1646 DIDescriptor DI(MD);
1649 if (DI.isVariable() && !DIV.getName().empty())
1650 OS << "!\"" << DIV.getName() << '\"';
1653 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1654 OS << TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIndexName(
1656 } else if (i == AsmDescOp && MO.isImm()) {
1657 // Pretty print the inline asm operand descriptor.
1658 OS << '$' << AsmOpCount++;
1659 unsigned Flag = MO.getImm();
1660 switch (InlineAsm::getKind(Flag)) {
1661 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1662 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1663 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1664 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1665 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1666 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1667 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1671 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1674 << TM->getSubtargetImpl()
1679 OS << ":RC" << RCID;
1682 unsigned TiedTo = 0;
1683 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1684 OS << " tiedto:$" << TiedTo;
1688 // Compute the index of the next operand descriptor.
1689 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1694 // Briefly indicate whether any call clobbers were omitted.
1695 if (OmittedAnyCallClobbers) {
1696 if (!FirstOp) OS << ",";
1700 bool HaveSemi = false;
1701 const unsigned PrintableFlags = FrameSetup;
1702 if (Flags & PrintableFlags) {
1703 if (!HaveSemi) OS << ";"; HaveSemi = true;
1706 if (Flags & FrameSetup)
1710 if (!memoperands_empty()) {
1711 if (!HaveSemi) OS << ";"; HaveSemi = true;
1714 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1717 if (std::next(i) != e)
1722 // Print the regclass of any virtual registers encountered.
1723 if (MRI && !VirtRegs.empty()) {
1724 if (!HaveSemi) OS << ";"; HaveSemi = true;
1725 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1726 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1727 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1728 for (unsigned j = i+1; j != VirtRegs.size();) {
1729 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1733 if (VirtRegs[i] != VirtRegs[j])
1734 OS << "," << PrintReg(VirtRegs[j]);
1735 VirtRegs.erase(VirtRegs.begin()+j);
1740 // Print debug location information.
1741 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1742 if (!HaveSemi) OS << ";";
1743 DIVariable DV(getOperand(e - 1).getMetadata());
1744 OS << " line no:" << DV.getLineNumber();
1745 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1746 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1747 if (!InlinedAtDL.isUnknown() && MF) {
1748 OS << " inlined @[ ";
1749 printDebugLoc(InlinedAtDL, MF, OS);
1753 if (isIndirectDebugValue())
1755 } else if (!debugLoc.isUnknown() && MF) {
1756 if (!HaveSemi) OS << ";";
1758 printDebugLoc(debugLoc, MF, OS);
1764 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1765 const TargetRegisterInfo *RegInfo,
1766 bool AddIfNotFound) {
1767 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1768 bool hasAliases = isPhysReg &&
1769 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1771 SmallVector<unsigned,4> DeadOps;
1772 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1773 MachineOperand &MO = getOperand(i);
1774 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1776 unsigned Reg = MO.getReg();
1780 if (Reg == IncomingReg) {
1783 // The register is already marked kill.
1785 if (isPhysReg && isRegTiedToDefOperand(i))
1786 // Two-address uses of physregs must not be marked kill.
1791 } else if (hasAliases && MO.isKill() &&
1792 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1793 // A super-register kill already exists.
1794 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1796 if (RegInfo->isSubRegister(IncomingReg, Reg))
1797 DeadOps.push_back(i);
1801 // Trim unneeded kill operands.
1802 while (!DeadOps.empty()) {
1803 unsigned OpIdx = DeadOps.back();
1804 if (getOperand(OpIdx).isImplicit())
1805 RemoveOperand(OpIdx);
1807 getOperand(OpIdx).setIsKill(false);
1811 // If not found, this means an alias of one of the operands is killed. Add a
1812 // new implicit operand if required.
1813 if (!Found && AddIfNotFound) {
1814 addOperand(MachineOperand::CreateReg(IncomingReg,
1823 void MachineInstr::clearRegisterKills(unsigned Reg,
1824 const TargetRegisterInfo *RegInfo) {
1825 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1827 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1828 MachineOperand &MO = getOperand(i);
1829 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1831 unsigned OpReg = MO.getReg();
1832 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1833 MO.setIsKill(false);
1837 bool MachineInstr::addRegisterDead(unsigned Reg,
1838 const TargetRegisterInfo *RegInfo,
1839 bool AddIfNotFound) {
1840 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1841 bool hasAliases = isPhysReg &&
1842 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1844 SmallVector<unsigned,4> DeadOps;
1845 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1846 MachineOperand &MO = getOperand(i);
1847 if (!MO.isReg() || !MO.isDef())
1849 unsigned MOReg = MO.getReg();
1856 } else if (hasAliases && MO.isDead() &&
1857 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1858 // There exists a super-register that's marked dead.
1859 if (RegInfo->isSuperRegister(Reg, MOReg))
1861 if (RegInfo->isSubRegister(Reg, MOReg))
1862 DeadOps.push_back(i);
1866 // Trim unneeded dead operands.
1867 while (!DeadOps.empty()) {
1868 unsigned OpIdx = DeadOps.back();
1869 if (getOperand(OpIdx).isImplicit())
1870 RemoveOperand(OpIdx);
1872 getOperand(OpIdx).setIsDead(false);
1876 // If not found, this means an alias of one of the operands is dead. Add a
1877 // new implicit operand if required.
1878 if (Found || !AddIfNotFound)
1881 addOperand(MachineOperand::CreateReg(Reg,
1889 void MachineInstr::addRegisterDefined(unsigned Reg,
1890 const TargetRegisterInfo *RegInfo) {
1891 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1892 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1896 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1897 const MachineOperand &MO = getOperand(i);
1898 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1899 MO.getSubReg() == 0)
1903 addOperand(MachineOperand::CreateReg(Reg,
1908 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1909 const TargetRegisterInfo &TRI) {
1910 bool HasRegMask = false;
1911 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1912 MachineOperand &MO = getOperand(i);
1913 if (MO.isRegMask()) {
1917 if (!MO.isReg() || !MO.isDef()) continue;
1918 unsigned Reg = MO.getReg();
1919 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1921 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1923 if (TRI.regsOverlap(*I, Reg)) {
1927 // If there are no uses, including partial uses, the def is dead.
1928 if (Dead) MO.setIsDead();
1931 // This is a call with a register mask operand.
1932 // Mask clobbers are always dead, so add defs for the non-dead defines.
1934 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1936 addRegisterDefined(*I, &TRI);
1940 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1941 // Build up a buffer of hash code components.
1942 SmallVector<size_t, 8> HashComponents;
1943 HashComponents.reserve(MI->getNumOperands() + 1);
1944 HashComponents.push_back(MI->getOpcode());
1945 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1946 const MachineOperand &MO = MI->getOperand(i);
1947 if (MO.isReg() && MO.isDef() &&
1948 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1949 continue; // Skip virtual register defs.
1951 HashComponents.push_back(hash_value(MO));
1953 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1956 void MachineInstr::emitError(StringRef Msg) const {
1957 // Find the source location cookie.
1958 unsigned LocCookie = 0;
1959 const MDNode *LocMD = nullptr;
1960 for (unsigned i = getNumOperands(); i != 0; --i) {
1961 if (getOperand(i-1).isMetadata() &&
1962 (LocMD = getOperand(i-1).getMetadata()) &&
1963 LocMD->getNumOperands() != 0) {
1964 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1965 LocCookie = CI->getZExtValue();
1971 if (const MachineBasicBlock *MBB = getParent())
1972 if (const MachineFunction *MF = MBB->getParent())
1973 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1974 report_fatal_error(Msg);