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::setHasAllowContract(bool B) { 202 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 203 cast<FPMathOperator>(this)->setHasAllowContract(B); 204 } 205 206 void Instruction::setHasApproxFunc(bool B) { 207 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 208 cast<FPMathOperator>(this)->setHasApproxFunc(B); 209 } 210 211 void Instruction::setFastMathFlags(FastMathFlags FMF) { 212 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op"); 213 cast<FPMathOperator>(this)->setFastMathFlags(FMF); 214 } 215 216 void Instruction::copyFastMathFlags(FastMathFlags FMF) { 217 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op"); 218 cast<FPMathOperator>(this)->copyFastMathFlags(FMF); 219 } 220 221 bool Instruction::isFast() const { 222 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 223 return cast<FPMathOperator>(this)->isFast(); 224 } 225 226 bool Instruction::hasAllowReassoc() const { 227 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 228 return cast<FPMathOperator>(this)->hasAllowReassoc(); 229 } 230 231 bool Instruction::hasNoNaNs() const { 232 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 233 return cast<FPMathOperator>(this)->hasNoNaNs(); 234 } 235 236 bool Instruction::hasNoInfs() const { 237 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 238 return cast<FPMathOperator>(this)->hasNoInfs(); 239 } 240 241 bool Instruction::hasNoSignedZeros() const { 242 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 243 return cast<FPMathOperator>(this)->hasNoSignedZeros(); 244 } 245 246 bool Instruction::hasAllowReciprocal() const { 247 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 248 return cast<FPMathOperator>(this)->hasAllowReciprocal(); 249 } 250 251 bool Instruction::hasAllowContract() const { 252 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 253 return cast<FPMathOperator>(this)->hasAllowContract(); 254 } 255 256 bool Instruction::hasApproxFunc() const { 257 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 258 return cast<FPMathOperator>(this)->hasApproxFunc(); 259 } 260 261 FastMathFlags Instruction::getFastMathFlags() const { 262 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"); 263 return cast<FPMathOperator>(this)->getFastMathFlags(); 264 } 265 266 void Instruction::copyFastMathFlags(const Instruction *I) { 267 copyFastMathFlags(I->getFastMathFlags()); 268 } 269 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()); 276 } 277 } 278 279 // Copy the exact flag. 280 if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) 281 if (isa<PossiblyExactOperator>(this)) 282 setIsExact(PE->isExact()); 283 284 // Copy the fast-math flags. 285 if (auto *FP = dyn_cast<FPMathOperator>(V)) 286 if (isa<FPMathOperator>(this)) 287 copyFastMathFlags(FP->getFastMathFlags()); 288 289 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V)) 290 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this)) 291 DestGEP->setIsInBounds(SrcGEP->isInBounds() | DestGEP->isInBounds()); 292 } 293 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()); 299 } 300 } 301 302 if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) 303 if (isa<PossiblyExactOperator>(this)) 304 setIsExact(isExact() & PE->isExact()); 305 306 if (auto *FP = dyn_cast<FPMathOperator>(V)) { 307 if (isa<FPMathOperator>(this)) { 308 FastMathFlags FM = getFastMathFlags(); 309 FM &= FP->getFastMathFlags(); 310 copyFastMathFlags(FM); 311 } 312 } 313 314 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V)) 315 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this)) 316 DestGEP->setIsInBounds(SrcGEP->isInBounds() & DestGEP->isInBounds()); 317 } 318 319 const char *Instruction::getOpcodeName(unsigned OpCode) { 320 switch (OpCode) { 321 // Terminators 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"; 334 335 // Standard unary operators... 336 case FNeg: return "fneg"; 337 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"; 351 352 // Logical operators... 353 case And: return "and"; 354 case Or : return "or"; 355 case Xor: return "xor"; 356 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"; 365 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"; 380 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"; 399 400 default: return "<Invalid operator> "; 401 } 402 } 403 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"); 411 412 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1)) 413 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() && 414 (AI->getAlignment() == cast<AllocaInst>(I2)->getAlignment() || 415 IgnoreAlignment); 416 if (const LoadInst *LI = dyn_cast<LoadInst>(I1)) 417 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() && 418 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() || 419 IgnoreAlignment) && 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() || 425 IgnoreAlignment) && 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(); 467 468 return true; 469 } 470 471 bool Instruction::isIdenticalTo(const Instruction *I) const { 472 return isIdenticalToWhenDefined(I) && 473 SubclassOptionalData == I->SubclassOptionalData; 474 } 475 476 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const { 477 if (getOpcode() != I->getOpcode() || 478 getNumOperands() != I->getNumOperands() || 479 getType() != I->getType()) 480 return false; 481 482 // If both instructions have no operands, they are identical. 483 if (getNumOperands() == 0 && I->getNumOperands() == 0) 484 return haveSameSpecialState(this, I); 485 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())) 489 return false; 490 491 // WARNING: this logic must be kept in sync with EliminateDuplicatePHINodes()! 492 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) { 493 const PHINode *otherPHI = cast<PHINode>(I); 494 return std::equal(thisPHI->block_begin(), thisPHI->block_end(), 495 otherPHI->block_begin()); 496 } 497 498 return haveSameSpecialState(this, I); 499 } 500 501 // Keep this in sync with FunctionComparator::cmpOperations in 502 // lib/Transforms/IPO/MergeFunctions.cpp. 503 bool Instruction::isSameOperationAs(const Instruction *I, 504 unsigned flags) const { 505 bool IgnoreAlignment = flags & CompareIgnoringAlignment; 506 bool UseScalarTypes = flags & CompareUsingScalarTypes; 507 508 if (getOpcode() != I->getOpcode() || 509 getNumOperands() != I->getNumOperands() || 510 (UseScalarTypes ? 511 getType()->getScalarType() != I->getType()->getScalarType() : 512 getType() != I->getType())) 513 return false; 514 515 // We have two instructions of identical opcode and #operands. Check to see 516 // if all operands are the same type 517 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 518 if (UseScalarTypes ? 519 getOperand(i)->getType()->getScalarType() != 520 I->getOperand(i)->getType()->getScalarType() : 521 getOperand(i)->getType() != I->getOperand(i)->getType()) 522 return false; 523 524 return haveSameSpecialState(this, I, IgnoreAlignment); 525 } 526 527 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const { 528 for (const Use &U : uses()) { 529 // PHI nodes uses values in the corresponding predecessor block. For other 530 // instructions, just check to see whether the parent of the use matches up. 531 const Instruction *I = cast<Instruction>(U.getUser()); 532 const PHINode *PN = dyn_cast<PHINode>(I); 533 if (!PN) { 534 if (I->getParent() != BB) 535 return true; 536 continue; 537 } 538 539 if (PN->getIncomingBlock(U) != BB) 540 return true; 541 } 542 return false; 543 } 544 545 bool Instruction::mayReadFromMemory() const { 546 switch (getOpcode()) { 547 default: return false; 548 case Instruction::VAArg: 549 case Instruction::Load: 550 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory 551 case Instruction::AtomicCmpXchg: 552 case Instruction::AtomicRMW: 553 case Instruction::CatchPad: 554 case Instruction::CatchRet: 555 return true; 556 case Instruction::Call: 557 case Instruction::Invoke: 558 case Instruction::CallBr: 559 return !cast<CallBase>(this)->doesNotReadMemory(); 560 case Instruction::Store: 561 return !cast<StoreInst>(this)->isUnordered(); 562 } 563 } 564 565 bool Instruction::mayWriteToMemory() const { 566 switch (getOpcode()) { 567 default: return false; 568 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory 569 case Instruction::Store: 570 case Instruction::VAArg: 571 case Instruction::AtomicCmpXchg: 572 case Instruction::AtomicRMW: 573 case Instruction::CatchPad: 574 case Instruction::CatchRet: 575 return true; 576 case Instruction::Call: 577 case Instruction::Invoke: 578 case Instruction::CallBr: 579 return !cast<CallBase>(this)->onlyReadsMemory(); 580 case Instruction::Load: 581 return !cast<LoadInst>(this)->isUnordered(); 582 } 583 } 584 585 bool Instruction::isAtomic() const { 586 switch (getOpcode()) { 587 default: 588 return false; 589 case Instruction::AtomicCmpXchg: 590 case Instruction::AtomicRMW: 591 case Instruction::Fence: 592 return true; 593 case Instruction::Load: 594 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic; 595 case Instruction::Store: 596 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic; 597 } 598 } 599 600 bool Instruction::hasAtomicLoad() const { 601 assert(isAtomic()); 602 switch (getOpcode()) { 603 default: 604 return false; 605 case Instruction::AtomicCmpXchg: 606 case Instruction::AtomicRMW: 607 case Instruction::Load: 608 return true; 609 } 610 } 611 612 bool Instruction::hasAtomicStore() const { 613 assert(isAtomic()); 614 switch (getOpcode()) { 615 default: 616 return false; 617 case Instruction::AtomicCmpXchg: 618 case Instruction::AtomicRMW: 619 case Instruction::Store: 620 return true; 621 } 622 } 623 624 bool Instruction::mayThrow() const { 625 if (const CallInst *CI = dyn_cast<CallInst>(this)) 626 return !CI->doesNotThrow(); 627 if (const auto *CRI = dyn_cast<CleanupReturnInst>(this)) 628 return CRI->unwindsToCaller(); 629 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this)) 630 return CatchSwitch->unwindsToCaller(); 631 return isa<ResumeInst>(this); 632 } 633 634 bool Instruction::isSafeToRemove() const { 635 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) && 636 !this->isTerminator(); 637 } 638 639 bool Instruction::isLifetimeStartOrEnd() const { 640 auto II = dyn_cast<IntrinsicInst>(this); 641 if (!II) 642 return false; 643 Intrinsic::ID ID = II->getIntrinsicID(); 644 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end; 645 } 646 647 const Instruction *Instruction::getNextNonDebugInstruction() const { 648 for (const Instruction *I = getNextNode(); I; I = I->getNextNode()) 649 if (!isa<DbgInfoIntrinsic>(I)) 650 return I; 651 return nullptr; 652 } 653 654 const Instruction *Instruction::getPrevNonDebugInstruction() const { 655 for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode()) 656 if (!isa<DbgInfoIntrinsic>(I)) 657 return I; 658 return nullptr; 659 } 660 661 bool Instruction::isAssociative() const { 662 unsigned Opcode = getOpcode(); 663 if (isAssociative(Opcode)) 664 return true; 665 666 switch (Opcode) { 667 case FMul: 668 case FAdd: 669 return cast<FPMathOperator>(this)->hasAllowReassoc() && 670 cast<FPMathOperator>(this)->hasNoSignedZeros(); 671 default: 672 return false; 673 } 674 } 675 676 bool Instruction::isCommutative() const { 677 if (auto *II = dyn_cast<IntrinsicInst>(this)) 678 return II->isCommutative(); 679 // TODO: Should allow icmp/fcmp? 680 return isCommutative(getOpcode()); 681 } 682 683 unsigned Instruction::getNumSuccessors() const { 684 switch (getOpcode()) { 685 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 686 case Instruction::OPC: \ 687 return static_cast<const CLASS *>(this)->getNumSuccessors(); 688 #include "llvm/IR/Instruction.def" 689 default: 690 break; 691 } 692 llvm_unreachable("not a terminator"); 693 } 694 695 BasicBlock *Instruction::getSuccessor(unsigned idx) const { 696 switch (getOpcode()) { 697 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 698 case Instruction::OPC: \ 699 return static_cast<const CLASS *>(this)->getSuccessor(idx); 700 #include "llvm/IR/Instruction.def" 701 default: 702 break; 703 } 704 llvm_unreachable("not a terminator"); 705 } 706 707 void Instruction::setSuccessor(unsigned idx, BasicBlock *B) { 708 switch (getOpcode()) { 709 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 710 case Instruction::OPC: \ 711 return static_cast<CLASS *>(this)->setSuccessor(idx, B); 712 #include "llvm/IR/Instruction.def" 713 default: 714 break; 715 } 716 llvm_unreachable("not a terminator"); 717 } 718 719 void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) { 720 for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors(); 721 Idx != NumSuccessors; ++Idx) 722 if (getSuccessor(Idx) == OldBB) 723 setSuccessor(Idx, NewBB); 724 } 725 726 Instruction *Instruction::cloneImpl() const { 727 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl"); 728 } 729 730 void Instruction::swapProfMetadata() { 731 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof); 732 if (!ProfileData || ProfileData->getNumOperands() != 3 || 733 !isa<MDString>(ProfileData->getOperand(0))) 734 return; 735 736 MDString *MDName = cast<MDString>(ProfileData->getOperand(0)); 737 if (MDName->getString() != "branch_weights") 738 return; 739 740 // The first operand is the name. Fetch them backwards and build a new one. 741 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2), 742 ProfileData->getOperand(1)}; 743 setMetadata(LLVMContext::MD_prof, 744 MDNode::get(ProfileData->getContext(), Ops)); 745 } 746 747 void Instruction::copyMetadata(const Instruction &SrcInst, 748 ArrayRef<unsigned> WL) { 749 if (!SrcInst.hasMetadata()) 750 return; 751 752 DenseSet<unsigned> WLS; 753 for (unsigned M : WL) 754 WLS.insert(M); 755 756 // Otherwise, enumerate and copy over metadata from the old instruction to the 757 // new one. 758 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs; 759 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs); 760 for (const auto &MD : TheMDs) { 761 if (WL.empty() || WLS.count(MD.first)) 762 setMetadata(MD.first, MD.second); 763 } 764 if (WL.empty() || WLS.count(LLVMContext::MD_dbg)) 765 setDebugLoc(SrcInst.getDebugLoc()); 766 } 767 768 Instruction *Instruction::clone() const { 769 Instruction *New = nullptr; 770 switch (getOpcode()) { 771 default: 772 llvm_unreachable("Unhandled Opcode."); 773 #define HANDLE_INST(num, opc, clas) \ 774 case Instruction::opc: \ 775 New = cast<clas>(this)->cloneImpl(); \ 776 break; 777 #include "llvm/IR/Instruction.def" 778 #undef HANDLE_INST 779 } 780 781 New->SubclassOptionalData = SubclassOptionalData; 782 New->copyMetadata(*this); 783 return New; 784 } 785