Instruction.cpp 26 KB

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