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/Value.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineMemOperand.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetInstrDesc.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/DebugInfo.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/LeakDetector.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/FoldingSet.h"
37 //===----------------------------------------------------------------------===//
38 // MachineOperand Implementation
39 //===----------------------------------------------------------------------===//
41 /// AddRegOperandToRegInfo - Add this register operand to the specified
42 /// MachineRegisterInfo. If it is null, then the next/prev fields should be
43 /// explicitly nulled out.
44 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
45 assert(isReg() && "Can only add reg operand to use lists");
47 // If the reginfo pointer is null, just explicitly null out or next/prev
48 // pointers, to ensure they are not garbage.
50 Contents.Reg.Prev = 0;
51 Contents.Reg.Next = 0;
55 // Otherwise, add this operand to the head of the registers use/def list.
56 MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
58 // For SSA values, we prefer to keep the definition at the start of the list.
59 // we do this by skipping over the definition if it is at the head of the
61 if (*Head && (*Head)->isDef())
62 Head = &(*Head)->Contents.Reg.Next;
64 Contents.Reg.Next = *Head;
65 if (Contents.Reg.Next) {
66 assert(getReg() == Contents.Reg.Next->getReg() &&
67 "Different regs on the same list!");
68 Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
71 Contents.Reg.Prev = Head;
75 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
76 /// MachineRegisterInfo it is linked with.
77 void MachineOperand::RemoveRegOperandFromRegInfo() {
78 assert(isOnRegUseList() && "Reg operand is not on a use list");
79 // Unlink this from the doubly linked list of operands.
80 MachineOperand *NextOp = Contents.Reg.Next;
81 *Contents.Reg.Prev = NextOp;
83 assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
84 NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
86 Contents.Reg.Prev = 0;
87 Contents.Reg.Next = 0;
90 void MachineOperand::setReg(unsigned Reg) {
91 if (getReg() == Reg) return; // No change.
93 // Otherwise, we have to change the register. If this operand is embedded
94 // into a machine function, we need to update the old and new register's
96 if (MachineInstr *MI = getParent())
97 if (MachineBasicBlock *MBB = MI->getParent())
98 if (MachineFunction *MF = MBB->getParent()) {
99 RemoveRegOperandFromRegInfo();
100 Contents.Reg.RegNo = Reg;
101 AddRegOperandToRegInfo(&MF->getRegInfo());
105 // Otherwise, just change the register, no problem. :)
106 Contents.Reg.RegNo = Reg;
109 /// ChangeToImmediate - Replace this operand with a new immediate operand of
110 /// the specified value. If an operand is known to be an immediate already,
111 /// the setImm method should be used.
112 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
113 // If this operand is currently a register operand, and if this is in a
114 // function, deregister the operand from the register's use/def list.
115 if (isReg() && getParent() && getParent()->getParent() &&
116 getParent()->getParent()->getParent())
117 RemoveRegOperandFromRegInfo();
119 OpKind = MO_Immediate;
120 Contents.ImmVal = ImmVal;
123 /// ChangeToRegister - Replace this operand with a new register operand of
124 /// the specified value. If an operand is known to be an register already,
125 /// the setReg method should be used.
126 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
127 bool isKill, bool isDead, bool isUndef) {
128 // If this operand is already a register operand, use setReg to update the
129 // register's use/def lists.
131 assert(!isEarlyClobber());
134 // Otherwise, change this to a register and set the reg#.
135 OpKind = MO_Register;
136 Contents.Reg.RegNo = Reg;
138 // If this operand is embedded in a function, add the operand to the
139 // register's use/def list.
140 if (MachineInstr *MI = getParent())
141 if (MachineBasicBlock *MBB = MI->getParent())
142 if (MachineFunction *MF = MBB->getParent())
143 AddRegOperandToRegInfo(&MF->getRegInfo());
151 IsEarlyClobber = false;
155 /// isIdenticalTo - Return true if this operand is identical to the specified
157 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
158 if (getType() != Other.getType() ||
159 getTargetFlags() != Other.getTargetFlags())
163 default: llvm_unreachable("Unrecognized operand type");
164 case MachineOperand::MO_Register:
165 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
166 getSubReg() == Other.getSubReg();
167 case MachineOperand::MO_Immediate:
168 return getImm() == Other.getImm();
169 case MachineOperand::MO_FPImmediate:
170 return getFPImm() == Other.getFPImm();
171 case MachineOperand::MO_MachineBasicBlock:
172 return getMBB() == Other.getMBB();
173 case MachineOperand::MO_FrameIndex:
174 return getIndex() == Other.getIndex();
175 case MachineOperand::MO_ConstantPoolIndex:
176 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
177 case MachineOperand::MO_JumpTableIndex:
178 return getIndex() == Other.getIndex();
179 case MachineOperand::MO_GlobalAddress:
180 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
181 case MachineOperand::MO_ExternalSymbol:
182 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
183 getOffset() == Other.getOffset();
184 case MachineOperand::MO_BlockAddress:
185 return getBlockAddress() == Other.getBlockAddress();
189 /// print - Print the specified machine operand.
191 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
192 // If the instruction is embedded into a basic block, we can find the
193 // target info for the instruction.
195 if (const MachineInstr *MI = getParent())
196 if (const MachineBasicBlock *MBB = MI->getParent())
197 if (const MachineFunction *MF = MBB->getParent())
198 TM = &MF->getTarget();
201 case MachineOperand::MO_Register:
202 if (getReg() == 0 || TargetRegisterInfo::isVirtualRegister(getReg())) {
203 OS << "%reg" << getReg();
206 OS << "%" << TM->getRegisterInfo()->get(getReg()).Name;
208 OS << "%physreg" << getReg();
211 if (getSubReg() != 0)
212 OS << ':' << getSubReg();
214 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
217 bool NeedComma = false;
219 if (NeedComma) OS << ',';
220 if (isEarlyClobber())
221 OS << "earlyclobber,";
226 } else if (isImplicit()) {
231 if (isKill() || isDead() || isUndef()) {
232 if (NeedComma) OS << ',';
233 if (isKill()) OS << "kill";
234 if (isDead()) OS << "dead";
236 if (isKill() || isDead())
244 case MachineOperand::MO_Immediate:
247 case MachineOperand::MO_FPImmediate:
248 if (getFPImm()->getType()->isFloatTy())
249 OS << getFPImm()->getValueAPF().convertToFloat();
251 OS << getFPImm()->getValueAPF().convertToDouble();
253 case MachineOperand::MO_MachineBasicBlock:
254 OS << "<BB#" << getMBB()->getNumber() << ">";
256 case MachineOperand::MO_FrameIndex:
257 OS << "<fi#" << getIndex() << '>';
259 case MachineOperand::MO_ConstantPoolIndex:
260 OS << "<cp#" << getIndex();
261 if (getOffset()) OS << "+" << getOffset();
264 case MachineOperand::MO_JumpTableIndex:
265 OS << "<jt#" << getIndex() << '>';
267 case MachineOperand::MO_GlobalAddress:
269 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
270 if (getOffset()) OS << "+" << getOffset();
273 case MachineOperand::MO_ExternalSymbol:
274 OS << "<es:" << getSymbolName();
275 if (getOffset()) OS << "+" << getOffset();
278 case MachineOperand::MO_BlockAddress:
280 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
284 llvm_unreachable("Unrecognized operand type");
287 if (unsigned TF = getTargetFlags())
288 OS << "[TF=" << TF << ']';
291 //===----------------------------------------------------------------------===//
292 // MachineMemOperand Implementation
293 //===----------------------------------------------------------------------===//
295 MachineMemOperand::MachineMemOperand(const Value *v, unsigned int f,
296 int64_t o, uint64_t s, unsigned int a)
297 : Offset(o), Size(s), V(v),
298 Flags((f & 7) | ((Log2_32(a) + 1) << 3)) {
299 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
300 assert((isLoad() || isStore()) && "Not a load/store!");
303 /// Profile - Gather unique data for the object.
305 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
306 ID.AddInteger(Offset);
309 ID.AddInteger(Flags);
312 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
313 // The Value and Offset may differ due to CSE. But the flags and size
314 // should be the same.
315 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
316 assert(MMO->getSize() == getSize() && "Size mismatch!");
318 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
319 // Update the alignment value.
320 Flags = (Flags & 7) | ((Log2_32(MMO->getBaseAlignment()) + 1) << 3);
321 // Also update the base and offset, because the new alignment may
322 // not be applicable with the old ones.
324 Offset = MMO->getOffset();
328 /// getAlignment - Return the minimum known alignment in bytes of the
329 /// actual memory reference.
330 uint64_t MachineMemOperand::getAlignment() const {
331 return MinAlign(getBaseAlignment(), getOffset());
334 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
335 assert((MMO.isLoad() || MMO.isStore()) &&
336 "SV has to be a load, store or both.");
338 if (MMO.isVolatile())
347 // Print the address information.
352 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
354 // If the alignment of the memory reference itself differs from the alignment
355 // of the base pointer, print the base alignment explicitly, next to the base
357 if (MMO.getBaseAlignment() != MMO.getAlignment())
358 OS << "(align=" << MMO.getBaseAlignment() << ")";
360 if (MMO.getOffset() != 0)
361 OS << "+" << MMO.getOffset();
364 // Print the alignment of the reference.
365 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
366 MMO.getBaseAlignment() != MMO.getSize())
367 OS << "(align=" << MMO.getAlignment() << ")";
372 //===----------------------------------------------------------------------===//
373 // MachineInstr Implementation
374 //===----------------------------------------------------------------------===//
376 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
377 /// TID NULL and no operands.
378 MachineInstr::MachineInstr()
379 : TID(0), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0),
380 Parent(0), debugLoc(DebugLoc::getUnknownLoc()) {
381 // Make sure that we get added to a machine basicblock
382 LeakDetector::addGarbageObject(this);
385 void MachineInstr::addImplicitDefUseOperands() {
386 if (TID->ImplicitDefs)
387 for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
388 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
389 if (TID->ImplicitUses)
390 for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
391 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
394 /// MachineInstr ctor - This constructor create a MachineInstr and add the
395 /// implicit operands. It reserves space for number of operands specified by
396 /// TargetInstrDesc or the numOperands if it is not zero. (for
397 /// instructions with variable number of operands).
398 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
399 : TID(&tid), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0), Parent(0),
400 debugLoc(DebugLoc::getUnknownLoc()) {
401 if (!NoImp && TID->getImplicitDefs())
402 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
404 if (!NoImp && TID->getImplicitUses())
405 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
407 Operands.reserve(NumImplicitOps + TID->getNumOperands());
409 addImplicitDefUseOperands();
410 // Make sure that we get added to a machine basicblock
411 LeakDetector::addGarbageObject(this);
414 /// MachineInstr ctor - As above, but with a DebugLoc.
415 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
417 : TID(&tid), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0),
418 Parent(0), debugLoc(dl) {
419 if (!NoImp && TID->getImplicitDefs())
420 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
422 if (!NoImp && TID->getImplicitUses())
423 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
425 Operands.reserve(NumImplicitOps + TID->getNumOperands());
427 addImplicitDefUseOperands();
428 // Make sure that we get added to a machine basicblock
429 LeakDetector::addGarbageObject(this);
432 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
433 /// that the MachineInstr is created and added to the end of the specified
436 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
437 : TID(&tid), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0), Parent(0),
438 debugLoc(DebugLoc::getUnknownLoc()) {
439 assert(MBB && "Cannot use inserting ctor with null basic block!");
440 if (TID->ImplicitDefs)
441 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
443 if (TID->ImplicitUses)
444 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
446 Operands.reserve(NumImplicitOps + TID->getNumOperands());
447 addImplicitDefUseOperands();
448 // Make sure that we get added to a machine basicblock
449 LeakDetector::addGarbageObject(this);
450 MBB->push_back(this); // Add instruction to end of basic block!
453 /// MachineInstr ctor - As above, but with a DebugLoc.
455 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
456 const TargetInstrDesc &tid)
457 : TID(&tid), NumImplicitOps(0), MemRefs(0), MemRefsEnd(0),
458 Parent(0), debugLoc(dl) {
459 assert(MBB && "Cannot use inserting ctor with null basic block!");
460 if (TID->ImplicitDefs)
461 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
463 if (TID->ImplicitUses)
464 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
466 Operands.reserve(NumImplicitOps + TID->getNumOperands());
467 addImplicitDefUseOperands();
468 // Make sure that we get added to a machine basicblock
469 LeakDetector::addGarbageObject(this);
470 MBB->push_back(this); // Add instruction to end of basic block!
473 /// MachineInstr ctor - Copies MachineInstr arg exactly
475 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
476 : TID(&MI.getDesc()), NumImplicitOps(0),
477 MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
478 Parent(0), debugLoc(MI.getDebugLoc()) {
479 Operands.reserve(MI.getNumOperands());
482 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
483 addOperand(MI.getOperand(i));
484 NumImplicitOps = MI.NumImplicitOps;
486 // Set parent to null.
489 LeakDetector::addGarbageObject(this);
492 MachineInstr::~MachineInstr() {
493 LeakDetector::removeGarbageObject(this);
495 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
496 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
497 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
498 "Reg operand def/use list corrupted");
503 /// getRegInfo - If this instruction is embedded into a MachineFunction,
504 /// return the MachineRegisterInfo object for the current function, otherwise
506 MachineRegisterInfo *MachineInstr::getRegInfo() {
507 if (MachineBasicBlock *MBB = getParent())
508 return &MBB->getParent()->getRegInfo();
512 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
513 /// this instruction from their respective use lists. This requires that the
514 /// operands already be on their use lists.
515 void MachineInstr::RemoveRegOperandsFromUseLists() {
516 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
517 if (Operands[i].isReg())
518 Operands[i].RemoveRegOperandFromRegInfo();
522 /// AddRegOperandsToUseLists - Add all of the register operands in
523 /// this instruction from their respective use lists. This requires that the
524 /// operands not be on their use lists yet.
525 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
526 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
527 if (Operands[i].isReg())
528 Operands[i].AddRegOperandToRegInfo(&RegInfo);
533 /// addOperand - Add the specified operand to the instruction. If it is an
534 /// implicit operand, it is added to the end of the operand list. If it is
535 /// an explicit operand it is added at the end of the explicit operand list
536 /// (before the first implicit operand).
537 void MachineInstr::addOperand(const MachineOperand &Op) {
538 bool isImpReg = Op.isReg() && Op.isImplicit();
539 assert((isImpReg || !OperandsComplete()) &&
540 "Trying to add an operand to a machine instr that is already done!");
542 MachineRegisterInfo *RegInfo = getRegInfo();
544 // If we are adding the operand to the end of the list, our job is simpler.
545 // This is true most of the time, so this is a reasonable optimization.
546 if (isImpReg || NumImplicitOps == 0) {
547 // We can only do this optimization if we know that the operand list won't
549 if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
550 Operands.push_back(Op);
552 // Set the parent of the operand.
553 Operands.back().ParentMI = this;
555 // If the operand is a register, update the operand's use list.
557 Operands.back().AddRegOperandToRegInfo(RegInfo);
562 // Otherwise, we have to insert a real operand before any implicit ones.
563 unsigned OpNo = Operands.size()-NumImplicitOps;
565 // If this instruction isn't embedded into a function, then we don't need to
566 // update any operand lists.
568 // Simple insertion, no reginfo update needed for other register operands.
569 Operands.insert(Operands.begin()+OpNo, Op);
570 Operands[OpNo].ParentMI = this;
572 // Do explicitly set the reginfo for this operand though, to ensure the
573 // next/prev fields are properly nulled out.
574 if (Operands[OpNo].isReg())
575 Operands[OpNo].AddRegOperandToRegInfo(0);
577 } else if (Operands.size()+1 <= Operands.capacity()) {
578 // Otherwise, we have to remove register operands from their register use
579 // list, add the operand, then add the register operands back to their use
580 // list. This also must handle the case when the operand list reallocates
581 // to somewhere else.
583 // If insertion of this operand won't cause reallocation of the operand
584 // list, just remove the implicit operands, add the operand, then re-add all
585 // the rest of the operands.
586 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
587 assert(Operands[i].isReg() && "Should only be an implicit reg!");
588 Operands[i].RemoveRegOperandFromRegInfo();
591 // Add the operand. If it is a register, add it to the reg list.
592 Operands.insert(Operands.begin()+OpNo, Op);
593 Operands[OpNo].ParentMI = this;
595 if (Operands[OpNo].isReg())
596 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
598 // Re-add all the implicit ops.
599 for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
600 assert(Operands[i].isReg() && "Should only be an implicit reg!");
601 Operands[i].AddRegOperandToRegInfo(RegInfo);
604 // Otherwise, we will be reallocating the operand list. Remove all reg
605 // operands from their list, then readd them after the operand list is
607 RemoveRegOperandsFromUseLists();
609 Operands.insert(Operands.begin()+OpNo, Op);
610 Operands[OpNo].ParentMI = this;
612 // Re-add all the operands.
613 AddRegOperandsToUseLists(*RegInfo);
617 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
618 /// fewer operand than it started with.
620 void MachineInstr::RemoveOperand(unsigned OpNo) {
621 assert(OpNo < Operands.size() && "Invalid operand number");
623 // Special case removing the last one.
624 if (OpNo == Operands.size()-1) {
625 // If needed, remove from the reg def/use list.
626 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
627 Operands.back().RemoveRegOperandFromRegInfo();
633 // Otherwise, we are removing an interior operand. If we have reginfo to
634 // update, remove all operands that will be shifted down from their reg lists,
635 // move everything down, then re-add them.
636 MachineRegisterInfo *RegInfo = getRegInfo();
638 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
639 if (Operands[i].isReg())
640 Operands[i].RemoveRegOperandFromRegInfo();
644 Operands.erase(Operands.begin()+OpNo);
647 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
648 if (Operands[i].isReg())
649 Operands[i].AddRegOperandToRegInfo(RegInfo);
654 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
655 /// This function should be used only occasionally. The setMemRefs function
656 /// is the primary method for setting up a MachineInstr's MemRefs list.
657 void MachineInstr::addMemOperand(MachineFunction &MF,
658 MachineMemOperand *MO) {
659 mmo_iterator OldMemRefs = MemRefs;
660 mmo_iterator OldMemRefsEnd = MemRefsEnd;
662 size_t NewNum = (MemRefsEnd - MemRefs) + 1;
663 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
664 mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
666 std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
667 NewMemRefs[NewNum - 1] = MO;
669 MemRefs = NewMemRefs;
670 MemRefsEnd = NewMemRefsEnd;
673 /// removeFromParent - This method unlinks 'this' from the containing basic
674 /// block, and returns it, but does not delete it.
675 MachineInstr *MachineInstr::removeFromParent() {
676 assert(getParent() && "Not embedded in a basic block!");
677 getParent()->remove(this);
682 /// eraseFromParent - This method unlinks 'this' from the containing basic
683 /// block, and deletes it.
684 void MachineInstr::eraseFromParent() {
685 assert(getParent() && "Not embedded in a basic block!");
686 getParent()->erase(this);
690 /// OperandComplete - Return true if it's illegal to add a new operand
692 bool MachineInstr::OperandsComplete() const {
693 unsigned short NumOperands = TID->getNumOperands();
694 if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
695 return true; // Broken: we have all the operands of this instruction!
699 /// getNumExplicitOperands - Returns the number of non-implicit operands.
701 unsigned MachineInstr::getNumExplicitOperands() const {
702 unsigned NumOperands = TID->getNumOperands();
703 if (!TID->isVariadic())
706 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
707 const MachineOperand &MO = getOperand(i);
708 if (!MO.isReg() || !MO.isImplicit())
715 /// isLabel - Returns true if the MachineInstr represents a label.
717 bool MachineInstr::isLabel() const {
718 return getOpcode() == TargetInstrInfo::DBG_LABEL ||
719 getOpcode() == TargetInstrInfo::EH_LABEL ||
720 getOpcode() == TargetInstrInfo::GC_LABEL;
723 /// isDebugLabel - Returns true if the MachineInstr represents a debug label.
725 bool MachineInstr::isDebugLabel() const {
726 return getOpcode() == TargetInstrInfo::DBG_LABEL;
729 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
730 /// the specific register or -1 if it is not found. It further tightens
731 /// the search criteria to a use that kills the register if isKill is true.
732 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
733 const TargetRegisterInfo *TRI) const {
734 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
735 const MachineOperand &MO = getOperand(i);
736 if (!MO.isReg() || !MO.isUse())
738 unsigned MOReg = MO.getReg();
743 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
744 TargetRegisterInfo::isPhysicalRegister(Reg) &&
745 TRI->isSubRegister(MOReg, Reg)))
746 if (!isKill || MO.isKill())
752 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
753 /// the specified register or -1 if it is not found. If isDead is true, defs
754 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
755 /// also checks if there is a def of a super-register.
756 int MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead,
757 const TargetRegisterInfo *TRI) const {
758 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
759 const MachineOperand &MO = getOperand(i);
760 if (!MO.isReg() || !MO.isDef())
762 unsigned MOReg = MO.getReg();
765 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
766 TargetRegisterInfo::isPhysicalRegister(Reg) &&
767 TRI->isSubRegister(MOReg, Reg)))
768 if (!isDead || MO.isDead())
774 /// findFirstPredOperandIdx() - Find the index of the first operand in the
775 /// operand list that is used to represent the predicate. It returns -1 if
777 int MachineInstr::findFirstPredOperandIdx() const {
778 const TargetInstrDesc &TID = getDesc();
779 if (TID.isPredicable()) {
780 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
781 if (TID.OpInfo[i].isPredicate())
788 /// isRegTiedToUseOperand - Given the index of a register def operand,
789 /// check if the register def is tied to a source operand, due to either
790 /// two-address elimination or inline assembly constraints. Returns the
791 /// first tied use operand index by reference is UseOpIdx is not null.
793 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
794 if (getOpcode() == TargetInstrInfo::INLINEASM) {
795 assert(DefOpIdx >= 2);
796 const MachineOperand &MO = getOperand(DefOpIdx);
797 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
799 // Determine the actual operand index that corresponds to this index.
801 unsigned DefPart = 0;
802 for (unsigned i = 1, e = getNumOperands(); i < e; ) {
803 const MachineOperand &FMO = getOperand(i);
804 // After the normal asm operands there may be additional imp-def regs.
807 // Skip over this def.
808 unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
809 unsigned PrevDef = i + 1;
810 i = PrevDef + NumOps;
812 DefPart = DefOpIdx - PrevDef;
817 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
818 const MachineOperand &FMO = getOperand(i);
821 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
824 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
827 *UseOpIdx = (unsigned)i + 1 + DefPart;
834 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
835 const TargetInstrDesc &TID = getDesc();
836 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
837 const MachineOperand &MO = getOperand(i);
838 if (MO.isReg() && MO.isUse() &&
839 TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
841 *UseOpIdx = (unsigned)i;
848 /// isRegTiedToDefOperand - Return true if the operand of the specified index
849 /// is a register use and it is tied to an def operand. It also returns the def
850 /// operand index by reference.
852 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
853 if (getOpcode() == TargetInstrInfo::INLINEASM) {
854 const MachineOperand &MO = getOperand(UseOpIdx);
855 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
858 // Find the flag operand corresponding to UseOpIdx
859 unsigned FlagIdx, NumOps=0;
860 for (FlagIdx = 1; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
861 const MachineOperand &UFMO = getOperand(FlagIdx);
862 // After the normal asm operands there may be additional imp-def regs.
865 NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
866 assert(NumOps < getNumOperands() && "Invalid inline asm flag");
867 if (UseOpIdx < FlagIdx+NumOps+1)
870 if (FlagIdx >= UseOpIdx)
872 const MachineOperand &UFMO = getOperand(FlagIdx);
874 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
879 // Remember to adjust the index. First operand is asm string, then there
880 // is a flag for each.
882 const MachineOperand &FMO = getOperand(DefIdx);
884 // Skip over this def.
885 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
888 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
894 const TargetInstrDesc &TID = getDesc();
895 if (UseOpIdx >= TID.getNumOperands())
897 const MachineOperand &MO = getOperand(UseOpIdx);
898 if (!MO.isReg() || !MO.isUse())
900 int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
904 *DefOpIdx = (unsigned)DefIdx;
908 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
910 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
911 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
912 const MachineOperand &MO = MI->getOperand(i);
913 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
915 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
916 MachineOperand &MOp = getOperand(j);
917 if (!MOp.isIdenticalTo(MO))
928 /// copyPredicates - Copies predicate operand(s) from MI.
929 void MachineInstr::copyPredicates(const MachineInstr *MI) {
930 const TargetInstrDesc &TID = MI->getDesc();
931 if (!TID.isPredicable())
933 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
934 if (TID.OpInfo[i].isPredicate()) {
935 // Predicated operands must be last operands.
936 addOperand(MI->getOperand(i));
941 /// isSafeToMove - Return true if it is safe to move this instruction. If
942 /// SawStore is set to true, it means that there is a store (or call) between
943 /// the instruction's location and its intended destination.
944 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
946 AliasAnalysis *AA) const {
947 // Ignore stuff that we obviously can't move.
948 if (TID->mayStore() || TID->isCall()) {
952 if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
955 // See if this instruction does a load. If so, we have to guarantee that the
956 // loaded value doesn't change between the load and the its intended
957 // destination. The check for isInvariantLoad gives the targe the chance to
958 // classify the load as always returning a constant, e.g. a constant pool
960 if (TID->mayLoad() && !isInvariantLoad(AA))
961 // Otherwise, this is a real load. If there is a store between the load and
962 // end of block, or if the load is volatile, we can't move it.
963 return !SawStore && !hasVolatileMemoryRef();
968 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
969 /// instruction which defined the specified register instead of copying it.
970 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
972 AliasAnalysis *AA) const {
973 bool SawStore = false;
974 if (!TII->isTriviallyReMaterializable(this, AA) ||
975 !isSafeToMove(TII, SawStore, AA))
977 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
978 const MachineOperand &MO = getOperand(i);
981 // FIXME: For now, do not remat any instruction with register operands.
982 // Later on, we can loosen the restriction is the register operands have
983 // not been modified between the def and use. Note, this is different from
984 // MachineSink because the code is no longer in two-address form (at least
988 else if (!MO.isDead() && MO.getReg() != DstReg)
994 /// hasVolatileMemoryRef - Return true if this instruction may have a
995 /// volatile memory reference, or if the information describing the
996 /// memory reference is not available. Return false if it is known to
997 /// have no volatile memory references.
998 bool MachineInstr::hasVolatileMemoryRef() const {
999 // An instruction known never to access memory won't have a volatile access.
1000 if (!TID->mayStore() &&
1003 !TID->hasUnmodeledSideEffects())
1006 // Otherwise, if the instruction has no memory reference information,
1007 // conservatively assume it wasn't preserved.
1008 if (memoperands_empty())
1011 // Check the memory reference information for volatile references.
1012 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1013 if ((*I)->isVolatile())
1019 /// isInvariantLoad - Return true if this instruction is loading from a
1020 /// location whose value is invariant across the function. For example,
1021 /// loading a value from the constant pool or from from the argument area
1022 /// of a function if it does not change. This should only return true of
1023 /// *all* loads the instruction does are invariant (if it does multiple loads).
1024 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1025 // If the instruction doesn't load at all, it isn't an invariant load.
1026 if (!TID->mayLoad())
1029 // If the instruction has lost its memoperands, conservatively assume that
1030 // it may not be an invariant load.
1031 if (memoperands_empty())
1034 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1036 for (mmo_iterator I = memoperands_begin(),
1037 E = memoperands_end(); I != E; ++I) {
1038 if ((*I)->isVolatile()) return false;
1039 if ((*I)->isStore()) return false;
1041 if (const Value *V = (*I)->getValue()) {
1042 // A load from a constant PseudoSourceValue is invariant.
1043 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1044 if (PSV->isConstant(MFI))
1046 // If we have an AliasAnalysis, ask it whether the memory is constant.
1047 if (AA && AA->pointsToConstantMemory(V))
1051 // Otherwise assume conservatively.
1055 // Everything checks out.
1059 void MachineInstr::dump() const {
1060 errs() << " " << *this;
1063 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1064 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1065 const MachineFunction *MF = 0;
1066 if (const MachineBasicBlock *MBB = getParent()) {
1067 MF = MBB->getParent();
1069 TM = &MF->getTarget();
1072 // Print explicitly defined operands on the left of an assignment syntax.
1073 unsigned StartOp = 0, e = getNumOperands();
1074 for (; StartOp < e && getOperand(StartOp).isReg() &&
1075 getOperand(StartOp).isDef() &&
1076 !getOperand(StartOp).isImplicit();
1078 if (StartOp != 0) OS << ", ";
1079 getOperand(StartOp).print(OS, TM);
1085 // Print the opcode name.
1086 OS << getDesc().getName();
1088 // Print the rest of the operands.
1089 bool OmittedAnyCallClobbers = false;
1090 bool FirstOp = true;
1091 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1092 const MachineOperand &MO = getOperand(i);
1094 // Omit call-clobbered registers which aren't used anywhere. This makes
1095 // call instructions much less noisy on targets where calls clobber lots
1096 // of registers. Don't rely on MO.isDead() because we may be called before
1097 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1098 if (MF && getDesc().isCall() &&
1099 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1100 unsigned Reg = MO.getReg();
1101 if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
1102 const MachineRegisterInfo &MRI = MF->getRegInfo();
1103 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1104 bool HasAliasLive = false;
1105 for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1106 unsigned AliasReg = *Alias; ++Alias)
1107 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1108 HasAliasLive = true;
1111 if (!HasAliasLive) {
1112 OmittedAnyCallClobbers = true;
1119 if (FirstOp) FirstOp = false; else OS << ",";
1124 // Briefly indicate whether any call clobbers were omitted.
1125 if (OmittedAnyCallClobbers) {
1126 if (FirstOp) FirstOp = false; else OS << ",";
1130 bool HaveSemi = false;
1131 if (!memoperands_empty()) {
1132 if (!HaveSemi) OS << ";"; HaveSemi = true;
1135 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1143 if (!debugLoc.isUnknown() && MF) {
1144 if (!HaveSemi) OS << ";"; HaveSemi = true;
1146 // TODO: print InlinedAtLoc information
1148 DebugLocTuple DLT = MF->getDebugLocTuple(debugLoc);
1149 DICompileUnit CU(DLT.Scope);
1151 OS << " dbg:" << CU.getDirectory() << '/' << CU.getFilename() << ":"
1152 << DLT.Line << ":" << DLT.Col;
1158 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1159 const TargetRegisterInfo *RegInfo,
1160 bool AddIfNotFound) {
1161 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1162 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1164 SmallVector<unsigned,4> DeadOps;
1165 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1166 MachineOperand &MO = getOperand(i);
1167 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1169 unsigned Reg = MO.getReg();
1173 if (Reg == IncomingReg) {
1176 // The register is already marked kill.
1178 if (isPhysReg && isRegTiedToDefOperand(i))
1179 // Two-address uses of physregs must not be marked kill.
1184 } else if (hasAliases && MO.isKill() &&
1185 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1186 // A super-register kill already exists.
1187 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1189 if (RegInfo->isSubRegister(IncomingReg, Reg))
1190 DeadOps.push_back(i);
1194 // Trim unneeded kill operands.
1195 while (!DeadOps.empty()) {
1196 unsigned OpIdx = DeadOps.back();
1197 if (getOperand(OpIdx).isImplicit())
1198 RemoveOperand(OpIdx);
1200 getOperand(OpIdx).setIsKill(false);
1204 // If not found, this means an alias of one of the operands is killed. Add a
1205 // new implicit operand if required.
1206 if (!Found && AddIfNotFound) {
1207 addOperand(MachineOperand::CreateReg(IncomingReg,
1216 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1217 const TargetRegisterInfo *RegInfo,
1218 bool AddIfNotFound) {
1219 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1220 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1222 SmallVector<unsigned,4> DeadOps;
1223 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1224 MachineOperand &MO = getOperand(i);
1225 if (!MO.isReg() || !MO.isDef())
1227 unsigned Reg = MO.getReg();
1231 if (Reg == IncomingReg) {
1234 // The register is already marked dead.
1239 } else if (hasAliases && MO.isDead() &&
1240 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1241 // There exists a super-register that's marked dead.
1242 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1244 if (RegInfo->getSubRegisters(IncomingReg) &&
1245 RegInfo->getSuperRegisters(Reg) &&
1246 RegInfo->isSubRegister(IncomingReg, Reg))
1247 DeadOps.push_back(i);
1251 // Trim unneeded dead operands.
1252 while (!DeadOps.empty()) {
1253 unsigned OpIdx = DeadOps.back();
1254 if (getOperand(OpIdx).isImplicit())
1255 RemoveOperand(OpIdx);
1257 getOperand(OpIdx).setIsDead(false);
1261 // If not found, this means an alias of one of the operands is dead. Add a
1262 // new implicit operand if required.
1263 if (Found || !AddIfNotFound)
1266 addOperand(MachineOperand::CreateReg(IncomingReg,