2e59f37182698b32218b1b49cb5560dad9360ab4
1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Methods common to all machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/ADT/FoldingSet.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 using namespace llvm;
45 //===----------------------------------------------------------------------===//
46 // MachineOperand Implementation
47 //===----------------------------------------------------------------------===//
49 void MachineOperand::setReg(unsigned Reg) {
50 if (getReg() == Reg) return; // No change.
52 // Otherwise, we have to change the register. If this operand is embedded
53 // into a machine function, we need to update the old and new register's
54 // use/def lists.
55 if (MachineInstr *MI = getParent())
56 if (MachineBasicBlock *MBB = MI->getParent())
57 if (MachineFunction *MF = MBB->getParent()) {
58 MachineRegisterInfo &MRI = MF->getRegInfo();
59 MRI.removeRegOperandFromUseList(this);
60 SmallContents.RegNo = Reg;
61 MRI.addRegOperandToUseList(this);
62 return;
63 }
65 // Otherwise, just change the register, no problem. :)
66 SmallContents.RegNo = Reg;
67 }
69 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
70 const TargetRegisterInfo &TRI) {
71 assert(TargetRegisterInfo::isVirtualRegister(Reg));
72 if (SubIdx && getSubReg())
73 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
74 setReg(Reg);
75 if (SubIdx)
76 setSubReg(SubIdx);
77 }
79 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
80 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
81 if (getSubReg()) {
82 Reg = TRI.getSubReg(Reg, getSubReg());
83 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
84 // That won't happen in legal code.
85 setSubReg(0);
86 }
87 setReg(Reg);
88 }
90 /// Change a def to a use, or a use to a def.
91 void MachineOperand::setIsDef(bool Val) {
92 assert(isReg() && "Wrong MachineOperand accessor");
93 assert((!Val || !isDebug()) && "Marking a debug operation as def");
94 if (IsDef == Val)
95 return;
96 // MRI may keep uses and defs in different list positions.
97 if (MachineInstr *MI = getParent())
98 if (MachineBasicBlock *MBB = MI->getParent())
99 if (MachineFunction *MF = MBB->getParent()) {
100 MachineRegisterInfo &MRI = MF->getRegInfo();
101 MRI.removeRegOperandFromUseList(this);
102 IsDef = Val;
103 MRI.addRegOperandToUseList(this);
104 return;
105 }
106 IsDef = Val;
107 }
109 // If this operand is currently a register operand, and if this is in a
110 // function, deregister the operand from the register's use/def list.
111 void MachineOperand::removeRegFromUses() {
112 if (!isReg() || !isOnRegUseList())
113 return;
115 if (MachineInstr *MI = getParent()) {
116 if (MachineBasicBlock *MBB = MI->getParent()) {
117 if (MachineFunction *MF = MBB->getParent())
118 MF->getRegInfo().removeRegOperandFromUseList(this);
119 }
120 }
121 }
123 /// ChangeToImmediate - Replace this operand with a new immediate operand of
124 /// the specified value. If an operand is known to be an immediate already,
125 /// the setImm method should be used.
126 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
127 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
129 removeRegFromUses();
131 OpKind = MO_Immediate;
132 Contents.ImmVal = ImmVal;
133 }
135 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
136 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
138 removeRegFromUses();
140 OpKind = MO_FPImmediate;
141 Contents.CFP = FPImm;
142 }
144 /// ChangeToRegister - Replace this operand with a new register operand of
145 /// the specified value. If an operand is known to be an register already,
146 /// the setReg method should be used.
147 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
148 bool isKill, bool isDead, bool isUndef,
149 bool isDebug) {
150 MachineRegisterInfo *RegInfo = nullptr;
151 if (MachineInstr *MI = getParent())
152 if (MachineBasicBlock *MBB = MI->getParent())
153 if (MachineFunction *MF = MBB->getParent())
154 RegInfo = &MF->getRegInfo();
155 // If this operand is already a register operand, remove it from the
156 // register's use/def lists.
157 bool WasReg = isReg();
158 if (RegInfo && WasReg)
159 RegInfo->removeRegOperandFromUseList(this);
161 // Change this to a register and set the reg#.
162 OpKind = MO_Register;
163 SmallContents.RegNo = Reg;
164 SubReg_TargetFlags = 0;
165 IsDef = isDef;
166 IsImp = isImp;
167 IsKill = isKill;
168 IsDead = isDead;
169 IsUndef = isUndef;
170 IsInternalRead = false;
171 IsEarlyClobber = false;
172 IsDebug = isDebug;
173 // Ensure isOnRegUseList() returns false.
174 Contents.Reg.Prev = nullptr;
175 // Preserve the tie when the operand was already a register.
176 if (!WasReg)
177 TiedTo = 0;
179 // If this operand is embedded in a function, add the operand to the
180 // register's use/def list.
181 if (RegInfo)
182 RegInfo->addRegOperandToUseList(this);
183 }
185 /// isIdenticalTo - Return true if this operand is identical to the specified
186 /// operand. Note that this should stay in sync with the hash_value overload
187 /// below.
188 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
189 if (getType() != Other.getType() ||
190 getTargetFlags() != Other.getTargetFlags())
191 return false;
193 switch (getType()) {
194 case MachineOperand::MO_Register:
195 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
196 getSubReg() == Other.getSubReg();
197 case MachineOperand::MO_Immediate:
198 return getImm() == Other.getImm();
199 case MachineOperand::MO_CImmediate:
200 return getCImm() == Other.getCImm();
201 case MachineOperand::MO_FPImmediate:
202 return getFPImm() == Other.getFPImm();
203 case MachineOperand::MO_MachineBasicBlock:
204 return getMBB() == Other.getMBB();
205 case MachineOperand::MO_FrameIndex:
206 return getIndex() == Other.getIndex();
207 case MachineOperand::MO_ConstantPoolIndex:
208 case MachineOperand::MO_TargetIndex:
209 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
210 case MachineOperand::MO_JumpTableIndex:
211 return getIndex() == Other.getIndex();
212 case MachineOperand::MO_GlobalAddress:
213 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
214 case MachineOperand::MO_ExternalSymbol:
215 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
216 getOffset() == Other.getOffset();
217 case MachineOperand::MO_BlockAddress:
218 return getBlockAddress() == Other.getBlockAddress() &&
219 getOffset() == Other.getOffset();
220 case MachineOperand::MO_RegisterMask:
221 case MachineOperand::MO_RegisterLiveOut:
222 return getRegMask() == Other.getRegMask();
223 case MachineOperand::MO_MCSymbol:
224 return getMCSymbol() == Other.getMCSymbol();
225 case MachineOperand::MO_CFIIndex:
226 return getCFIIndex() == Other.getCFIIndex();
227 case MachineOperand::MO_Metadata:
228 return getMetadata() == Other.getMetadata();
229 }
230 llvm_unreachable("Invalid machine operand type");
231 }
233 // Note: this must stay exactly in sync with isIdenticalTo above.
234 hash_code llvm::hash_value(const MachineOperand &MO) {
235 switch (MO.getType()) {
236 case MachineOperand::MO_Register:
237 // Register operands don't have target flags.
238 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
239 case MachineOperand::MO_Immediate:
240 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
241 case MachineOperand::MO_CImmediate:
242 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
243 case MachineOperand::MO_FPImmediate:
244 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
245 case MachineOperand::MO_MachineBasicBlock:
246 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
247 case MachineOperand::MO_FrameIndex:
248 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
249 case MachineOperand::MO_ConstantPoolIndex:
250 case MachineOperand::MO_TargetIndex:
251 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
252 MO.getOffset());
253 case MachineOperand::MO_JumpTableIndex:
254 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
255 case MachineOperand::MO_ExternalSymbol:
256 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
257 MO.getSymbolName());
258 case MachineOperand::MO_GlobalAddress:
259 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
260 MO.getOffset());
261 case MachineOperand::MO_BlockAddress:
262 return hash_combine(MO.getType(), MO.getTargetFlags(),
263 MO.getBlockAddress(), MO.getOffset());
264 case MachineOperand::MO_RegisterMask:
265 case MachineOperand::MO_RegisterLiveOut:
266 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
267 case MachineOperand::MO_Metadata:
268 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
269 case MachineOperand::MO_MCSymbol:
270 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
271 case MachineOperand::MO_CFIIndex:
272 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
273 }
274 llvm_unreachable("Invalid machine operand type");
275 }
277 /// print - Print the specified machine operand.
278 ///
279 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
280 // If the instruction is embedded into a basic block, we can find the
281 // target info for the instruction.
282 if (!TM)
283 if (const MachineInstr *MI = getParent())
284 if (const MachineBasicBlock *MBB = MI->getParent())
285 if (const MachineFunction *MF = MBB->getParent())
286 TM = &MF->getTarget();
287 const TargetRegisterInfo *TRI =
288 TM ? TM->getSubtargetImpl()->getRegisterInfo() : nullptr;
290 switch (getType()) {
291 case MachineOperand::MO_Register:
292 OS << PrintReg(getReg(), TRI, getSubReg());
294 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
295 isInternalRead() || isEarlyClobber() || isTied()) {
296 OS << '<';
297 bool NeedComma = false;
298 if (isDef()) {
299 if (NeedComma) OS << ',';
300 if (isEarlyClobber())
301 OS << "earlyclobber,";
302 if (isImplicit())
303 OS << "imp-";
304 OS << "def";
305 NeedComma = true;
306 // <def,read-undef> only makes sense when getSubReg() is set.
307 // Don't clutter the output otherwise.
308 if (isUndef() && getSubReg())
309 OS << ",read-undef";
310 } else if (isImplicit()) {
311 OS << "imp-use";
312 NeedComma = true;
313 }
315 if (isKill()) {
316 if (NeedComma) OS << ',';
317 OS << "kill";
318 NeedComma = true;
319 }
320 if (isDead()) {
321 if (NeedComma) OS << ',';
322 OS << "dead";
323 NeedComma = true;
324 }
325 if (isUndef() && isUse()) {
326 if (NeedComma) OS << ',';
327 OS << "undef";
328 NeedComma = true;
329 }
330 if (isInternalRead()) {
331 if (NeedComma) OS << ',';
332 OS << "internal";
333 NeedComma = true;
334 }
335 if (isTied()) {
336 if (NeedComma) OS << ',';
337 OS << "tied";
338 if (TiedTo != 15)
339 OS << unsigned(TiedTo - 1);
340 }
341 OS << '>';
342 }
343 break;
344 case MachineOperand::MO_Immediate:
345 OS << getImm();
346 break;
347 case MachineOperand::MO_CImmediate:
348 getCImm()->getValue().print(OS, false);
349 break;
350 case MachineOperand::MO_FPImmediate:
351 if (getFPImm()->getType()->isFloatTy())
352 OS << getFPImm()->getValueAPF().convertToFloat();
353 else
354 OS << getFPImm()->getValueAPF().convertToDouble();
355 break;
356 case MachineOperand::MO_MachineBasicBlock:
357 OS << "<BB#" << getMBB()->getNumber() << ">";
358 break;
359 case MachineOperand::MO_FrameIndex:
360 OS << "<fi#" << getIndex() << '>';
361 break;
362 case MachineOperand::MO_ConstantPoolIndex:
363 OS << "<cp#" << getIndex();
364 if (getOffset()) OS << "+" << getOffset();
365 OS << '>';
366 break;
367 case MachineOperand::MO_TargetIndex:
368 OS << "<ti#" << getIndex();
369 if (getOffset()) OS << "+" << getOffset();
370 OS << '>';
371 break;
372 case MachineOperand::MO_JumpTableIndex:
373 OS << "<jt#" << getIndex() << '>';
374 break;
375 case MachineOperand::MO_GlobalAddress:
376 OS << "<ga:";
377 getGlobal()->printAsOperand(OS, /*PrintType=*/false);
378 if (getOffset()) OS << "+" << getOffset();
379 OS << '>';
380 break;
381 case MachineOperand::MO_ExternalSymbol:
382 OS << "<es:" << getSymbolName();
383 if (getOffset()) OS << "+" << getOffset();
384 OS << '>';
385 break;
386 case MachineOperand::MO_BlockAddress:
387 OS << '<';
388 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false);
389 if (getOffset()) OS << "+" << getOffset();
390 OS << '>';
391 break;
392 case MachineOperand::MO_RegisterMask:
393 OS << "<regmask>";
394 break;
395 case MachineOperand::MO_RegisterLiveOut:
396 OS << "<regliveout>";
397 break;
398 case MachineOperand::MO_Metadata:
399 OS << '<';
400 getMetadata()->printAsOperand(OS, /*PrintType=*/false);
401 OS << '>';
402 break;
403 case MachineOperand::MO_MCSymbol:
404 OS << "<MCSym=" << *getMCSymbol() << '>';
405 break;
406 case MachineOperand::MO_CFIIndex:
407 OS << "<call frame instruction>";
408 break;
409 }
411 if (unsigned TF = getTargetFlags())
412 OS << "[TF=" << TF << ']';
413 }
415 //===----------------------------------------------------------------------===//
416 // MachineMemOperand Implementation
417 //===----------------------------------------------------------------------===//
419 /// getAddrSpace - Return the LLVM IR address space number that this pointer
420 /// points into.
421 unsigned MachinePointerInfo::getAddrSpace() const {
422 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
423 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
424 }
426 /// getConstantPool - Return a MachinePointerInfo record that refers to the
427 /// constant pool.
428 MachinePointerInfo MachinePointerInfo::getConstantPool() {
429 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
430 }
432 /// getFixedStack - Return a MachinePointerInfo record that refers to the
433 /// the specified FrameIndex.
434 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
435 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
436 }
438 MachinePointerInfo MachinePointerInfo::getJumpTable() {
439 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
440 }
442 MachinePointerInfo MachinePointerInfo::getGOT() {
443 return MachinePointerInfo(PseudoSourceValue::getGOT());
444 }
446 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
447 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
448 }
450 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
451 uint64_t s, unsigned int a,
452 const AAMDNodes &AAInfo,
453 const MDNode *Ranges)
454 : PtrInfo(ptrinfo), Size(s),
455 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
456 AAInfo(AAInfo), Ranges(Ranges) {
457 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
458 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
459 "invalid pointer value");
460 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
461 assert((isLoad() || isStore()) && "Not a load/store!");
462 }
464 /// Profile - Gather unique data for the object.
465 ///
466 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
467 ID.AddInteger(getOffset());
468 ID.AddInteger(Size);
469 ID.AddPointer(getOpaqueValue());
470 ID.AddInteger(Flags);
471 }
473 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
474 // The Value and Offset may differ due to CSE. But the flags and size
475 // should be the same.
476 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
477 assert(MMO->getSize() == getSize() && "Size mismatch!");
479 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
480 // Update the alignment value.
481 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
482 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
483 // Also update the base and offset, because the new alignment may
484 // not be applicable with the old ones.
485 PtrInfo = MMO->PtrInfo;
486 }
487 }
489 /// getAlignment - Return the minimum known alignment in bytes of the
490 /// actual memory reference.
491 uint64_t MachineMemOperand::getAlignment() const {
492 return MinAlign(getBaseAlignment(), getOffset());
493 }
495 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
496 assert((MMO.isLoad() || MMO.isStore()) &&
497 "SV has to be a load, store or both.");
499 if (MMO.isVolatile())
500 OS << "Volatile ";
502 if (MMO.isLoad())
503 OS << "LD";
504 if (MMO.isStore())
505 OS << "ST";
506 OS << MMO.getSize();
508 // Print the address information.
509 OS << "[";
510 if (const Value *V = MMO.getValue())
511 V->printAsOperand(OS, /*PrintType=*/false);
512 else if (const PseudoSourceValue *PSV = MMO.getPseudoValue())
513 PSV->printCustom(OS);
514 else
515 OS << "<unknown>";
517 unsigned AS = MMO.getAddrSpace();
518 if (AS != 0)
519 OS << "(addrspace=" << AS << ')';
521 // If the alignment of the memory reference itself differs from the alignment
522 // of the base pointer, print the base alignment explicitly, next to the base
523 // pointer.
524 if (MMO.getBaseAlignment() != MMO.getAlignment())
525 OS << "(align=" << MMO.getBaseAlignment() << ")";
527 if (MMO.getOffset() != 0)
528 OS << "+" << MMO.getOffset();
529 OS << "]";
531 // Print the alignment of the reference.
532 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
533 MMO.getBaseAlignment() != MMO.getSize())
534 OS << "(align=" << MMO.getAlignment() << ")";
536 // Print TBAA info.
537 if (const MDNode *TBAAInfo = MMO.getAAInfo().TBAA) {
538 OS << "(tbaa=";
539 if (TBAAInfo->getNumOperands() > 0)
540 TBAAInfo->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
541 else
542 OS << "<unknown>";
543 OS << ")";
544 }
546 // Print AA scope info.
547 if (const MDNode *ScopeInfo = MMO.getAAInfo().Scope) {
548 OS << "(alias.scope=";
549 if (ScopeInfo->getNumOperands() > 0)
550 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
551 ScopeInfo->getOperand(i)->printAsOperand(OS, /*PrintType=*/false);
552 if (i != ie-1)
553 OS << ",";
554 }
555 else
556 OS << "<unknown>";
557 OS << ")";
558 }
560 // Print AA noalias scope info.
561 if (const MDNode *NoAliasInfo = MMO.getAAInfo().NoAlias) {
562 OS << "(noalias=";
563 if (NoAliasInfo->getNumOperands() > 0)
564 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
565 NoAliasInfo->getOperand(i)->printAsOperand(OS, /*PrintType=*/false);
566 if (i != ie-1)
567 OS << ",";
568 }
569 else
570 OS << "<unknown>";
571 OS << ")";
572 }
574 // Print nontemporal info.
575 if (MMO.isNonTemporal())
576 OS << "(nontemporal)";
578 return OS;
579 }
581 //===----------------------------------------------------------------------===//
582 // MachineInstr Implementation
583 //===----------------------------------------------------------------------===//
585 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
586 if (MCID->ImplicitDefs)
587 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
588 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
589 if (MCID->ImplicitUses)
590 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
591 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
592 }
594 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
595 /// implicit operands. It reserves space for the number of operands specified by
596 /// the MCInstrDesc.
597 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
598 const DebugLoc dl, bool NoImp)
599 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0),
600 Flags(0), AsmPrinterFlags(0),
601 NumMemRefs(0), MemRefs(nullptr), debugLoc(dl) {
602 // Reserve space for the expected number of operands.
603 if (unsigned NumOps = MCID->getNumOperands() +
604 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
605 CapOperands = OperandCapacity::get(NumOps);
606 Operands = MF.allocateOperandArray(CapOperands);
607 }
609 if (!NoImp)
610 addImplicitDefUseOperands(MF);
611 }
613 /// MachineInstr ctor - Copies MachineInstr arg exactly
614 ///
615 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
616 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
617 Flags(0), AsmPrinterFlags(0),
618 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
619 debugLoc(MI.getDebugLoc()) {
620 CapOperands = OperandCapacity::get(MI.getNumOperands());
621 Operands = MF.allocateOperandArray(CapOperands);
623 // Copy operands.
624 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
625 addOperand(MF, MI.getOperand(i));
627 // Copy all the sensible flags.
628 setFlags(MI.Flags);
629 }
631 /// getRegInfo - If this instruction is embedded into a MachineFunction,
632 /// return the MachineRegisterInfo object for the current function, otherwise
633 /// return null.
634 MachineRegisterInfo *MachineInstr::getRegInfo() {
635 if (MachineBasicBlock *MBB = getParent())
636 return &MBB->getParent()->getRegInfo();
637 return nullptr;
638 }
640 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
641 /// this instruction from their respective use lists. This requires that the
642 /// operands already be on their use lists.
643 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
644 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
645 if (Operands[i].isReg())
646 MRI.removeRegOperandFromUseList(&Operands[i]);
647 }
649 /// AddRegOperandsToUseLists - Add all of the register operands in
650 /// this instruction from their respective use lists. This requires that the
651 /// operands not be on their use lists yet.
652 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
653 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
654 if (Operands[i].isReg())
655 MRI.addRegOperandToUseList(&Operands[i]);
656 }
658 void MachineInstr::addOperand(const MachineOperand &Op) {
659 MachineBasicBlock *MBB = getParent();
660 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
661 MachineFunction *MF = MBB->getParent();
662 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
663 addOperand(*MF, Op);
664 }
666 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
667 /// ranges. If MRI is non-null also update use-def chains.
668 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
669 unsigned NumOps, MachineRegisterInfo *MRI) {
670 if (MRI)
671 return MRI->moveOperands(Dst, Src, NumOps);
673 // Here it would be convenient to call memmove, so that isn't allowed because
674 // MachineOperand has a constructor and so isn't a POD type.
675 if (Dst < Src)
676 for (unsigned i = 0; i != NumOps; ++i)
677 new (Dst + i) MachineOperand(Src[i]);
678 else
679 for (unsigned i = NumOps; i ; --i)
680 new (Dst + i - 1) MachineOperand(Src[i - 1]);
681 }
683 /// addOperand - Add the specified operand to the instruction. If it is an
684 /// implicit operand, it is added to the end of the operand list. If it is
685 /// an explicit operand it is added at the end of the explicit operand list
686 /// (before the first implicit operand).
687 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
688 assert(MCID && "Cannot add operands before providing an instr descriptor");
690 // Check if we're adding one of our existing operands.
691 if (&Op >= Operands && &Op < Operands + NumOperands) {
692 // This is unusual: MI->addOperand(MI->getOperand(i)).
693 // If adding Op requires reallocating or moving existing operands around,
694 // the Op reference could go stale. Support it by copying Op.
695 MachineOperand CopyOp(Op);
696 return addOperand(MF, CopyOp);
697 }
699 // Find the insert location for the new operand. Implicit registers go at
700 // the end, everything else goes before the implicit regs.
701 //
702 // FIXME: Allow mixed explicit and implicit operands on inline asm.
703 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
704 // implicit-defs, but they must not be moved around. See the FIXME in
705 // InstrEmitter.cpp.
706 unsigned OpNo = getNumOperands();
707 bool isImpReg = Op.isReg() && Op.isImplicit();
708 if (!isImpReg && !isInlineAsm()) {
709 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
710 --OpNo;
711 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
712 }
713 }
715 #ifndef NDEBUG
716 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
717 // OpNo now points as the desired insertion point. Unless this is a variadic
718 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
719 // RegMask operands go between the explicit and implicit operands.
720 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
721 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
722 "Trying to add an operand to a machine instr that is already done!");
723 #endif
725 MachineRegisterInfo *MRI = getRegInfo();
727 // Determine if the Operands array needs to be reallocated.
728 // Save the old capacity and operand array.
729 OperandCapacity OldCap = CapOperands;
730 MachineOperand *OldOperands = Operands;
731 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
732 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
733 Operands = MF.allocateOperandArray(CapOperands);
734 // Move the operands before the insertion point.
735 if (OpNo)
736 moveOperands(Operands, OldOperands, OpNo, MRI);
737 }
739 // Move the operands following the insertion point.
740 if (OpNo != NumOperands)
741 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
742 MRI);
743 ++NumOperands;
745 // Deallocate the old operand array.
746 if (OldOperands != Operands && OldOperands)
747 MF.deallocateOperandArray(OldCap, OldOperands);
749 // Copy Op into place. It still needs to be inserted into the MRI use lists.
750 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
751 NewMO->ParentMI = this;
753 // When adding a register operand, tell MRI about it.
754 if (NewMO->isReg()) {
755 // Ensure isOnRegUseList() returns false, regardless of Op's status.
756 NewMO->Contents.Reg.Prev = nullptr;
757 // Ignore existing ties. This is not a property that can be copied.
758 NewMO->TiedTo = 0;
759 // Add the new operand to MRI, but only for instructions in an MBB.
760 if (MRI)
761 MRI->addRegOperandToUseList(NewMO);
762 // The MCID operand information isn't accurate until we start adding
763 // explicit operands. The implicit operands are added first, then the
764 // explicits are inserted before them.
765 if (!isImpReg) {
766 // Tie uses to defs as indicated in MCInstrDesc.
767 if (NewMO->isUse()) {
768 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
769 if (DefIdx != -1)
770 tieOperands(DefIdx, OpNo);
771 }
772 // If the register operand is flagged as early, mark the operand as such.
773 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
774 NewMO->setIsEarlyClobber(true);
775 }
776 }
777 }
779 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
780 /// fewer operand than it started with.
781 ///
782 void MachineInstr::RemoveOperand(unsigned OpNo) {
783 assert(OpNo < getNumOperands() && "Invalid operand number");
784 untieRegOperand(OpNo);
786 #ifndef NDEBUG
787 // Moving tied operands would break the ties.
788 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
789 if (Operands[i].isReg())
790 assert(!Operands[i].isTied() && "Cannot move tied operands");
791 #endif
793 MachineRegisterInfo *MRI = getRegInfo();
794 if (MRI && Operands[OpNo].isReg())
795 MRI->removeRegOperandFromUseList(Operands + OpNo);
797 // Don't call the MachineOperand destructor. A lot of this code depends on
798 // MachineOperand having a trivial destructor anyway, and adding a call here
799 // wouldn't make it 'destructor-correct'.
801 if (unsigned N = NumOperands - 1 - OpNo)
802 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
803 --NumOperands;
804 }
806 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
807 /// This function should be used only occasionally. The setMemRefs function
808 /// is the primary method for setting up a MachineInstr's MemRefs list.
809 void MachineInstr::addMemOperand(MachineFunction &MF,
810 MachineMemOperand *MO) {
811 mmo_iterator OldMemRefs = MemRefs;
812 unsigned OldNumMemRefs = NumMemRefs;
814 unsigned NewNum = NumMemRefs + 1;
815 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
817 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
818 NewMemRefs[NewNum - 1] = MO;
819 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
820 }
822 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
823 assert(!isBundledWithPred() && "Must be called on bundle header");
824 for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
825 if (MII->getDesc().getFlags() & Mask) {
826 if (Type == AnyInBundle)
827 return true;
828 } else {
829 if (Type == AllInBundle && !MII->isBundle())
830 return false;
831 }
832 // This was the last instruction in the bundle.
833 if (!MII->isBundledWithSucc())
834 return Type == AllInBundle;
835 }
836 }
838 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
839 MICheckType Check) const {
840 // If opcodes or number of operands are not the same then the two
841 // instructions are obviously not identical.
842 if (Other->getOpcode() != getOpcode() ||
843 Other->getNumOperands() != getNumOperands())
844 return false;
846 if (isBundle()) {
847 // Both instructions are bundles, compare MIs inside the bundle.
848 MachineBasicBlock::const_instr_iterator I1 = *this;
849 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
850 MachineBasicBlock::const_instr_iterator I2 = *Other;
851 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
852 while (++I1 != E1 && I1->isInsideBundle()) {
853 ++I2;
854 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
855 return false;
856 }
857 }
859 // Check operands to make sure they match.
860 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
861 const MachineOperand &MO = getOperand(i);
862 const MachineOperand &OMO = Other->getOperand(i);
863 if (!MO.isReg()) {
864 if (!MO.isIdenticalTo(OMO))
865 return false;
866 continue;
867 }
869 // Clients may or may not want to ignore defs when testing for equality.
870 // For example, machine CSE pass only cares about finding common
871 // subexpressions, so it's safe to ignore virtual register defs.
872 if (MO.isDef()) {
873 if (Check == IgnoreDefs)
874 continue;
875 else if (Check == IgnoreVRegDefs) {
876 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
877 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
878 if (MO.getReg() != OMO.getReg())
879 return false;
880 } else {
881 if (!MO.isIdenticalTo(OMO))
882 return false;
883 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
884 return false;
885 }
886 } else {
887 if (!MO.isIdenticalTo(OMO))
888 return false;
889 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
890 return false;
891 }
892 }
893 // If DebugLoc does not match then two dbg.values are not identical.
894 if (isDebugValue())
895 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
896 && getDebugLoc() != Other->getDebugLoc())
897 return false;
898 return true;
899 }
901 MachineInstr *MachineInstr::removeFromParent() {
902 assert(getParent() && "Not embedded in a basic block!");
903 return getParent()->remove(this);
904 }
906 MachineInstr *MachineInstr::removeFromBundle() {
907 assert(getParent() && "Not embedded in a basic block!");
908 return getParent()->remove_instr(this);
909 }
911 void MachineInstr::eraseFromParent() {
912 assert(getParent() && "Not embedded in a basic block!");
913 getParent()->erase(this);
914 }
916 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
917 assert(getParent() && "Not embedded in a basic block!");
918 MachineBasicBlock *MBB = getParent();
919 MachineFunction *MF = MBB->getParent();
920 assert(MF && "Not embedded in a function!");
922 MachineInstr *MI = (MachineInstr *)this;
923 MachineRegisterInfo &MRI = MF->getRegInfo();
925 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
926 const MachineOperand &MO = MI->getOperand(i);
927 if (!MO.isReg() || !MO.isDef())
928 continue;
929 unsigned Reg = MO.getReg();
930 if (!TargetRegisterInfo::isVirtualRegister(Reg))
931 continue;
932 MRI.markUsesInDebugValueAsUndef(Reg);
933 }
934 MI->eraseFromParent();
935 }
937 void MachineInstr::eraseFromBundle() {
938 assert(getParent() && "Not embedded in a basic block!");
939 getParent()->erase_instr(this);
940 }
942 /// getNumExplicitOperands - Returns the number of non-implicit operands.
943 ///
944 unsigned MachineInstr::getNumExplicitOperands() const {
945 unsigned NumOperands = MCID->getNumOperands();
946 if (!MCID->isVariadic())
947 return NumOperands;
949 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
950 const MachineOperand &MO = getOperand(i);
951 if (!MO.isReg() || !MO.isImplicit())
952 NumOperands++;
953 }
954 return NumOperands;
955 }
957 void MachineInstr::bundleWithPred() {
958 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
959 setFlag(BundledPred);
960 MachineBasicBlock::instr_iterator Pred = this;
961 --Pred;
962 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
963 Pred->setFlag(BundledSucc);
964 }
966 void MachineInstr::bundleWithSucc() {
967 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
968 setFlag(BundledSucc);
969 MachineBasicBlock::instr_iterator Succ = this;
970 ++Succ;
971 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
972 Succ->setFlag(BundledPred);
973 }
975 void MachineInstr::unbundleFromPred() {
976 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
977 clearFlag(BundledPred);
978 MachineBasicBlock::instr_iterator Pred = this;
979 --Pred;
980 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
981 Pred->clearFlag(BundledSucc);
982 }
984 void MachineInstr::unbundleFromSucc() {
985 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
986 clearFlag(BundledSucc);
987 MachineBasicBlock::instr_iterator Succ = this;
988 ++Succ;
989 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
990 Succ->clearFlag(BundledPred);
991 }
993 bool MachineInstr::isStackAligningInlineAsm() const {
994 if (isInlineAsm()) {
995 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
996 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
997 return true;
998 }
999 return false;
1000 }
1002 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1003 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1004 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1005 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1006 }
1008 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1009 unsigned *GroupNo) const {
1010 assert(isInlineAsm() && "Expected an inline asm instruction");
1011 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1013 // Ignore queries about the initial operands.
1014 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1015 return -1;
1017 unsigned Group = 0;
1018 unsigned NumOps;
1019 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1020 i += NumOps) {
1021 const MachineOperand &FlagMO = getOperand(i);
1022 // If we reach the implicit register operands, stop looking.
1023 if (!FlagMO.isImm())
1024 return -1;
1025 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1026 if (i + NumOps > OpIdx) {
1027 if (GroupNo)
1028 *GroupNo = Group;
1029 return i;
1030 }
1031 ++Group;
1032 }
1033 return -1;
1034 }
1036 const TargetRegisterClass*
1037 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1038 const TargetInstrInfo *TII,
1039 const TargetRegisterInfo *TRI) const {
1040 assert(getParent() && "Can't have an MBB reference here!");
1041 assert(getParent()->getParent() && "Can't have an MF reference here!");
1042 const MachineFunction &MF = *getParent()->getParent();
1044 // Most opcodes have fixed constraints in their MCInstrDesc.
1045 if (!isInlineAsm())
1046 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1048 if (!getOperand(OpIdx).isReg())
1049 return nullptr;
1051 // For tied uses on inline asm, get the constraint from the def.
1052 unsigned DefIdx;
1053 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1054 OpIdx = DefIdx;
1056 // Inline asm stores register class constraints in the flag word.
1057 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1058 if (FlagIdx < 0)
1059 return nullptr;
1061 unsigned Flag = getOperand(FlagIdx).getImm();
1062 unsigned RCID;
1063 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1064 return TRI->getRegClass(RCID);
1066 // Assume that all registers in a memory operand are pointers.
1067 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1068 return TRI->getPointerRegClass(MF);
1070 return nullptr;
1071 }
1073 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1074 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1075 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1076 // Check every operands inside the bundle if we have
1077 // been asked to.
1078 if (ExploreBundle)
1079 for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
1080 ++OpndIt)
1081 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1082 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1083 else
1084 // Otherwise, just check the current operands.
1085 for (ConstMIOperands OpndIt(this); OpndIt.isValid() && CurRC; ++OpndIt)
1086 CurRC = getRegClassConstraintEffectForVRegImpl(OpndIt.getOperandNo(), Reg,
1087 CurRC, TII, TRI);
1088 return CurRC;
1089 }
1091 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1092 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1093 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1094 assert(CurRC && "Invalid initial register class");
1095 // Check if Reg is constrained by some of its use/def from MI.
1096 const MachineOperand &MO = getOperand(OpIdx);
1097 if (!MO.isReg() || MO.getReg() != Reg)
1098 return CurRC;
1099 // If yes, accumulate the constraints through the operand.
1100 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1101 }
1103 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1104 unsigned OpIdx, const TargetRegisterClass *CurRC,
1105 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1106 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1107 const MachineOperand &MO = getOperand(OpIdx);
1108 assert(MO.isReg() &&
1109 "Cannot get register constraints for non-register operand");
1110 assert(CurRC && "Invalid initial register class");
1111 if (unsigned SubIdx = MO.getSubReg()) {
1112 if (OpRC)
1113 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1114 else
1115 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1116 } else if (OpRC)
1117 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1118 return CurRC;
1119 }
1121 /// Return the number of instructions inside the MI bundle, not counting the
1122 /// header instruction.
1123 unsigned MachineInstr::getBundleSize() const {
1124 MachineBasicBlock::const_instr_iterator I = this;
1125 unsigned Size = 0;
1126 while (I->isBundledWithSucc())
1127 ++Size, ++I;
1128 return Size;
1129 }
1131 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1132 /// the specific register or -1 if it is not found. It further tightens
1133 /// the search criteria to a use that kills the register if isKill is true.
1134 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1135 const TargetRegisterInfo *TRI) const {
1136 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1137 const MachineOperand &MO = getOperand(i);
1138 if (!MO.isReg() || !MO.isUse())
1139 continue;
1140 unsigned MOReg = MO.getReg();
1141 if (!MOReg)
1142 continue;
1143 if (MOReg == Reg ||
1144 (TRI &&
1145 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1146 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1147 TRI->isSubRegister(MOReg, Reg)))
1148 if (!isKill || MO.isKill())
1149 return i;
1150 }
1151 return -1;
1152 }
1154 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1155 /// indicating if this instruction reads or writes Reg. This also considers
1156 /// partial defines.
1157 std::pair<bool,bool>
1158 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1159 SmallVectorImpl<unsigned> *Ops) const {
1160 bool PartDef = false; // Partial redefine.
1161 bool FullDef = false; // Full define.
1162 bool Use = false;
1164 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1165 const MachineOperand &MO = getOperand(i);
1166 if (!MO.isReg() || MO.getReg() != Reg)
1167 continue;
1168 if (Ops)
1169 Ops->push_back(i);
1170 if (MO.isUse())
1171 Use |= !MO.isUndef();
1172 else if (MO.getSubReg() && !MO.isUndef())
1173 // A partial <def,undef> doesn't count as reading the register.
1174 PartDef = true;
1175 else
1176 FullDef = true;
1177 }
1178 // A partial redefine uses Reg unless there is also a full define.
1179 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1180 }
1182 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1183 /// the specified register or -1 if it is not found. If isDead is true, defs
1184 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1185 /// also checks if there is a def of a super-register.
1186 int
1187 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1188 const TargetRegisterInfo *TRI) const {
1189 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1190 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1191 const MachineOperand &MO = getOperand(i);
1192 // Accept regmask operands when Overlap is set.
1193 // Ignore them when looking for a specific def operand (Overlap == false).
1194 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1195 return i;
1196 if (!MO.isReg() || !MO.isDef())
1197 continue;
1198 unsigned MOReg = MO.getReg();
1199 bool Found = (MOReg == Reg);
1200 if (!Found && TRI && isPhys &&
1201 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1202 if (Overlap)
1203 Found = TRI->regsOverlap(MOReg, Reg);
1204 else
1205 Found = TRI->isSubRegister(MOReg, Reg);
1206 }
1207 if (Found && (!isDead || MO.isDead()))
1208 return i;
1209 }
1210 return -1;
1211 }
1213 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1214 /// operand list that is used to represent the predicate. It returns -1 if
1215 /// none is found.
1216 int MachineInstr::findFirstPredOperandIdx() const {
1217 // Don't call MCID.findFirstPredOperandIdx() because this variant
1218 // is sometimes called on an instruction that's not yet complete, and
1219 // so the number of operands is less than the MCID indicates. In
1220 // particular, the PTX target does this.
1221 const MCInstrDesc &MCID = getDesc();
1222 if (MCID.isPredicable()) {
1223 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1224 if (MCID.OpInfo[i].isPredicate())
1225 return i;
1226 }
1228 return -1;
1229 }
1231 // MachineOperand::TiedTo is 4 bits wide.
1232 const unsigned TiedMax = 15;
1234 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1235 ///
1236 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1237 /// field. TiedTo can have these values:
1238 ///
1239 /// 0: Operand is not tied to anything.
1240 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1241 /// TiedMax: Tied to an operand >= TiedMax-1.
1242 ///
1243 /// The tied def must be one of the first TiedMax operands on a normal
1244 /// instruction. INLINEASM instructions allow more tied defs.
1245 ///
1246 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1247 MachineOperand &DefMO = getOperand(DefIdx);
1248 MachineOperand &UseMO = getOperand(UseIdx);
1249 assert(DefMO.isDef() && "DefIdx must be a def operand");
1250 assert(UseMO.isUse() && "UseIdx must be a use operand");
1251 assert(!DefMO.isTied() && "Def is already tied to another use");
1252 assert(!UseMO.isTied() && "Use is already tied to another def");
1254 if (DefIdx < TiedMax)
1255 UseMO.TiedTo = DefIdx + 1;
1256 else {
1257 // Inline asm can use the group descriptors to find tied operands, but on
1258 // normal instruction, the tied def must be within the first TiedMax
1259 // operands.
1260 assert(isInlineAsm() && "DefIdx out of range");
1261 UseMO.TiedTo = TiedMax;
1262 }
1264 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1265 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1266 }
1268 /// Given the index of a tied register operand, find the operand it is tied to.
1269 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1270 /// which must exist.
1271 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1272 const MachineOperand &MO = getOperand(OpIdx);
1273 assert(MO.isTied() && "Operand isn't tied");
1275 // Normally TiedTo is in range.
1276 if (MO.TiedTo < TiedMax)
1277 return MO.TiedTo - 1;
1279 // Uses on normal instructions can be out of range.
1280 if (!isInlineAsm()) {
1281 // Normal tied defs must be in the 0..TiedMax-1 range.
1282 if (MO.isUse())
1283 return TiedMax - 1;
1284 // MO is a def. Search for the tied use.
1285 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1286 const MachineOperand &UseMO = getOperand(i);
1287 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1288 return i;
1289 }
1290 llvm_unreachable("Can't find tied use");
1291 }
1293 // Now deal with inline asm by parsing the operand group descriptor flags.
1294 // Find the beginning of each operand group.
1295 SmallVector<unsigned, 8> GroupIdx;
1296 unsigned OpIdxGroup = ~0u;
1297 unsigned NumOps;
1298 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1299 i += NumOps) {
1300 const MachineOperand &FlagMO = getOperand(i);
1301 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1302 unsigned CurGroup = GroupIdx.size();
1303 GroupIdx.push_back(i);
1304 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1305 // OpIdx belongs to this operand group.
1306 if (OpIdx > i && OpIdx < i + NumOps)
1307 OpIdxGroup = CurGroup;
1308 unsigned TiedGroup;
1309 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1310 continue;
1311 // Operands in this group are tied to operands in TiedGroup which must be
1312 // earlier. Find the number of operands between the two groups.
1313 unsigned Delta = i - GroupIdx[TiedGroup];
1315 // OpIdx is a use tied to TiedGroup.
1316 if (OpIdxGroup == CurGroup)
1317 return OpIdx - Delta;
1319 // OpIdx is a def tied to this use group.
1320 if (OpIdxGroup == TiedGroup)
1321 return OpIdx + Delta;
1322 }
1323 llvm_unreachable("Invalid tied operand on inline asm");
1324 }
1326 /// clearKillInfo - Clears kill flags on all operands.
1327 ///
1328 void MachineInstr::clearKillInfo() {
1329 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1330 MachineOperand &MO = getOperand(i);
1331 if (MO.isReg() && MO.isUse())
1332 MO.setIsKill(false);
1333 }
1334 }
1336 void MachineInstr::substituteRegister(unsigned FromReg,
1337 unsigned ToReg,
1338 unsigned SubIdx,
1339 const TargetRegisterInfo &RegInfo) {
1340 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1341 if (SubIdx)
1342 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1343 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1344 MachineOperand &MO = getOperand(i);
1345 if (!MO.isReg() || MO.getReg() != FromReg)
1346 continue;
1347 MO.substPhysReg(ToReg, RegInfo);
1348 }
1349 } else {
1350 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1351 MachineOperand &MO = getOperand(i);
1352 if (!MO.isReg() || MO.getReg() != FromReg)
1353 continue;
1354 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1355 }
1356 }
1357 }
1359 /// isSafeToMove - Return true if it is safe to move this instruction. If
1360 /// SawStore is set to true, it means that there is a store (or call) between
1361 /// the instruction's location and its intended destination.
1362 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1363 AliasAnalysis *AA,
1364 bool &SawStore) const {
1365 // Ignore stuff that we obviously can't move.
1366 //
1367 // Treat volatile loads as stores. This is not strictly necessary for
1368 // volatiles, but it is required for atomic loads. It is not allowed to move
1369 // a load across an atomic load with Ordering > Monotonic.
1370 if (mayStore() || isCall() ||
1371 (mayLoad() && hasOrderedMemoryRef())) {
1372 SawStore = true;
1373 return false;
1374 }
1376 if (isPosition() || isDebugValue() || isTerminator() ||
1377 hasUnmodeledSideEffects())
1378 return false;
1380 // See if this instruction does a load. If so, we have to guarantee that the
1381 // loaded value doesn't change between the load and the its intended
1382 // destination. The check for isInvariantLoad gives the targe the chance to
1383 // classify the load as always returning a constant, e.g. a constant pool
1384 // load.
1385 if (mayLoad() && !isInvariantLoad(AA))
1386 // Otherwise, this is a real load. If there is a store between the load and
1387 // end of block, we can't move it.
1388 return !SawStore;
1390 return true;
1391 }
1393 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1394 /// or volatile memory reference, or if the information describing the memory
1395 /// reference is not available. Return false if it is known to have no ordered
1396 /// memory references.
1397 bool MachineInstr::hasOrderedMemoryRef() const {
1398 // An instruction known never to access memory won't have a volatile access.
1399 if (!mayStore() &&
1400 !mayLoad() &&
1401 !isCall() &&
1402 !hasUnmodeledSideEffects())
1403 return false;
1405 // Otherwise, if the instruction has no memory reference information,
1406 // conservatively assume it wasn't preserved.
1407 if (memoperands_empty())
1408 return true;
1410 // Check the memory reference information for ordered references.
1411 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1412 if (!(*I)->isUnordered())
1413 return true;
1415 return false;
1416 }
1418 /// isInvariantLoad - Return true if this instruction is loading from a
1419 /// location whose value is invariant across the function. For example,
1420 /// loading a value from the constant pool or from the argument area
1421 /// of a function if it does not change. This should only return true of
1422 /// *all* loads the instruction does are invariant (if it does multiple loads).
1423 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1424 // If the instruction doesn't load at all, it isn't an invariant load.
1425 if (!mayLoad())
1426 return false;
1428 // If the instruction has lost its memoperands, conservatively assume that
1429 // it may not be an invariant load.
1430 if (memoperands_empty())
1431 return false;
1433 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1435 for (mmo_iterator I = memoperands_begin(),
1436 E = memoperands_end(); I != E; ++I) {
1437 if ((*I)->isVolatile()) return false;
1438 if ((*I)->isStore()) return false;
1439 if ((*I)->isInvariant()) return true;
1442 // A load from a constant PseudoSourceValue is invariant.
1443 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue())
1444 if (PSV->isConstant(MFI))
1445 continue;
1447 if (const Value *V = (*I)->getValue()) {
1448 // If we have an AliasAnalysis, ask it whether the memory is constant.
1449 if (AA && AA->pointsToConstantMemory(
1450 AliasAnalysis::Location(V, (*I)->getSize(),
1451 (*I)->getAAInfo())))
1452 continue;
1453 }
1455 // Otherwise assume conservatively.
1456 return false;
1457 }
1459 // Everything checks out.
1460 return true;
1461 }
1463 /// isConstantValuePHI - If the specified instruction is a PHI that always
1464 /// merges together the same virtual register, return the register, otherwise
1465 /// return 0.
1466 unsigned MachineInstr::isConstantValuePHI() const {
1467 if (!isPHI())
1468 return 0;
1469 assert(getNumOperands() >= 3 &&
1470 "It's illegal to have a PHI without source operands");
1472 unsigned Reg = getOperand(1).getReg();
1473 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1474 if (getOperand(i).getReg() != Reg)
1475 return 0;
1476 return Reg;
1477 }
1479 bool MachineInstr::hasUnmodeledSideEffects() const {
1480 if (hasProperty(MCID::UnmodeledSideEffects))
1481 return true;
1482 if (isInlineAsm()) {
1483 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1484 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1485 return true;
1486 }
1488 return false;
1489 }
1491 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1492 ///
1493 bool MachineInstr::allDefsAreDead() const {
1494 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1495 const MachineOperand &MO = getOperand(i);
1496 if (!MO.isReg() || MO.isUse())
1497 continue;
1498 if (!MO.isDead())
1499 return false;
1500 }
1501 return true;
1502 }
1504 /// copyImplicitOps - Copy implicit register operands from specified
1505 /// instruction to this instruction.
1506 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1507 const MachineInstr *MI) {
1508 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1509 i != e; ++i) {
1510 const MachineOperand &MO = MI->getOperand(i);
1511 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1512 addOperand(MF, MO);
1513 }
1514 }
1516 void MachineInstr::dump() const {
1517 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1518 dbgs() << " " << *this;
1519 #endif
1520 }
1522 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1523 raw_ostream &CommentOS) {
1524 const LLVMContext &Ctx = MF->getFunction()->getContext();
1525 DL.print(Ctx, CommentOS);
1526 }
1528 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
1529 bool SkipOpers) const {
1530 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1531 const MachineFunction *MF = nullptr;
1532 const MachineRegisterInfo *MRI = nullptr;
1533 if (const MachineBasicBlock *MBB = getParent()) {
1534 MF = MBB->getParent();
1535 if (!TM && MF)
1536 TM = &MF->getTarget();
1537 if (MF)
1538 MRI = &MF->getRegInfo();
1539 }
1541 // Save a list of virtual registers.
1542 SmallVector<unsigned, 8> VirtRegs;
1544 // Print explicitly defined operands on the left of an assignment syntax.
1545 unsigned StartOp = 0, e = getNumOperands();
1546 for (; StartOp < e && getOperand(StartOp).isReg() &&
1547 getOperand(StartOp).isDef() &&
1548 !getOperand(StartOp).isImplicit();
1549 ++StartOp) {
1550 if (StartOp != 0) OS << ", ";
1551 getOperand(StartOp).print(OS, TM);
1552 unsigned Reg = getOperand(StartOp).getReg();
1553 if (TargetRegisterInfo::isVirtualRegister(Reg))
1554 VirtRegs.push_back(Reg);
1555 }
1557 if (StartOp != 0)
1558 OS << " = ";
1560 // Print the opcode name.
1561 if (TM && TM->getSubtargetImpl()->getInstrInfo())
1562 OS << TM->getSubtargetImpl()->getInstrInfo()->getName(getOpcode());
1563 else
1564 OS << "UNKNOWN";
1566 if (SkipOpers)
1567 return;
1569 // Print the rest of the operands.
1570 bool OmittedAnyCallClobbers = false;
1571 bool FirstOp = true;
1572 unsigned AsmDescOp = ~0u;
1573 unsigned AsmOpCount = 0;
1575 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1576 // Print asm string.
1577 OS << " ";
1578 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1580 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1581 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1582 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1583 OS << " [sideeffect]";
1584 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1585 OS << " [mayload]";
1586 if (ExtraInfo & InlineAsm::Extra_MayStore)
1587 OS << " [maystore]";
1588 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1589 OS << " [alignstack]";
1590 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1591 OS << " [attdialect]";
1592 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1593 OS << " [inteldialect]";
1595 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1596 FirstOp = false;
1597 }
1600 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1601 const MachineOperand &MO = getOperand(i);
1603 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1604 VirtRegs.push_back(MO.getReg());
1606 // Omit call-clobbered registers which aren't used anywhere. This makes
1607 // call instructions much less noisy on targets where calls clobber lots
1608 // of registers. Don't rely on MO.isDead() because we may be called before
1609 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1610 if (MF && isCall() &&
1611 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1612 unsigned Reg = MO.getReg();
1613 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1614 const MachineRegisterInfo &MRI = MF->getRegInfo();
1615 if (MRI.use_empty(Reg)) {
1616 bool HasAliasLive = false;
1617 for (MCRegAliasIterator AI(
1618 Reg, TM->getSubtargetImpl()->getRegisterInfo(), true);
1619 AI.isValid(); ++AI) {
1620 unsigned AliasReg = *AI;
1621 if (!MRI.use_empty(AliasReg)) {
1622 HasAliasLive = true;
1623 break;
1624 }
1625 }
1626 if (!HasAliasLive) {
1627 OmittedAnyCallClobbers = true;
1628 continue;
1629 }
1630 }
1631 }
1632 }
1634 if (FirstOp) FirstOp = false; else OS << ",";
1635 OS << " ";
1636 if (i < getDesc().NumOperands) {
1637 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1638 if (MCOI.isPredicate())
1639 OS << "pred:";
1640 if (MCOI.isOptionalDef())
1641 OS << "opt:";
1642 }
1643 if (isDebugValue() && MO.isMetadata()) {
1644 // Pretty print DBG_VALUE instructions.
1645 const MDNode *MD = MO.getMetadata();
1646 DIDescriptor DI(MD);
1647 DIVariable DIV(MD);
1649 if (DI.isVariable() && !DIV.getName().empty())
1650 OS << "!\"" << DIV.getName() << '\"';
1651 else
1652 MO.print(OS, TM);
1653 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1654 OS << TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIndexName(
1655 MO.getImm());
1656 } else if (i == AsmDescOp && MO.isImm()) {
1657 // Pretty print the inline asm operand descriptor.
1658 OS << '$' << AsmOpCount++;
1659 unsigned Flag = MO.getImm();
1660 switch (InlineAsm::getKind(Flag)) {
1661 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1662 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1663 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1664 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1665 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1666 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1667 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1668 }
1670 unsigned RCID = 0;
1671 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1672 if (TM)
1673 OS << ':'
1674 << TM->getSubtargetImpl()
1675 ->getRegisterInfo()
1676 ->getRegClass(RCID)
1677 ->getName();
1678 else
1679 OS << ":RC" << RCID;
1680 }
1682 unsigned TiedTo = 0;
1683 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1684 OS << " tiedto:$" << TiedTo;
1686 OS << ']';
1688 // Compute the index of the next operand descriptor.
1689 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1690 } else
1691 MO.print(OS, TM);
1692 }
1694 // Briefly indicate whether any call clobbers were omitted.
1695 if (OmittedAnyCallClobbers) {
1696 if (!FirstOp) OS << ",";
1697 OS << " ...";
1698 }
1700 bool HaveSemi = false;
1701 const unsigned PrintableFlags = FrameSetup;
1702 if (Flags & PrintableFlags) {
1703 if (!HaveSemi) OS << ";"; HaveSemi = true;
1704 OS << " flags: ";
1706 if (Flags & FrameSetup)
1707 OS << "FrameSetup";
1708 }
1710 if (!memoperands_empty()) {
1711 if (!HaveSemi) OS << ";"; HaveSemi = true;
1713 OS << " mem:";
1714 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1715 i != e; ++i) {
1716 OS << **i;
1717 if (std::next(i) != e)
1718 OS << " ";
1719 }
1720 }
1722 // Print the regclass of any virtual registers encountered.
1723 if (MRI && !VirtRegs.empty()) {
1724 if (!HaveSemi) OS << ";"; HaveSemi = true;
1725 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1726 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1727 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1728 for (unsigned j = i+1; j != VirtRegs.size();) {
1729 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1730 ++j;
1731 continue;
1732 }
1733 if (VirtRegs[i] != VirtRegs[j])
1734 OS << "," << PrintReg(VirtRegs[j]);
1735 VirtRegs.erase(VirtRegs.begin()+j);
1736 }
1737 }
1738 }
1740 // Print debug location information.
1741 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1742 if (!HaveSemi) OS << ";";
1743 DIVariable DV(getOperand(e - 1).getMetadata());
1744 OS << " line no:" << DV.getLineNumber();
1745 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1746 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1747 if (!InlinedAtDL.isUnknown() && MF) {
1748 OS << " inlined @[ ";
1749 printDebugLoc(InlinedAtDL, MF, OS);
1750 OS << " ]";
1751 }
1752 }
1753 if (isIndirectDebugValue())
1754 OS << " indirect";
1755 } else if (!debugLoc.isUnknown() && MF) {
1756 if (!HaveSemi) OS << ";";
1757 OS << " dbg:";
1758 printDebugLoc(debugLoc, MF, OS);
1759 }
1761 OS << '\n';
1762 }
1764 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1765 const TargetRegisterInfo *RegInfo,
1766 bool AddIfNotFound) {
1767 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1768 bool hasAliases = isPhysReg &&
1769 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1770 bool Found = false;
1771 SmallVector<unsigned,4> DeadOps;
1772 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1773 MachineOperand &MO = getOperand(i);
1774 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1775 continue;
1776 unsigned Reg = MO.getReg();
1777 if (!Reg)
1778 continue;
1780 if (Reg == IncomingReg) {
1781 if (!Found) {
1782 if (MO.isKill())
1783 // The register is already marked kill.
1784 return true;
1785 if (isPhysReg && isRegTiedToDefOperand(i))
1786 // Two-address uses of physregs must not be marked kill.
1787 return true;
1788 MO.setIsKill();
1789 Found = true;
1790 }
1791 } else if (hasAliases && MO.isKill() &&
1792 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1793 // A super-register kill already exists.
1794 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1795 return true;
1796 if (RegInfo->isSubRegister(IncomingReg, Reg))
1797 DeadOps.push_back(i);
1798 }
1799 }
1801 // Trim unneeded kill operands.
1802 while (!DeadOps.empty()) {
1803 unsigned OpIdx = DeadOps.back();
1804 if (getOperand(OpIdx).isImplicit())
1805 RemoveOperand(OpIdx);
1806 else
1807 getOperand(OpIdx).setIsKill(false);
1808 DeadOps.pop_back();
1809 }
1811 // If not found, this means an alias of one of the operands is killed. Add a
1812 // new implicit operand if required.
1813 if (!Found && AddIfNotFound) {
1814 addOperand(MachineOperand::CreateReg(IncomingReg,
1815 false /*IsDef*/,
1816 true /*IsImp*/,
1817 true /*IsKill*/));
1818 return true;
1819 }
1820 return Found;
1821 }
1823 void MachineInstr::clearRegisterKills(unsigned Reg,
1824 const TargetRegisterInfo *RegInfo) {
1825 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1826 RegInfo = nullptr;
1827 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1828 MachineOperand &MO = getOperand(i);
1829 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1830 continue;
1831 unsigned OpReg = MO.getReg();
1832 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1833 MO.setIsKill(false);
1834 }
1835 }
1837 bool MachineInstr::addRegisterDead(unsigned Reg,
1838 const TargetRegisterInfo *RegInfo,
1839 bool AddIfNotFound) {
1840 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1841 bool hasAliases = isPhysReg &&
1842 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1843 bool Found = false;
1844 SmallVector<unsigned,4> DeadOps;
1845 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1846 MachineOperand &MO = getOperand(i);
1847 if (!MO.isReg() || !MO.isDef())
1848 continue;
1849 unsigned MOReg = MO.getReg();
1850 if (!MOReg)
1851 continue;
1853 if (MOReg == Reg) {
1854 MO.setIsDead();
1855 Found = true;
1856 } else if (hasAliases && MO.isDead() &&
1857 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1858 // There exists a super-register that's marked dead.
1859 if (RegInfo->isSuperRegister(Reg, MOReg))
1860 return true;
1861 if (RegInfo->isSubRegister(Reg, MOReg))
1862 DeadOps.push_back(i);
1863 }
1864 }
1866 // Trim unneeded dead operands.
1867 while (!DeadOps.empty()) {
1868 unsigned OpIdx = DeadOps.back();
1869 if (getOperand(OpIdx).isImplicit())
1870 RemoveOperand(OpIdx);
1871 else
1872 getOperand(OpIdx).setIsDead(false);
1873 DeadOps.pop_back();
1874 }
1876 // If not found, this means an alias of one of the operands is dead. Add a
1877 // new implicit operand if required.
1878 if (Found || !AddIfNotFound)
1879 return Found;
1881 addOperand(MachineOperand::CreateReg(Reg,
1882 true /*IsDef*/,
1883 true /*IsImp*/,
1884 false /*IsKill*/,
1885 true /*IsDead*/));
1886 return true;
1887 }
1889 void MachineInstr::addRegisterDefined(unsigned Reg,
1890 const TargetRegisterInfo *RegInfo) {
1891 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1892 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1893 if (MO)
1894 return;
1895 } else {
1896 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1897 const MachineOperand &MO = getOperand(i);
1898 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1899 MO.getSubReg() == 0)
1900 return;
1901 }
1902 }
1903 addOperand(MachineOperand::CreateReg(Reg,
1904 true /*IsDef*/,
1905 true /*IsImp*/));
1906 }
1908 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1909 const TargetRegisterInfo &TRI) {
1910 bool HasRegMask = false;
1911 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1912 MachineOperand &MO = getOperand(i);
1913 if (MO.isRegMask()) {
1914 HasRegMask = true;
1915 continue;
1916 }
1917 if (!MO.isReg() || !MO.isDef()) continue;
1918 unsigned Reg = MO.getReg();
1919 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1920 bool Dead = true;
1921 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1922 I != E; ++I)
1923 if (TRI.regsOverlap(*I, Reg)) {
1924 Dead = false;
1925 break;
1926 }
1927 // If there are no uses, including partial uses, the def is dead.
1928 if (Dead) MO.setIsDead();
1929 }
1931 // This is a call with a register mask operand.
1932 // Mask clobbers are always dead, so add defs for the non-dead defines.
1933 if (HasRegMask)
1934 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1935 I != E; ++I)
1936 addRegisterDefined(*I, &TRI);
1937 }
1939 unsigned
1940 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1941 // Build up a buffer of hash code components.
1942 SmallVector<size_t, 8> HashComponents;
1943 HashComponents.reserve(MI->getNumOperands() + 1);
1944 HashComponents.push_back(MI->getOpcode());
1945 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1946 const MachineOperand &MO = MI->getOperand(i);
1947 if (MO.isReg() && MO.isDef() &&
1948 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1949 continue; // Skip virtual register defs.
1951 HashComponents.push_back(hash_value(MO));
1952 }
1953 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1954 }
1956 void MachineInstr::emitError(StringRef Msg) const {
1957 // Find the source location cookie.
1958 unsigned LocCookie = 0;
1959 const MDNode *LocMD = nullptr;
1960 for (unsigned i = getNumOperands(); i != 0; --i) {
1961 if (getOperand(i-1).isMetadata() &&
1962 (LocMD = getOperand(i-1).getMetadata()) &&
1963 LocMD->getNumOperands() != 0) {
1964 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1965 LocCookie = CI->getZExtValue();
1966 break;
1967 }
1968 }
1969 }
1971 if (const MachineBasicBlock *MBB = getParent())
1972 if (const MachineFunction *MF = MBB->getParent())
1973 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1974 report_fatal_error(Msg);
1975 }