1 //===-- Instruction.cpp - Implement the Instruction class -----------------===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Instruction class for the IR library. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Instruction.h" 14 #include "llvm/ADT/DenseSet.h" 15 #include "llvm/IR/Constants.h" 16 #include "llvm/IR/Instructions.h" 17 #include "llvm/IR/IntrinsicInst.h" 18 #include "llvm/IR/Intrinsics.h" 19 #include "llvm/IR/MDBuilder.h" 20 #include "llvm/IR/Operator.h" 21 #include "llvm/IR/Type.h" 22 using namespace llvm; 23 24 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps, 25 Instruction *InsertBefore) 26 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) { 27 28 // If requested, insert this instruction into a basic block... 29 if (InsertBefore) { 30 BasicBlock *BB = InsertBefore->getParent(); 31 assert(BB && "Instruction to insert before is not in a basic block!"); 32 BB->getInstList().insert(InsertBefore->getIterator(), this); 33 } 34 } 35 36 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps, 37 BasicBlock *InsertAtEnd) 38 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) { 39 40 // append this instruction into the basic block 41 assert(InsertAtEnd && "Basic block to append to may not be NULL!"); 42 InsertAtEnd->getInstList().push_back(this); 43 } 44 45 Instruction::~Instruction() { 46 assert(!Parent && "Instruction still linked in the program!"); 47 48 // Replace any extant metadata uses of this instruction with undef to 49 // preserve debug info accuracy. Some alternatives include: 50 // - Treat Instruction like any other Value, and point its extant metadata 51 // uses to an empty ValueAsMetadata node. This makes extant dbg.value uses 52 // trivially dead (i.e. fair game for deletion in many passes), leading to 53 // stale dbg.values being in effect for too long. 54 // - Call salvageDebugInfoOrMarkUndef. Not needed to make instruction removal 55 // correct. OTOH results in wasted work in some common cases (e.g. when all 56 // instructions in a BasicBlock are deleted). 57 if (isUsedByMetadata()) 58 ValueAsMetadata::handleRAUW(this, UndefValue::get(getType())); 59 } 60 61 62 void Instruction::setParent(BasicBlock *P) { 63 Parent = P; 64 } 65 66 const Module *Instruction::getModule() const { 67 return getParent()->getModule(); 68 } 69 70 const Function *Instruction::getFunction() const { 71 return getParent()->getParent(); 72 } 73 74 void Instruction::removeFromParent() { 75 getParent()->getInstList().remove(getIterator()); 76 } 77 78 iplist<Instruction>::iterator Instruction::eraseFromParent() { 79 return getParent()->getInstList().erase(getIterator()); 80 } 81 82 /// Insert an unlinked instruction into a basic block immediately before the 83 /// specified instruction. 84 void Instruction::insertBefore(Instruction *InsertPos) { 85 InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this); 86 } 87 88 /// Insert an unlinked instruction into a basic block immediately after the 89 /// specified instruction. 90 void Instruction::insertAfter(Instruction *InsertPos) { 91 InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(), 92 this); 93 } 94 95 /// Unlink this instruction from its current basic block and insert it into the 96 /// basic block that MovePos lives in, right before MovePos. 97 void Instruction::moveBefore(Instruction *MovePos) { 98 moveBefore(*MovePos->getParent(), MovePos->getIterator()); 99 } 100 101 void Instruction::moveAfter(Instruction *MovePos) { 102 moveBefore(*MovePos->getParent(), ++MovePos->getIterator()); 103 } 104 105 void Instruction::moveBefore(BasicBlock &BB, 106 SymbolTableList<Instruction>::iterator I) { 107 assert(I == BB.end() || I->getParent() == &BB); 108 BB.getInstList().splice(I, getParent()->getInstList(), getIterator()); 109 } 110 111 bool Instruction::comesBefore(const Instruction *Other) const { 112 assert(Parent && Other->Parent && 113 "instructions without BB parents have no order"); 114 assert(Parent == Other->Parent && "cross-BB instruction order comparison"); 115 if (!Parent->isInstrOrderValid()) 116 Parent->renumberInstructions(); 117 return Order < Other->Order; 118 } 119 120 bool Instruction::isOnlyUserOfAnyOperand() { 121 return any_of(operands(), [](Value *V) { return V->hasOneUser(); }); 122 } 123 124 void Instruction::setHasNoUnsignedWrap(bool b) { 125 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b); 126 } 127 128 void Instruction::setHasNoSignedWrap(bool b) { 129 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b); 130 } 131 132 void Instruction::setIsExact(bool b) { 133 cast<PossiblyExactOperator>(this)->setIsExact(b); 134 } 135 136 bool Instruction::hasNoUnsignedWrap() const { 137 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap(); 138 } 139 140 bool Instruction::hasNoSignedWrap() const { 141 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap(); 142 } 143 144 void Instruction::dropPoisonGeneratingFlags() { 145 switch (getOpcode()) { 146 case Instruction::Add: 147 case Instruction::Sub: 148 case Instruction::Mul: 149 case Instruction::Shl: 150 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false); 151 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false); 152 break; 153 154 case Instruction::UDiv: 155 case Instruction::SDiv: 156 case Instruction::AShr: 157 case Instruction::LShr: 158 cast<PossiblyExactOperator>(this)->setIsExact(false); 159 break; 160 161 case Instruction::GetElementPtr: 162 cast<GetElementPtrInst>(this)->setIsInBounds(false); 163 break; 164 } 165 // TODO: FastMathFlags! 166 } 167 168 169 bool Instruction::isExact() const { 170 return cast<PossiblyExactOperator>(this)->isExact(); 171 } 172 173 void Instruction::setFast(bool B) { 174 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 175 cast<FPMathOperator>(this)->setFast(B); 176 } 177 178 void Instruction::setHasAllowReassoc(bool B) { 179 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 180 cast<FPMathOperator>(this)->setHasAllowReassoc(B); 181 } 182 183 void Instruction::setHasNoNaNs(bool B) { 184 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 185 cast<FPMathOperator>(this)->setHasNoNaNs(B); 186 } 187 188 void Instruction::setHasNoInfs(bool B) { 189 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 190 cast<FPMathOperator>(this)->setHasNoInfs(B); 191 } 192 193 void Instruction::setHasNoSignedZeros(bool B) { 194 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 195 cast<FPMathOperator>(this)->setHasNoSignedZeros(B); 196 } 197 198 void Instruction::setHasAllowReciprocal(bool B) { 199 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 200 cast<FPMathOperator>(this)->setHasAllowReciprocal(B); 201 } 202 203 void Instruction::setHasAllowContract(bool B) { 204 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 205 cast<FPMathOperator>(this)->setHasAllowContract(B); 206 } 207 208 void Instruction::setHasApproxFunc(bool B) { 209 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 210 cast<FPMathOperator>(this)->setHasApproxFunc(B); 211 } 212 213 void Instruction::setFastMathFlags(FastMathFlags FMF) { 214 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 215 cast<FPMathOperator>(this)->setFastMathFlags(FMF); 216 } 217 218 void Instruction::copyFastMathFlags(FastMathFlags FMF) { 219 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op"); 220 cast<FPMathOperator>(this)->copyFastMathFlags(FMF); 221 } 222 223 bool Instruction::isFast() const { 224 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 225 return cast<FPMathOperator>(this)->isFast(); 226 } 227 228 bool Instruction::hasAllowReassoc() const { 229 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 230 return cast<FPMathOperator>(this)->hasAllowReassoc(); 231 } 232 233 bool Instruction::hasNoNaNs() const { 234 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 235 return cast<FPMathOperator>(this)->hasNoNaNs(); 236 } 237 238 bool Instruction::hasNoInfs() const { 239 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 240 return cast<FPMathOperator>(this)->hasNoInfs(); 241 } 242 243 bool Instruction::hasNoSignedZeros() const { 244 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 245 return cast<FPMathOperator>(this)->hasNoSignedZeros(); 246 } 247 248 bool Instruction::hasAllowReciprocal() const { 249 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 250 return cast<FPMathOperator>(this)->hasAllowReciprocal(); 251 } 252 253 bool Instruction::hasAllowContract() const { 254 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 255 return cast<FPMathOperator>(this)->hasAllowContract(); 256 } 257 258 bool Instruction::hasApproxFunc() const { 259 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 260 return cast<FPMathOperator>(this)->hasApproxFunc(); 261 } 262 263 FastMathFlags Instruction::getFastMathFlags() const { 264 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 265 return cast<FPMathOperator>(this)->getFastMathFlags(); 266 } 267 268 void Instruction::copyFastMathFlags(const Instruction *I) { 269 copyFastMathFlags(I->getFastMathFlags()); 270 } 271 272 void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) { 273 // Copy the wrapping flags. 274 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) { 275 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) { 276 setHasNoSignedWrap(OB->hasNoSignedWrap()); 277 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap()); 278 } 279 } 280 281 // Copy the exact flag. 282 if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) 283 if (isa<PossiblyExactOperator>(this)) 284 setIsExact(PE->isExact()); 285 286 // Copy the fast-math flags. 287 if (auto *FP = dyn_cast<FPMathOperator>(V)) 288 if (isa<FPMathOperator>(this)) 289 copyFastMathFlags(FP->getFastMathFlags()); 290 291 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V)) 292 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this)) 293 DestGEP->setIsInBounds(SrcGEP->isInBounds() | DestGEP->isInBounds()); 294 } 295 296 void Instruction::andIRFlags(const Value *V) { 297 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) { 298 if (isa<OverflowingBinaryOperator>(this)) { 299 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap()); 300 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap()); 301 } 302 } 303 304 if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) 305 if (isa<PossiblyExactOperator>(this)) 306 setIsExact(isExact() & PE->isExact()); 307 308 if (auto *FP = dyn_cast<FPMathOperator>(V)) { 309 if (isa<FPMathOperator>(this)) { 310 FastMathFlags FM = getFastMathFlags(); 311 FM &= FP->getFastMathFlags(); 312 copyFastMathFlags(FM); 313 } 314 } 315 316 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V)) 317 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this)) 318 DestGEP->setIsInBounds(SrcGEP->isInBounds() & DestGEP->isInBounds()); 319 } 320 321 const char *Instruction::getOpcodeName(unsigned OpCode) { 322 switch (OpCode) { 323 // Terminators 324 case Ret: return "ret"; 325 case Br: return "br"; 326 case Switch: return "switch"; 327 case IndirectBr: return "indirectbr"; 328 case Invoke: return "invoke"; 329 case Resume: return "resume"; 330 case Unreachable: return "unreachable"; 331 case CleanupRet: return "cleanupret"; 332 case CatchRet: return "catchret"; 333 case CatchPad: return "catchpad"; 334 case CatchSwitch: return "catchswitch"; 335 case CallBr: return "callbr"; 336 337 // Standard unary operators... 338 case FNeg: return "fneg"; 339 340 // Standard binary operators... 341 case Add: return "add"; 342 case FAdd: return "fadd"; 343 case Sub: return "sub"; 344 case FSub: return "fsub"; 345 case Mul: return "mul"; 346 case FMul: return "fmul"; 347 case UDiv: return "udiv"; 348 case SDiv: return "sdiv"; 349 case FDiv: return "fdiv"; 350 case URem: return "urem"; 351 case SRem: return "srem"; 352 case FRem: return "frem"; 353 354 // Logical operators... 355 case And: return "and"; 356 case Or : return "or"; 357 case Xor: return "xor"; 358 359 // Memory instructions... 360 case Alloca: return "alloca"; 361 case Load: return "load"; 362 case Store: return "store"; 363 case AtomicCmpXchg: return "cmpxchg"; 364 case AtomicRMW: return "atomicrmw"; 365 case Fence: return "fence"; 366 case GetElementPtr: return "getelementptr"; 367 368 // Convert instructions... 369 case Trunc: return "trunc"; 370 case ZExt: return "zext"; 371 case SExt: return "sext"; 372 case FPTrunc: return "fptrunc"; 373 case FPExt: return "fpext"; 374 case FPToUI: return "fptoui"; 375 case FPToSI: return "fptosi"; 376 case UIToFP: return "uitofp"; 377 case SIToFP: return "sitofp"; 378 case IntToPtr: return "inttoptr"; 379 case PtrToInt: return "ptrtoint"; 380 case BitCast: return "bitcast"; 381 case AddrSpaceCast: return "addrspacecast"; 382 383 // Other instructions... 384 case ICmp: return "icmp"; 385 case FCmp: return "fcmp"; 386 case PHI: return "phi"; 387 case Select: return "select"; 388 case Call: return "call"; 389 case Shl: return "shl"; 390 case LShr: return "lshr"; 391 case AShr: return "ashr"; 392 case VAArg: return "va_arg"; 393 case ExtractElement: return "extractelement"; 394 case InsertElement: return "insertelement"; 395 case ShuffleVector: return "shufflevector"; 396 case ExtractValue: return "extractvalue"; 397 case InsertValue: return "insertvalue"; 398 case LandingPad: return "landingpad"; 399 case CleanupPad: return "cleanuppad"; 400 case Freeze: return "freeze"; 401 402 default: return "<Invalid operator> "; 403 } 404 } 405 406 /// Return true if both instructions have the same special state. This must be 407 /// kept in sync with FunctionComparator::cmpOperations in 408 /// lib/Transforms/IPO/MergeFunctions.cpp. 409 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2, 410 bool IgnoreAlignment = false) { 411 assert(I1->getOpcode() == I2->getOpcode() && 412 "Can not compare special state of different instructions"); 413 414 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1)) 415 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() && 416 (AI->getAlignment() == cast<AllocaInst>(I2)->getAlignment() || 417 IgnoreAlignment); 418 if (const LoadInst *LI = dyn_cast<LoadInst>(I1)) 419 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() && 420 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() || 421 IgnoreAlignment) && 422 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() && 423 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID(); 424 if (const StoreInst *SI = dyn_cast<StoreInst>(I1)) 425 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() && 426 (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() || 427 IgnoreAlignment) && 428 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() && 429 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID(); 430 if (const CmpInst *CI = dyn_cast<CmpInst>(I1)) 431 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate(); 432 if (const CallInst *CI = dyn_cast<CallInst>(I1)) 433 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() && 434 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() && 435 CI->getAttributes() == cast<CallInst>(I2)->getAttributes() && 436 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2)); 437 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1)) 438 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() && 439 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() && 440 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2)); 441 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1)) 442 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() && 443 CI->getAttributes() == cast<CallBrInst>(I2)->getAttributes() && 444 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2)); 445 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) 446 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices(); 447 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) 448 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices(); 449 if (const FenceInst *FI = dyn_cast<FenceInst>(I1)) 450 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() && 451 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID(); 452 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1)) 453 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() && 454 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() && 455 CXI->getSuccessOrdering() == 456 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() && 457 CXI->getFailureOrdering() == 458 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() && 459 CXI->getSyncScopeID() == 460 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID(); 461 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1)) 462 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() && 463 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() && 464 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() && 465 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID(); 466 if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I1)) 467 return SVI->getShuffleMask() == 468 cast<ShuffleVectorInst>(I2)->getShuffleMask(); 469 470 return true; 471 } 472 473 bool Instruction::isIdenticalTo(const Instruction *I) const { 474 return isIdenticalToWhenDefined(I) && 475 SubclassOptionalData == I->SubclassOptionalData; 476 } 477 478 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const { 479 if (getOpcode() != I->getOpcode() || 480 getNumOperands() != I->getNumOperands() || 481 getType() != I->getType()) 482 return false; 483 484 // If both instructions have no operands, they are identical. 485 if (getNumOperands() == 0 && I->getNumOperands() == 0) 486 return haveSameSpecialState(this, I); 487 488 // We have two instructions of identical opcode and #operands. Check to see 489 // if all operands are the same. 490 if (!std::equal(op_begin(), op_end(), I->op_begin())) 491 return false; 492 493 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()! 494 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) { 495 const PHINode *otherPHI = cast<PHINode>(I); 496 return std::equal(thisPHI->block_begin(), thisPHI->block_end(), 497 otherPHI->block_begin()); 498 } 499 500 return haveSameSpecialState(this, I); 501 } 502 503 // Keep this in sync with FunctionComparator::cmpOperations in 504 // lib/Transforms/IPO/MergeFunctions.cpp. 505 bool Instruction::isSameOperationAs(const Instruction *I, 506 unsigned flags) const { 507 bool IgnoreAlignment = flags & CompareIgnoringAlignment; 508 bool UseScalarTypes = flags & CompareUsingScalarTypes; 509 510 if (getOpcode() != I->getOpcode() || 511 getNumOperands() != I->getNumOperands() || 512 (UseScalarTypes ? 513 getType()->getScalarType() != I->getType()->getScalarType() : 514 getType() != I->getType())) 515 return false; 516 517 // We have two instructions of identical opcode and #operands. Check to see 518 // if all operands are the same type 519 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 520 if (UseScalarTypes ? 521 getOperand(i)->getType()->getScalarType() != 522 I->getOperand(i)->getType()->getScalarType() : 523 getOperand(i)->getType() != I->getOperand(i)->getType()) 524 return false; 525 526 return haveSameSpecialState(this, I, IgnoreAlignment); 527 } 528 529 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const { 530 for (const Use &U : uses()) { 531 // PHI nodes uses values in the corresponding predecessor block. For other 532 // instructions, just check to see whether the parent of the use matches up. 533 const Instruction *I = cast<Instruction>(U.getUser()); 534 const PHINode *PN = dyn_cast<PHINode>(I); 535 if (!PN) { 536 if (I->getParent() != BB) 537 return true; 538 continue; 539 } 540 541 if (PN->getIncomingBlock(U) != BB) 542 return true; 543 } 544 return false; 545 } 546 547 bool Instruction::mayReadFromMemory() const { 548 switch (getOpcode()) { 549 default: return false; 550 case Instruction::VAArg: 551 case Instruction::Load: 552 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory 553 case Instruction::AtomicCmpXchg: 554 case Instruction::AtomicRMW: 555 case Instruction::CatchPad: 556 case Instruction::CatchRet: 557 return true; 558 case Instruction::Call: 559 case Instruction::Invoke: 560 case Instruction::CallBr: 561 return !cast<CallBase>(this)->doesNotReadMemory(); 562 case Instruction::Store: 563 return !cast<StoreInst>(this)->isUnordered(); 564 } 565 } 566 567 bool Instruction::mayWriteToMemory() const { 568 switch (getOpcode()) { 569 default: return false; 570 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory 571 case Instruction::Store: 572 case Instruction::VAArg: 573 case Instruction::AtomicCmpXchg: 574 case Instruction::AtomicRMW: 575 case Instruction::CatchPad: 576 case Instruction::CatchRet: 577 return true; 578 case Instruction::Call: 579 case Instruction::Invoke: 580 case Instruction::CallBr: 581 return !cast<CallBase>(this)->onlyReadsMemory(); 582 case Instruction::Load: 583 return !cast<LoadInst>(this)->isUnordered(); 584 } 585 } 586 587 bool Instruction::isAtomic() const { 588 switch (getOpcode()) { 589 default: 590 return false; 591 case Instruction::AtomicCmpXchg: 592 case Instruction::AtomicRMW: 593 case Instruction::Fence: 594 return true; 595 case Instruction::Load: 596 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic; 597 case Instruction::Store: 598 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic; 599 } 600 } 601 602 bool Instruction::hasAtomicLoad() const { 603 assert(isAtomic()); 604 switch (getOpcode()) { 605 default: 606 return false; 607 case Instruction::AtomicCmpXchg: 608 case Instruction::AtomicRMW: 609 case Instruction::Load: 610 return true; 611 } 612 } 613 614 bool Instruction::hasAtomicStore() const { 615 assert(isAtomic()); 616 switch (getOpcode()) { 617 default: 618 return false; 619 case Instruction::AtomicCmpXchg: 620 case Instruction::AtomicRMW: 621 case Instruction::Store: 622 return true; 623 } 624 } 625 626 bool Instruction::isVolatile() const { 627 switch (getOpcode()) { 628 default: 629 return false; 630 case Instruction::AtomicRMW: 631 return cast<AtomicRMWInst>(this)->isVolatile(); 632 case Instruction::Store: 633 return cast<StoreInst>(this)->isVolatile(); 634 case Instruction::Load: 635 return cast<LoadInst>(this)->isVolatile(); 636 case Instruction::AtomicCmpXchg: 637 return cast<AtomicCmpXchgInst>(this)->isVolatile(); 638 case Instruction::Call: 639 case Instruction::Invoke: 640 // There are a very limited number of intrinsics with volatile flags. 641 if (auto *II = dyn_cast<IntrinsicInst>(this)) { 642 if (auto *MI = dyn_cast<MemIntrinsic>(II)) 643 return MI->isVolatile(); 644 switch (II->getIntrinsicID()) { 645 default: break; 646 case Intrinsic::matrix_column_major_load: 647 return cast<ConstantInt>(II->getArgOperand(2))->isOne(); 648 case Intrinsic::matrix_column_major_store: 649 return cast<ConstantInt>(II->getArgOperand(3))->isOne(); 650 } 651 } 652 return false; 653 } 654 } 655 656 bool Instruction::mayThrow() const { 657 if (const CallInst *CI = dyn_cast<CallInst>(this)) 658 return !CI->doesNotThrow(); 659 if (const auto *CRI = dyn_cast<CleanupReturnInst>(this)) 660 return CRI->unwindsToCaller(); 661 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this)) 662 return CatchSwitch->unwindsToCaller(); 663 return isa<ResumeInst>(this); 664 } 665 666 bool Instruction::isSafeToRemove() const { 667 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) && 668 !this->isTerminator(); 669 } 670 671 bool Instruction::willReturn() const { 672 if (const auto *CB = dyn_cast<CallBase>(this)) 673 // FIXME: Temporarily assume that all side-effect free intrinsics will 674 // return. Remove this workaround once all intrinsics are appropriately 675 // annotated. 676 return CB->hasFnAttr(Attribute::WillReturn) || 677 (isa<IntrinsicInst>(CB) && CB->onlyReadsMemory()); 678 return true; 679 } 680 681 bool Instruction::isLifetimeStartOrEnd() const { 682 auto *II = dyn_cast<IntrinsicInst>(this); 683 if (!II) 684 return false; 685 Intrinsic::ID ID = II->getIntrinsicID(); 686 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end; 687 } 688 689 bool Instruction::isLaunderOrStripInvariantGroup() const { 690 auto *II = dyn_cast<IntrinsicInst>(this); 691 if (!II) 692 return false; 693 Intrinsic::ID ID = II->getIntrinsicID(); 694 return ID == Intrinsic::launder_invariant_group || 695 ID == Intrinsic::strip_invariant_group; 696 } 697 698 bool Instruction::isDebugOrPseudoInst() const { 699 return isa<DbgInfoIntrinsic>(this) || isa<PseudoProbeInst>(this); 700 } 701 702 const Instruction * 703 Instruction::getNextNonDebugInstruction(bool SkipPseudoOp) const { 704 for (const Instruction *I = getNextNode(); I; I = I->getNextNode()) 705 if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I))) 706 return I; 707 return nullptr; 708 } 709 710 const Instruction * 711 Instruction::getPrevNonDebugInstruction(bool SkipPseudoOp) const { 712 for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode()) 713 if (!isa<DbgInfoIntrinsic>(I) && !(SkipPseudoOp && isa<PseudoProbeInst>(I))) 714 return I; 715 return nullptr; 716 } 717 718 bool Instruction::isAssociative() const { 719 unsigned Opcode = getOpcode(); 720 if (isAssociative(Opcode)) 721 return true; 722 723 switch (Opcode) { 724 case FMul: 725 case FAdd: 726 return cast<FPMathOperator>(this)->hasAllowReassoc() && 727 cast<FPMathOperator>(this)->hasNoSignedZeros(); 728 default: 729 return false; 730 } 731 } 732 733 bool Instruction::isCommutative() const { 734 if (auto *II = dyn_cast<IntrinsicInst>(this)) 735 return II->isCommutative(); 736 // TODO: Should allow icmp/fcmp? 737 return isCommutative(getOpcode()); 738 } 739 740 unsigned Instruction::getNumSuccessors() const { 741 switch (getOpcode()) { 742 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 743 case Instruction::OPC: \ 744 return static_cast<const CLASS *>(this)->getNumSuccessors(); 745 #include "llvm/IR/Instruction.def" 746 default: 747 break; 748 } 749 llvm_unreachable("not a terminator"); 750 } 751 752 BasicBlock *Instruction::getSuccessor(unsigned idx) const { 753 switch (getOpcode()) { 754 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 755 case Instruction::OPC: \ 756 return static_cast<const CLASS *>(this)->getSuccessor(idx); 757 #include "llvm/IR/Instruction.def" 758 default: 759 break; 760 } 761 llvm_unreachable("not a terminator"); 762 } 763 764 void Instruction::setSuccessor(unsigned idx, BasicBlock *B) { 765 switch (getOpcode()) { 766 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 767 case Instruction::OPC: \ 768 return static_cast<CLASS *>(this)->setSuccessor(idx, B); 769 #include "llvm/IR/Instruction.def" 770 default: 771 break; 772 } 773 llvm_unreachable("not a terminator"); 774 } 775 776 void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) { 777 for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors(); 778 Idx != NumSuccessors; ++Idx) 779 if (getSuccessor(Idx) == OldBB) 780 setSuccessor(Idx, NewBB); 781 } 782 783 Instruction *Instruction::cloneImpl() const { 784 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl"); 785 } 786 787 void Instruction::swapProfMetadata() { 788 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof); 789 if (!ProfileData || ProfileData->getNumOperands() != 3 || 790 !isa<MDString>(ProfileData->getOperand(0))) 791 return; 792 793 MDString *MDName = cast<MDString>(ProfileData->getOperand(0)); 794 if (MDName->getString() != "branch_weights") 795 return; 796 797 // The first operand is the name. Fetch them backwards and build a new one. 798 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2), 799 ProfileData->getOperand(1)}; 800 setMetadata(LLVMContext::MD_prof, 801 MDNode::get(ProfileData->getContext(), Ops)); 802 } 803 804 void Instruction::copyMetadata(const Instruction &SrcInst, 805 ArrayRef<unsigned> WL) { 806 if (!SrcInst.hasMetadata()) 807 return; 808 809 DenseSet<unsigned> WLS; 810 for (unsigned M : WL) 811 WLS.insert(M); 812 813 // Otherwise, enumerate and copy over metadata from the old instruction to the 814 // new one. 815 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs; 816 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs); 817 for (const auto &MD : TheMDs) { 818 if (WL.empty() || WLS.count(MD.first)) 819 setMetadata(MD.first, MD.second); 820 } 821 if (WL.empty() || WLS.count(LLVMContext::MD_dbg)) 822 setDebugLoc(SrcInst.getDebugLoc()); 823 } 824 825 Instruction *Instruction::clone() const { 826 Instruction *New = nullptr; 827 switch (getOpcode()) { 828 default: 829 llvm_unreachable("Unhandled Opcode."); 830 #define HANDLE_INST(num, opc, clas) \ 831 case Instruction::opc: \ 832 New = cast<clas>(this)->cloneImpl(); \ 833 break; 834 #include "llvm/IR/Instruction.def" 835 #undef HANDLE_INST 836 } 837 838 New->SubclassOptionalData = SubclassOptionalData; 839 New->copyMetadata(*this); 840 return New; 841 } 842