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/Constants.h"
16 #include "llvm/DebugInfo.h"
17 #include "llvm/Function.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Metadata.h"
21 #include "llvm/Module.h"
22 #include "llvm/Type.h"
23 #include "llvm/Value.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/LeakDetector.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/FoldingSet.h"
43 #include "llvm/ADT/Hashing.h"
46 //===----------------------------------------------------------------------===//
47 // MachineOperand Implementation
48 //===----------------------------------------------------------------------===//
50 /// AddRegOperandToRegInfo - Add this register operand to the specified
51 /// MachineRegisterInfo. If it is null, then the next/prev fields should be
52 /// explicitly nulled out.
53 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
54 assert(isReg() && "Can only add reg operand to use lists");
56 // If the reginfo pointer is null, just explicitly null out or next/prev
57 // pointers, to ensure they are not garbage.
59 Contents.Reg.Prev = 0;
60 Contents.Reg.Next = 0;
64 // Otherwise, add this operand to the head of the registers use/def list.
65 MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
67 // For SSA values, we prefer to keep the definition at the start of the list.
68 // we do this by skipping over the definition if it is at the head of the
70 if (*Head && (*Head)->isDef())
71 Head = &(*Head)->Contents.Reg.Next;
73 Contents.Reg.Next = *Head;
74 if (Contents.Reg.Next) {
75 assert(getReg() == Contents.Reg.Next->getReg() &&
76 "Different regs on the same list!");
77 Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
80 Contents.Reg.Prev = Head;
84 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
85 /// MachineRegisterInfo it is linked with.
86 void MachineOperand::RemoveRegOperandFromRegInfo() {
87 assert(isOnRegUseList() && "Reg operand is not on a use list");
88 // Unlink this from the doubly linked list of operands.
89 MachineOperand *NextOp = Contents.Reg.Next;
90 *Contents.Reg.Prev = NextOp;
92 assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
93 NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
95 Contents.Reg.Prev = 0;
96 Contents.Reg.Next = 0;
99 void MachineOperand::setReg(unsigned Reg) {
100 if (getReg() == Reg) return; // No change.
102 // Otherwise, we have to change the register. If this operand is embedded
103 // into a machine function, we need to update the old and new register's
105 if (MachineInstr *MI = getParent())
106 if (MachineBasicBlock *MBB = MI->getParent())
107 if (MachineFunction *MF = MBB->getParent()) {
108 RemoveRegOperandFromRegInfo();
109 SmallContents.RegNo = Reg;
110 AddRegOperandToRegInfo(&MF->getRegInfo());
114 // Otherwise, just change the register, no problem. :)
115 SmallContents.RegNo = Reg;
118 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
119 const TargetRegisterInfo &TRI) {
120 assert(TargetRegisterInfo::isVirtualRegister(Reg));
121 if (SubIdx && getSubReg())
122 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
128 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
129 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
131 Reg = TRI.getSubReg(Reg, getSubReg());
132 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
133 // That won't happen in legal code.
139 /// ChangeToImmediate - Replace this operand with a new immediate operand of
140 /// the specified value. If an operand is known to be an immediate already,
141 /// the setImm method should be used.
142 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
143 // If this operand is currently a register operand, and if this is in a
144 // function, deregister the operand from the register's use/def list.
145 if (isReg() && getParent() && getParent()->getParent() &&
146 getParent()->getParent()->getParent())
147 RemoveRegOperandFromRegInfo();
149 OpKind = MO_Immediate;
150 Contents.ImmVal = ImmVal;
153 /// ChangeToRegister - Replace this operand with a new register operand of
154 /// the specified value. If an operand is known to be an register already,
155 /// the setReg method should be used.
156 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
157 bool isKill, bool isDead, bool isUndef,
159 // If this operand is already a register operand, use setReg to update the
160 // register's use/def lists.
162 assert(!isEarlyClobber());
165 // Otherwise, change this to a register and set the reg#.
166 OpKind = MO_Register;
167 SmallContents.RegNo = Reg;
169 // If this operand is embedded in a function, add the operand to the
170 // register's use/def list.
171 if (MachineInstr *MI = getParent())
172 if (MachineBasicBlock *MBB = MI->getParent())
173 if (MachineFunction *MF = MBB->getParent())
174 AddRegOperandToRegInfo(&MF->getRegInfo());
182 IsInternalRead = false;
183 IsEarlyClobber = false;
188 /// isIdenticalTo - Return true if this operand is identical to the specified
189 /// operand. Note that this should stay in sync with the hash_value overload
191 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
192 if (getType() != Other.getType() ||
193 getTargetFlags() != Other.getTargetFlags())
197 case MachineOperand::MO_Register:
198 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
199 getSubReg() == Other.getSubReg();
200 case MachineOperand::MO_Immediate:
201 return getImm() == Other.getImm();
202 case MachineOperand::MO_CImmediate:
203 return getCImm() == Other.getCImm();
204 case MachineOperand::MO_FPImmediate:
205 return getFPImm() == Other.getFPImm();
206 case MachineOperand::MO_MachineBasicBlock:
207 return getMBB() == Other.getMBB();
208 case MachineOperand::MO_FrameIndex:
209 return getIndex() == Other.getIndex();
210 case MachineOperand::MO_ConstantPoolIndex:
211 case MachineOperand::MO_TargetIndex:
212 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
213 case MachineOperand::MO_JumpTableIndex:
214 return getIndex() == Other.getIndex();
215 case MachineOperand::MO_GlobalAddress:
216 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
217 case MachineOperand::MO_ExternalSymbol:
218 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
219 getOffset() == Other.getOffset();
220 case MachineOperand::MO_BlockAddress:
221 return getBlockAddress() == Other.getBlockAddress();
222 case MO_RegisterMask:
223 return getRegMask() == Other.getRegMask();
224 case MachineOperand::MO_MCSymbol:
225 return getMCSymbol() == Other.getMCSymbol();
226 case MachineOperand::MO_Metadata:
227 return getMetadata() == Other.getMetadata();
229 llvm_unreachable("Invalid machine operand type");
232 // Note: this must stay exactly in sync with isIdenticalTo above.
233 hash_code llvm::hash_value(const MachineOperand &MO) {
234 switch (MO.getType()) {
235 case MachineOperand::MO_Register:
236 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getReg(),
237 MO.getSubReg(), MO.isDef());
238 case MachineOperand::MO_Immediate:
239 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
240 case MachineOperand::MO_CImmediate:
241 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
242 case MachineOperand::MO_FPImmediate:
243 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
244 case MachineOperand::MO_MachineBasicBlock:
245 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
246 case MachineOperand::MO_FrameIndex:
247 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
248 case MachineOperand::MO_ConstantPoolIndex:
249 case MachineOperand::MO_TargetIndex:
250 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
252 case MachineOperand::MO_JumpTableIndex:
253 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
254 case MachineOperand::MO_ExternalSymbol:
255 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
257 case MachineOperand::MO_GlobalAddress:
258 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
260 case MachineOperand::MO_BlockAddress:
261 return hash_combine(MO.getType(), MO.getTargetFlags(),
262 MO.getBlockAddress());
263 case MachineOperand::MO_RegisterMask:
264 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
265 case MachineOperand::MO_Metadata:
266 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
267 case MachineOperand::MO_MCSymbol:
268 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
270 llvm_unreachable("Invalid machine operand type");
273 /// print - Print the specified machine operand.
275 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
276 // If the instruction is embedded into a basic block, we can find the
277 // target info for the instruction.
279 if (const MachineInstr *MI = getParent())
280 if (const MachineBasicBlock *MBB = MI->getParent())
281 if (const MachineFunction *MF = MBB->getParent())
282 TM = &MF->getTarget();
283 const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
286 case MachineOperand::MO_Register:
287 OS << PrintReg(getReg(), TRI, getSubReg());
289 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
290 isInternalRead() || isEarlyClobber()) {
292 bool NeedComma = false;
294 if (NeedComma) OS << ',';
295 if (isEarlyClobber())
296 OS << "earlyclobber,";
301 // <def,read-undef> only makes sense when getSubReg() is set.
302 // Don't clutter the output otherwise.
303 if (isUndef() && getSubReg())
305 } else if (isImplicit()) {
310 if (isKill() || isDead() || (isUndef() && isUse()) || isInternalRead()) {
311 if (NeedComma) OS << ',';
321 if (isUndef() && isUse()) {
322 if (NeedComma) OS << ',';
326 if (isInternalRead()) {
327 if (NeedComma) OS << ',';
335 case MachineOperand::MO_Immediate:
338 case MachineOperand::MO_CImmediate:
339 getCImm()->getValue().print(OS, false);
341 case MachineOperand::MO_FPImmediate:
342 if (getFPImm()->getType()->isFloatTy())
343 OS << getFPImm()->getValueAPF().convertToFloat();
345 OS << getFPImm()->getValueAPF().convertToDouble();
347 case MachineOperand::MO_MachineBasicBlock:
348 OS << "<BB#" << getMBB()->getNumber() << ">";
350 case MachineOperand::MO_FrameIndex:
351 OS << "<fi#" << getIndex() << '>';
353 case MachineOperand::MO_ConstantPoolIndex:
354 OS << "<cp#" << getIndex();
355 if (getOffset()) OS << "+" << getOffset();
358 case MachineOperand::MO_TargetIndex:
359 OS << "<ti#" << getIndex();
360 if (getOffset()) OS << "+" << getOffset();
363 case MachineOperand::MO_JumpTableIndex:
364 OS << "<jt#" << getIndex() << '>';
366 case MachineOperand::MO_GlobalAddress:
368 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
369 if (getOffset()) OS << "+" << getOffset();
372 case MachineOperand::MO_ExternalSymbol:
373 OS << "<es:" << getSymbolName();
374 if (getOffset()) OS << "+" << getOffset();
377 case MachineOperand::MO_BlockAddress:
379 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
382 case MachineOperand::MO_RegisterMask:
385 case MachineOperand::MO_Metadata:
387 WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
390 case MachineOperand::MO_MCSymbol:
391 OS << "<MCSym=" << *getMCSymbol() << '>';
395 if (unsigned TF = getTargetFlags())
396 OS << "[TF=" << TF << ']';
399 //===----------------------------------------------------------------------===//
400 // MachineMemOperand Implementation
401 //===----------------------------------------------------------------------===//
403 /// getAddrSpace - Return the LLVM IR address space number that this pointer
405 unsigned MachinePointerInfo::getAddrSpace() const {
406 if (V == 0) return 0;
407 return cast<PointerType>(V->getType())->getAddressSpace();
410 /// getConstantPool - Return a MachinePointerInfo record that refers to the
412 MachinePointerInfo MachinePointerInfo::getConstantPool() {
413 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
416 /// getFixedStack - Return a MachinePointerInfo record that refers to the
417 /// the specified FrameIndex.
418 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
419 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
422 MachinePointerInfo MachinePointerInfo::getJumpTable() {
423 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
426 MachinePointerInfo MachinePointerInfo::getGOT() {
427 return MachinePointerInfo(PseudoSourceValue::getGOT());
430 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
431 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
434 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
435 uint64_t s, unsigned int a,
436 const MDNode *TBAAInfo,
437 const MDNode *Ranges)
438 : PtrInfo(ptrinfo), Size(s),
439 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
440 TBAAInfo(TBAAInfo), Ranges(Ranges) {
441 assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
442 "invalid pointer value");
443 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
444 assert((isLoad() || isStore()) && "Not a load/store!");
447 /// Profile - Gather unique data for the object.
449 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
450 ID.AddInteger(getOffset());
452 ID.AddPointer(getValue());
453 ID.AddInteger(Flags);
456 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
457 // The Value and Offset may differ due to CSE. But the flags and size
458 // should be the same.
459 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
460 assert(MMO->getSize() == getSize() && "Size mismatch!");
462 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
463 // Update the alignment value.
464 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
465 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
466 // Also update the base and offset, because the new alignment may
467 // not be applicable with the old ones.
468 PtrInfo = MMO->PtrInfo;
472 /// getAlignment - Return the minimum known alignment in bytes of the
473 /// actual memory reference.
474 uint64_t MachineMemOperand::getAlignment() const {
475 return MinAlign(getBaseAlignment(), getOffset());
478 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
479 assert((MMO.isLoad() || MMO.isStore()) &&
480 "SV has to be a load, store or both.");
482 if (MMO.isVolatile())
491 // Print the address information.
496 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
498 // If the alignment of the memory reference itself differs from the alignment
499 // of the base pointer, print the base alignment explicitly, next to the base
501 if (MMO.getBaseAlignment() != MMO.getAlignment())
502 OS << "(align=" << MMO.getBaseAlignment() << ")";
504 if (MMO.getOffset() != 0)
505 OS << "+" << MMO.getOffset();
508 // Print the alignment of the reference.
509 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
510 MMO.getBaseAlignment() != MMO.getSize())
511 OS << "(align=" << MMO.getAlignment() << ")";
514 if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
516 if (TBAAInfo->getNumOperands() > 0)
517 WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
523 // Print nontemporal info.
524 if (MMO.isNonTemporal())
525 OS << "(nontemporal)";
530 //===----------------------------------------------------------------------===//
531 // MachineInstr Implementation
532 //===----------------------------------------------------------------------===//
534 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
535 /// MCID NULL and no operands.
536 MachineInstr::MachineInstr()
537 : MCID(0), Flags(0), AsmPrinterFlags(0),
538 NumMemRefs(0), MemRefs(0),
540 // Make sure that we get added to a machine basicblock
541 LeakDetector::addGarbageObject(this);
544 void MachineInstr::addImplicitDefUseOperands() {
545 if (MCID->ImplicitDefs)
546 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
547 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
548 if (MCID->ImplicitUses)
549 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
550 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
553 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
554 /// implicit operands. It reserves space for the number of operands specified by
556 MachineInstr::MachineInstr(const MCInstrDesc &tid, bool NoImp)
557 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
558 NumMemRefs(0), MemRefs(0), Parent(0) {
559 unsigned NumImplicitOps = 0;
561 NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
562 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
564 addImplicitDefUseOperands();
565 // Make sure that we get added to a machine basicblock
566 LeakDetector::addGarbageObject(this);
569 /// MachineInstr ctor - As above, but with a DebugLoc.
570 MachineInstr::MachineInstr(const MCInstrDesc &tid, const DebugLoc dl,
572 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
573 NumMemRefs(0), MemRefs(0), Parent(0), debugLoc(dl) {
574 unsigned NumImplicitOps = 0;
576 NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
577 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
579 addImplicitDefUseOperands();
580 // Make sure that we get added to a machine basicblock
581 LeakDetector::addGarbageObject(this);
584 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
585 /// that the MachineInstr is created and added to the end of the specified
587 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &tid)
588 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
589 NumMemRefs(0), MemRefs(0), Parent(0) {
590 assert(MBB && "Cannot use inserting ctor with null basic block!");
591 unsigned NumImplicitOps =
592 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
593 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
594 addImplicitDefUseOperands();
595 // Make sure that we get added to a machine basicblock
596 LeakDetector::addGarbageObject(this);
597 MBB->push_back(this); // Add instruction to end of basic block!
600 /// MachineInstr ctor - As above, but with a DebugLoc.
602 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
603 const MCInstrDesc &tid)
604 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
605 NumMemRefs(0), MemRefs(0), Parent(0), debugLoc(dl) {
606 assert(MBB && "Cannot use inserting ctor with null basic block!");
607 unsigned NumImplicitOps =
608 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
609 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
610 addImplicitDefUseOperands();
611 // Make sure that we get added to a machine basicblock
612 LeakDetector::addGarbageObject(this);
613 MBB->push_back(this); // Add instruction to end of basic block!
616 /// MachineInstr ctor - Copies MachineInstr arg exactly
618 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
619 : MCID(&MI.getDesc()), Flags(0), AsmPrinterFlags(0),
620 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
621 Parent(0), debugLoc(MI.getDebugLoc()) {
622 Operands.reserve(MI.getNumOperands());
625 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
626 addOperand(MI.getOperand(i));
628 // Copy all the flags.
631 // Set parent to null.
634 LeakDetector::addGarbageObject(this);
637 MachineInstr::~MachineInstr() {
638 LeakDetector::removeGarbageObject(this);
640 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
641 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
642 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
643 "Reg operand def/use list corrupted");
648 /// getRegInfo - If this instruction is embedded into a MachineFunction,
649 /// return the MachineRegisterInfo object for the current function, otherwise
651 MachineRegisterInfo *MachineInstr::getRegInfo() {
652 if (MachineBasicBlock *MBB = getParent())
653 return &MBB->getParent()->getRegInfo();
657 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
658 /// this instruction from their respective use lists. This requires that the
659 /// operands already be on their use lists.
660 void MachineInstr::RemoveRegOperandsFromUseLists() {
661 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
662 if (Operands[i].isReg())
663 Operands[i].RemoveRegOperandFromRegInfo();
667 /// AddRegOperandsToUseLists - Add all of the register operands in
668 /// this instruction from their respective use lists. This requires that the
669 /// operands not be on their use lists yet.
670 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
671 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
672 if (Operands[i].isReg())
673 Operands[i].AddRegOperandToRegInfo(&RegInfo);
678 /// addOperand - Add the specified operand to the instruction. If it is an
679 /// implicit operand, it is added to the end of the operand list. If it is
680 /// an explicit operand it is added at the end of the explicit operand list
681 /// (before the first implicit operand).
682 void MachineInstr::addOperand(const MachineOperand &Op) {
683 assert(MCID && "Cannot add operands before providing an instr descriptor");
684 bool isImpReg = Op.isReg() && Op.isImplicit();
685 MachineRegisterInfo *RegInfo = getRegInfo();
687 // If the Operands backing store is reallocated, all register operands must
688 // be removed and re-added to RegInfo. It is storing pointers to operands.
689 bool Reallocate = RegInfo &&
690 !Operands.empty() && Operands.size() == Operands.capacity();
692 // Find the insert location for the new operand. Implicit registers go at
693 // the end, everything goes before the implicit regs.
694 unsigned OpNo = Operands.size();
696 // Remove all the implicit operands from RegInfo if they need to be shifted.
697 // FIXME: Allow mixed explicit and implicit operands on inline asm.
698 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
699 // implicit-defs, but they must not be moved around. See the FIXME in
701 if (!isImpReg && !isInlineAsm()) {
702 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
705 Operands[OpNo].RemoveRegOperandFromRegInfo();
709 // OpNo now points as the desired insertion point. Unless this is a variadic
710 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
711 // RegMask operands go between the explicit and implicit operands.
712 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
713 OpNo < MCID->getNumOperands()) &&
714 "Trying to add an operand to a machine instr that is already done!");
716 // All operands from OpNo have been removed from RegInfo. If the Operands
717 // backing store needs to be reallocated, we also need to remove any other
718 // register operands.
720 for (unsigned i = 0; i != OpNo; ++i)
721 if (Operands[i].isReg())
722 Operands[i].RemoveRegOperandFromRegInfo();
724 // Insert the new operand at OpNo.
725 Operands.insert(Operands.begin() + OpNo, Op);
726 Operands[OpNo].ParentMI = this;
728 // The Operands backing store has now been reallocated, so we can re-add the
729 // operands before OpNo.
731 for (unsigned i = 0; i != OpNo; ++i)
732 if (Operands[i].isReg())
733 Operands[i].AddRegOperandToRegInfo(RegInfo);
735 // When adding a register operand, tell RegInfo about it.
736 if (Operands[OpNo].isReg()) {
737 // Add the new operand to RegInfo, even when RegInfo is NULL.
738 // This will initialize the linked list pointers.
739 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
740 // If the register operand is flagged as early, mark the operand as such.
741 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
742 Operands[OpNo].setIsEarlyClobber(true);
745 // Re-add all the implicit ops.
747 for (unsigned i = OpNo + 1, e = Operands.size(); i != e; ++i) {
748 assert(Operands[i].isReg() && "Should only be an implicit reg!");
749 Operands[i].AddRegOperandToRegInfo(RegInfo);
754 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
755 /// fewer operand than it started with.
757 void MachineInstr::RemoveOperand(unsigned OpNo) {
758 assert(OpNo < Operands.size() && "Invalid operand number");
760 // Special case removing the last one.
761 if (OpNo == Operands.size()-1) {
762 // If needed, remove from the reg def/use list.
763 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
764 Operands.back().RemoveRegOperandFromRegInfo();
770 // Otherwise, we are removing an interior operand. If we have reginfo to
771 // update, remove all operands that will be shifted down from their reg lists,
772 // move everything down, then re-add them.
773 MachineRegisterInfo *RegInfo = getRegInfo();
775 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
776 if (Operands[i].isReg())
777 Operands[i].RemoveRegOperandFromRegInfo();
781 Operands.erase(Operands.begin()+OpNo);
784 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
785 if (Operands[i].isReg())
786 Operands[i].AddRegOperandToRegInfo(RegInfo);
791 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
792 /// This function should be used only occasionally. The setMemRefs function
793 /// is the primary method for setting up a MachineInstr's MemRefs list.
794 void MachineInstr::addMemOperand(MachineFunction &MF,
795 MachineMemOperand *MO) {
796 mmo_iterator OldMemRefs = MemRefs;
797 uint16_t OldNumMemRefs = NumMemRefs;
799 uint16_t NewNum = NumMemRefs + 1;
800 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
802 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
803 NewMemRefs[NewNum - 1] = MO;
805 MemRefs = NewMemRefs;
809 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
810 const MachineBasicBlock *MBB = getParent();
811 MachineBasicBlock::const_instr_iterator MII = *this; ++MII;
812 while (MII != MBB->end() && MII->isInsideBundle()) {
813 if (MII->getDesc().getFlags() & Mask) {
814 if (Type == AnyInBundle)
817 if (Type == AllInBundle)
823 return Type == AllInBundle;
826 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
827 MICheckType Check) const {
828 // If opcodes or number of operands are not the same then the two
829 // instructions are obviously not identical.
830 if (Other->getOpcode() != getOpcode() ||
831 Other->getNumOperands() != getNumOperands())
835 // Both instructions are bundles, compare MIs inside the bundle.
836 MachineBasicBlock::const_instr_iterator I1 = *this;
837 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
838 MachineBasicBlock::const_instr_iterator I2 = *Other;
839 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
840 while (++I1 != E1 && I1->isInsideBundle()) {
842 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
847 // Check operands to make sure they match.
848 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
849 const MachineOperand &MO = getOperand(i);
850 const MachineOperand &OMO = Other->getOperand(i);
852 if (!MO.isIdenticalTo(OMO))
857 // Clients may or may not want to ignore defs when testing for equality.
858 // For example, machine CSE pass only cares about finding common
859 // subexpressions, so it's safe to ignore virtual register defs.
861 if (Check == IgnoreDefs)
863 else if (Check == IgnoreVRegDefs) {
864 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
865 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
866 if (MO.getReg() != OMO.getReg())
869 if (!MO.isIdenticalTo(OMO))
871 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
875 if (!MO.isIdenticalTo(OMO))
877 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
881 // If DebugLoc does not match then two dbg.values are not identical.
883 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
884 && getDebugLoc() != Other->getDebugLoc())
889 /// removeFromParent - This method unlinks 'this' from the containing basic
890 /// block, and returns it, but does not delete it.
891 MachineInstr *MachineInstr::removeFromParent() {
892 assert(getParent() && "Not embedded in a basic block!");
894 // If it's a bundle then remove the MIs inside the bundle as well.
896 MachineBasicBlock *MBB = getParent();
897 MachineBasicBlock::instr_iterator MII = *this; ++MII;
898 MachineBasicBlock::instr_iterator E = MBB->instr_end();
899 while (MII != E && MII->isInsideBundle()) {
900 MachineInstr *MI = &*MII;
905 getParent()->remove(this);
910 /// eraseFromParent - This method unlinks 'this' from the containing basic
911 /// block, and deletes it.
912 void MachineInstr::eraseFromParent() {
913 assert(getParent() && "Not embedded in a basic block!");
914 // If it's a bundle then remove the MIs inside the bundle as well.
916 MachineBasicBlock *MBB = getParent();
917 MachineBasicBlock::instr_iterator MII = *this; ++MII;
918 MachineBasicBlock::instr_iterator E = MBB->instr_end();
919 while (MII != E && MII->isInsideBundle()) {
920 MachineInstr *MI = &*MII;
925 // Erase the individual instruction, which may itself be inside a bundle.
926 getParent()->erase_instr(this);
930 /// getNumExplicitOperands - Returns the number of non-implicit operands.
932 unsigned MachineInstr::getNumExplicitOperands() const {
933 unsigned NumOperands = MCID->getNumOperands();
934 if (!MCID->isVariadic())
937 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
938 const MachineOperand &MO = getOperand(i);
939 if (!MO.isReg() || !MO.isImplicit())
945 /// isBundled - Return true if this instruction part of a bundle. This is true
946 /// if either itself or its following instruction is marked "InsideBundle".
947 bool MachineInstr::isBundled() const {
948 if (isInsideBundle())
950 MachineBasicBlock::const_instr_iterator nextMI = this;
952 return nextMI != Parent->instr_end() && nextMI->isInsideBundle();
955 bool MachineInstr::isStackAligningInlineAsm() const {
957 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
958 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
964 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
965 unsigned *GroupNo) const {
966 assert(isInlineAsm() && "Expected an inline asm instruction");
967 assert(OpIdx < getNumOperands() && "OpIdx out of range");
969 // Ignore queries about the initial operands.
970 if (OpIdx < InlineAsm::MIOp_FirstOperand)
975 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
977 const MachineOperand &FlagMO = getOperand(i);
978 // If we reach the implicit register operands, stop looking.
981 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
982 if (i + NumOps > OpIdx) {
992 const TargetRegisterClass*
993 MachineInstr::getRegClassConstraint(unsigned OpIdx,
994 const TargetInstrInfo *TII,
995 const TargetRegisterInfo *TRI) const {
996 assert(getParent() && "Can't have an MBB reference here!");
997 assert(getParent()->getParent() && "Can't have an MF reference here!");
998 const MachineFunction &MF = *getParent()->getParent();
1000 // Most opcodes have fixed constraints in their MCInstrDesc.
1002 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1004 if (!getOperand(OpIdx).isReg())
1007 // For tied uses on inline asm, get the constraint from the def.
1009 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1012 // Inline asm stores register class constraints in the flag word.
1013 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1017 unsigned Flag = getOperand(FlagIdx).getImm();
1019 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1020 return TRI->getRegClass(RCID);
1022 // Assume that all registers in a memory operand are pointers.
1023 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1024 return TRI->getPointerRegClass(MF);
1029 /// getBundleSize - Return the number of instructions inside the MI bundle.
1030 unsigned MachineInstr::getBundleSize() const {
1031 assert(isBundle() && "Expecting a bundle");
1033 MachineBasicBlock::const_instr_iterator I = *this;
1035 while ((++I)->isInsideBundle()) {
1038 assert(Size > 1 && "Malformed bundle");
1043 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1044 /// the specific register or -1 if it is not found. It further tightens
1045 /// the search criteria to a use that kills the register if isKill is true.
1046 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1047 const TargetRegisterInfo *TRI) const {
1048 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1049 const MachineOperand &MO = getOperand(i);
1050 if (!MO.isReg() || !MO.isUse())
1052 unsigned MOReg = MO.getReg();
1057 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1058 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1059 TRI->isSubRegister(MOReg, Reg)))
1060 if (!isKill || MO.isKill())
1066 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1067 /// indicating if this instruction reads or writes Reg. This also considers
1068 /// partial defines.
1069 std::pair<bool,bool>
1070 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1071 SmallVectorImpl<unsigned> *Ops) const {
1072 bool PartDef = false; // Partial redefine.
1073 bool FullDef = false; // Full define.
1076 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1077 const MachineOperand &MO = getOperand(i);
1078 if (!MO.isReg() || MO.getReg() != Reg)
1083 Use |= !MO.isUndef();
1084 else if (MO.getSubReg() && !MO.isUndef())
1085 // A partial <def,undef> doesn't count as reading the register.
1090 // A partial redefine uses Reg unless there is also a full define.
1091 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1094 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1095 /// the specified register or -1 if it is not found. If isDead is true, defs
1096 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1097 /// also checks if there is a def of a super-register.
1099 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1100 const TargetRegisterInfo *TRI) const {
1101 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1102 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1103 const MachineOperand &MO = getOperand(i);
1104 // Accept regmask operands when Overlap is set.
1105 // Ignore them when looking for a specific def operand (Overlap == false).
1106 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1108 if (!MO.isReg() || !MO.isDef())
1110 unsigned MOReg = MO.getReg();
1111 bool Found = (MOReg == Reg);
1112 if (!Found && TRI && isPhys &&
1113 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1115 Found = TRI->regsOverlap(MOReg, Reg);
1117 Found = TRI->isSubRegister(MOReg, Reg);
1119 if (Found && (!isDead || MO.isDead()))
1125 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1126 /// operand list that is used to represent the predicate. It returns -1 if
1128 int MachineInstr::findFirstPredOperandIdx() const {
1129 // Don't call MCID.findFirstPredOperandIdx() because this variant
1130 // is sometimes called on an instruction that's not yet complete, and
1131 // so the number of operands is less than the MCID indicates. In
1132 // particular, the PTX target does this.
1133 const MCInstrDesc &MCID = getDesc();
1134 if (MCID.isPredicable()) {
1135 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1136 if (MCID.OpInfo[i].isPredicate())
1143 /// isRegTiedToUseOperand - Given the index of a register def operand,
1144 /// check if the register def is tied to a source operand, due to either
1145 /// two-address elimination or inline assembly constraints. Returns the
1146 /// first tied use operand index by reference is UseOpIdx is not null.
1148 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
1149 if (isInlineAsm()) {
1150 assert(DefOpIdx > InlineAsm::MIOp_FirstOperand);
1151 const MachineOperand &MO = getOperand(DefOpIdx);
1152 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
1154 // Determine the actual operand index that corresponds to this index.
1156 int FlagIdx = findInlineAsmFlagIdx(DefOpIdx, &DefNo);
1160 // Which part of the group is DefOpIdx?
1161 unsigned DefPart = DefOpIdx - (FlagIdx + 1);
1163 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
1165 const MachineOperand &FMO = getOperand(i);
1168 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
1171 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
1174 *UseOpIdx = (unsigned)i + 1 + DefPart;
1181 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
1182 const MCInstrDesc &MCID = getDesc();
1183 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
1184 const MachineOperand &MO = getOperand(i);
1185 if (MO.isReg() && MO.isUse() &&
1186 MCID.getOperandConstraint(i, MCOI::TIED_TO) == (int)DefOpIdx) {
1188 *UseOpIdx = (unsigned)i;
1195 /// isRegTiedToDefOperand - Return true if the operand of the specified index
1196 /// is a register use and it is tied to an def operand. It also returns the def
1197 /// operand index by reference.
1199 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
1200 if (isInlineAsm()) {
1201 const MachineOperand &MO = getOperand(UseOpIdx);
1202 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
1205 // Find the flag operand corresponding to UseOpIdx
1206 int FlagIdx = findInlineAsmFlagIdx(UseOpIdx);
1210 const MachineOperand &UFMO = getOperand(FlagIdx);
1212 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
1216 unsigned DefIdx = InlineAsm::MIOp_FirstOperand;
1217 // Remember to adjust the index. First operand is asm string, second is
1218 // the HasSideEffects and AlignStack bits, then there is a flag for each.
1220 const MachineOperand &FMO = getOperand(DefIdx);
1221 assert(FMO.isImm());
1222 // Skip over this def.
1223 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
1226 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
1232 const MCInstrDesc &MCID = getDesc();
1233 if (UseOpIdx >= MCID.getNumOperands())
1235 const MachineOperand &MO = getOperand(UseOpIdx);
1236 if (!MO.isReg() || !MO.isUse())
1238 int DefIdx = MCID.getOperandConstraint(UseOpIdx, MCOI::TIED_TO);
1242 *DefOpIdx = (unsigned)DefIdx;
1246 /// clearKillInfo - Clears kill flags on all operands.
1248 void MachineInstr::clearKillInfo() {
1249 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1250 MachineOperand &MO = getOperand(i);
1251 if (MO.isReg() && MO.isUse())
1252 MO.setIsKill(false);
1256 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1258 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1259 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1260 const MachineOperand &MO = MI->getOperand(i);
1261 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1263 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1264 MachineOperand &MOp = getOperand(j);
1265 if (!MOp.isIdenticalTo(MO))
1276 /// copyPredicates - Copies predicate operand(s) from MI.
1277 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1278 assert(!isBundle() && "MachineInstr::copyPredicates() can't handle bundles");
1280 const MCInstrDesc &MCID = MI->getDesc();
1281 if (!MCID.isPredicable())
1283 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1284 if (MCID.OpInfo[i].isPredicate()) {
1285 // Predicated operands must be last operands.
1286 addOperand(MI->getOperand(i));
1291 void MachineInstr::substituteRegister(unsigned FromReg,
1294 const TargetRegisterInfo &RegInfo) {
1295 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1297 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1298 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1299 MachineOperand &MO = getOperand(i);
1300 if (!MO.isReg() || MO.getReg() != FromReg)
1302 MO.substPhysReg(ToReg, RegInfo);
1305 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1306 MachineOperand &MO = getOperand(i);
1307 if (!MO.isReg() || MO.getReg() != FromReg)
1309 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1314 /// isSafeToMove - Return true if it is safe to move this instruction. If
1315 /// SawStore is set to true, it means that there is a store (or call) between
1316 /// the instruction's location and its intended destination.
1317 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1319 bool &SawStore) const {
1320 // Ignore stuff that we obviously can't move.
1321 if (mayStore() || isCall()) {
1326 if (isLabel() || isDebugValue() ||
1327 isTerminator() || hasUnmodeledSideEffects())
1330 // See if this instruction does a load. If so, we have to guarantee that the
1331 // loaded value doesn't change between the load and the its intended
1332 // destination. The check for isInvariantLoad gives the targe the chance to
1333 // classify the load as always returning a constant, e.g. a constant pool
1335 if (mayLoad() && !isInvariantLoad(AA))
1336 // Otherwise, this is a real load. If there is a store between the load and
1337 // end of block, or if the load is volatile, we can't move it.
1338 return !SawStore && !hasVolatileMemoryRef();
1343 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1344 /// instruction which defined the specified register instead of copying it.
1345 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1347 unsigned DstReg) const {
1348 bool SawStore = false;
1349 if (!TII->isTriviallyReMaterializable(this, AA) ||
1350 !isSafeToMove(TII, AA, SawStore))
1352 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1353 const MachineOperand &MO = getOperand(i);
1356 // FIXME: For now, do not remat any instruction with register operands.
1357 // Later on, we can loosen the restriction is the register operands have
1358 // not been modified between the def and use. Note, this is different from
1359 // MachineSink because the code is no longer in two-address form (at least
1363 else if (!MO.isDead() && MO.getReg() != DstReg)
1369 /// hasVolatileMemoryRef - Return true if this instruction may have a
1370 /// volatile memory reference, or if the information describing the
1371 /// memory reference is not available. Return false if it is known to
1372 /// have no volatile memory references.
1373 bool MachineInstr::hasVolatileMemoryRef() const {
1374 // An instruction known never to access memory won't have a volatile access.
1378 !hasUnmodeledSideEffects())
1381 // Otherwise, if the instruction has no memory reference information,
1382 // conservatively assume it wasn't preserved.
1383 if (memoperands_empty())
1386 // Check the memory reference information for volatile references.
1387 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1388 if ((*I)->isVolatile())
1394 /// isInvariantLoad - Return true if this instruction is loading from a
1395 /// location whose value is invariant across the function. For example,
1396 /// loading a value from the constant pool or from the argument area
1397 /// of a function if it does not change. This should only return true of
1398 /// *all* loads the instruction does are invariant (if it does multiple loads).
1399 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1400 // If the instruction doesn't load at all, it isn't an invariant load.
1404 // If the instruction has lost its memoperands, conservatively assume that
1405 // it may not be an invariant load.
1406 if (memoperands_empty())
1409 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1411 for (mmo_iterator I = memoperands_begin(),
1412 E = memoperands_end(); I != E; ++I) {
1413 if ((*I)->isVolatile()) return false;
1414 if ((*I)->isStore()) return false;
1415 if ((*I)->isInvariant()) return true;
1417 if (const Value *V = (*I)->getValue()) {
1418 // A load from a constant PseudoSourceValue is invariant.
1419 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1420 if (PSV->isConstant(MFI))
1422 // If we have an AliasAnalysis, ask it whether the memory is constant.
1423 if (AA && AA->pointsToConstantMemory(
1424 AliasAnalysis::Location(V, (*I)->getSize(),
1425 (*I)->getTBAAInfo())))
1429 // Otherwise assume conservatively.
1433 // Everything checks out.
1437 /// isConstantValuePHI - If the specified instruction is a PHI that always
1438 /// merges together the same virtual register, return the register, otherwise
1440 unsigned MachineInstr::isConstantValuePHI() const {
1443 assert(getNumOperands() >= 3 &&
1444 "It's illegal to have a PHI without source operands");
1446 unsigned Reg = getOperand(1).getReg();
1447 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1448 if (getOperand(i).getReg() != Reg)
1453 bool MachineInstr::hasUnmodeledSideEffects() const {
1454 if (hasProperty(MCID::UnmodeledSideEffects))
1456 if (isInlineAsm()) {
1457 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1458 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1465 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1467 bool MachineInstr::allDefsAreDead() const {
1468 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1469 const MachineOperand &MO = getOperand(i);
1470 if (!MO.isReg() || MO.isUse())
1478 /// copyImplicitOps - Copy implicit register operands from specified
1479 /// instruction to this instruction.
1480 void MachineInstr::copyImplicitOps(const MachineInstr *MI) {
1481 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1483 const MachineOperand &MO = MI->getOperand(i);
1484 if (MO.isReg() && MO.isImplicit())
1489 void MachineInstr::dump() const {
1490 dbgs() << " " << *this;
1493 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1494 raw_ostream &CommentOS) {
1495 const LLVMContext &Ctx = MF->getFunction()->getContext();
1496 if (!DL.isUnknown()) { // Print source line info.
1497 DIScope Scope(DL.getScope(Ctx));
1498 // Omit the directory, because it's likely to be long and uninteresting.
1500 CommentOS << Scope.getFilename();
1502 CommentOS << "<unknown>";
1503 CommentOS << ':' << DL.getLine();
1504 if (DL.getCol() != 0)
1505 CommentOS << ':' << DL.getCol();
1506 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1507 if (!InlinedAtDL.isUnknown()) {
1508 CommentOS << " @[ ";
1509 printDebugLoc(InlinedAtDL, MF, CommentOS);
1515 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1516 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1517 const MachineFunction *MF = 0;
1518 const MachineRegisterInfo *MRI = 0;
1519 if (const MachineBasicBlock *MBB = getParent()) {
1520 MF = MBB->getParent();
1522 TM = &MF->getTarget();
1524 MRI = &MF->getRegInfo();
1527 // Save a list of virtual registers.
1528 SmallVector<unsigned, 8> VirtRegs;
1530 // Print explicitly defined operands on the left of an assignment syntax.
1531 unsigned StartOp = 0, e = getNumOperands();
1532 for (; StartOp < e && getOperand(StartOp).isReg() &&
1533 getOperand(StartOp).isDef() &&
1534 !getOperand(StartOp).isImplicit();
1536 if (StartOp != 0) OS << ", ";
1537 getOperand(StartOp).print(OS, TM);
1538 unsigned Reg = getOperand(StartOp).getReg();
1539 if (TargetRegisterInfo::isVirtualRegister(Reg))
1540 VirtRegs.push_back(Reg);
1546 // Print the opcode name.
1547 if (TM && TM->getInstrInfo())
1548 OS << TM->getInstrInfo()->getName(getOpcode());
1552 // Print the rest of the operands.
1553 bool OmittedAnyCallClobbers = false;
1554 bool FirstOp = true;
1555 unsigned AsmDescOp = ~0u;
1556 unsigned AsmOpCount = 0;
1558 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1559 // Print asm string.
1561 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1563 // Print HasSideEffects, IsAlignStack
1564 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1565 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1566 OS << " [sideeffect]";
1567 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1568 OS << " [alignstack]";
1570 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1575 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1576 const MachineOperand &MO = getOperand(i);
1578 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1579 VirtRegs.push_back(MO.getReg());
1581 // Omit call-clobbered registers which aren't used anywhere. This makes
1582 // call instructions much less noisy on targets where calls clobber lots
1583 // of registers. Don't rely on MO.isDead() because we may be called before
1584 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1585 if (MF && isCall() &&
1586 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1587 unsigned Reg = MO.getReg();
1588 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1589 const MachineRegisterInfo &MRI = MF->getRegInfo();
1590 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1591 bool HasAliasLive = false;
1592 for (MCRegAliasIterator AI(Reg, TM->getRegisterInfo(), true);
1593 AI.isValid(); ++AI) {
1594 unsigned AliasReg = *AI;
1595 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1596 HasAliasLive = true;
1600 if (!HasAliasLive) {
1601 OmittedAnyCallClobbers = true;
1608 if (FirstOp) FirstOp = false; else OS << ",";
1610 if (i < getDesc().NumOperands) {
1611 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1612 if (MCOI.isPredicate())
1614 if (MCOI.isOptionalDef())
1617 if (isDebugValue() && MO.isMetadata()) {
1618 // Pretty print DBG_VALUE instructions.
1619 const MDNode *MD = MO.getMetadata();
1620 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1621 OS << "!\"" << MDS->getString() << '\"';
1624 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1625 OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1626 } else if (i == AsmDescOp && MO.isImm()) {
1627 // Pretty print the inline asm operand descriptor.
1628 OS << '$' << AsmOpCount++;
1629 unsigned Flag = MO.getImm();
1630 switch (InlineAsm::getKind(Flag)) {
1631 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1632 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1633 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1634 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1635 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1636 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1637 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1641 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1643 OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
1645 OS << ":RC" << RCID;
1648 unsigned TiedTo = 0;
1649 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1650 OS << " tiedto:$" << TiedTo;
1654 // Compute the index of the next operand descriptor.
1655 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1660 // Briefly indicate whether any call clobbers were omitted.
1661 if (OmittedAnyCallClobbers) {
1662 if (!FirstOp) OS << ",";
1666 bool HaveSemi = false;
1668 if (!HaveSemi) OS << ";"; HaveSemi = true;
1671 if (Flags & FrameSetup)
1675 if (!memoperands_empty()) {
1676 if (!HaveSemi) OS << ";"; HaveSemi = true;
1679 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1682 if (llvm::next(i) != e)
1687 // Print the regclass of any virtual registers encountered.
1688 if (MRI && !VirtRegs.empty()) {
1689 if (!HaveSemi) OS << ";"; HaveSemi = true;
1690 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1691 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1692 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1693 for (unsigned j = i+1; j != VirtRegs.size();) {
1694 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1698 if (VirtRegs[i] != VirtRegs[j])
1699 OS << "," << PrintReg(VirtRegs[j]);
1700 VirtRegs.erase(VirtRegs.begin()+j);
1705 // Print debug location information.
1706 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1707 if (!HaveSemi) OS << ";"; HaveSemi = true;
1708 DIVariable DV(getOperand(e - 1).getMetadata());
1709 OS << " line no:" << DV.getLineNumber();
1710 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1711 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1712 if (!InlinedAtDL.isUnknown()) {
1713 OS << " inlined @[ ";
1714 printDebugLoc(InlinedAtDL, MF, OS);
1718 } else if (!debugLoc.isUnknown() && MF) {
1719 if (!HaveSemi) OS << ";"; HaveSemi = true;
1721 printDebugLoc(debugLoc, MF, OS);
1727 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1728 const TargetRegisterInfo *RegInfo,
1729 bool AddIfNotFound) {
1730 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1731 bool hasAliases = isPhysReg &&
1732 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1734 SmallVector<unsigned,4> DeadOps;
1735 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1736 MachineOperand &MO = getOperand(i);
1737 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1739 unsigned Reg = MO.getReg();
1743 if (Reg == IncomingReg) {
1746 // The register is already marked kill.
1748 if (isPhysReg && isRegTiedToDefOperand(i))
1749 // Two-address uses of physregs must not be marked kill.
1754 } else if (hasAliases && MO.isKill() &&
1755 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1756 // A super-register kill already exists.
1757 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1759 if (RegInfo->isSubRegister(IncomingReg, Reg))
1760 DeadOps.push_back(i);
1764 // Trim unneeded kill operands.
1765 while (!DeadOps.empty()) {
1766 unsigned OpIdx = DeadOps.back();
1767 if (getOperand(OpIdx).isImplicit())
1768 RemoveOperand(OpIdx);
1770 getOperand(OpIdx).setIsKill(false);
1774 // If not found, this means an alias of one of the operands is killed. Add a
1775 // new implicit operand if required.
1776 if (!Found && AddIfNotFound) {
1777 addOperand(MachineOperand::CreateReg(IncomingReg,
1786 void MachineInstr::clearRegisterKills(unsigned Reg,
1787 const TargetRegisterInfo *RegInfo) {
1788 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1790 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1791 MachineOperand &MO = getOperand(i);
1792 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1794 unsigned OpReg = MO.getReg();
1795 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1796 MO.setIsKill(false);
1800 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1801 const TargetRegisterInfo *RegInfo,
1802 bool AddIfNotFound) {
1803 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1804 bool hasAliases = isPhysReg &&
1805 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1807 SmallVector<unsigned,4> DeadOps;
1808 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1809 MachineOperand &MO = getOperand(i);
1810 if (!MO.isReg() || !MO.isDef())
1812 unsigned Reg = MO.getReg();
1816 if (Reg == IncomingReg) {
1819 } else if (hasAliases && MO.isDead() &&
1820 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1821 // There exists a super-register that's marked dead.
1822 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1824 if (RegInfo->isSubRegister(IncomingReg, Reg))
1825 DeadOps.push_back(i);
1829 // Trim unneeded dead operands.
1830 while (!DeadOps.empty()) {
1831 unsigned OpIdx = DeadOps.back();
1832 if (getOperand(OpIdx).isImplicit())
1833 RemoveOperand(OpIdx);
1835 getOperand(OpIdx).setIsDead(false);
1839 // If not found, this means an alias of one of the operands is dead. Add a
1840 // new implicit operand if required.
1841 if (Found || !AddIfNotFound)
1844 addOperand(MachineOperand::CreateReg(IncomingReg,
1852 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1853 const TargetRegisterInfo *RegInfo) {
1854 if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1855 MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1859 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1860 const MachineOperand &MO = getOperand(i);
1861 if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1862 MO.getSubReg() == 0)
1866 addOperand(MachineOperand::CreateReg(IncomingReg,
1871 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1872 const TargetRegisterInfo &TRI) {
1873 bool HasRegMask = false;
1874 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1875 MachineOperand &MO = getOperand(i);
1876 if (MO.isRegMask()) {
1880 if (!MO.isReg() || !MO.isDef()) continue;
1881 unsigned Reg = MO.getReg();
1882 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1884 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1886 if (TRI.regsOverlap(*I, Reg)) {
1890 // If there are no uses, including partial uses, the def is dead.
1891 if (Dead) MO.setIsDead();
1894 // This is a call with a register mask operand.
1895 // Mask clobbers are always dead, so add defs for the non-dead defines.
1897 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1899 addRegisterDefined(*I, &TRI);
1903 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1904 // Build up a buffer of hash code components.
1905 SmallVector<size_t, 8> HashComponents;
1906 HashComponents.reserve(MI->getNumOperands() + 1);
1907 HashComponents.push_back(MI->getOpcode());
1908 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1909 const MachineOperand &MO = MI->getOperand(i);
1910 if (MO.isReg() && MO.isDef() &&
1911 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1912 continue; // Skip virtual register defs.
1914 HashComponents.push_back(hash_value(MO));
1916 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1919 void MachineInstr::emitError(StringRef Msg) const {
1920 // Find the source location cookie.
1921 unsigned LocCookie = 0;
1922 const MDNode *LocMD = 0;
1923 for (unsigned i = getNumOperands(); i != 0; --i) {
1924 if (getOperand(i-1).isMetadata() &&
1925 (LocMD = getOperand(i-1).getMetadata()) &&
1926 LocMD->getNumOperands() != 0) {
1927 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1928 LocCookie = CI->getZExtValue();
1934 if (const MachineBasicBlock *MBB = getParent())
1935 if (const MachineFunction *MF = MBB->getParent())
1936 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1937 report_fatal_error(Msg);