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