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/Function.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Metadata.h"
19 #include "llvm/Type.h"
20 #include "llvm/Value.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetInstrDesc.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/LeakDetector.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/ADT/FoldingSet.h"
42 //===----------------------------------------------------------------------===//
43 // MachineOperand Implementation
44 //===----------------------------------------------------------------------===//
46 /// AddRegOperandToRegInfo - Add this register operand to the specified
47 /// MachineRegisterInfo. If it is null, then the next/prev fields should be
48 /// explicitly nulled out.
49 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
50 assert(isReg() && "Can only add reg operand to use lists");
52 // If the reginfo pointer is null, just explicitly null out or next/prev
53 // pointers, to ensure they are not garbage.
55 Contents.Reg.Prev = 0;
56 Contents.Reg.Next = 0;
60 // Otherwise, add this operand to the head of the registers use/def list.
61 MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
63 // For SSA values, we prefer to keep the definition at the start of the list.
64 // we do this by skipping over the definition if it is at the head of the
66 if (*Head && (*Head)->isDef())
67 Head = &(*Head)->Contents.Reg.Next;
69 Contents.Reg.Next = *Head;
70 if (Contents.Reg.Next) {
71 assert(getReg() == Contents.Reg.Next->getReg() &&
72 "Different regs on the same list!");
73 Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
76 Contents.Reg.Prev = Head;
80 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
81 /// MachineRegisterInfo it is linked with.
82 void MachineOperand::RemoveRegOperandFromRegInfo() {
83 assert(isOnRegUseList() && "Reg operand is not on a use list");
84 // Unlink this from the doubly linked list of operands.
85 MachineOperand *NextOp = Contents.Reg.Next;
86 *Contents.Reg.Prev = NextOp;
88 assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
89 NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
91 Contents.Reg.Prev = 0;
92 Contents.Reg.Next = 0;
95 void MachineOperand::setReg(unsigned Reg) {
96 if (getReg() == Reg) return; // No change.
98 // Otherwise, we have to change the register. If this operand is embedded
99 // into a machine function, we need to update the old and new register's
101 if (MachineInstr *MI = getParent())
102 if (MachineBasicBlock *MBB = MI->getParent())
103 if (MachineFunction *MF = MBB->getParent()) {
104 RemoveRegOperandFromRegInfo();
105 SmallContents.RegNo = Reg;
106 AddRegOperandToRegInfo(&MF->getRegInfo());
110 // Otherwise, just change the register, no problem. :)
111 SmallContents.RegNo = Reg;
114 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
115 const TargetRegisterInfo &TRI) {
116 assert(TargetRegisterInfo::isVirtualRegister(Reg));
117 if (SubIdx && getSubReg())
118 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
124 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
125 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
127 Reg = TRI.getSubReg(Reg, getSubReg());
128 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
129 // That won't happen in legal code.
135 /// ChangeToImmediate - Replace this operand with a new immediate operand of
136 /// the specified value. If an operand is known to be an immediate already,
137 /// the setImm method should be used.
138 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
139 // If this operand is currently a register operand, and if this is in a
140 // function, deregister the operand from the register's use/def list.
141 if (isReg() && getParent() && getParent()->getParent() &&
142 getParent()->getParent()->getParent())
143 RemoveRegOperandFromRegInfo();
145 OpKind = MO_Immediate;
146 Contents.ImmVal = ImmVal;
149 /// ChangeToRegister - Replace this operand with a new register operand of
150 /// the specified value. If an operand is known to be an register already,
151 /// the setReg method should be used.
152 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
153 bool isKill, bool isDead, bool isUndef,
155 // If this operand is already a register operand, use setReg to update the
156 // register's use/def lists.
158 assert(!isEarlyClobber());
161 // Otherwise, change this to a register and set the reg#.
162 OpKind = MO_Register;
163 SmallContents.RegNo = Reg;
165 // If this operand is embedded in a function, add the operand to the
166 // register's use/def list.
167 if (MachineInstr *MI = getParent())
168 if (MachineBasicBlock *MBB = MI->getParent())
169 if (MachineFunction *MF = MBB->getParent())
170 AddRegOperandToRegInfo(&MF->getRegInfo());
178 IsEarlyClobber = false;
183 /// isIdenticalTo - Return true if this operand is identical to the specified
185 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
186 if (getType() != Other.getType() ||
187 getTargetFlags() != Other.getTargetFlags())
191 default: llvm_unreachable("Unrecognized operand type");
192 case MachineOperand::MO_Register:
193 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
194 getSubReg() == Other.getSubReg();
195 case MachineOperand::MO_Immediate:
196 return getImm() == Other.getImm();
197 case MachineOperand::MO_FPImmediate:
198 return getFPImm() == Other.getFPImm();
199 case MachineOperand::MO_MachineBasicBlock:
200 return getMBB() == Other.getMBB();
201 case MachineOperand::MO_FrameIndex:
202 return getIndex() == Other.getIndex();
203 case MachineOperand::MO_ConstantPoolIndex:
204 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
205 case MachineOperand::MO_JumpTableIndex:
206 return getIndex() == Other.getIndex();
207 case MachineOperand::MO_GlobalAddress:
208 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
209 case MachineOperand::MO_ExternalSymbol:
210 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
211 getOffset() == Other.getOffset();
212 case MachineOperand::MO_BlockAddress:
213 return getBlockAddress() == Other.getBlockAddress();
214 case MachineOperand::MO_MCSymbol:
215 return getMCSymbol() == Other.getMCSymbol();
216 case MachineOperand::MO_Metadata:
217 return getMetadata() == Other.getMetadata();
221 /// print - Print the specified machine operand.
223 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
224 // If the instruction is embedded into a basic block, we can find the
225 // target info for the instruction.
227 if (const MachineInstr *MI = getParent())
228 if (const MachineBasicBlock *MBB = MI->getParent())
229 if (const MachineFunction *MF = MBB->getParent())
230 TM = &MF->getTarget();
231 const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
234 case MachineOperand::MO_Register:
235 OS << PrintReg(getReg(), TRI, getSubReg());
237 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
240 bool NeedComma = false;
242 if (NeedComma) OS << ',';
243 if (isEarlyClobber())
244 OS << "earlyclobber,";
249 } else if (isImplicit()) {
254 if (isKill() || isDead() || isUndef()) {
255 if (NeedComma) OS << ',';
256 if (isKill()) OS << "kill";
257 if (isDead()) OS << "dead";
259 if (isKill() || isDead())
267 case MachineOperand::MO_Immediate:
270 case MachineOperand::MO_FPImmediate:
271 if (getFPImm()->getType()->isFloatTy())
272 OS << getFPImm()->getValueAPF().convertToFloat();
274 OS << getFPImm()->getValueAPF().convertToDouble();
276 case MachineOperand::MO_MachineBasicBlock:
277 OS << "<BB#" << getMBB()->getNumber() << ">";
279 case MachineOperand::MO_FrameIndex:
280 OS << "<fi#" << getIndex() << '>';
282 case MachineOperand::MO_ConstantPoolIndex:
283 OS << "<cp#" << getIndex();
284 if (getOffset()) OS << "+" << getOffset();
287 case MachineOperand::MO_JumpTableIndex:
288 OS << "<jt#" << getIndex() << '>';
290 case MachineOperand::MO_GlobalAddress:
292 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
293 if (getOffset()) OS << "+" << getOffset();
296 case MachineOperand::MO_ExternalSymbol:
297 OS << "<es:" << getSymbolName();
298 if (getOffset()) OS << "+" << getOffset();
301 case MachineOperand::MO_BlockAddress:
303 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
306 case MachineOperand::MO_Metadata:
308 WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
311 case MachineOperand::MO_MCSymbol:
312 OS << "<MCSym=" << *getMCSymbol() << '>';
315 llvm_unreachable("Unrecognized operand type");
318 if (unsigned TF = getTargetFlags())
319 OS << "[TF=" << TF << ']';
322 //===----------------------------------------------------------------------===//
323 // MachineMemOperand Implementation
324 //===----------------------------------------------------------------------===//
326 /// getAddrSpace - Return the LLVM IR address space number that this pointer
328 unsigned MachinePointerInfo::getAddrSpace() const {
329 if (V == 0) return 0;
330 return cast<PointerType>(V->getType())->getAddressSpace();
333 /// getConstantPool - Return a MachinePointerInfo record that refers to the
335 MachinePointerInfo MachinePointerInfo::getConstantPool() {
336 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
339 /// getFixedStack - Return a MachinePointerInfo record that refers to the
340 /// the specified FrameIndex.
341 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
342 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
345 MachinePointerInfo MachinePointerInfo::getJumpTable() {
346 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
349 MachinePointerInfo MachinePointerInfo::getGOT() {
350 return MachinePointerInfo(PseudoSourceValue::getGOT());
353 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
354 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
357 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
358 uint64_t s, unsigned int a,
359 const MDNode *TBAAInfo)
360 : PtrInfo(ptrinfo), Size(s),
361 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
363 assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
364 "invalid pointer value");
365 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
366 assert((isLoad() || isStore()) && "Not a load/store!");
369 /// Profile - Gather unique data for the object.
371 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
372 ID.AddInteger(getOffset());
374 ID.AddPointer(getValue());
375 ID.AddInteger(Flags);
378 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
379 // The Value and Offset may differ due to CSE. But the flags and size
380 // should be the same.
381 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
382 assert(MMO->getSize() == getSize() && "Size mismatch!");
384 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
385 // Update the alignment value.
386 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
387 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
388 // Also update the base and offset, because the new alignment may
389 // not be applicable with the old ones.
390 PtrInfo = MMO->PtrInfo;
394 /// getAlignment - Return the minimum known alignment in bytes of the
395 /// actual memory reference.
396 uint64_t MachineMemOperand::getAlignment() const {
397 return MinAlign(getBaseAlignment(), getOffset());
400 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
401 assert((MMO.isLoad() || MMO.isStore()) &&
402 "SV has to be a load, store or both.");
404 if (MMO.isVolatile())
413 // Print the address information.
418 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
420 // If the alignment of the memory reference itself differs from the alignment
421 // of the base pointer, print the base alignment explicitly, next to the base
423 if (MMO.getBaseAlignment() != MMO.getAlignment())
424 OS << "(align=" << MMO.getBaseAlignment() << ")";
426 if (MMO.getOffset() != 0)
427 OS << "+" << MMO.getOffset();
430 // Print the alignment of the reference.
431 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
432 MMO.getBaseAlignment() != MMO.getSize())
433 OS << "(align=" << MMO.getAlignment() << ")";
436 if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
438 if (TBAAInfo->getNumOperands() > 0)
439 WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
445 // Print nontemporal info.
446 if (MMO.isNonTemporal())
447 OS << "(nontemporal)";
452 //===----------------------------------------------------------------------===//
453 // MachineInstr Implementation
454 //===----------------------------------------------------------------------===//
456 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
457 /// TID NULL and no operands.
458 MachineInstr::MachineInstr()
459 : TID(0), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
460 MemRefs(0), MemRefsEnd(0),
462 // Make sure that we get added to a machine basicblock
463 LeakDetector::addGarbageObject(this);
466 void MachineInstr::addImplicitDefUseOperands() {
467 if (TID->ImplicitDefs)
468 for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
469 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
470 if (TID->ImplicitUses)
471 for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
472 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
475 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
476 /// implicit operands. It reserves space for the number of operands specified by
477 /// the TargetInstrDesc.
478 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
479 : TID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
480 MemRefs(0), MemRefsEnd(0), Parent(0) {
482 NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
483 Operands.reserve(NumImplicitOps + TID->getNumOperands());
485 addImplicitDefUseOperands();
486 // Make sure that we get added to a machine basicblock
487 LeakDetector::addGarbageObject(this);
490 /// MachineInstr ctor - As above, but with a DebugLoc.
491 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
493 : TID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
494 MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
496 NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
497 Operands.reserve(NumImplicitOps + TID->getNumOperands());
499 addImplicitDefUseOperands();
500 // Make sure that we get added to a machine basicblock
501 LeakDetector::addGarbageObject(this);
504 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
505 /// that the MachineInstr is created and added to the end of the specified
507 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
508 : TID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
509 MemRefs(0), MemRefsEnd(0), Parent(0) {
510 assert(MBB && "Cannot use inserting ctor with null basic block!");
511 NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
512 Operands.reserve(NumImplicitOps + TID->getNumOperands());
513 addImplicitDefUseOperands();
514 // Make sure that we get added to a machine basicblock
515 LeakDetector::addGarbageObject(this);
516 MBB->push_back(this); // Add instruction to end of basic block!
519 /// MachineInstr ctor - As above, but with a DebugLoc.
521 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
522 const TargetInstrDesc &tid)
523 : TID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
524 MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
525 assert(MBB && "Cannot use inserting ctor with null basic block!");
526 NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
527 Operands.reserve(NumImplicitOps + TID->getNumOperands());
528 addImplicitDefUseOperands();
529 // Make sure that we get added to a machine basicblock
530 LeakDetector::addGarbageObject(this);
531 MBB->push_back(this); // Add instruction to end of basic block!
534 /// MachineInstr ctor - Copies MachineInstr arg exactly
536 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
537 : TID(&MI.getDesc()), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
538 MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
539 Parent(0), debugLoc(MI.getDebugLoc()) {
540 Operands.reserve(MI.getNumOperands());
543 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
544 addOperand(MI.getOperand(i));
545 NumImplicitOps = MI.NumImplicitOps;
547 // Copy all the flags.
550 // Set parent to null.
553 LeakDetector::addGarbageObject(this);
556 MachineInstr::~MachineInstr() {
557 LeakDetector::removeGarbageObject(this);
559 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
560 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
561 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
562 "Reg operand def/use list corrupted");
567 /// getRegInfo - If this instruction is embedded into a MachineFunction,
568 /// return the MachineRegisterInfo object for the current function, otherwise
570 MachineRegisterInfo *MachineInstr::getRegInfo() {
571 if (MachineBasicBlock *MBB = getParent())
572 return &MBB->getParent()->getRegInfo();
576 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
577 /// this instruction from their respective use lists. This requires that the
578 /// operands already be on their use lists.
579 void MachineInstr::RemoveRegOperandsFromUseLists() {
580 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
581 if (Operands[i].isReg())
582 Operands[i].RemoveRegOperandFromRegInfo();
586 /// AddRegOperandsToUseLists - Add all of the register operands in
587 /// this instruction from their respective use lists. This requires that the
588 /// operands not be on their use lists yet.
589 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
590 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
591 if (Operands[i].isReg())
592 Operands[i].AddRegOperandToRegInfo(&RegInfo);
597 /// addOperand - Add the specified operand to the instruction. If it is an
598 /// implicit operand, it is added to the end of the operand list. If it is
599 /// an explicit operand it is added at the end of the explicit operand list
600 /// (before the first implicit operand).
601 void MachineInstr::addOperand(const MachineOperand &Op) {
602 bool isImpReg = Op.isReg() && Op.isImplicit();
603 assert((isImpReg || !OperandsComplete()) &&
604 "Trying to add an operand to a machine instr that is already done!");
606 MachineRegisterInfo *RegInfo = getRegInfo();
608 // If we are adding the operand to the end of the list, our job is simpler.
609 // This is true most of the time, so this is a reasonable optimization.
610 if (isImpReg || NumImplicitOps == 0) {
611 // We can only do this optimization if we know that the operand list won't
613 if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
614 Operands.push_back(Op);
616 // Set the parent of the operand.
617 Operands.back().ParentMI = this;
619 // If the operand is a register, update the operand's use list.
621 Operands.back().AddRegOperandToRegInfo(RegInfo);
622 // If the register operand is flagged as early, mark the operand as such
623 unsigned OpNo = Operands.size() - 1;
624 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
625 Operands[OpNo].setIsEarlyClobber(true);
631 // Otherwise, we have to insert a real operand before any implicit ones.
632 unsigned OpNo = Operands.size()-NumImplicitOps;
634 // If this instruction isn't embedded into a function, then we don't need to
635 // update any operand lists.
637 // Simple insertion, no reginfo update needed for other register operands.
638 Operands.insert(Operands.begin()+OpNo, Op);
639 Operands[OpNo].ParentMI = this;
641 // Do explicitly set the reginfo for this operand though, to ensure the
642 // next/prev fields are properly nulled out.
643 if (Operands[OpNo].isReg()) {
644 Operands[OpNo].AddRegOperandToRegInfo(0);
645 // If the register operand is flagged as early, mark the operand as such
646 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
647 Operands[OpNo].setIsEarlyClobber(true);
650 } else if (Operands.size()+1 <= Operands.capacity()) {
651 // Otherwise, we have to remove register operands from their register use
652 // list, add the operand, then add the register operands back to their use
653 // list. This also must handle the case when the operand list reallocates
654 // to somewhere else.
656 // If insertion of this operand won't cause reallocation of the operand
657 // list, just remove the implicit operands, add the operand, then re-add all
658 // the rest of the operands.
659 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
660 assert(Operands[i].isReg() && "Should only be an implicit reg!");
661 Operands[i].RemoveRegOperandFromRegInfo();
664 // Add the operand. If it is a register, add it to the reg list.
665 Operands.insert(Operands.begin()+OpNo, Op);
666 Operands[OpNo].ParentMI = this;
668 if (Operands[OpNo].isReg()) {
669 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
670 // If the register operand is flagged as early, mark the operand as such
671 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
672 Operands[OpNo].setIsEarlyClobber(true);
675 // Re-add all the implicit ops.
676 for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
677 assert(Operands[i].isReg() && "Should only be an implicit reg!");
678 Operands[i].AddRegOperandToRegInfo(RegInfo);
681 // Otherwise, we will be reallocating the operand list. Remove all reg
682 // operands from their list, then readd them after the operand list is
684 RemoveRegOperandsFromUseLists();
686 Operands.insert(Operands.begin()+OpNo, Op);
687 Operands[OpNo].ParentMI = this;
689 // Re-add all the operands.
690 AddRegOperandsToUseLists(*RegInfo);
692 // If the register operand is flagged as early, mark the operand as such
693 if (Operands[OpNo].isReg()
694 && TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
695 Operands[OpNo].setIsEarlyClobber(true);
699 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
700 /// fewer operand than it started with.
702 void MachineInstr::RemoveOperand(unsigned OpNo) {
703 assert(OpNo < Operands.size() && "Invalid operand number");
705 // Special case removing the last one.
706 if (OpNo == Operands.size()-1) {
707 // If needed, remove from the reg def/use list.
708 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
709 Operands.back().RemoveRegOperandFromRegInfo();
715 // Otherwise, we are removing an interior operand. If we have reginfo to
716 // update, remove all operands that will be shifted down from their reg lists,
717 // move everything down, then re-add them.
718 MachineRegisterInfo *RegInfo = getRegInfo();
720 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
721 if (Operands[i].isReg())
722 Operands[i].RemoveRegOperandFromRegInfo();
726 Operands.erase(Operands.begin()+OpNo);
729 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
730 if (Operands[i].isReg())
731 Operands[i].AddRegOperandToRegInfo(RegInfo);
736 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
737 /// This function should be used only occasionally. The setMemRefs function
738 /// is the primary method for setting up a MachineInstr's MemRefs list.
739 void MachineInstr::addMemOperand(MachineFunction &MF,
740 MachineMemOperand *MO) {
741 mmo_iterator OldMemRefs = MemRefs;
742 mmo_iterator OldMemRefsEnd = MemRefsEnd;
744 size_t NewNum = (MemRefsEnd - MemRefs) + 1;
745 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
746 mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
748 std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
749 NewMemRefs[NewNum - 1] = MO;
751 MemRefs = NewMemRefs;
752 MemRefsEnd = NewMemRefsEnd;
755 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
756 MICheckType Check) const {
757 // If opcodes or number of operands are not the same then the two
758 // instructions are obviously not identical.
759 if (Other->getOpcode() != getOpcode() ||
760 Other->getNumOperands() != getNumOperands())
763 // Check operands to make sure they match.
764 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
765 const MachineOperand &MO = getOperand(i);
766 const MachineOperand &OMO = Other->getOperand(i);
767 // Clients may or may not want to ignore defs when testing for equality.
768 // For example, machine CSE pass only cares about finding common
769 // subexpressions, so it's safe to ignore virtual register defs.
770 if (Check != CheckDefs && MO.isReg() && MO.isDef()) {
771 if (Check == IgnoreDefs)
773 // Check == IgnoreVRegDefs
774 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
775 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
776 if (MO.getReg() != OMO.getReg())
778 } else if (!MO.isIdenticalTo(OMO))
784 /// removeFromParent - This method unlinks 'this' from the containing basic
785 /// block, and returns it, but does not delete it.
786 MachineInstr *MachineInstr::removeFromParent() {
787 assert(getParent() && "Not embedded in a basic block!");
788 getParent()->remove(this);
793 /// eraseFromParent - This method unlinks 'this' from the containing basic
794 /// block, and deletes it.
795 void MachineInstr::eraseFromParent() {
796 assert(getParent() && "Not embedded in a basic block!");
797 getParent()->erase(this);
801 /// OperandComplete - Return true if it's illegal to add a new operand
803 bool MachineInstr::OperandsComplete() const {
804 unsigned short NumOperands = TID->getNumOperands();
805 if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
806 return true; // Broken: we have all the operands of this instruction!
810 /// getNumExplicitOperands - Returns the number of non-implicit operands.
812 unsigned MachineInstr::getNumExplicitOperands() const {
813 unsigned NumOperands = TID->getNumOperands();
814 if (!TID->isVariadic())
817 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
818 const MachineOperand &MO = getOperand(i);
819 if (!MO.isReg() || !MO.isImplicit())
825 bool MachineInstr::isStackAligningInlineAsm() const {
827 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
828 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
834 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
835 /// the specific register or -1 if it is not found. It further tightens
836 /// the search criteria to a use that kills the register if isKill is true.
837 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
838 const TargetRegisterInfo *TRI) const {
839 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
840 const MachineOperand &MO = getOperand(i);
841 if (!MO.isReg() || !MO.isUse())
843 unsigned MOReg = MO.getReg();
848 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
849 TargetRegisterInfo::isPhysicalRegister(Reg) &&
850 TRI->isSubRegister(MOReg, Reg)))
851 if (!isKill || MO.isKill())
857 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
858 /// indicating if this instruction reads or writes Reg. This also considers
861 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
862 SmallVectorImpl<unsigned> *Ops) const {
863 bool PartDef = false; // Partial redefine.
864 bool FullDef = false; // Full define.
867 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
868 const MachineOperand &MO = getOperand(i);
869 if (!MO.isReg() || MO.getReg() != Reg)
874 Use |= !MO.isUndef();
875 else if (MO.getSubReg())
880 // A partial redefine uses Reg unless there is also a full define.
881 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
884 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
885 /// the specified register or -1 if it is not found. If isDead is true, defs
886 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
887 /// also checks if there is a def of a super-register.
889 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
890 const TargetRegisterInfo *TRI) const {
891 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
892 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
893 const MachineOperand &MO = getOperand(i);
894 if (!MO.isReg() || !MO.isDef())
896 unsigned MOReg = MO.getReg();
897 bool Found = (MOReg == Reg);
898 if (!Found && TRI && isPhys &&
899 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
901 Found = TRI->regsOverlap(MOReg, Reg);
903 Found = TRI->isSubRegister(MOReg, Reg);
905 if (Found && (!isDead || MO.isDead()))
911 /// findFirstPredOperandIdx() - Find the index of the first operand in the
912 /// operand list that is used to represent the predicate. It returns -1 if
914 int MachineInstr::findFirstPredOperandIdx() const {
915 const TargetInstrDesc &TID = getDesc();
916 if (TID.isPredicable()) {
917 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
918 if (TID.OpInfo[i].isPredicate())
925 /// isRegTiedToUseOperand - Given the index of a register def operand,
926 /// check if the register def is tied to a source operand, due to either
927 /// two-address elimination or inline assembly constraints. Returns the
928 /// first tied use operand index by reference is UseOpIdx is not null.
930 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
932 assert(DefOpIdx > InlineAsm::MIOp_FirstOperand);
933 const MachineOperand &MO = getOperand(DefOpIdx);
934 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
936 // Determine the actual operand index that corresponds to this index.
938 unsigned DefPart = 0;
939 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
941 const MachineOperand &FMO = getOperand(i);
942 // After the normal asm operands there may be additional imp-def regs.
945 // Skip over this def.
946 unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
947 unsigned PrevDef = i + 1;
948 i = PrevDef + NumOps;
950 DefPart = DefOpIdx - PrevDef;
955 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
957 const MachineOperand &FMO = getOperand(i);
960 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
963 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
966 *UseOpIdx = (unsigned)i + 1 + DefPart;
973 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
974 const TargetInstrDesc &TID = getDesc();
975 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
976 const MachineOperand &MO = getOperand(i);
977 if (MO.isReg() && MO.isUse() &&
978 TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
980 *UseOpIdx = (unsigned)i;
987 /// isRegTiedToDefOperand - Return true if the operand of the specified index
988 /// is a register use and it is tied to an def operand. It also returns the def
989 /// operand index by reference.
991 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
993 const MachineOperand &MO = getOperand(UseOpIdx);
994 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
997 // Find the flag operand corresponding to UseOpIdx
998 unsigned FlagIdx, NumOps=0;
999 for (FlagIdx = InlineAsm::MIOp_FirstOperand;
1000 FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
1001 const MachineOperand &UFMO = getOperand(FlagIdx);
1002 // After the normal asm operands there may be additional imp-def regs.
1005 NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
1006 assert(NumOps < getNumOperands() && "Invalid inline asm flag");
1007 if (UseOpIdx < FlagIdx+NumOps+1)
1010 if (FlagIdx >= UseOpIdx)
1012 const MachineOperand &UFMO = getOperand(FlagIdx);
1014 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
1018 unsigned DefIdx = InlineAsm::MIOp_FirstOperand;
1019 // Remember to adjust the index. First operand is asm string, second is
1020 // the HasSideEffects and AlignStack bits, then there is a flag for each.
1022 const MachineOperand &FMO = getOperand(DefIdx);
1023 assert(FMO.isImm());
1024 // Skip over this def.
1025 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
1028 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
1034 const TargetInstrDesc &TID = getDesc();
1035 if (UseOpIdx >= TID.getNumOperands())
1037 const MachineOperand &MO = getOperand(UseOpIdx);
1038 if (!MO.isReg() || !MO.isUse())
1040 int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
1044 *DefOpIdx = (unsigned)DefIdx;
1048 /// clearKillInfo - Clears kill flags on all operands.
1050 void MachineInstr::clearKillInfo() {
1051 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1052 MachineOperand &MO = getOperand(i);
1053 if (MO.isReg() && MO.isUse())
1054 MO.setIsKill(false);
1058 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1060 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1061 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1062 const MachineOperand &MO = MI->getOperand(i);
1063 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1065 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1066 MachineOperand &MOp = getOperand(j);
1067 if (!MOp.isIdenticalTo(MO))
1078 /// copyPredicates - Copies predicate operand(s) from MI.
1079 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1080 const TargetInstrDesc &TID = MI->getDesc();
1081 if (!TID.isPredicable())
1083 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1084 if (TID.OpInfo[i].isPredicate()) {
1085 // Predicated operands must be last operands.
1086 addOperand(MI->getOperand(i));
1091 void MachineInstr::substituteRegister(unsigned FromReg,
1094 const TargetRegisterInfo &RegInfo) {
1095 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1097 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1098 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1099 MachineOperand &MO = getOperand(i);
1100 if (!MO.isReg() || MO.getReg() != FromReg)
1102 MO.substPhysReg(ToReg, RegInfo);
1105 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1106 MachineOperand &MO = getOperand(i);
1107 if (!MO.isReg() || MO.getReg() != FromReg)
1109 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1114 /// isSafeToMove - Return true if it is safe to move this instruction. If
1115 /// SawStore is set to true, it means that there is a store (or call) between
1116 /// the instruction's location and its intended destination.
1117 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1119 bool &SawStore) const {
1120 // Ignore stuff that we obviously can't move.
1121 if (TID->mayStore() || TID->isCall()) {
1126 if (isLabel() || isDebugValue() ||
1127 TID->isTerminator() || hasUnmodeledSideEffects())
1130 // See if this instruction does a load. If so, we have to guarantee that the
1131 // loaded value doesn't change between the load and the its intended
1132 // destination. The check for isInvariantLoad gives the targe the chance to
1133 // classify the load as always returning a constant, e.g. a constant pool
1135 if (TID->mayLoad() && !isInvariantLoad(AA))
1136 // Otherwise, this is a real load. If there is a store between the load and
1137 // end of block, or if the load is volatile, we can't move it.
1138 return !SawStore && !hasVolatileMemoryRef();
1143 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1144 /// instruction which defined the specified register instead of copying it.
1145 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1147 unsigned DstReg) const {
1148 bool SawStore = false;
1149 if (!TII->isTriviallyReMaterializable(this, AA) ||
1150 !isSafeToMove(TII, AA, SawStore))
1152 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1153 const MachineOperand &MO = getOperand(i);
1156 // FIXME: For now, do not remat any instruction with register operands.
1157 // Later on, we can loosen the restriction is the register operands have
1158 // not been modified between the def and use. Note, this is different from
1159 // MachineSink because the code is no longer in two-address form (at least
1163 else if (!MO.isDead() && MO.getReg() != DstReg)
1169 /// hasVolatileMemoryRef - Return true if this instruction may have a
1170 /// volatile memory reference, or if the information describing the
1171 /// memory reference is not available. Return false if it is known to
1172 /// have no volatile memory references.
1173 bool MachineInstr::hasVolatileMemoryRef() const {
1174 // An instruction known never to access memory won't have a volatile access.
1175 if (!TID->mayStore() &&
1178 !hasUnmodeledSideEffects())
1181 // Otherwise, if the instruction has no memory reference information,
1182 // conservatively assume it wasn't preserved.
1183 if (memoperands_empty())
1186 // Check the memory reference information for volatile references.
1187 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1188 if ((*I)->isVolatile())
1194 /// isInvariantLoad - Return true if this instruction is loading from a
1195 /// location whose value is invariant across the function. For example,
1196 /// loading a value from the constant pool or from the argument area
1197 /// of a function if it does not change. This should only return true of
1198 /// *all* loads the instruction does are invariant (if it does multiple loads).
1199 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1200 // If the instruction doesn't load at all, it isn't an invariant load.
1201 if (!TID->mayLoad())
1204 // If the instruction has lost its memoperands, conservatively assume that
1205 // it may not be an invariant load.
1206 if (memoperands_empty())
1209 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1211 for (mmo_iterator I = memoperands_begin(),
1212 E = memoperands_end(); I != E; ++I) {
1213 if ((*I)->isVolatile()) return false;
1214 if ((*I)->isStore()) return false;
1216 if (const Value *V = (*I)->getValue()) {
1217 // A load from a constant PseudoSourceValue is invariant.
1218 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1219 if (PSV->isConstant(MFI))
1221 // If we have an AliasAnalysis, ask it whether the memory is constant.
1222 if (AA && AA->pointsToConstantMemory(
1223 AliasAnalysis::Location(V, (*I)->getSize(),
1224 (*I)->getTBAAInfo())))
1228 // Otherwise assume conservatively.
1232 // Everything checks out.
1236 /// isConstantValuePHI - If the specified instruction is a PHI that always
1237 /// merges together the same virtual register, return the register, otherwise
1239 unsigned MachineInstr::isConstantValuePHI() const {
1242 assert(getNumOperands() >= 3 &&
1243 "It's illegal to have a PHI without source operands");
1245 unsigned Reg = getOperand(1).getReg();
1246 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1247 if (getOperand(i).getReg() != Reg)
1252 bool MachineInstr::hasUnmodeledSideEffects() const {
1253 if (getDesc().hasUnmodeledSideEffects())
1255 if (isInlineAsm()) {
1256 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1257 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1264 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1266 bool MachineInstr::allDefsAreDead() const {
1267 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1268 const MachineOperand &MO = getOperand(i);
1269 if (!MO.isReg() || MO.isUse())
1277 /// copyImplicitOps - Copy implicit register operands from specified
1278 /// instruction to this instruction.
1279 void MachineInstr::copyImplicitOps(const MachineInstr *MI) {
1280 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1282 const MachineOperand &MO = MI->getOperand(i);
1283 if (MO.isReg() && MO.isImplicit())
1288 void MachineInstr::dump() const {
1289 dbgs() << " " << *this;
1292 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1293 raw_ostream &CommentOS) {
1294 const LLVMContext &Ctx = MF->getFunction()->getContext();
1295 if (!DL.isUnknown()) { // Print source line info.
1296 DIScope Scope(DL.getScope(Ctx));
1297 // Omit the directory, because it's likely to be long and uninteresting.
1299 CommentOS << Scope.getFilename();
1301 CommentOS << "<unknown>";
1302 CommentOS << ':' << DL.getLine();
1303 if (DL.getCol() != 0)
1304 CommentOS << ':' << DL.getCol();
1305 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1306 if (!InlinedAtDL.isUnknown()) {
1307 CommentOS << " @[ ";
1308 printDebugLoc(InlinedAtDL, MF, CommentOS);
1314 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1315 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1316 const MachineFunction *MF = 0;
1317 const MachineRegisterInfo *MRI = 0;
1318 if (const MachineBasicBlock *MBB = getParent()) {
1319 MF = MBB->getParent();
1321 TM = &MF->getTarget();
1323 MRI = &MF->getRegInfo();
1326 // Save a list of virtual registers.
1327 SmallVector<unsigned, 8> VirtRegs;
1329 // Print explicitly defined operands on the left of an assignment syntax.
1330 unsigned StartOp = 0, e = getNumOperands();
1331 for (; StartOp < e && getOperand(StartOp).isReg() &&
1332 getOperand(StartOp).isDef() &&
1333 !getOperand(StartOp).isImplicit();
1335 if (StartOp != 0) OS << ", ";
1336 getOperand(StartOp).print(OS, TM);
1337 unsigned Reg = getOperand(StartOp).getReg();
1338 if (TargetRegisterInfo::isVirtualRegister(Reg))
1339 VirtRegs.push_back(Reg);
1345 // Print the opcode name.
1346 OS << getDesc().getName();
1348 // Print the rest of the operands.
1349 bool OmittedAnyCallClobbers = false;
1350 bool FirstOp = true;
1352 if (isInlineAsm()) {
1353 // Print asm string.
1355 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1357 // Print HasSideEffects, IsAlignStack
1358 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1359 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1360 OS << " [sideeffect]";
1361 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1362 OS << " [alignstack]";
1364 StartOp = InlineAsm::MIOp_FirstOperand;
1369 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1370 const MachineOperand &MO = getOperand(i);
1372 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1373 VirtRegs.push_back(MO.getReg());
1375 // Omit call-clobbered registers which aren't used anywhere. This makes
1376 // call instructions much less noisy on targets where calls clobber lots
1377 // of registers. Don't rely on MO.isDead() because we may be called before
1378 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1379 if (MF && getDesc().isCall() &&
1380 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1381 unsigned Reg = MO.getReg();
1382 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1383 const MachineRegisterInfo &MRI = MF->getRegInfo();
1384 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1385 bool HasAliasLive = false;
1386 for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1387 unsigned AliasReg = *Alias; ++Alias)
1388 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1389 HasAliasLive = true;
1392 if (!HasAliasLive) {
1393 OmittedAnyCallClobbers = true;
1400 if (FirstOp) FirstOp = false; else OS << ",";
1402 if (i < getDesc().NumOperands) {
1403 const TargetOperandInfo &TOI = getDesc().OpInfo[i];
1404 if (TOI.isPredicate())
1406 if (TOI.isOptionalDef())
1409 if (isDebugValue() && MO.isMetadata()) {
1410 // Pretty print DBG_VALUE instructions.
1411 const MDNode *MD = MO.getMetadata();
1412 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1413 OS << "!\"" << MDS->getString() << '\"';
1416 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1417 OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1422 // Briefly indicate whether any call clobbers were omitted.
1423 if (OmittedAnyCallClobbers) {
1424 if (!FirstOp) OS << ",";
1428 bool HaveSemi = false;
1430 if (!HaveSemi) OS << ";"; HaveSemi = true;
1433 if (Flags & FrameSetup)
1437 if (!memoperands_empty()) {
1438 if (!HaveSemi) OS << ";"; HaveSemi = true;
1441 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1444 if (llvm::next(i) != e)
1449 // Print the regclass of any virtual registers encountered.
1450 if (MRI && !VirtRegs.empty()) {
1451 if (!HaveSemi) OS << ";"; HaveSemi = true;
1452 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1453 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1454 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1455 for (unsigned j = i+1; j != VirtRegs.size();) {
1456 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1460 if (VirtRegs[i] != VirtRegs[j])
1461 OS << "," << PrintReg(VirtRegs[j]);
1462 VirtRegs.erase(VirtRegs.begin()+j);
1467 // Print debug location information.
1468 if (!debugLoc.isUnknown() && MF) {
1469 if (!HaveSemi) OS << ";"; HaveSemi = true;
1471 printDebugLoc(debugLoc, MF, OS);
1477 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1478 const TargetRegisterInfo *RegInfo,
1479 bool AddIfNotFound) {
1480 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1481 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1483 SmallVector<unsigned,4> DeadOps;
1484 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1485 MachineOperand &MO = getOperand(i);
1486 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1488 unsigned Reg = MO.getReg();
1492 if (Reg == IncomingReg) {
1495 // The register is already marked kill.
1497 if (isPhysReg && isRegTiedToDefOperand(i))
1498 // Two-address uses of physregs must not be marked kill.
1503 } else if (hasAliases && MO.isKill() &&
1504 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1505 // A super-register kill already exists.
1506 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1508 if (RegInfo->isSubRegister(IncomingReg, Reg))
1509 DeadOps.push_back(i);
1513 // Trim unneeded kill operands.
1514 while (!DeadOps.empty()) {
1515 unsigned OpIdx = DeadOps.back();
1516 if (getOperand(OpIdx).isImplicit())
1517 RemoveOperand(OpIdx);
1519 getOperand(OpIdx).setIsKill(false);
1523 // If not found, this means an alias of one of the operands is killed. Add a
1524 // new implicit operand if required.
1525 if (!Found && AddIfNotFound) {
1526 addOperand(MachineOperand::CreateReg(IncomingReg,
1535 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1536 const TargetRegisterInfo *RegInfo,
1537 bool AddIfNotFound) {
1538 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1539 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1541 SmallVector<unsigned,4> DeadOps;
1542 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1543 MachineOperand &MO = getOperand(i);
1544 if (!MO.isReg() || !MO.isDef())
1546 unsigned Reg = MO.getReg();
1550 if (Reg == IncomingReg) {
1553 } else if (hasAliases && MO.isDead() &&
1554 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1555 // There exists a super-register that's marked dead.
1556 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1558 if (RegInfo->getSubRegisters(IncomingReg) &&
1559 RegInfo->getSuperRegisters(Reg) &&
1560 RegInfo->isSubRegister(IncomingReg, Reg))
1561 DeadOps.push_back(i);
1565 // Trim unneeded dead operands.
1566 while (!DeadOps.empty()) {
1567 unsigned OpIdx = DeadOps.back();
1568 if (getOperand(OpIdx).isImplicit())
1569 RemoveOperand(OpIdx);
1571 getOperand(OpIdx).setIsDead(false);
1575 // If not found, this means an alias of one of the operands is dead. Add a
1576 // new implicit operand if required.
1577 if (Found || !AddIfNotFound)
1580 addOperand(MachineOperand::CreateReg(IncomingReg,
1588 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1589 const TargetRegisterInfo *RegInfo) {
1590 if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1591 MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1595 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1596 const MachineOperand &MO = getOperand(i);
1597 if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1598 MO.getSubReg() == 0)
1602 addOperand(MachineOperand::CreateReg(IncomingReg,
1607 void MachineInstr::setPhysRegsDeadExcept(const SmallVectorImpl<unsigned> &UsedRegs,
1608 const TargetRegisterInfo &TRI) {
1609 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1610 MachineOperand &MO = getOperand(i);
1611 if (!MO.isReg() || !MO.isDef()) continue;
1612 unsigned Reg = MO.getReg();
1613 if (Reg == 0) continue;
1615 for (SmallVectorImpl<unsigned>::const_iterator I = UsedRegs.begin(),
1616 E = UsedRegs.end(); I != E; ++I)
1617 if (TRI.regsOverlap(*I, Reg)) {
1621 // If there are no uses, including partial uses, the def is dead.
1622 if (Dead) MO.setIsDead();
1627 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1628 unsigned Hash = MI->getOpcode() * 37;
1629 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1630 const MachineOperand &MO = MI->getOperand(i);
1631 uint64_t Key = (uint64_t)MO.getType() << 32;
1632 switch (MO.getType()) {
1634 case MachineOperand::MO_Register:
1635 if (MO.isDef() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1636 continue; // Skip virtual register defs.
1639 case MachineOperand::MO_Immediate:
1642 case MachineOperand::MO_FrameIndex:
1643 case MachineOperand::MO_ConstantPoolIndex:
1644 case MachineOperand::MO_JumpTableIndex:
1645 Key |= MO.getIndex();
1647 case MachineOperand::MO_MachineBasicBlock:
1648 Key |= DenseMapInfo<void*>::getHashValue(MO.getMBB());
1650 case MachineOperand::MO_GlobalAddress:
1651 Key |= DenseMapInfo<void*>::getHashValue(MO.getGlobal());
1653 case MachineOperand::MO_BlockAddress:
1654 Key |= DenseMapInfo<void*>::getHashValue(MO.getBlockAddress());
1656 case MachineOperand::MO_MCSymbol:
1657 Key |= DenseMapInfo<void*>::getHashValue(MO.getMCSymbol());
1660 Key += ~(Key << 32);
1662 Key += ~(Key << 13);
1666 Key += ~(Key << 27);
1668 Hash = (unsigned)Key + Hash * 37;