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), AsmPrinterFlags(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), AsmPrinterFlags(0),
400 MemRefs(0), MemRefsEnd(0), Parent(0),
401 debugLoc(DebugLoc::getUnknownLoc()) {
402 if (!NoImp && TID->getImplicitDefs())
403 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
405 if (!NoImp && TID->getImplicitUses())
406 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
408 Operands.reserve(NumImplicitOps + TID->getNumOperands());
410 addImplicitDefUseOperands();
411 // Make sure that we get added to a machine basicblock
412 LeakDetector::addGarbageObject(this);
415 /// MachineInstr ctor - As above, but with a DebugLoc.
416 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
418 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
419 Parent(0), debugLoc(dl) {
420 if (!NoImp && TID->getImplicitDefs())
421 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
423 if (!NoImp && TID->getImplicitUses())
424 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
426 Operands.reserve(NumImplicitOps + TID->getNumOperands());
428 addImplicitDefUseOperands();
429 // Make sure that we get added to a machine basicblock
430 LeakDetector::addGarbageObject(this);
433 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
434 /// that the MachineInstr is created and added to the end of the specified
437 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
438 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
439 MemRefs(0), MemRefsEnd(0), Parent(0),
440 debugLoc(DebugLoc::getUnknownLoc()) {
441 assert(MBB && "Cannot use inserting ctor with null basic block!");
442 if (TID->ImplicitDefs)
443 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
445 if (TID->ImplicitUses)
446 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
448 Operands.reserve(NumImplicitOps + TID->getNumOperands());
449 addImplicitDefUseOperands();
450 // Make sure that we get added to a machine basicblock
451 LeakDetector::addGarbageObject(this);
452 MBB->push_back(this); // Add instruction to end of basic block!
455 /// MachineInstr ctor - As above, but with a DebugLoc.
457 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
458 const TargetInstrDesc &tid)
459 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
460 Parent(0), debugLoc(dl) {
461 assert(MBB && "Cannot use inserting ctor with null basic block!");
462 if (TID->ImplicitDefs)
463 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
465 if (TID->ImplicitUses)
466 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
468 Operands.reserve(NumImplicitOps + TID->getNumOperands());
469 addImplicitDefUseOperands();
470 // Make sure that we get added to a machine basicblock
471 LeakDetector::addGarbageObject(this);
472 MBB->push_back(this); // Add instruction to end of basic block!
475 /// MachineInstr ctor - Copies MachineInstr arg exactly
477 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
478 : TID(&MI.getDesc()), NumImplicitOps(0), AsmPrinterFlags(0),
479 MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
480 Parent(0), debugLoc(MI.getDebugLoc()) {
481 Operands.reserve(MI.getNumOperands());
484 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
485 addOperand(MI.getOperand(i));
486 NumImplicitOps = MI.NumImplicitOps;
488 // Set parent to null.
491 LeakDetector::addGarbageObject(this);
494 MachineInstr::~MachineInstr() {
495 LeakDetector::removeGarbageObject(this);
497 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
498 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
499 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
500 "Reg operand def/use list corrupted");
505 /// getRegInfo - If this instruction is embedded into a MachineFunction,
506 /// return the MachineRegisterInfo object for the current function, otherwise
508 MachineRegisterInfo *MachineInstr::getRegInfo() {
509 if (MachineBasicBlock *MBB = getParent())
510 return &MBB->getParent()->getRegInfo();
514 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
515 /// this instruction from their respective use lists. This requires that the
516 /// operands already be on their use lists.
517 void MachineInstr::RemoveRegOperandsFromUseLists() {
518 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
519 if (Operands[i].isReg())
520 Operands[i].RemoveRegOperandFromRegInfo();
524 /// AddRegOperandsToUseLists - Add all of the register operands in
525 /// this instruction from their respective use lists. This requires that the
526 /// operands not be on their use lists yet.
527 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
528 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
529 if (Operands[i].isReg())
530 Operands[i].AddRegOperandToRegInfo(&RegInfo);
535 /// addOperand - Add the specified operand to the instruction. If it is an
536 /// implicit operand, it is added to the end of the operand list. If it is
537 /// an explicit operand it is added at the end of the explicit operand list
538 /// (before the first implicit operand).
539 void MachineInstr::addOperand(const MachineOperand &Op) {
540 bool isImpReg = Op.isReg() && Op.isImplicit();
541 assert((isImpReg || !OperandsComplete()) &&
542 "Trying to add an operand to a machine instr that is already done!");
544 MachineRegisterInfo *RegInfo = getRegInfo();
546 // If we are adding the operand to the end of the list, our job is simpler.
547 // This is true most of the time, so this is a reasonable optimization.
548 if (isImpReg || NumImplicitOps == 0) {
549 // We can only do this optimization if we know that the operand list won't
551 if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
552 Operands.push_back(Op);
554 // Set the parent of the operand.
555 Operands.back().ParentMI = this;
557 // If the operand is a register, update the operand's use list.
559 Operands.back().AddRegOperandToRegInfo(RegInfo);
560 // If the register operand is flagged as early, mark the operand as such
561 unsigned OpNo = Operands.size() - 1;
562 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
563 Operands[OpNo].setIsEarlyClobber(true);
569 // Otherwise, we have to insert a real operand before any implicit ones.
570 unsigned OpNo = Operands.size()-NumImplicitOps;
572 // If this instruction isn't embedded into a function, then we don't need to
573 // update any operand lists.
575 // Simple insertion, no reginfo update needed for other register operands.
576 Operands.insert(Operands.begin()+OpNo, Op);
577 Operands[OpNo].ParentMI = this;
579 // Do explicitly set the reginfo for this operand though, to ensure the
580 // next/prev fields are properly nulled out.
581 if (Operands[OpNo].isReg()) {
582 Operands[OpNo].AddRegOperandToRegInfo(0);
583 // If the register operand is flagged as early, mark the operand as such
584 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
585 Operands[OpNo].setIsEarlyClobber(true);
588 } else if (Operands.size()+1 <= Operands.capacity()) {
589 // Otherwise, we have to remove register operands from their register use
590 // list, add the operand, then add the register operands back to their use
591 // list. This also must handle the case when the operand list reallocates
592 // to somewhere else.
594 // If insertion of this operand won't cause reallocation of the operand
595 // list, just remove the implicit operands, add the operand, then re-add all
596 // the rest of the operands.
597 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
598 assert(Operands[i].isReg() && "Should only be an implicit reg!");
599 Operands[i].RemoveRegOperandFromRegInfo();
602 // Add the operand. If it is a register, add it to the reg list.
603 Operands.insert(Operands.begin()+OpNo, Op);
604 Operands[OpNo].ParentMI = this;
606 if (Operands[OpNo].isReg()) {
607 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
608 // If the register operand is flagged as early, mark the operand as such
609 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
610 Operands[OpNo].setIsEarlyClobber(true);
613 // Re-add all the implicit ops.
614 for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
615 assert(Operands[i].isReg() && "Should only be an implicit reg!");
616 Operands[i].AddRegOperandToRegInfo(RegInfo);
619 // Otherwise, we will be reallocating the operand list. Remove all reg
620 // operands from their list, then readd them after the operand list is
622 RemoveRegOperandsFromUseLists();
624 Operands.insert(Operands.begin()+OpNo, Op);
625 Operands[OpNo].ParentMI = this;
627 // Re-add all the operands.
628 AddRegOperandsToUseLists(*RegInfo);
630 // If the register operand is flagged as early, mark the operand as such
631 if (Operands[OpNo].isReg()
632 && TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
633 Operands[OpNo].setIsEarlyClobber(true);
637 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
638 /// fewer operand than it started with.
640 void MachineInstr::RemoveOperand(unsigned OpNo) {
641 assert(OpNo < Operands.size() && "Invalid operand number");
643 // Special case removing the last one.
644 if (OpNo == Operands.size()-1) {
645 // If needed, remove from the reg def/use list.
646 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
647 Operands.back().RemoveRegOperandFromRegInfo();
653 // Otherwise, we are removing an interior operand. If we have reginfo to
654 // update, remove all operands that will be shifted down from their reg lists,
655 // move everything down, then re-add them.
656 MachineRegisterInfo *RegInfo = getRegInfo();
658 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
659 if (Operands[i].isReg())
660 Operands[i].RemoveRegOperandFromRegInfo();
664 Operands.erase(Operands.begin()+OpNo);
667 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
668 if (Operands[i].isReg())
669 Operands[i].AddRegOperandToRegInfo(RegInfo);
674 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
675 /// This function should be used only occasionally. The setMemRefs function
676 /// is the primary method for setting up a MachineInstr's MemRefs list.
677 void MachineInstr::addMemOperand(MachineFunction &MF,
678 MachineMemOperand *MO) {
679 mmo_iterator OldMemRefs = MemRefs;
680 mmo_iterator OldMemRefsEnd = MemRefsEnd;
682 size_t NewNum = (MemRefsEnd - MemRefs) + 1;
683 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
684 mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
686 std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
687 NewMemRefs[NewNum - 1] = MO;
689 MemRefs = NewMemRefs;
690 MemRefsEnd = NewMemRefsEnd;
693 /// removeFromParent - This method unlinks 'this' from the containing basic
694 /// block, and returns it, but does not delete it.
695 MachineInstr *MachineInstr::removeFromParent() {
696 assert(getParent() && "Not embedded in a basic block!");
697 getParent()->remove(this);
702 /// eraseFromParent - This method unlinks 'this' from the containing basic
703 /// block, and deletes it.
704 void MachineInstr::eraseFromParent() {
705 assert(getParent() && "Not embedded in a basic block!");
706 getParent()->erase(this);
710 /// OperandComplete - Return true if it's illegal to add a new operand
712 bool MachineInstr::OperandsComplete() const {
713 unsigned short NumOperands = TID->getNumOperands();
714 if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
715 return true; // Broken: we have all the operands of this instruction!
719 /// getNumExplicitOperands - Returns the number of non-implicit operands.
721 unsigned MachineInstr::getNumExplicitOperands() const {
722 unsigned NumOperands = TID->getNumOperands();
723 if (!TID->isVariadic())
726 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
727 const MachineOperand &MO = getOperand(i);
728 if (!MO.isReg() || !MO.isImplicit())
735 /// isLabel - Returns true if the MachineInstr represents a label.
737 bool MachineInstr::isLabel() const {
738 return getOpcode() == TargetInstrInfo::DBG_LABEL ||
739 getOpcode() == TargetInstrInfo::EH_LABEL ||
740 getOpcode() == TargetInstrInfo::GC_LABEL;
743 /// isDebugLabel - Returns true if the MachineInstr represents a debug label.
745 bool MachineInstr::isDebugLabel() const {
746 return getOpcode() == TargetInstrInfo::DBG_LABEL;
749 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
750 /// the specific register or -1 if it is not found. It further tightens
751 /// the search criteria to a use that kills the register if isKill is true.
752 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
753 const TargetRegisterInfo *TRI) const {
754 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
755 const MachineOperand &MO = getOperand(i);
756 if (!MO.isReg() || !MO.isUse())
758 unsigned MOReg = MO.getReg();
763 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
764 TargetRegisterInfo::isPhysicalRegister(Reg) &&
765 TRI->isSubRegister(MOReg, Reg)))
766 if (!isKill || MO.isKill())
772 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
773 /// the specified register or -1 if it is not found. If isDead is true, defs
774 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
775 /// also checks if there is a def of a super-register.
776 int MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead,
777 const TargetRegisterInfo *TRI) const {
778 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
779 const MachineOperand &MO = getOperand(i);
780 if (!MO.isReg() || !MO.isDef())
782 unsigned MOReg = MO.getReg();
785 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
786 TargetRegisterInfo::isPhysicalRegister(Reg) &&
787 TRI->isSubRegister(MOReg, Reg)))
788 if (!isDead || MO.isDead())
794 /// findFirstPredOperandIdx() - Find the index of the first operand in the
795 /// operand list that is used to represent the predicate. It returns -1 if
797 int MachineInstr::findFirstPredOperandIdx() const {
798 const TargetInstrDesc &TID = getDesc();
799 if (TID.isPredicable()) {
800 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
801 if (TID.OpInfo[i].isPredicate())
808 /// isRegTiedToUseOperand - Given the index of a register def operand,
809 /// check if the register def is tied to a source operand, due to either
810 /// two-address elimination or inline assembly constraints. Returns the
811 /// first tied use operand index by reference is UseOpIdx is not null.
813 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
814 if (getOpcode() == TargetInstrInfo::INLINEASM) {
815 assert(DefOpIdx >= 2);
816 const MachineOperand &MO = getOperand(DefOpIdx);
817 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
819 // Determine the actual operand index that corresponds to this index.
821 unsigned DefPart = 0;
822 for (unsigned i = 1, e = getNumOperands(); i < e; ) {
823 const MachineOperand &FMO = getOperand(i);
824 // After the normal asm operands there may be additional imp-def regs.
827 // Skip over this def.
828 unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
829 unsigned PrevDef = i + 1;
830 i = PrevDef + NumOps;
832 DefPart = DefOpIdx - PrevDef;
837 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
838 const MachineOperand &FMO = getOperand(i);
841 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
844 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
847 *UseOpIdx = (unsigned)i + 1 + DefPart;
854 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
855 const TargetInstrDesc &TID = getDesc();
856 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
857 const MachineOperand &MO = getOperand(i);
858 if (MO.isReg() && MO.isUse() &&
859 TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
861 *UseOpIdx = (unsigned)i;
868 /// isRegTiedToDefOperand - Return true if the operand of the specified index
869 /// is a register use and it is tied to an def operand. It also returns the def
870 /// operand index by reference.
872 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
873 if (getOpcode() == TargetInstrInfo::INLINEASM) {
874 const MachineOperand &MO = getOperand(UseOpIdx);
875 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
878 // Find the flag operand corresponding to UseOpIdx
879 unsigned FlagIdx, NumOps=0;
880 for (FlagIdx = 1; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
881 const MachineOperand &UFMO = getOperand(FlagIdx);
882 // After the normal asm operands there may be additional imp-def regs.
885 NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
886 assert(NumOps < getNumOperands() && "Invalid inline asm flag");
887 if (UseOpIdx < FlagIdx+NumOps+1)
890 if (FlagIdx >= UseOpIdx)
892 const MachineOperand &UFMO = getOperand(FlagIdx);
894 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
899 // Remember to adjust the index. First operand is asm string, then there
900 // is a flag for each.
902 const MachineOperand &FMO = getOperand(DefIdx);
904 // Skip over this def.
905 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
908 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
914 const TargetInstrDesc &TID = getDesc();
915 if (UseOpIdx >= TID.getNumOperands())
917 const MachineOperand &MO = getOperand(UseOpIdx);
918 if (!MO.isReg() || !MO.isUse())
920 int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
924 *DefOpIdx = (unsigned)DefIdx;
928 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
930 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
931 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
932 const MachineOperand &MO = MI->getOperand(i);
933 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
935 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
936 MachineOperand &MOp = getOperand(j);
937 if (!MOp.isIdenticalTo(MO))
948 /// copyPredicates - Copies predicate operand(s) from MI.
949 void MachineInstr::copyPredicates(const MachineInstr *MI) {
950 const TargetInstrDesc &TID = MI->getDesc();
951 if (!TID.isPredicable())
953 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
954 if (TID.OpInfo[i].isPredicate()) {
955 // Predicated operands must be last operands.
956 addOperand(MI->getOperand(i));
961 /// isSafeToMove - Return true if it is safe to move this instruction. If
962 /// SawStore is set to true, it means that there is a store (or call) between
963 /// the instruction's location and its intended destination.
964 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
966 AliasAnalysis *AA) const {
967 // Ignore stuff that we obviously can't move.
968 if (TID->mayStore() || TID->isCall()) {
972 if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
975 // See if this instruction does a load. If so, we have to guarantee that the
976 // loaded value doesn't change between the load and the its intended
977 // destination. The check for isInvariantLoad gives the targe the chance to
978 // classify the load as always returning a constant, e.g. a constant pool
980 if (TID->mayLoad() && !isInvariantLoad(AA))
981 // Otherwise, this is a real load. If there is a store between the load and
982 // end of block, or if the load is volatile, we can't move it.
983 return !SawStore && !hasVolatileMemoryRef();
988 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
989 /// instruction which defined the specified register instead of copying it.
990 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
992 AliasAnalysis *AA) const {
993 bool SawStore = false;
994 if (!TII->isTriviallyReMaterializable(this, AA) ||
995 !isSafeToMove(TII, SawStore, AA))
997 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
998 const MachineOperand &MO = getOperand(i);
1001 // FIXME: For now, do not remat any instruction with register operands.
1002 // Later on, we can loosen the restriction is the register operands have
1003 // not been modified between the def and use. Note, this is different from
1004 // MachineSink because the code is no longer in two-address form (at least
1008 else if (!MO.isDead() && MO.getReg() != DstReg)
1014 /// hasVolatileMemoryRef - Return true if this instruction may have a
1015 /// volatile memory reference, or if the information describing the
1016 /// memory reference is not available. Return false if it is known to
1017 /// have no volatile memory references.
1018 bool MachineInstr::hasVolatileMemoryRef() const {
1019 // An instruction known never to access memory won't have a volatile access.
1020 if (!TID->mayStore() &&
1023 !TID->hasUnmodeledSideEffects())
1026 // Otherwise, if the instruction has no memory reference information,
1027 // conservatively assume it wasn't preserved.
1028 if (memoperands_empty())
1031 // Check the memory reference information for volatile references.
1032 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1033 if ((*I)->isVolatile())
1039 /// isInvariantLoad - Return true if this instruction is loading from a
1040 /// location whose value is invariant across the function. For example,
1041 /// loading a value from the constant pool or from from the argument area
1042 /// of a function if it does not change. This should only return true of
1043 /// *all* loads the instruction does are invariant (if it does multiple loads).
1044 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1045 // If the instruction doesn't load at all, it isn't an invariant load.
1046 if (!TID->mayLoad())
1049 // If the instruction has lost its memoperands, conservatively assume that
1050 // it may not be an invariant load.
1051 if (memoperands_empty())
1054 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1056 for (mmo_iterator I = memoperands_begin(),
1057 E = memoperands_end(); I != E; ++I) {
1058 if ((*I)->isVolatile()) return false;
1059 if ((*I)->isStore()) return false;
1061 if (const Value *V = (*I)->getValue()) {
1062 // A load from a constant PseudoSourceValue is invariant.
1063 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1064 if (PSV->isConstant(MFI))
1066 // If we have an AliasAnalysis, ask it whether the memory is constant.
1067 if (AA && AA->pointsToConstantMemory(V))
1071 // Otherwise assume conservatively.
1075 // Everything checks out.
1079 /// isConstantValuePHI - If the specified instruction is a PHI that always
1080 /// merges together the same virtual register, return the register, otherwise
1082 unsigned MachineInstr::isConstantValuePHI() const {
1083 if (getOpcode() != TargetInstrInfo::PHI)
1085 assert(getNumOperands() >= 3 &&
1086 "It's illegal to have a PHI without source operands");
1088 unsigned Reg = getOperand(1).getReg();
1089 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1090 if (getOperand(i).getReg() != Reg)
1095 void MachineInstr::dump() const {
1096 errs() << " " << *this;
1099 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1100 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1101 const MachineFunction *MF = 0;
1102 if (const MachineBasicBlock *MBB = getParent()) {
1103 MF = MBB->getParent();
1105 TM = &MF->getTarget();
1108 // Print explicitly defined operands on the left of an assignment syntax.
1109 unsigned StartOp = 0, e = getNumOperands();
1110 for (; StartOp < e && getOperand(StartOp).isReg() &&
1111 getOperand(StartOp).isDef() &&
1112 !getOperand(StartOp).isImplicit();
1114 if (StartOp != 0) OS << ", ";
1115 getOperand(StartOp).print(OS, TM);
1121 // Print the opcode name.
1122 OS << getDesc().getName();
1124 // Print the rest of the operands.
1125 bool OmittedAnyCallClobbers = false;
1126 bool FirstOp = true;
1127 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1128 const MachineOperand &MO = getOperand(i);
1130 // Omit call-clobbered registers which aren't used anywhere. This makes
1131 // call instructions much less noisy on targets where calls clobber lots
1132 // of registers. Don't rely on MO.isDead() because we may be called before
1133 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1134 if (MF && getDesc().isCall() &&
1135 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1136 unsigned Reg = MO.getReg();
1137 if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
1138 const MachineRegisterInfo &MRI = MF->getRegInfo();
1139 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1140 bool HasAliasLive = false;
1141 for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1142 unsigned AliasReg = *Alias; ++Alias)
1143 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1144 HasAliasLive = true;
1147 if (!HasAliasLive) {
1148 OmittedAnyCallClobbers = true;
1155 if (FirstOp) FirstOp = false; else OS << ",";
1160 // Briefly indicate whether any call clobbers were omitted.
1161 if (OmittedAnyCallClobbers) {
1162 if (FirstOp) FirstOp = false; else OS << ",";
1166 bool HaveSemi = false;
1167 if (!memoperands_empty()) {
1168 if (!HaveSemi) OS << ";"; HaveSemi = true;
1171 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1179 if (!debugLoc.isUnknown() && MF) {
1180 if (!HaveSemi) OS << ";"; HaveSemi = true;
1182 // TODO: print InlinedAtLoc information
1184 DebugLocTuple DLT = MF->getDebugLocTuple(debugLoc);
1185 DIScope Scope(DLT.Scope);
1187 // Omit the directory, since it's usually long and uninteresting.
1188 if (!Scope.isNull())
1189 OS << Scope.getFilename();
1192 OS << ':' << DLT.Line;
1194 OS << ':' << DLT.Col;
1200 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1201 const TargetRegisterInfo *RegInfo,
1202 bool AddIfNotFound) {
1203 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1204 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1206 SmallVector<unsigned,4> DeadOps;
1207 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1208 MachineOperand &MO = getOperand(i);
1209 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1211 unsigned Reg = MO.getReg();
1215 if (Reg == IncomingReg) {
1218 // The register is already marked kill.
1220 if (isPhysReg && isRegTiedToDefOperand(i))
1221 // Two-address uses of physregs must not be marked kill.
1226 } else if (hasAliases && MO.isKill() &&
1227 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1228 // A super-register kill already exists.
1229 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1231 if (RegInfo->isSubRegister(IncomingReg, Reg))
1232 DeadOps.push_back(i);
1236 // Trim unneeded kill operands.
1237 while (!DeadOps.empty()) {
1238 unsigned OpIdx = DeadOps.back();
1239 if (getOperand(OpIdx).isImplicit())
1240 RemoveOperand(OpIdx);
1242 getOperand(OpIdx).setIsKill(false);
1246 // If not found, this means an alias of one of the operands is killed. Add a
1247 // new implicit operand if required.
1248 if (!Found && AddIfNotFound) {
1249 addOperand(MachineOperand::CreateReg(IncomingReg,
1258 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1259 const TargetRegisterInfo *RegInfo,
1260 bool AddIfNotFound) {
1261 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1262 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1264 SmallVector<unsigned,4> DeadOps;
1265 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1266 MachineOperand &MO = getOperand(i);
1267 if (!MO.isReg() || !MO.isDef())
1269 unsigned Reg = MO.getReg();
1273 if (Reg == IncomingReg) {
1276 // The register is already marked dead.
1281 } else if (hasAliases && MO.isDead() &&
1282 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1283 // There exists a super-register that's marked dead.
1284 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1286 if (RegInfo->getSubRegisters(IncomingReg) &&
1287 RegInfo->getSuperRegisters(Reg) &&
1288 RegInfo->isSubRegister(IncomingReg, Reg))
1289 DeadOps.push_back(i);
1293 // Trim unneeded dead operands.
1294 while (!DeadOps.empty()) {
1295 unsigned OpIdx = DeadOps.back();
1296 if (getOperand(OpIdx).isImplicit())
1297 RemoveOperand(OpIdx);
1299 getOperand(OpIdx).setIsDead(false);
1303 // If not found, this means an alias of one of the operands is dead. Add a
1304 // new implicit operand if required.
1305 if (Found || !AddIfNotFound)
1308 addOperand(MachineOperand::CreateReg(IncomingReg,