1 //===-- Instruction.cpp - Implement the Instruction class -----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Instruction class for the IR library.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/Instruction.h"
14 #include "llvm/IR/IntrinsicInst.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/MDBuilder.h"
19 #include "llvm/IR/Operator.h"
20 #include "llvm/IR/Type.h"
23 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
24 Instruction *InsertBefore)
25 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
27 // If requested, insert this instruction into a basic block...
29 BasicBlock *BB = InsertBefore->getParent();
30 assert(BB && "Instruction to insert before is not in a basic block!");
31 BB->getInstList().insert(InsertBefore->getIterator(), this);
35 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
36 BasicBlock *InsertAtEnd)
37 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
39 // append this instruction into the basic block
40 assert(InsertAtEnd && "Basic block to append to may not be NULL!");
41 InsertAtEnd->getInstList().push_back(this);
44 Instruction::~Instruction() {
45 assert(!Parent && "Instruction still linked in the program!");
47 // Replace any extant metadata uses of this instruction with undef to
48 // preserve debug info accuracy. Some alternatives include:
49 // - Treat Instruction like any other Value, and point its extant metadata
50 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses
51 // trivially dead (i.e. fair game for deletion in many passes), leading to
52 // stale dbg.values being in effect for too long.
53 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal
54 // correct. OTOH results in wasted work in some common cases (e.g. when all
55 // instructions in a BasicBlock are deleted).
56 if (isUsedByMetadata())
57 ValueAsMetadata::handleRAUW(this, UndefValue::get(getType()));
59 if (hasMetadataHashEntry())
60 clearMetadataHashEntries();
64 void Instruction::setParent(BasicBlock *P) {
68 const Module *Instruction::getModule() const {
69 return getParent()->getModule();
72 const Function *Instruction::getFunction() const {
73 return getParent()->getParent();
76 void Instruction::removeFromParent() {
77 getParent()->getInstList().remove(getIterator());
80 iplist<Instruction>::iterator Instruction::eraseFromParent() {
81 return getParent()->getInstList().erase(getIterator());
84 /// Insert an unlinked instruction into a basic block immediately before the
85 /// specified instruction.
86 void Instruction::insertBefore(Instruction *InsertPos) {
87 InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
90 /// Insert an unlinked instruction into a basic block immediately after the
91 /// specified instruction.
92 void Instruction::insertAfter(Instruction *InsertPos) {
93 InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
97 /// Unlink this instruction from its current basic block and insert it into the
98 /// basic block that MovePos lives in, right before MovePos.
99 void Instruction::moveBefore(Instruction *MovePos) {
100 moveBefore(*MovePos->getParent(), MovePos->getIterator());
103 void Instruction::moveAfter(Instruction *MovePos) {
104 moveBefore(*MovePos->getParent(), ++MovePos->getIterator());
107 void Instruction::moveBefore(BasicBlock &BB,
108 SymbolTableList<Instruction>::iterator I) {
109 assert(I == BB.end() || I->getParent() == &BB);
110 BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
113 bool Instruction::comesBefore(const Instruction *Other) const {
114 assert(Parent && Other->Parent &&
115 "instructions without BB parents have no order");
116 assert(Parent == Other->Parent && "cross-BB instruction order comparison");
117 if (!Parent->isInstrOrderValid())
118 Parent->renumberInstructions();
119 return Order < Other->Order;
122 void Instruction::setHasNoUnsignedWrap(bool b) {
123 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
126 void Instruction::setHasNoSignedWrap(bool b) {
127 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
130 void Instruction::setIsExact(bool b) {
131 cast<PossiblyExactOperator>(this)->setIsExact(b);
134 bool Instruction::hasNoUnsignedWrap() const {
135 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
138 bool Instruction::hasNoSignedWrap() const {
139 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
142 void Instruction::dropPoisonGeneratingFlags() {
143 switch (getOpcode()) {
144 case Instruction::Add:
145 case Instruction::Sub:
146 case Instruction::Mul:
147 case Instruction::Shl:
148 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
149 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
152 case Instruction::UDiv:
153 case Instruction::SDiv:
154 case Instruction::AShr:
155 case Instruction::LShr:
156 cast<PossiblyExactOperator>(this)->setIsExact(false);
159 case Instruction::GetElementPtr:
160 cast<GetElementPtrInst>(this)->setIsInBounds(false);
163 // TODO: FastMathFlags!
167 bool Instruction::isExact() const {
168 return cast<PossiblyExactOperator>(this)->isExact();
171 void Instruction::setFast(bool B) {
172 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
173 cast<FPMathOperator>(this)->setFast(B);
176 void Instruction::setHasAllowReassoc(bool B) {
177 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
178 cast<FPMathOperator>(this)->setHasAllowReassoc(B);
181 void Instruction::setHasNoNaNs(bool B) {
182 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
183 cast<FPMathOperator>(this)->setHasNoNaNs(B);
186 void Instruction::setHasNoInfs(bool B) {
187 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
188 cast<FPMathOperator>(this)->setHasNoInfs(B);
191 void Instruction::setHasNoSignedZeros(bool B) {
192 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
193 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
196 void Instruction::setHasAllowReciprocal(bool B) {
197 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
198 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
201 void Instruction::setHasAllowContract(bool B) {
202 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
203 cast<FPMathOperator>(this)->setHasAllowContract(B);
206 void Instruction::setHasApproxFunc(bool B) {
207 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
208 cast<FPMathOperator>(this)->setHasApproxFunc(B);
211 void Instruction::setFastMathFlags(FastMathFlags FMF) {
212 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
213 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
216 void Instruction::copyFastMathFlags(FastMathFlags FMF) {
217 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
218 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
221 bool Instruction::isFast() const {
222 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
223 return cast<FPMathOperator>(this)->isFast();
226 bool Instruction::hasAllowReassoc() const {
227 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
228 return cast<FPMathOperator>(this)->hasAllowReassoc();
231 bool Instruction::hasNoNaNs() const {
232 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
233 return cast<FPMathOperator>(this)->hasNoNaNs();
236 bool Instruction::hasNoInfs() const {
237 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
238 return cast<FPMathOperator>(this)->hasNoInfs();
241 bool Instruction::hasNoSignedZeros() const {
242 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
243 return cast<FPMathOperator>(this)->hasNoSignedZeros();
246 bool Instruction::hasAllowReciprocal() const {
247 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
248 return cast<FPMathOperator>(this)->hasAllowReciprocal();
251 bool Instruction::hasAllowContract() const {
252 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
253 return cast<FPMathOperator>(this)->hasAllowContract();
256 bool Instruction::hasApproxFunc() const {
257 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
258 return cast<FPMathOperator>(this)->hasApproxFunc();
261 FastMathFlags Instruction::getFastMathFlags() const {
262 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
263 return cast<FPMathOperator>(this)->getFastMathFlags();
266 void Instruction::copyFastMathFlags(const Instruction *I) {
267 copyFastMathFlags(I->getFastMathFlags());
270 void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
271 // Copy the wrapping flags.
272 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
273 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
274 setHasNoSignedWrap(OB->hasNoSignedWrap());
275 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
279 // Copy the exact flag.
280 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
281 if (isa<PossiblyExactOperator>(this))
282 setIsExact(PE->isExact());
284 // Copy the fast-math flags.
285 if (auto *FP = dyn_cast<FPMathOperator>(V))
286 if (isa<FPMathOperator>(this))
287 copyFastMathFlags(FP->getFastMathFlags());
289 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
290 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
291 DestGEP->setIsInBounds(SrcGEP->isInBounds() | DestGEP->isInBounds());
294 void Instruction::andIRFlags(const Value *V) {
295 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
296 if (isa<OverflowingBinaryOperator>(this)) {
297 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
298 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
302 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
303 if (isa<PossiblyExactOperator>(this))
304 setIsExact(isExact() & PE->isExact());
306 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
307 if (isa<FPMathOperator>(this)) {
308 FastMathFlags FM = getFastMathFlags();
309 FM &= FP->getFastMathFlags();
310 copyFastMathFlags(FM);
314 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
315 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
316 DestGEP->setIsInBounds(SrcGEP->isInBounds() & DestGEP->isInBounds());
319 const char *Instruction::getOpcodeName(unsigned OpCode) {
322 case Ret: return "ret";
323 case Br: return "br";
324 case Switch: return "switch";
325 case IndirectBr: return "indirectbr";
326 case Invoke: return "invoke";
327 case Resume: return "resume";
328 case Unreachable: return "unreachable";
329 case CleanupRet: return "cleanupret";
330 case CatchRet: return "catchret";
331 case CatchPad: return "catchpad";
332 case CatchSwitch: return "catchswitch";
333 case CallBr: return "callbr";
335 // Standard unary operators...
336 case FNeg: return "fneg";
338 // Standard binary operators...
339 case Add: return "add";
340 case FAdd: return "fadd";
341 case Sub: return "sub";
342 case FSub: return "fsub";
343 case Mul: return "mul";
344 case FMul: return "fmul";
345 case UDiv: return "udiv";
346 case SDiv: return "sdiv";
347 case FDiv: return "fdiv";
348 case URem: return "urem";
349 case SRem: return "srem";
350 case FRem: return "frem";
352 // Logical operators...
353 case And: return "and";
354 case Or : return "or";
355 case Xor: return "xor";
357 // Memory instructions...
358 case Alloca: return "alloca";
359 case Load: return "load";
360 case Store: return "store";
361 case AtomicCmpXchg: return "cmpxchg";
362 case AtomicRMW: return "atomicrmw";
363 case Fence: return "fence";
364 case GetElementPtr: return "getelementptr";
366 // Convert instructions...
367 case Trunc: return "trunc";
368 case ZExt: return "zext";
369 case SExt: return "sext";
370 case FPTrunc: return "fptrunc";
371 case FPExt: return "fpext";
372 case FPToUI: return "fptoui";
373 case FPToSI: return "fptosi";
374 case UIToFP: return "uitofp";
375 case SIToFP: return "sitofp";
376 case IntToPtr: return "inttoptr";
377 case PtrToInt: return "ptrtoint";
378 case BitCast: return "bitcast";
379 case AddrSpaceCast: return "addrspacecast";
381 // Other instructions...
382 case ICmp: return "icmp";
383 case FCmp: return "fcmp";
384 case PHI: return "phi";
385 case Select: return "select";
386 case Call: return "call";
387 case Shl: return "shl";
388 case LShr: return "lshr";
389 case AShr: return "ashr";
390 case VAArg: return "va_arg";
391 case ExtractElement: return "extractelement";
392 case InsertElement: return "insertelement";
393 case ShuffleVector: return "shufflevector";
394 case ExtractValue: return "extractvalue";
395 case InsertValue: return "insertvalue";
396 case LandingPad: return "landingpad";
397 case CleanupPad: return "cleanuppad";
398 case Freeze: return "freeze";
400 default: return "<Invalid operator> ";
404 /// Return true if both instructions have the same special state. This must be
405 /// kept in sync with FunctionComparator::cmpOperations in
406 /// lib/Transforms/IPO/MergeFunctions.cpp.
407 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
408 bool IgnoreAlignment = false) {
409 assert(I1->getOpcode() == I2->getOpcode() &&
410 "Can not compare special state of different instructions");
412 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
413 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
414 (AI->getAlignment() == cast<AllocaInst>(I2)->getAlignment() ||
416 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
417 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
418 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
420 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
421 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
422 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
423 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
424 (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
426 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
427 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
428 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
429 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
430 if (const CallInst *CI = dyn_cast<CallInst>(I1))
431 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
432 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
433 CI->getAttributes() == cast<CallInst>(I2)->getAttributes() &&
434 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
435 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
436 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
437 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() &&
438 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
439 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
440 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
441 CI->getAttributes() == cast<CallBrInst>(I2)->getAttributes() &&
442 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
443 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
444 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
445 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
446 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
447 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
448 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
449 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
450 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
451 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
452 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
453 CXI->getSuccessOrdering() ==
454 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
455 CXI->getFailureOrdering() ==
456 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
457 CXI->getSyncScopeID() ==
458 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
459 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
460 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
461 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
462 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
463 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
464 if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I1))
465 return SVI->getShuffleMask() ==
466 cast<ShuffleVectorInst>(I2)->getShuffleMask();
471 bool Instruction::isIdenticalTo(const Instruction *I) const {
472 return isIdenticalToWhenDefined(I) &&
473 SubclassOptionalData == I->SubclassOptionalData;
476 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
477 if (getOpcode() != I->getOpcode() ||
478 getNumOperands() != I->getNumOperands() ||
479 getType() != I->getType())
482 // If both instructions have no operands, they are identical.
483 if (getNumOperands() == 0 && I->getNumOperands() == 0)
484 return haveSameSpecialState(this, I);
486 // We have two instructions of identical opcode and #operands. Check to see
487 // if all operands are the same.
488 if (!std::equal(op_begin(), op_end(), I->op_begin()))
491 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
492 const PHINode *otherPHI = cast<PHINode>(I);
493 return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
494 otherPHI->block_begin());
497 return haveSameSpecialState(this, I);
500 // Keep this in sync with FunctionComparator::cmpOperations in
501 // lib/Transforms/IPO/MergeFunctions.cpp.
502 bool Instruction::isSameOperationAs(const Instruction *I,
503 unsigned flags) const {
504 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
505 bool UseScalarTypes = flags & CompareUsingScalarTypes;
507 if (getOpcode() != I->getOpcode() ||
508 getNumOperands() != I->getNumOperands() ||
510 getType()->getScalarType() != I->getType()->getScalarType() :
511 getType() != I->getType()))
514 // We have two instructions of identical opcode and #operands. Check to see
515 // if all operands are the same type
516 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
518 getOperand(i)->getType()->getScalarType() !=
519 I->getOperand(i)->getType()->getScalarType() :
520 getOperand(i)->getType() != I->getOperand(i)->getType())
523 return haveSameSpecialState(this, I, IgnoreAlignment);
526 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
527 for (const Use &U : uses()) {
528 // PHI nodes uses values in the corresponding predecessor block. For other
529 // instructions, just check to see whether the parent of the use matches up.
530 const Instruction *I = cast<Instruction>(U.getUser());
531 const PHINode *PN = dyn_cast<PHINode>(I);
533 if (I->getParent() != BB)
538 if (PN->getIncomingBlock(U) != BB)
544 bool Instruction::mayReadFromMemory() const {
545 switch (getOpcode()) {
546 default: return false;
547 case Instruction::VAArg:
548 case Instruction::Load:
549 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
550 case Instruction::AtomicCmpXchg:
551 case Instruction::AtomicRMW:
552 case Instruction::CatchPad:
553 case Instruction::CatchRet:
555 case Instruction::Call:
556 case Instruction::Invoke:
557 case Instruction::CallBr:
558 return !cast<CallBase>(this)->doesNotReadMemory();
559 case Instruction::Store:
560 return !cast<StoreInst>(this)->isUnordered();
564 bool Instruction::mayWriteToMemory() const {
565 switch (getOpcode()) {
566 default: return false;
567 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
568 case Instruction::Store:
569 case Instruction::VAArg:
570 case Instruction::AtomicCmpXchg:
571 case Instruction::AtomicRMW:
572 case Instruction::CatchPad:
573 case Instruction::CatchRet:
575 case Instruction::Call:
576 case Instruction::Invoke:
577 case Instruction::CallBr:
578 return !cast<CallBase>(this)->onlyReadsMemory();
579 case Instruction::Load:
580 return !cast<LoadInst>(this)->isUnordered();
584 bool Instruction::isAtomic() const {
585 switch (getOpcode()) {
588 case Instruction::AtomicCmpXchg:
589 case Instruction::AtomicRMW:
590 case Instruction::Fence:
592 case Instruction::Load:
593 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
594 case Instruction::Store:
595 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
599 bool Instruction::hasAtomicLoad() const {
601 switch (getOpcode()) {
604 case Instruction::AtomicCmpXchg:
605 case Instruction::AtomicRMW:
606 case Instruction::Load:
611 bool Instruction::hasAtomicStore() const {
613 switch (getOpcode()) {
616 case Instruction::AtomicCmpXchg:
617 case Instruction::AtomicRMW:
618 case Instruction::Store:
623 bool Instruction::mayThrow() const {
624 if (const CallInst *CI = dyn_cast<CallInst>(this))
625 return !CI->doesNotThrow();
626 if (const auto *CRI = dyn_cast<CleanupReturnInst>(this))
627 return CRI->unwindsToCaller();
628 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this))
629 return CatchSwitch->unwindsToCaller();
630 return isa<ResumeInst>(this);
633 bool Instruction::isSafeToRemove() const {
634 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
635 !this->isTerminator();
638 bool Instruction::isLifetimeStartOrEnd() const {
639 auto II = dyn_cast<IntrinsicInst>(this);
642 Intrinsic::ID ID = II->getIntrinsicID();
643 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
646 const Instruction *Instruction::getNextNonDebugInstruction() const {
647 for (const Instruction *I = getNextNode(); I; I = I->getNextNode())
648 if (!isa<DbgInfoIntrinsic>(I))
653 const Instruction *Instruction::getPrevNonDebugInstruction() const {
654 for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode())
655 if (!isa<DbgInfoIntrinsic>(I))
660 bool Instruction::isAssociative() const {
661 unsigned Opcode = getOpcode();
662 if (isAssociative(Opcode))
668 return cast<FPMathOperator>(this)->hasAllowReassoc() &&
669 cast<FPMathOperator>(this)->hasNoSignedZeros();
675 unsigned Instruction::getNumSuccessors() const {
676 switch (getOpcode()) {
677 #define HANDLE_TERM_INST(N, OPC, CLASS) \
678 case Instruction::OPC: \
679 return static_cast<const CLASS *>(this)->getNumSuccessors();
680 #include "llvm/IR/Instruction.def"
684 llvm_unreachable("not a terminator");
687 BasicBlock *Instruction::getSuccessor(unsigned idx) const {
688 switch (getOpcode()) {
689 #define HANDLE_TERM_INST(N, OPC, CLASS) \
690 case Instruction::OPC: \
691 return static_cast<const CLASS *>(this)->getSuccessor(idx);
692 #include "llvm/IR/Instruction.def"
696 llvm_unreachable("not a terminator");
699 void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
700 switch (getOpcode()) {
701 #define HANDLE_TERM_INST(N, OPC, CLASS) \
702 case Instruction::OPC: \
703 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
704 #include "llvm/IR/Instruction.def"
708 llvm_unreachable("not a terminator");
711 void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) {
712 for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors();
713 Idx != NumSuccessors; ++Idx)
714 if (getSuccessor(Idx) == OldBB)
715 setSuccessor(Idx, NewBB);
718 Instruction *Instruction::cloneImpl() const {
719 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
722 void Instruction::swapProfMetadata() {
723 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
724 if (!ProfileData || ProfileData->getNumOperands() != 3 ||
725 !isa<MDString>(ProfileData->getOperand(0)))
728 MDString *MDName = cast<MDString>(ProfileData->getOperand(0));
729 if (MDName->getString() != "branch_weights")
732 // The first operand is the name. Fetch them backwards and build a new one.
733 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
734 ProfileData->getOperand(1)};
735 setMetadata(LLVMContext::MD_prof,
736 MDNode::get(ProfileData->getContext(), Ops));
739 void Instruction::copyMetadata(const Instruction &SrcInst,
740 ArrayRef<unsigned> WL) {
741 if (!SrcInst.hasMetadata())
744 DenseSet<unsigned> WLS;
745 for (unsigned M : WL)
748 // Otherwise, enumerate and copy over metadata from the old instruction to the
750 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
751 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
752 for (const auto &MD : TheMDs) {
753 if (WL.empty() || WLS.count(MD.first))
754 setMetadata(MD.first, MD.second);
756 if (WL.empty() || WLS.count(LLVMContext::MD_dbg))
757 setDebugLoc(SrcInst.getDebugLoc());
760 Instruction *Instruction::clone() const {
761 Instruction *New = nullptr;
762 switch (getOpcode()) {
764 llvm_unreachable("Unhandled Opcode.");
765 #define HANDLE_INST(num, opc, clas) \
766 case Instruction::opc: \
767 New = cast<clas>(this)->cloneImpl(); \
769 #include "llvm/IR/Instruction.def"
773 New->SubclassOptionalData = SubclassOptionalData;
774 New->copyMetadata(*this);