1 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===// 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 contains the declaration of the Instruction class, which is the 10 // base class for all of the LLVM instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_IR_INSTRUCTION_H 15 #define LLVM_IR_INSTRUCTION_H 16 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/Bitfields.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/ilist_node.h" 22 #include "llvm/IR/DebugLoc.h" 23 #include "llvm/IR/SymbolTableListTraits.h" 24 #include "llvm/IR/User.h" 25 #include "llvm/IR/Value.h" 26 #include "llvm/Support/AtomicOrdering.h" 27 #include <cstdint> 28 #include <utility> 29 30 namespace llvm { 31 32 class BasicBlock; 33 class FastMathFlags; 34 class MDNode; 35 class Module; 36 struct AAMDNodes; 37 38 template <> struct ilist_alloc_traits<Instruction> { 39 static inline void deleteNode(Instruction *V); 40 }; 41 42 class Instruction : public User, 43 public ilist_node_with_parent<Instruction, BasicBlock> { 44 BasicBlock *Parent; 45 DebugLoc DbgLoc; // 'dbg' Metadata cache. 46 47 /// Relative order of this instruction in its parent basic block. Used for 48 /// O(1) local dominance checks between instructions. 49 mutable unsigned Order = 0; 50 51 protected: 52 // The 15 first bits of `Value::SubclassData` are available for subclasses of 53 // `Instruction` to use. 54 using OpaqueField = Bitfield::Element<uint16_t, 0, 15>; 55 56 // Template alias so that all Instruction storing alignment use the same 57 // definiton. 58 // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent = 59 // 2^32. We store them as Log2(Alignment), so we need 6 bits to encode the 33 60 // possible values. 61 template <unsigned Offset> 62 using AlignmentBitfieldElementT = 63 typename Bitfield::Element<unsigned, Offset, 6, 64 Value::MaxAlignmentExponent>; 65 66 template <unsigned Offset> 67 using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>; 68 69 template <unsigned Offset> 70 using AtomicOrderingBitfieldElementT = 71 typename Bitfield::Element<AtomicOrdering, Offset, 3, 72 AtomicOrdering::LAST>; 73 74 private: 75 // The last bit is used to store whether the instruction has metadata attached 76 // or not. 77 using HasMetadataField = Bitfield::Element<bool, 15, 1>; 78 79 protected: 80 ~Instruction(); // Use deleteValue() to delete a generic Instruction. 81 82 public: 83 Instruction(const Instruction &) = delete; 84 Instruction &operator=(const Instruction &) = delete; 85 86 /// Specialize the methods defined in Value, as we know that an instruction 87 /// can only be used by other instructions. 88 Instruction *user_back() { return cast<Instruction>(*user_begin());} 89 const Instruction *user_back() const { return cast<Instruction>(*user_begin());} 90 91 inline const BasicBlock *getParent() const { return Parent; } 92 inline BasicBlock *getParent() { return Parent; } 93 94 /// Return the module owning the function this instruction belongs to 95 /// or nullptr it the function does not have a module. 96 /// 97 /// Note: this is undefined behavior if the instruction does not have a 98 /// parent, or the parent basic block does not have a parent function. 99 const Module *getModule() const; 100 Module *getModule() { 101 return const_cast<Module *>( 102 static_cast<const Instruction *>(this)->getModule()); 103 } 104 105 /// Return the function this instruction belongs to. 106 /// 107 /// Note: it is undefined behavior to call this on an instruction not 108 /// currently inserted into a function. 109 const Function *getFunction() const; 110 Function *getFunction() { 111 return const_cast<Function *>( 112 static_cast<const Instruction *>(this)->getFunction()); 113 } 114 115 /// This method unlinks 'this' from the containing basic block, but does not 116 /// delete it. 117 void removeFromParent(); 118 119 /// This method unlinks 'this' from the containing basic block and deletes it. 120 /// 121 /// \returns an iterator pointing to the element after the erased one 122 SymbolTableList<Instruction>::iterator eraseFromParent(); 123 124 /// Insert an unlinked instruction into a basic block immediately before 125 /// the specified instruction. 126 void insertBefore(Instruction *InsertPos); 127 128 /// Insert an unlinked instruction into a basic block immediately after the 129 /// specified instruction. 130 void insertAfter(Instruction *InsertPos); 131 132 /// Unlink this instruction from its current basic block and insert it into 133 /// the basic block that MovePos lives in, right before MovePos. 134 void moveBefore(Instruction *MovePos); 135 136 /// Unlink this instruction and insert into BB before I. 137 /// 138 /// \pre I is a valid iterator into BB. 139 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I); 140 141 /// Unlink this instruction from its current basic block and insert it into 142 /// the basic block that MovePos lives in, right after MovePos. 143 void moveAfter(Instruction *MovePos); 144 145 /// Given an instruction Other in the same basic block as this instruction, 146 /// return true if this instruction comes before Other. In this worst case, 147 /// this takes linear time in the number of instructions in the block. The 148 /// results are cached, so in common cases when the block remains unmodified, 149 /// it takes constant time. 150 bool comesBefore(const Instruction *Other) const; 151 152 //===--------------------------------------------------------------------===// 153 // Subclass classification. 154 //===--------------------------------------------------------------------===// 155 156 /// Returns a member of one of the enums like Instruction::Add. 157 unsigned getOpcode() const { return getValueID() - InstructionVal; } 158 159 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); } 160 bool isTerminator() const { return isTerminator(getOpcode()); } 161 bool isUnaryOp() const { return isUnaryOp(getOpcode()); } 162 bool isBinaryOp() const { return isBinaryOp(getOpcode()); } 163 bool isIntDivRem() const { return isIntDivRem(getOpcode()); } 164 bool isShift() const { return isShift(getOpcode()); } 165 bool isCast() const { return isCast(getOpcode()); } 166 bool isFuncletPad() const { return isFuncletPad(getOpcode()); } 167 bool isExceptionalTerminator() const { 168 return isExceptionalTerminator(getOpcode()); 169 } 170 171 /// It checks if this instruction is the only user of at least one of 172 /// its operands. 173 bool isOnlyUserOfAnyOperand(); 174 175 static const char* getOpcodeName(unsigned OpCode); 176 177 static inline bool isTerminator(unsigned OpCode) { 178 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd; 179 } 180 181 static inline bool isUnaryOp(unsigned Opcode) { 182 return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd; 183 } 184 static inline bool isBinaryOp(unsigned Opcode) { 185 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd; 186 } 187 188 static inline bool isIntDivRem(unsigned Opcode) { 189 return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem; 190 } 191 192 /// Determine if the Opcode is one of the shift instructions. 193 static inline bool isShift(unsigned Opcode) { 194 return Opcode >= Shl && Opcode <= AShr; 195 } 196 197 /// Return true if this is a logical shift left or a logical shift right. 198 inline bool isLogicalShift() const { 199 return getOpcode() == Shl || getOpcode() == LShr; 200 } 201 202 /// Return true if this is an arithmetic shift right. 203 inline bool isArithmeticShift() const { 204 return getOpcode() == AShr; 205 } 206 207 /// Determine if the Opcode is and/or/xor. 208 static inline bool isBitwiseLogicOp(unsigned Opcode) { 209 return Opcode == And || Opcode == Or || Opcode == Xor; 210 } 211 212 /// Return true if this is and/or/xor. 213 inline bool isBitwiseLogicOp() const { 214 return isBitwiseLogicOp(getOpcode()); 215 } 216 217 /// Determine if the OpCode is one of the CastInst instructions. 218 static inline bool isCast(unsigned OpCode) { 219 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd; 220 } 221 222 /// Determine if the OpCode is one of the FuncletPadInst instructions. 223 static inline bool isFuncletPad(unsigned OpCode) { 224 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd; 225 } 226 227 /// Returns true if the OpCode is a terminator related to exception handling. 228 static inline bool isExceptionalTerminator(unsigned OpCode) { 229 switch (OpCode) { 230 case Instruction::CatchSwitch: 231 case Instruction::CatchRet: 232 case Instruction::CleanupRet: 233 case Instruction::Invoke: 234 case Instruction::Resume: 235 return true; 236 default: 237 return false; 238 } 239 } 240 241 //===--------------------------------------------------------------------===// 242 // Metadata manipulation. 243 //===--------------------------------------------------------------------===// 244 245 /// Return true if this instruction has any metadata attached to it. 246 bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); } 247 248 /// Return true if this instruction has metadata attached to it other than a 249 /// debug location. 250 bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); } 251 252 /// Return true if this instruction has the given type of metadata attached. 253 bool hasMetadata(unsigned KindID) const { 254 return getMetadata(KindID) != nullptr; 255 } 256 257 /// Return true if this instruction has the given type of metadata attached. 258 bool hasMetadata(StringRef Kind) const { 259 return getMetadata(Kind) != nullptr; 260 } 261 262 /// Get the metadata of given kind attached to this Instruction. 263 /// If the metadata is not found then return null. 264 MDNode *getMetadata(unsigned KindID) const { 265 if (!hasMetadata()) return nullptr; 266 return getMetadataImpl(KindID); 267 } 268 269 /// Get the metadata of given kind attached to this Instruction. 270 /// If the metadata is not found then return null. 271 MDNode *getMetadata(StringRef Kind) const { 272 if (!hasMetadata()) return nullptr; 273 return getMetadataImpl(Kind); 274 } 275 276 /// Get all metadata attached to this Instruction. The first element of each 277 /// pair returned is the KindID, the second element is the metadata value. 278 /// This list is returned sorted by the KindID. 279 void 280 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 281 if (hasMetadata()) 282 getAllMetadataImpl(MDs); 283 } 284 285 /// This does the same thing as getAllMetadata, except that it filters out the 286 /// debug location. 287 void getAllMetadataOtherThanDebugLoc( 288 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 289 Value::getAllMetadata(MDs); 290 } 291 292 /// Set the metadata of the specified kind to the specified node. This updates 293 /// or replaces metadata if already present, or removes it if Node is null. 294 void setMetadata(unsigned KindID, MDNode *Node); 295 void setMetadata(StringRef Kind, MDNode *Node); 296 297 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty, 298 /// specifies the list of meta data that needs to be copied. If \p WL is 299 /// empty, all meta data will be copied. 300 void copyMetadata(const Instruction &SrcInst, 301 ArrayRef<unsigned> WL = ArrayRef<unsigned>()); 302 303 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode 304 /// has three operands (including name string), swap the order of the 305 /// metadata. 306 void swapProfMetadata(); 307 308 /// Drop all unknown metadata except for debug locations. 309 /// @{ 310 /// Passes are required to drop metadata they don't understand. This is a 311 /// convenience method for passes to do so. 312 /// dropUndefImplyingAttrsAndUnknownMetadata should be used instead of 313 /// this API if the Instruction being modified is a call. 314 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs); 315 void dropUnknownNonDebugMetadata() { 316 return dropUnknownNonDebugMetadata(None); 317 } 318 void dropUnknownNonDebugMetadata(unsigned ID1) { 319 return dropUnknownNonDebugMetadata(makeArrayRef(ID1)); 320 } 321 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) { 322 unsigned IDs[] = {ID1, ID2}; 323 return dropUnknownNonDebugMetadata(IDs); 324 } 325 /// @} 326 327 /// Adds an !annotation metadata node with \p Annotation to this instruction. 328 /// If this instruction already has !annotation metadata, append \p Annotation 329 /// to the existing node. 330 void addAnnotationMetadata(StringRef Annotation); 331 332 /// Returns the AA metadata for this instruction. 333 AAMDNodes getAAMetadata() const; 334 335 /// Sets the AA metadata on this instruction from the AAMDNodes structure. 336 void setAAMetadata(const AAMDNodes &N); 337 338 /// Retrieve the raw weight values of a conditional branch or select. 339 /// Returns true on success with profile weights filled in. 340 /// Returns false if no metadata or invalid metadata was found. 341 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const; 342 343 /// Retrieve total raw weight values of a branch. 344 /// Returns true on success with profile total weights filled in. 345 /// Returns false if no metadata was found. 346 bool extractProfTotalWeight(uint64_t &TotalVal) const; 347 348 /// Set the debug location information for this instruction. 349 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); } 350 351 /// Return the debug location for this node as a DebugLoc. 352 const DebugLoc &getDebugLoc() const { return DbgLoc; } 353 354 /// Set or clear the nuw flag on this instruction, which must be an operator 355 /// which supports this flag. See LangRef.html for the meaning of this flag. 356 void setHasNoUnsignedWrap(bool b = true); 357 358 /// Set or clear the nsw flag on this instruction, which must be an operator 359 /// which supports this flag. See LangRef.html for the meaning of this flag. 360 void setHasNoSignedWrap(bool b = true); 361 362 /// Set or clear the exact flag on this instruction, which must be an operator 363 /// which supports this flag. See LangRef.html for the meaning of this flag. 364 void setIsExact(bool b = true); 365 366 /// Determine whether the no unsigned wrap flag is set. 367 bool hasNoUnsignedWrap() const; 368 369 /// Determine whether the no signed wrap flag is set. 370 bool hasNoSignedWrap() const; 371 372 /// Return true if this operator has flags which may cause this instruction 373 /// to evaluate to poison despite having non-poison inputs. 374 bool hasPoisonGeneratingFlags() const; 375 376 /// Drops flags that may cause this instruction to evaluate to poison despite 377 /// having non-poison inputs. 378 void dropPoisonGeneratingFlags(); 379 380 /// This function drops non-debug unknown metadata (through 381 /// dropUnknownNonDebugMetadata). For calls, it also drops parameter and 382 /// return attributes that can cause undefined behaviour. Both of these should 383 /// be done by passes which move instructions in IR. 384 void 385 dropUndefImplyingAttrsAndUnknownMetadata(ArrayRef<unsigned> KnownIDs = {}); 386 387 /// Determine whether the exact flag is set. 388 bool isExact() const; 389 390 /// Set or clear all fast-math-flags on this instruction, which must be an 391 /// operator which supports this flag. See LangRef.html for the meaning of 392 /// this flag. 393 void setFast(bool B); 394 395 /// Set or clear the reassociation flag on this instruction, which must be 396 /// an operator which supports this flag. See LangRef.html for the meaning of 397 /// this flag. 398 void setHasAllowReassoc(bool B); 399 400 /// Set or clear the no-nans flag on this instruction, which must be an 401 /// operator which supports this flag. See LangRef.html for the meaning of 402 /// this flag. 403 void setHasNoNaNs(bool B); 404 405 /// Set or clear the no-infs flag on this instruction, which must be an 406 /// operator which supports this flag. See LangRef.html for the meaning of 407 /// this flag. 408 void setHasNoInfs(bool B); 409 410 /// Set or clear the no-signed-zeros flag on this instruction, which must be 411 /// an operator which supports this flag. See LangRef.html for the meaning of 412 /// this flag. 413 void setHasNoSignedZeros(bool B); 414 415 /// Set or clear the allow-reciprocal flag on this instruction, which must be 416 /// an operator which supports this flag. See LangRef.html for the meaning of 417 /// this flag. 418 void setHasAllowReciprocal(bool B); 419 420 /// Set or clear the allow-contract flag on this instruction, which must be 421 /// an operator which supports this flag. See LangRef.html for the meaning of 422 /// this flag. 423 void setHasAllowContract(bool B); 424 425 /// Set or clear the approximate-math-functions flag on this instruction, 426 /// which must be an operator which supports this flag. See LangRef.html for 427 /// the meaning of this flag. 428 void setHasApproxFunc(bool B); 429 430 /// Convenience function for setting multiple fast-math flags on this 431 /// instruction, which must be an operator which supports these flags. See 432 /// LangRef.html for the meaning of these flags. 433 void setFastMathFlags(FastMathFlags FMF); 434 435 /// Convenience function for transferring all fast-math flag values to this 436 /// instruction, which must be an operator which supports these flags. See 437 /// LangRef.html for the meaning of these flags. 438 void copyFastMathFlags(FastMathFlags FMF); 439 440 /// Determine whether all fast-math-flags are set. 441 bool isFast() const; 442 443 /// Determine whether the allow-reassociation flag is set. 444 bool hasAllowReassoc() const; 445 446 /// Determine whether the no-NaNs flag is set. 447 bool hasNoNaNs() const; 448 449 /// Determine whether the no-infs flag is set. 450 bool hasNoInfs() const; 451 452 /// Determine whether the no-signed-zeros flag is set. 453 bool hasNoSignedZeros() const; 454 455 /// Determine whether the allow-reciprocal flag is set. 456 bool hasAllowReciprocal() const; 457 458 /// Determine whether the allow-contract flag is set. 459 bool hasAllowContract() const; 460 461 /// Determine whether the approximate-math-functions flag is set. 462 bool hasApproxFunc() const; 463 464 /// Convenience function for getting all the fast-math flags, which must be an 465 /// operator which supports these flags. See LangRef.html for the meaning of 466 /// these flags. 467 FastMathFlags getFastMathFlags() const; 468 469 /// Copy I's fast-math flags 470 void copyFastMathFlags(const Instruction *I); 471 472 /// Convenience method to copy supported exact, fast-math, and (optionally) 473 /// wrapping flags from V to this instruction. 474 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true); 475 476 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of 477 /// V and this instruction. 478 void andIRFlags(const Value *V); 479 480 /// Merge 2 debug locations and apply it to the Instruction. If the 481 /// instruction is a CallIns, we need to traverse the inline chain to find 482 /// the common scope. This is not efficient for N-way merging as each time 483 /// you merge 2 iterations, you need to rebuild the hashmap to find the 484 /// common scope. However, we still choose this API because: 485 /// 1) Simplicity: it takes 2 locations instead of a list of locations. 486 /// 2) In worst case, it increases the complexity from O(N*I) to 487 /// O(2*N*I), where N is # of Instructions to merge, and I is the 488 /// maximum level of inline stack. So it is still linear. 489 /// 3) Merging of call instructions should be extremely rare in real 490 /// applications, thus the N-way merging should be in code path. 491 /// The DebugLoc attached to this instruction will be overwritten by the 492 /// merged DebugLoc. 493 void applyMergedLocation(const DILocation *LocA, const DILocation *LocB); 494 495 /// Updates the debug location given that the instruction has been hoisted 496 /// from a block to a predecessor of that block. 497 /// Note: it is undefined behavior to call this on an instruction not 498 /// currently inserted into a function. 499 void updateLocationAfterHoist(); 500 501 /// Drop the instruction's debug location. This does not guarantee removal 502 /// of the !dbg source location attachment, as it must set a line 0 location 503 /// with scope information attached on call instructions. To guarantee 504 /// removal of the !dbg attachment, use the \ref setDebugLoc() API. 505 /// Note: it is undefined behavior to call this on an instruction not 506 /// currently inserted into a function. 507 void dropLocation(); 508 509 private: 510 // These are all implemented in Metadata.cpp. 511 MDNode *getMetadataImpl(unsigned KindID) const; 512 MDNode *getMetadataImpl(StringRef Kind) const; 513 void 514 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 515 516 public: 517 //===--------------------------------------------------------------------===// 518 // Predicates and helper methods. 519 //===--------------------------------------------------------------------===// 520 521 /// Return true if the instruction is associative: 522 /// 523 /// Associative operators satisfy: x op (y op z) === (x op y) op z 524 /// 525 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. 526 /// 527 bool isAssociative() const LLVM_READONLY; 528 static bool isAssociative(unsigned Opcode) { 529 return Opcode == And || Opcode == Or || Opcode == Xor || 530 Opcode == Add || Opcode == Mul; 531 } 532 533 /// Return true if the instruction is commutative: 534 /// 535 /// Commutative operators satisfy: (x op y) === (y op x) 536 /// 537 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when 538 /// applied to any type. 539 /// 540 bool isCommutative() const LLVM_READONLY; 541 static bool isCommutative(unsigned Opcode) { 542 switch (Opcode) { 543 case Add: case FAdd: 544 case Mul: case FMul: 545 case And: case Or: case Xor: 546 return true; 547 default: 548 return false; 549 } 550 } 551 552 /// Return true if the instruction is idempotent: 553 /// 554 /// Idempotent operators satisfy: x op x === x 555 /// 556 /// In LLVM, the And and Or operators are idempotent. 557 /// 558 bool isIdempotent() const { return isIdempotent(getOpcode()); } 559 static bool isIdempotent(unsigned Opcode) { 560 return Opcode == And || Opcode == Or; 561 } 562 563 /// Return true if the instruction is nilpotent: 564 /// 565 /// Nilpotent operators satisfy: x op x === Id, 566 /// 567 /// where Id is the identity for the operator, i.e. a constant such that 568 /// x op Id === x and Id op x === x for all x. 569 /// 570 /// In LLVM, the Xor operator is nilpotent. 571 /// 572 bool isNilpotent() const { return isNilpotent(getOpcode()); } 573 static bool isNilpotent(unsigned Opcode) { 574 return Opcode == Xor; 575 } 576 577 /// Return true if this instruction may modify memory. 578 bool mayWriteToMemory() const; 579 580 /// Return true if this instruction may read memory. 581 bool mayReadFromMemory() const; 582 583 /// Return true if this instruction may read or write memory. 584 bool mayReadOrWriteMemory() const { 585 return mayReadFromMemory() || mayWriteToMemory(); 586 } 587 588 /// Return true if this instruction has an AtomicOrdering of unordered or 589 /// higher. 590 bool isAtomic() const; 591 592 /// Return true if this atomic instruction loads from memory. 593 bool hasAtomicLoad() const; 594 595 /// Return true if this atomic instruction stores to memory. 596 bool hasAtomicStore() const; 597 598 /// Return true if this instruction has a volatile memory access. 599 bool isVolatile() const; 600 601 /// Return true if this instruction may throw an exception. 602 bool mayThrow() const; 603 604 /// Return true if this instruction behaves like a memory fence: it can load 605 /// or store to memory location without being given a memory location. 606 bool isFenceLike() const { 607 switch (getOpcode()) { 608 default: 609 return false; 610 // This list should be kept in sync with the list in mayWriteToMemory for 611 // all opcodes which don't have a memory location. 612 case Instruction::Fence: 613 case Instruction::CatchPad: 614 case Instruction::CatchRet: 615 case Instruction::Call: 616 case Instruction::Invoke: 617 return true; 618 } 619 } 620 621 /// Return true if the instruction may have side effects. 622 /// 623 /// Side effects are: 624 /// * Writing to memory. 625 /// * Unwinding. 626 /// * Not returning (e.g. an infinite loop). 627 /// 628 /// Note that this does not consider malloc and alloca to have side 629 /// effects because the newly allocated memory is completely invisible to 630 /// instructions which don't use the returned value. For cases where this 631 /// matters, isSafeToSpeculativelyExecute may be more appropriate. 632 bool mayHaveSideEffects() const; 633 634 /// Return true if the instruction can be removed if the result is unused. 635 /// 636 /// When constant folding some instructions cannot be removed even if their 637 /// results are unused. Specifically terminator instructions and calls that 638 /// may have side effects cannot be removed without semantically changing the 639 /// generated program. 640 bool isSafeToRemove() const; 641 642 /// Return true if the instruction will return (unwinding is considered as 643 /// a form of returning control flow here). 644 bool willReturn() const; 645 646 /// Return true if the instruction is a variety of EH-block. 647 bool isEHPad() const { 648 switch (getOpcode()) { 649 case Instruction::CatchSwitch: 650 case Instruction::CatchPad: 651 case Instruction::CleanupPad: 652 case Instruction::LandingPad: 653 return true; 654 default: 655 return false; 656 } 657 } 658 659 /// Return true if the instruction is a llvm.lifetime.start or 660 /// llvm.lifetime.end marker. 661 bool isLifetimeStartOrEnd() const; 662 663 /// Return true if the instruction is a llvm.launder.invariant.group or 664 /// llvm.strip.invariant.group. 665 bool isLaunderOrStripInvariantGroup() const; 666 667 /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst. 668 bool isDebugOrPseudoInst() const; 669 670 /// Return a pointer to the next non-debug instruction in the same basic 671 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 672 /// operations if \c SkipPseudoOp is true. 673 const Instruction * 674 getNextNonDebugInstruction(bool SkipPseudoOp = false) const; 675 Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) { 676 return const_cast<Instruction *>( 677 static_cast<const Instruction *>(this)->getNextNonDebugInstruction( 678 SkipPseudoOp)); 679 } 680 681 /// Return a pointer to the previous non-debug instruction in the same basic 682 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 683 /// operations if \c SkipPseudoOp is true. 684 const Instruction * 685 getPrevNonDebugInstruction(bool SkipPseudoOp = false) const; 686 Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) { 687 return const_cast<Instruction *>( 688 static_cast<const Instruction *>(this)->getPrevNonDebugInstruction( 689 SkipPseudoOp)); 690 } 691 692 /// Create a copy of 'this' instruction that is identical in all ways except 693 /// the following: 694 /// * The instruction has no parent 695 /// * The instruction has no name 696 /// 697 Instruction *clone() const; 698 699 /// Return true if the specified instruction is exactly identical to the 700 /// current one. This means that all operands match and any extra information 701 /// (e.g. load is volatile) agree. 702 bool isIdenticalTo(const Instruction *I) const; 703 704 /// This is like isIdenticalTo, except that it ignores the 705 /// SubclassOptionalData flags, which may specify conditions under which the 706 /// instruction's result is undefined. 707 bool isIdenticalToWhenDefined(const Instruction *I) const; 708 709 /// When checking for operation equivalence (using isSameOperationAs) it is 710 /// sometimes useful to ignore certain attributes. 711 enum OperationEquivalenceFlags { 712 /// Check for equivalence ignoring load/store alignment. 713 CompareIgnoringAlignment = 1<<0, 714 /// Check for equivalence treating a type and a vector of that type 715 /// as equivalent. 716 CompareUsingScalarTypes = 1<<1 717 }; 718 719 /// This function determines if the specified instruction executes the same 720 /// operation as the current one. This means that the opcodes, type, operand 721 /// types and any other factors affecting the operation must be the same. This 722 /// is similar to isIdenticalTo except the operands themselves don't have to 723 /// be identical. 724 /// @returns true if the specified instruction is the same operation as 725 /// the current one. 726 /// Determine if one instruction is the same operation as another. 727 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const; 728 729 /// Return true if there are any uses of this instruction in blocks other than 730 /// the specified block. Note that PHI nodes are considered to evaluate their 731 /// operands in the corresponding predecessor block. 732 bool isUsedOutsideOfBlock(const BasicBlock *BB) const; 733 734 /// Return the number of successors that this instruction has. The instruction 735 /// must be a terminator. 736 unsigned getNumSuccessors() const; 737 738 /// Return the specified successor. This instruction must be a terminator. 739 BasicBlock *getSuccessor(unsigned Idx) const; 740 741 /// Update the specified successor to point at the provided block. This 742 /// instruction must be a terminator. 743 void setSuccessor(unsigned Idx, BasicBlock *BB); 744 745 /// Replace specified successor OldBB to point at the provided block. 746 /// This instruction must be a terminator. 747 void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB); 748 749 /// Methods for support type inquiry through isa, cast, and dyn_cast: 750 static bool classof(const Value *V) { 751 return V->getValueID() >= Value::InstructionVal; 752 } 753 754 //---------------------------------------------------------------------- 755 // Exported enumerations. 756 // 757 enum TermOps { // These terminate basic blocks 758 #define FIRST_TERM_INST(N) TermOpsBegin = N, 759 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N, 760 #define LAST_TERM_INST(N) TermOpsEnd = N+1 761 #include "llvm/IR/Instruction.def" 762 }; 763 764 enum UnaryOps { 765 #define FIRST_UNARY_INST(N) UnaryOpsBegin = N, 766 #define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N, 767 #define LAST_UNARY_INST(N) UnaryOpsEnd = N+1 768 #include "llvm/IR/Instruction.def" 769 }; 770 771 enum BinaryOps { 772 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N, 773 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N, 774 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1 775 #include "llvm/IR/Instruction.def" 776 }; 777 778 enum MemoryOps { 779 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N, 780 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N, 781 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1 782 #include "llvm/IR/Instruction.def" 783 }; 784 785 enum CastOps { 786 #define FIRST_CAST_INST(N) CastOpsBegin = N, 787 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N, 788 #define LAST_CAST_INST(N) CastOpsEnd = N+1 789 #include "llvm/IR/Instruction.def" 790 }; 791 792 enum FuncletPadOps { 793 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N, 794 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N, 795 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1 796 #include "llvm/IR/Instruction.def" 797 }; 798 799 enum OtherOps { 800 #define FIRST_OTHER_INST(N) OtherOpsBegin = N, 801 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N, 802 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 803 #include "llvm/IR/Instruction.def" 804 }; 805 806 private: 807 friend class SymbolTableListTraits<Instruction>; 808 friend class BasicBlock; // For renumbering. 809 810 // Shadow Value::setValueSubclassData with a private forwarding method so that 811 // subclasses cannot accidentally use it. 812 void setValueSubclassData(unsigned short D) { 813 Value::setValueSubclassData(D); 814 } 815 816 unsigned short getSubclassDataFromValue() const { 817 return Value::getSubclassDataFromValue(); 818 } 819 820 void setParent(BasicBlock *P); 821 822 protected: 823 // Instruction subclasses can stick up to 15 bits of stuff into the 824 // SubclassData field of instruction with these members. 825 826 template <typename BitfieldElement> 827 typename BitfieldElement::Type getSubclassData() const { 828 static_assert( 829 std::is_same<BitfieldElement, HasMetadataField>::value || 830 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 831 "Must not overlap with the metadata bit"); 832 return Bitfield::get<BitfieldElement>(getSubclassDataFromValue()); 833 } 834 835 template <typename BitfieldElement> 836 void setSubclassData(typename BitfieldElement::Type Value) { 837 static_assert( 838 std::is_same<BitfieldElement, HasMetadataField>::value || 839 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 840 "Must not overlap with the metadata bit"); 841 auto Storage = getSubclassDataFromValue(); 842 Bitfield::set<BitfieldElement>(Storage, Value); 843 setValueSubclassData(Storage); 844 } 845 846 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 847 Instruction *InsertBefore = nullptr); 848 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 849 BasicBlock *InsertAtEnd); 850 851 private: 852 /// Create a copy of this instruction. 853 Instruction *cloneImpl() const; 854 }; 855 856 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) { 857 V->deleteValue(); 858 } 859 860 } // end namespace llvm 861 862 #endif // LLVM_IR_INSTRUCTION_H 863