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