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/StringRef.h" 20 #include "llvm/ADT/ilist_node.h" 21 #include "llvm/IR/DebugLoc.h" 22 #include "llvm/IR/SymbolTableListTraits.h" 23 #include "llvm/IR/User.h" 24 #include "llvm/IR/Value.h" 25 #include "llvm/Support/AtomicOrdering.h" 26 #include <cstdint> 27 #include <utility> 28 29 namespace llvm { 30 31 class BasicBlock; 32 class DataLayout; 33 class DbgMarker; 34 class FastMathFlags; 35 class MDNode; 36 class Module; 37 struct AAMDNodes; 38 class DbgMarker; 39 class DbgRecord; 40 41 template <> struct ilist_alloc_traits<Instruction> { 42 static inline void deleteNode(Instruction *V); 43 }; 44 45 iterator_range<simple_ilist<DbgRecord>::iterator> 46 getDbgRecordRange(DbgMarker *); 47 48 class InsertPosition { 49 using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>, 50 ilist_parent<BasicBlock>>; 51 InstListType::iterator InsertAt; 52 53 public: 54 InsertPosition(std::nullptr_t) : InsertAt() {} 55 LLVM_DEPRECATED("Use BasicBlock::iterators for insertion instead", 56 "BasicBlock::iterator") 57 InsertPosition(Instruction *InsertBefore); 58 InsertPosition(BasicBlock *InsertAtEnd); 59 InsertPosition(InstListType::iterator InsertAt) : InsertAt(InsertAt) {} 60 operator InstListType::iterator() const { return InsertAt; } 61 bool isValid() const { return InsertAt.isValid(); } 62 BasicBlock *getBasicBlock() { return InsertAt.getNodeParent(); } 63 }; 64 65 class Instruction : public User, 66 public ilist_node_with_parent<Instruction, BasicBlock, 67 ilist_iterator_bits<true>, 68 ilist_parent<BasicBlock>> { 69 public: 70 using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>, 71 ilist_parent<BasicBlock>>; 72 73 private: 74 DebugLoc DbgLoc; // 'dbg' Metadata cache. 75 76 /// Relative order of this instruction in its parent basic block. Used for 77 /// O(1) local dominance checks between instructions. 78 mutable unsigned Order = 0; 79 80 public: 81 /// Optional marker recording the position for debugging information that 82 /// takes effect immediately before this instruction. Null unless there is 83 /// debugging information present. 84 DbgMarker *DebugMarker = nullptr; 85 86 /// Clone any debug-info attached to \p From onto this instruction. Used to 87 /// copy debugging information from one block to another, when copying entire 88 /// blocks. \see DebugProgramInstruction.h , because the ordering of 89 /// DbgRecords is still important, fine grain control of which instructions 90 /// are moved and where they go is necessary. 91 /// \p From The instruction to clone debug-info from. 92 /// \p from_here Optional iterator to limit DbgRecords cloned to be a range 93 /// from 94 /// from_here to end(). 95 /// \p InsertAtHead Whether the cloned DbgRecords should be placed at the end 96 /// or the beginning of existing DbgRecords attached to this. 97 /// \returns A range over the newly cloned DbgRecords. 98 iterator_range<simple_ilist<DbgRecord>::iterator> cloneDebugInfoFrom( 99 const Instruction *From, 100 std::optional<simple_ilist<DbgRecord>::iterator> FromHere = std::nullopt, 101 bool InsertAtHead = false); 102 103 /// Return a range over the DbgRecords attached to this instruction. 104 iterator_range<simple_ilist<DbgRecord>::iterator> getDbgRecordRange() const { 105 return llvm::getDbgRecordRange(DebugMarker); 106 } 107 108 /// Return an iterator to the position of the "Next" DbgRecord after this 109 /// instruction, or std::nullopt. This is the position to pass to 110 /// BasicBlock::reinsertInstInDbgRecords when re-inserting an instruction. 111 std::optional<simple_ilist<DbgRecord>::iterator> getDbgReinsertionPosition(); 112 113 /// Returns true if any DbgRecords are attached to this instruction. 114 bool hasDbgRecords() const; 115 116 /// Transfer any DbgRecords on the position \p It onto this instruction, 117 /// by simply adopting the sequence of DbgRecords (which is efficient) if 118 /// possible, by merging two sequences otherwise. 119 void adoptDbgRecords(BasicBlock *BB, InstListType::iterator It, 120 bool InsertAtHead); 121 122 /// Erase any DbgRecords attached to this instruction. 123 void dropDbgRecords(); 124 125 /// Erase a single DbgRecord \p I that is attached to this instruction. 126 void dropOneDbgRecord(DbgRecord *I); 127 128 /// Handle the debug-info implications of this instruction being removed. Any 129 /// attached DbgRecords need to "fall" down onto the next instruction. 130 void handleMarkerRemoval(); 131 132 protected: 133 // The 15 first bits of `Value::SubclassData` are available for subclasses of 134 // `Instruction` to use. 135 using OpaqueField = Bitfield::Element<uint16_t, 0, 15>; 136 137 // Template alias so that all Instruction storing alignment use the same 138 // definiton. 139 // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent = 140 // 2^32. We store them as Log2(Alignment), so we need 6 bits to encode the 33 141 // possible values. 142 template <unsigned Offset> 143 using AlignmentBitfieldElementT = 144 typename Bitfield::Element<unsigned, Offset, 6, 145 Value::MaxAlignmentExponent>; 146 147 template <unsigned Offset> 148 using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>; 149 150 template <unsigned Offset> 151 using AtomicOrderingBitfieldElementT = 152 typename Bitfield::Element<AtomicOrdering, Offset, 3, 153 AtomicOrdering::LAST>; 154 155 private: 156 // The last bit is used to store whether the instruction has metadata attached 157 // or not. 158 using HasMetadataField = Bitfield::Element<bool, 15, 1>; 159 160 protected: 161 ~Instruction(); // Use deleteValue() to delete a generic Instruction. 162 163 public: 164 Instruction(const Instruction &) = delete; 165 Instruction &operator=(const Instruction &) = delete; 166 167 /// Specialize the methods defined in Value, as we know that an instruction 168 /// can only be used by other instructions. 169 Instruction *user_back() { return cast<Instruction>(*user_begin());} 170 const Instruction *user_back() const { return cast<Instruction>(*user_begin());} 171 172 /// Return the module owning the function this instruction belongs to 173 /// or nullptr it the function does not have a module. 174 /// 175 /// Note: this is undefined behavior if the instruction does not have a 176 /// parent, or the parent basic block does not have a parent function. 177 const Module *getModule() const; 178 Module *getModule() { 179 return const_cast<Module *>( 180 static_cast<const Instruction *>(this)->getModule()); 181 } 182 183 /// Return the function this instruction belongs to. 184 /// 185 /// Note: it is undefined behavior to call this on an instruction not 186 /// currently inserted into a function. 187 const Function *getFunction() const; 188 Function *getFunction() { 189 return const_cast<Function *>( 190 static_cast<const Instruction *>(this)->getFunction()); 191 } 192 193 /// Get the data layout of the module this instruction belongs to. 194 /// 195 /// Requires the instruction to have a parent module. 196 const DataLayout &getDataLayout() const; 197 198 /// This method unlinks 'this' from the containing basic block, but does not 199 /// delete it. 200 void removeFromParent(); 201 202 /// This method unlinks 'this' from the containing basic block and deletes it. 203 /// 204 /// \returns an iterator pointing to the element after the erased one 205 InstListType::iterator eraseFromParent(); 206 207 /// Insert an unlinked instruction into a basic block immediately before 208 /// the specified instruction. 209 /// 210 /// Deprecated in favour of the iterator-accepting flavour. Iterators at the 211 /// start of a block such as BasicBlock::getFirstNonPHIIt must be passed into 212 /// insertBefore without unwrapping/rewrapping. For all other positions, call 213 /// getIterator to fetch the instruction iterator. 214 LLVM_DEPRECATED("Use iterators as instruction positions", "") 215 void insertBefore(Instruction *InsertPos); 216 217 /// Insert an unlinked instruction into a basic block immediately before 218 /// the specified position. 219 void insertBefore(InstListType::iterator InsertPos); 220 221 /// Insert an unlinked instruction into a basic block immediately after the 222 /// specified instruction. 223 void insertAfter(Instruction *InsertPos); 224 225 /// Insert an unlinked instruction into a basic block immediately after the 226 /// specified position. 227 void insertAfter(InstListType::iterator InsertPos); 228 229 /// Inserts an unlinked instruction into \p ParentBB at position \p It and 230 /// returns the iterator of the inserted instruction. 231 InstListType::iterator insertInto(BasicBlock *ParentBB, 232 InstListType::iterator It); 233 234 void insertBefore(BasicBlock &BB, InstListType::iterator InsertPos); 235 236 /// Unlink this instruction from its current basic block and insert it into 237 /// the basic block that MovePos lives in, right before MovePos. 238 /// 239 /// Deprecated in favour of the iterator-accepting flavour. Iterators at the 240 /// start of a block such as BasicBlock::getFirstNonPHIIt must be passed into 241 /// moveBefore without unwrapping/rewrapping. For all other positions, call 242 /// getIterator to fetch the instruction iterator. 243 LLVM_DEPRECATED("Use iterators as instruction positions", "") 244 void moveBefore(Instruction *MovePos); 245 246 /// Unlink this instruction from its current basic block and insert it into 247 /// the basic block that MovePos lives in, right before MovePos. 248 void moveBefore(InstListType::iterator InsertPos); 249 250 /// Perform a \ref moveBefore operation, while signalling that the caller 251 /// intends to preserve the original ordering of instructions. This implicitly 252 /// means that any adjacent debug-info should move with this instruction. 253 void moveBeforePreserving(InstListType::iterator MovePos); 254 255 /// Perform a \ref moveBefore operation, while signalling that the caller 256 /// intends to preserve the original ordering of instructions. This implicitly 257 /// means that any adjacent debug-info should move with this instruction. 258 void moveBeforePreserving(BasicBlock &BB, InstListType::iterator I); 259 260 /// Perform a \ref moveBefore operation, while signalling that the caller 261 /// intends to preserve the original ordering of instructions. This implicitly 262 /// means that any adjacent debug-info should move with this instruction. 263 /// 264 /// Deprecated in favour of the iterator-accepting flavour of 265 /// moveBeforePreserving, as all insertions should be at iterator positions. 266 LLVM_DEPRECATED("Use iterators as instruction positions", "") 267 void moveBeforePreserving(Instruction *MovePos); 268 269 private: 270 /// RemoveDIs project: all other moves implemented with this method, 271 /// centralising debug-info updates into one place. 272 void moveBeforeImpl(BasicBlock &BB, InstListType::iterator I, bool Preserve); 273 274 public: 275 /// Unlink this instruction and insert into BB before I. 276 /// 277 /// \pre I is a valid iterator into BB. 278 void moveBefore(BasicBlock &BB, InstListType::iterator I); 279 280 /// Unlink this instruction from its current basic block and insert it into 281 /// the basic block that MovePos lives in, right after MovePos. 282 void moveAfter(Instruction *MovePos); 283 284 /// Unlink this instruction from its current basic block and insert it into 285 /// the basic block that MovePos lives in, right after MovePos. 286 void moveAfter(InstListType::iterator MovePos); 287 288 /// See \ref moveBeforePreserving . 289 void moveAfterPreserving(Instruction *MovePos); 290 291 /// Given an instruction Other in the same basic block as this instruction, 292 /// return true if this instruction comes before Other. In this worst case, 293 /// this takes linear time in the number of instructions in the block. The 294 /// results are cached, so in common cases when the block remains unmodified, 295 /// it takes constant time. 296 bool comesBefore(const Instruction *Other) const; 297 298 /// Get the first insertion point at which the result of this instruction 299 /// is defined. This is *not* the directly following instruction in a number 300 /// of cases, e.g. phi nodes or terminators that return values. This function 301 /// may return null if the insertion after the definition is not possible, 302 /// e.g. due to a catchswitch terminator. 303 std::optional<InstListType::iterator> getInsertionPointAfterDef(); 304 305 //===--------------------------------------------------------------------===// 306 // Subclass classification. 307 //===--------------------------------------------------------------------===// 308 309 /// Returns a member of one of the enums like Instruction::Add. 310 unsigned getOpcode() const { return getValueID() - InstructionVal; } 311 312 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); } 313 bool isTerminator() const { return isTerminator(getOpcode()); } 314 bool isUnaryOp() const { return isUnaryOp(getOpcode()); } 315 bool isBinaryOp() const { return isBinaryOp(getOpcode()); } 316 bool isIntDivRem() const { return isIntDivRem(getOpcode()); } 317 bool isFPDivRem() const { return isFPDivRem(getOpcode()); } 318 bool isShift() const { return isShift(getOpcode()); } 319 bool isCast() const { return isCast(getOpcode()); } 320 bool isFuncletPad() const { return isFuncletPad(getOpcode()); } 321 bool isSpecialTerminator() const { return isSpecialTerminator(getOpcode()); } 322 323 /// It checks if this instruction is the only user of at least one of 324 /// its operands. 325 bool isOnlyUserOfAnyOperand(); 326 327 static const char *getOpcodeName(unsigned Opcode); 328 329 static inline bool isTerminator(unsigned Opcode) { 330 return Opcode >= TermOpsBegin && Opcode < TermOpsEnd; 331 } 332 333 static inline bool isUnaryOp(unsigned Opcode) { 334 return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd; 335 } 336 static inline bool isBinaryOp(unsigned Opcode) { 337 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd; 338 } 339 340 static inline bool isIntDivRem(unsigned Opcode) { 341 return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem; 342 } 343 344 static inline bool isFPDivRem(unsigned Opcode) { 345 return Opcode == FDiv || Opcode == FRem; 346 } 347 348 /// Determine if the Opcode is one of the shift instructions. 349 static inline bool isShift(unsigned Opcode) { 350 return Opcode >= Shl && Opcode <= AShr; 351 } 352 353 /// Return true if this is a logical shift left or a logical shift right. 354 inline bool isLogicalShift() const { 355 return getOpcode() == Shl || getOpcode() == LShr; 356 } 357 358 /// Return true if this is an arithmetic shift right. 359 inline bool isArithmeticShift() const { 360 return getOpcode() == AShr; 361 } 362 363 /// Determine if the Opcode is and/or/xor. 364 static inline bool isBitwiseLogicOp(unsigned Opcode) { 365 return Opcode == And || Opcode == Or || Opcode == Xor; 366 } 367 368 /// Return true if this is and/or/xor. 369 inline bool isBitwiseLogicOp() const { 370 return isBitwiseLogicOp(getOpcode()); 371 } 372 373 /// Determine if the Opcode is one of the CastInst instructions. 374 static inline bool isCast(unsigned Opcode) { 375 return Opcode >= CastOpsBegin && Opcode < CastOpsEnd; 376 } 377 378 /// Determine if the Opcode is one of the FuncletPadInst instructions. 379 static inline bool isFuncletPad(unsigned Opcode) { 380 return Opcode >= FuncletPadOpsBegin && Opcode < FuncletPadOpsEnd; 381 } 382 383 /// Returns true if the Opcode is a "special" terminator that does more than 384 /// branch to a successor (e.g. have a side effect or return a value). 385 static inline bool isSpecialTerminator(unsigned Opcode) { 386 switch (Opcode) { 387 case Instruction::CatchSwitch: 388 case Instruction::CatchRet: 389 case Instruction::CleanupRet: 390 case Instruction::Invoke: 391 case Instruction::Resume: 392 case Instruction::CallBr: 393 return true; 394 default: 395 return false; 396 } 397 } 398 399 //===--------------------------------------------------------------------===// 400 // Metadata manipulation. 401 //===--------------------------------------------------------------------===// 402 403 /// Return true if this instruction has any metadata attached to it. 404 bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); } 405 406 // Return true if this instruction contains loop metadata other than 407 // a debug location 408 bool hasNonDebugLocLoopMetadata() const; 409 410 /// Return true if this instruction has metadata attached to it other than a 411 /// debug location. 412 bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); } 413 414 /// Return true if this instruction has the given type of metadata attached. 415 bool hasMetadata(unsigned KindID) const { 416 return getMetadata(KindID) != nullptr; 417 } 418 419 /// Return true if this instruction has the given type of metadata attached. 420 bool hasMetadata(StringRef Kind) const { 421 return getMetadata(Kind) != nullptr; 422 } 423 424 /// Get the metadata of given kind attached to this Instruction. 425 /// If the metadata is not found then return null. 426 MDNode *getMetadata(unsigned KindID) const { 427 // Handle 'dbg' as a special case since it is not stored in the hash table. 428 if (KindID == LLVMContext::MD_dbg) 429 return DbgLoc.getAsMDNode(); 430 return Value::getMetadata(KindID); 431 } 432 433 /// Get the metadata of given kind attached to this Instruction. 434 /// If the metadata is not found then return null. 435 MDNode *getMetadata(StringRef Kind) const { 436 if (!hasMetadata()) return nullptr; 437 return getMetadataImpl(Kind); 438 } 439 440 /// Get all metadata attached to this Instruction. The first element of each 441 /// pair returned is the KindID, the second element is the metadata value. 442 /// This list is returned sorted by the KindID. 443 void 444 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 445 if (hasMetadata()) 446 getAllMetadataImpl(MDs); 447 } 448 449 /// This does the same thing as getAllMetadata, except that it filters out the 450 /// debug location. 451 void getAllMetadataOtherThanDebugLoc( 452 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 453 Value::getAllMetadata(MDs); 454 } 455 456 /// Set the metadata of the specified kind to the specified node. This updates 457 /// or replaces metadata if already present, or removes it if Node is null. 458 void setMetadata(unsigned KindID, MDNode *Node); 459 void setMetadata(StringRef Kind, MDNode *Node); 460 461 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty, 462 /// specifies the list of meta data that needs to be copied. If \p WL is 463 /// empty, all meta data will be copied. 464 void copyMetadata(const Instruction &SrcInst, 465 ArrayRef<unsigned> WL = ArrayRef<unsigned>()); 466 467 /// Erase all metadata that matches the predicate. 468 void eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred); 469 470 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode 471 /// has three operands (including name string), swap the order of the 472 /// metadata. 473 void swapProfMetadata(); 474 475 /// Drop all unknown metadata except for debug locations. 476 /// @{ 477 /// Passes are required to drop metadata they don't understand. This is a 478 /// convenience method for passes to do so. 479 /// dropUBImplyingAttrsAndUnknownMetadata should be used instead of 480 /// this API if the Instruction being modified is a call. 481 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs = {}); 482 /// @} 483 484 /// Adds an !annotation metadata node with \p Annotation to this instruction. 485 /// If this instruction already has !annotation metadata, append \p Annotation 486 /// to the existing node. 487 void addAnnotationMetadata(StringRef Annotation); 488 /// Adds an !annotation metadata node with an array of \p Annotations 489 /// as a tuple to this instruction. If this instruction already has 490 /// !annotation metadata, append the tuple to 491 /// the existing node. 492 void addAnnotationMetadata(SmallVector<StringRef> Annotations); 493 /// Returns the AA metadata for this instruction. 494 AAMDNodes getAAMetadata() const; 495 496 /// Sets the AA metadata on this instruction from the AAMDNodes structure. 497 void setAAMetadata(const AAMDNodes &N); 498 499 /// Sets the nosanitize metadata on this instruction. 500 void setNoSanitizeMetadata(); 501 502 /// Retrieve total raw weight values of a branch. 503 /// Returns true on success with profile total weights filled in. 504 /// Returns false if no metadata was found. 505 bool extractProfTotalWeight(uint64_t &TotalVal) const; 506 507 /// Set the debug location information for this instruction. 508 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); } 509 510 /// Return the debug location for this node as a DebugLoc. 511 const DebugLoc &getDebugLoc() const { return DbgLoc; } 512 513 /// Fetch the debug location for this node, unless this is a debug intrinsic, 514 /// in which case fetch the debug location of the next non-debug node. 515 const DebugLoc &getStableDebugLoc() const; 516 517 /// Set or clear the nuw flag on this instruction, which must be an operator 518 /// which supports this flag. See LangRef.html for the meaning of this flag. 519 void setHasNoUnsignedWrap(bool b = true); 520 521 /// Set or clear the nsw flag on this instruction, which must be an operator 522 /// which supports this flag. See LangRef.html for the meaning of this flag. 523 void setHasNoSignedWrap(bool b = true); 524 525 /// Set or clear the exact flag on this instruction, which must be an operator 526 /// which supports this flag. See LangRef.html for the meaning of this flag. 527 void setIsExact(bool b = true); 528 529 /// Set or clear the nneg flag on this instruction, which must be a zext 530 /// instruction. 531 void setNonNeg(bool b = true); 532 533 /// Determine whether the no unsigned wrap flag is set. 534 bool hasNoUnsignedWrap() const LLVM_READONLY; 535 536 /// Determine whether the no signed wrap flag is set. 537 bool hasNoSignedWrap() const LLVM_READONLY; 538 539 /// Determine whether the the nneg flag is set. 540 bool hasNonNeg() const LLVM_READONLY; 541 542 /// Return true if this operator has flags which may cause this instruction 543 /// to evaluate to poison despite having non-poison inputs. 544 bool hasPoisonGeneratingFlags() const LLVM_READONLY; 545 546 /// Drops flags that may cause this instruction to evaluate to poison despite 547 /// having non-poison inputs. 548 void dropPoisonGeneratingFlags(); 549 550 /// Return true if this instruction has poison-generating metadata. 551 bool hasPoisonGeneratingMetadata() const LLVM_READONLY; 552 553 /// Drops metadata that may generate poison. 554 void dropPoisonGeneratingMetadata(); 555 556 /// Return true if this instruction has poison-generating attribute. 557 bool hasPoisonGeneratingReturnAttributes() const LLVM_READONLY; 558 559 /// Drops return attributes that may generate poison. 560 void dropPoisonGeneratingReturnAttributes(); 561 562 /// Return true if this instruction has poison-generating flags, 563 /// return attributes or metadata. 564 bool hasPoisonGeneratingAnnotations() const { 565 return hasPoisonGeneratingFlags() || 566 hasPoisonGeneratingReturnAttributes() || 567 hasPoisonGeneratingMetadata(); 568 } 569 570 /// Drops flags, return attributes and metadata that may generate poison. 571 void dropPoisonGeneratingAnnotations() { 572 dropPoisonGeneratingFlags(); 573 dropPoisonGeneratingReturnAttributes(); 574 dropPoisonGeneratingMetadata(); 575 } 576 577 /// This function drops non-debug unknown metadata (through 578 /// dropUnknownNonDebugMetadata). For calls, it also drops parameter and 579 /// return attributes that can cause undefined behaviour. Both of these should 580 /// be done by passes which move instructions in IR. 581 void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef<unsigned> KnownIDs = {}); 582 583 /// Drop any attributes or metadata that can cause immediate undefined 584 /// behavior. Retain other attributes/metadata on a best-effort basis. 585 /// This should be used when speculating instructions. 586 void dropUBImplyingAttrsAndMetadata(); 587 588 /// Determine whether the exact flag is set. 589 bool isExact() const LLVM_READONLY; 590 591 /// Set or clear all fast-math-flags on this instruction, which must be an 592 /// operator which supports this flag. See LangRef.html for the meaning of 593 /// this flag. 594 void setFast(bool B); 595 596 /// Set or clear the reassociation flag on this instruction, which must be 597 /// an operator which supports this flag. See LangRef.html for the meaning of 598 /// this flag. 599 void setHasAllowReassoc(bool B); 600 601 /// Set or clear the no-nans flag on this instruction, which must be an 602 /// operator which supports this flag. See LangRef.html for the meaning of 603 /// this flag. 604 void setHasNoNaNs(bool B); 605 606 /// Set or clear the no-infs flag on this instruction, which must be an 607 /// operator which supports this flag. See LangRef.html for the meaning of 608 /// this flag. 609 void setHasNoInfs(bool B); 610 611 /// Set or clear the no-signed-zeros flag on this instruction, which must be 612 /// an operator which supports this flag. See LangRef.html for the meaning of 613 /// this flag. 614 void setHasNoSignedZeros(bool B); 615 616 /// Set or clear the allow-reciprocal flag on this instruction, which must be 617 /// an operator which supports this flag. See LangRef.html for the meaning of 618 /// this flag. 619 void setHasAllowReciprocal(bool B); 620 621 /// Set or clear the allow-contract flag on this instruction, which must be 622 /// an operator which supports this flag. See LangRef.html for the meaning of 623 /// this flag. 624 void setHasAllowContract(bool B); 625 626 /// Set or clear the approximate-math-functions flag on this instruction, 627 /// which must be an operator which supports this flag. See LangRef.html for 628 /// the meaning of this flag. 629 void setHasApproxFunc(bool B); 630 631 /// Convenience function for setting multiple fast-math flags on this 632 /// instruction, which must be an operator which supports these flags. See 633 /// LangRef.html for the meaning of these flags. 634 void setFastMathFlags(FastMathFlags FMF); 635 636 /// Convenience function for transferring all fast-math flag values to this 637 /// instruction, which must be an operator which supports these flags. See 638 /// LangRef.html for the meaning of these flags. 639 void copyFastMathFlags(FastMathFlags FMF); 640 641 /// Determine whether all fast-math-flags are set. 642 bool isFast() const LLVM_READONLY; 643 644 /// Determine whether the allow-reassociation flag is set. 645 bool hasAllowReassoc() const LLVM_READONLY; 646 647 /// Determine whether the no-NaNs flag is set. 648 bool hasNoNaNs() const LLVM_READONLY; 649 650 /// Determine whether the no-infs flag is set. 651 bool hasNoInfs() const LLVM_READONLY; 652 653 /// Determine whether the no-signed-zeros flag is set. 654 bool hasNoSignedZeros() const LLVM_READONLY; 655 656 /// Determine whether the allow-reciprocal flag is set. 657 bool hasAllowReciprocal() const LLVM_READONLY; 658 659 /// Determine whether the allow-contract flag is set. 660 bool hasAllowContract() const LLVM_READONLY; 661 662 /// Determine whether the approximate-math-functions flag is set. 663 bool hasApproxFunc() const LLVM_READONLY; 664 665 /// Convenience function for getting all the fast-math flags, which must be an 666 /// operator which supports these flags. See LangRef.html for the meaning of 667 /// these flags. 668 FastMathFlags getFastMathFlags() const LLVM_READONLY; 669 670 /// Copy I's fast-math flags 671 void copyFastMathFlags(const Instruction *I); 672 673 /// Convenience method to copy supported exact, fast-math, and (optionally) 674 /// wrapping flags from V to this instruction. 675 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true); 676 677 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of 678 /// V and this instruction. 679 void andIRFlags(const Value *V); 680 681 /// Merge 2 debug locations and apply it to the Instruction. If the 682 /// instruction is a CallIns, we need to traverse the inline chain to find 683 /// the common scope. This is not efficient for N-way merging as each time 684 /// you merge 2 iterations, you need to rebuild the hashmap to find the 685 /// common scope. However, we still choose this API because: 686 /// 1) Simplicity: it takes 2 locations instead of a list of locations. 687 /// 2) In worst case, it increases the complexity from O(N*I) to 688 /// O(2*N*I), where N is # of Instructions to merge, and I is the 689 /// maximum level of inline stack. So it is still linear. 690 /// 3) Merging of call instructions should be extremely rare in real 691 /// applications, thus the N-way merging should be in code path. 692 /// The DebugLoc attached to this instruction will be overwritten by the 693 /// merged DebugLoc. 694 void applyMergedLocation(DILocation *LocA, DILocation *LocB); 695 696 /// Updates the debug location given that the instruction has been hoisted 697 /// from a block to a predecessor of that block. 698 /// Note: it is undefined behavior to call this on an instruction not 699 /// currently inserted into a function. 700 void updateLocationAfterHoist(); 701 702 /// Drop the instruction's debug location. This does not guarantee removal 703 /// of the !dbg source location attachment, as it must set a line 0 location 704 /// with scope information attached on call instructions. To guarantee 705 /// removal of the !dbg attachment, use the \ref setDebugLoc() API. 706 /// Note: it is undefined behavior to call this on an instruction not 707 /// currently inserted into a function. 708 void dropLocation(); 709 710 /// Merge the DIAssignID metadata from this instruction and those attached to 711 /// instructions in \p SourceInstructions. This process performs a RAUW on 712 /// the MetadataAsValue uses of the merged DIAssignID nodes. Not every 713 /// instruction in \p SourceInstructions needs to have DIAssignID 714 /// metadata. If none of them do then nothing happens. If this instruction 715 /// does not have a DIAssignID attachment but at least one in \p 716 /// SourceInstructions does then the merged one will be attached to 717 /// it. However, instructions without attachments in \p SourceInstructions 718 /// are not modified. 719 void mergeDIAssignID(ArrayRef<const Instruction *> SourceInstructions); 720 721 private: 722 // These are all implemented in Metadata.cpp. 723 MDNode *getMetadataImpl(StringRef Kind) const; 724 void 725 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 726 727 /// Update the LLVMContext ID-to-Instruction(s) mapping. If \p ID is nullptr 728 /// then clear the mapping for this instruction. 729 void updateDIAssignIDMapping(DIAssignID *ID); 730 731 public: 732 //===--------------------------------------------------------------------===// 733 // Predicates and helper methods. 734 //===--------------------------------------------------------------------===// 735 736 /// Return true if the instruction is associative: 737 /// 738 /// Associative operators satisfy: x op (y op z) === (x op y) op z 739 /// 740 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. 741 /// 742 bool isAssociative() const LLVM_READONLY; 743 static bool isAssociative(unsigned Opcode) { 744 return Opcode == And || Opcode == Or || Opcode == Xor || 745 Opcode == Add || Opcode == Mul; 746 } 747 748 /// Return true if the instruction is commutative: 749 /// 750 /// Commutative operators satisfy: (x op y) === (y op x) 751 /// 752 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when 753 /// applied to any type. 754 /// 755 bool isCommutative() const LLVM_READONLY; 756 static bool isCommutative(unsigned Opcode) { 757 switch (Opcode) { 758 case Add: case FAdd: 759 case Mul: case FMul: 760 case And: case Or: case Xor: 761 return true; 762 default: 763 return false; 764 } 765 } 766 767 /// Return true if the instruction is idempotent: 768 /// 769 /// Idempotent operators satisfy: x op x === x 770 /// 771 /// In LLVM, the And and Or operators are idempotent. 772 /// 773 bool isIdempotent() const { return isIdempotent(getOpcode()); } 774 static bool isIdempotent(unsigned Opcode) { 775 return Opcode == And || Opcode == Or; 776 } 777 778 /// Return true if the instruction is nilpotent: 779 /// 780 /// Nilpotent operators satisfy: x op x === Id, 781 /// 782 /// where Id is the identity for the operator, i.e. a constant such that 783 /// x op Id === x and Id op x === x for all x. 784 /// 785 /// In LLVM, the Xor operator is nilpotent. 786 /// 787 bool isNilpotent() const { return isNilpotent(getOpcode()); } 788 static bool isNilpotent(unsigned Opcode) { 789 return Opcode == Xor; 790 } 791 792 /// Return true if this instruction may modify memory. 793 bool mayWriteToMemory() const LLVM_READONLY; 794 795 /// Return true if this instruction may read memory. 796 bool mayReadFromMemory() const LLVM_READONLY; 797 798 /// Return true if this instruction may read or write memory. 799 bool mayReadOrWriteMemory() const { 800 return mayReadFromMemory() || mayWriteToMemory(); 801 } 802 803 /// Return true if this instruction has an AtomicOrdering of unordered or 804 /// higher. 805 bool isAtomic() const LLVM_READONLY; 806 807 /// Return true if this atomic instruction loads from memory. 808 bool hasAtomicLoad() const LLVM_READONLY; 809 810 /// Return true if this atomic instruction stores to memory. 811 bool hasAtomicStore() const LLVM_READONLY; 812 813 /// Return true if this instruction has a volatile memory access. 814 bool isVolatile() const LLVM_READONLY; 815 816 /// Return the type this instruction accesses in memory, if any. 817 Type *getAccessType() const LLVM_READONLY; 818 819 /// Return true if this instruction may throw an exception. 820 /// 821 /// If IncludePhaseOneUnwind is set, this will also include cases where 822 /// phase one unwinding may unwind past this frame due to skipping of 823 /// cleanup landingpads. 824 bool mayThrow(bool IncludePhaseOneUnwind = false) const LLVM_READONLY; 825 826 /// Return true if this instruction behaves like a memory fence: it can load 827 /// or store to memory location without being given a memory location. 828 bool isFenceLike() const { 829 switch (getOpcode()) { 830 default: 831 return false; 832 // This list should be kept in sync with the list in mayWriteToMemory for 833 // all opcodes which don't have a memory location. 834 case Instruction::Fence: 835 case Instruction::CatchPad: 836 case Instruction::CatchRet: 837 case Instruction::Call: 838 case Instruction::Invoke: 839 return true; 840 } 841 } 842 843 /// Return true if the instruction may have side effects. 844 /// 845 /// Side effects are: 846 /// * Writing to memory. 847 /// * Unwinding. 848 /// * Not returning (e.g. an infinite loop). 849 /// 850 /// Note that this does not consider malloc and alloca to have side 851 /// effects because the newly allocated memory is completely invisible to 852 /// instructions which don't use the returned value. For cases where this 853 /// matters, isSafeToSpeculativelyExecute may be more appropriate. 854 bool mayHaveSideEffects() const LLVM_READONLY; 855 856 /// Return true if the instruction can be removed if the result is unused. 857 /// 858 /// When constant folding some instructions cannot be removed even if their 859 /// results are unused. Specifically terminator instructions and calls that 860 /// may have side effects cannot be removed without semantically changing the 861 /// generated program. 862 bool isSafeToRemove() const LLVM_READONLY; 863 864 /// Return true if the instruction will return (unwinding is considered as 865 /// a form of returning control flow here). 866 bool willReturn() const LLVM_READONLY; 867 868 /// Return true if the instruction is a variety of EH-block. 869 bool isEHPad() const { 870 switch (getOpcode()) { 871 case Instruction::CatchSwitch: 872 case Instruction::CatchPad: 873 case Instruction::CleanupPad: 874 case Instruction::LandingPad: 875 return true; 876 default: 877 return false; 878 } 879 } 880 881 /// Return true if the instruction is a llvm.lifetime.start or 882 /// llvm.lifetime.end marker. 883 bool isLifetimeStartOrEnd() const LLVM_READONLY; 884 885 /// Return true if the instruction is a llvm.launder.invariant.group or 886 /// llvm.strip.invariant.group. 887 bool isLaunderOrStripInvariantGroup() const LLVM_READONLY; 888 889 /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst. 890 bool isDebugOrPseudoInst() const LLVM_READONLY; 891 892 /// Return a pointer to the next non-debug instruction in the same basic 893 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 894 /// operations if \c SkipPseudoOp is true. 895 const Instruction * 896 getNextNonDebugInstruction(bool SkipPseudoOp = false) const; 897 Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) { 898 return const_cast<Instruction *>( 899 static_cast<const Instruction *>(this)->getNextNonDebugInstruction( 900 SkipPseudoOp)); 901 } 902 903 /// Return a pointer to the previous non-debug instruction in the same basic 904 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 905 /// operations if \c SkipPseudoOp is true. 906 const Instruction * 907 getPrevNonDebugInstruction(bool SkipPseudoOp = false) const; 908 Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) { 909 return const_cast<Instruction *>( 910 static_cast<const Instruction *>(this)->getPrevNonDebugInstruction( 911 SkipPseudoOp)); 912 } 913 914 /// Create a copy of 'this' instruction that is identical in all ways except 915 /// the following: 916 /// * The instruction has no parent 917 /// * The instruction has no name 918 /// 919 Instruction *clone() const; 920 921 /// Return true if the specified instruction is exactly identical to the 922 /// current one. This means that all operands match and any extra information 923 /// (e.g. load is volatile) agree. 924 bool isIdenticalTo(const Instruction *I) const LLVM_READONLY; 925 926 /// This is like isIdenticalTo, except that it ignores the 927 /// SubclassOptionalData flags, which may specify conditions under which the 928 /// instruction's result is undefined. 929 bool 930 isIdenticalToWhenDefined(const Instruction *I, 931 bool IntersectAttrs = false) const LLVM_READONLY; 932 933 /// When checking for operation equivalence (using isSameOperationAs) it is 934 /// sometimes useful to ignore certain attributes. 935 enum OperationEquivalenceFlags { 936 /// Check for equivalence ignoring load/store alignment. 937 CompareIgnoringAlignment = 1 << 0, 938 /// Check for equivalence treating a type and a vector of that type 939 /// as equivalent. 940 CompareUsingScalarTypes = 1 << 1, 941 /// Check for equivalence with intersected callbase attrs. 942 CompareUsingIntersectedAttrs = 1 << 2, 943 }; 944 945 /// This function determines if the specified instruction executes the same 946 /// operation as the current one. This means that the opcodes, type, operand 947 /// types and any other factors affecting the operation must be the same. This 948 /// is similar to isIdenticalTo except the operands themselves don't have to 949 /// be identical. 950 /// @returns true if the specified instruction is the same operation as 951 /// the current one. 952 /// Determine if one instruction is the same operation as another. 953 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const LLVM_READONLY; 954 955 /// This function determines if the speficied instruction has the same 956 /// "special" characteristics as the current one. This means that opcode 957 /// specific details are the same. As a common example, if we are comparing 958 /// loads, then hasSameSpecialState would compare the alignments (among 959 /// other things). 960 /// @returns true if the specific instruction has the same opcde specific 961 /// characteristics as the current one. Determine if one instruction has the 962 /// same state as another. 963 bool hasSameSpecialState(const Instruction *I2, bool IgnoreAlignment = false, 964 bool IntersectAttrs = false) const LLVM_READONLY; 965 966 /// Return true if there are any uses of this instruction in blocks other than 967 /// the specified block. Note that PHI nodes are considered to evaluate their 968 /// operands in the corresponding predecessor block. 969 bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY; 970 971 /// Return the number of successors that this instruction has. The instruction 972 /// must be a terminator. 973 unsigned getNumSuccessors() const LLVM_READONLY; 974 975 /// Return the specified successor. This instruction must be a terminator. 976 BasicBlock *getSuccessor(unsigned Idx) const LLVM_READONLY; 977 978 /// Update the specified successor to point at the provided block. This 979 /// instruction must be a terminator. 980 void setSuccessor(unsigned Idx, BasicBlock *BB); 981 982 /// Replace specified successor OldBB to point at the provided block. 983 /// This instruction must be a terminator. 984 void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB); 985 986 /// Methods for support type inquiry through isa, cast, and dyn_cast: 987 static bool classof(const Value *V) { 988 return V->getValueID() >= Value::InstructionVal; 989 } 990 991 //---------------------------------------------------------------------- 992 // Exported enumerations. 993 // 994 enum TermOps { // These terminate basic blocks 995 #define FIRST_TERM_INST(N) TermOpsBegin = N, 996 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N, 997 #define LAST_TERM_INST(N) TermOpsEnd = N+1 998 #include "llvm/IR/Instruction.def" 999 }; 1000 1001 enum UnaryOps { 1002 #define FIRST_UNARY_INST(N) UnaryOpsBegin = N, 1003 #define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N, 1004 #define LAST_UNARY_INST(N) UnaryOpsEnd = N+1 1005 #include "llvm/IR/Instruction.def" 1006 }; 1007 1008 enum BinaryOps { 1009 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N, 1010 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N, 1011 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1 1012 #include "llvm/IR/Instruction.def" 1013 }; 1014 1015 enum MemoryOps { 1016 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N, 1017 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N, 1018 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1 1019 #include "llvm/IR/Instruction.def" 1020 }; 1021 1022 enum CastOps { 1023 #define FIRST_CAST_INST(N) CastOpsBegin = N, 1024 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N, 1025 #define LAST_CAST_INST(N) CastOpsEnd = N+1 1026 #include "llvm/IR/Instruction.def" 1027 }; 1028 1029 enum FuncletPadOps { 1030 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N, 1031 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N, 1032 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1 1033 #include "llvm/IR/Instruction.def" 1034 }; 1035 1036 enum OtherOps { 1037 #define FIRST_OTHER_INST(N) OtherOpsBegin = N, 1038 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N, 1039 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 1040 #include "llvm/IR/Instruction.def" 1041 }; 1042 1043 private: 1044 friend class SymbolTableListTraits<Instruction, ilist_iterator_bits<true>, 1045 ilist_parent<BasicBlock>>; 1046 friend class BasicBlock; // For renumbering. 1047 1048 // Shadow Value::setValueSubclassData with a private forwarding method so that 1049 // subclasses cannot accidentally use it. 1050 void setValueSubclassData(unsigned short D) { 1051 Value::setValueSubclassData(D); 1052 } 1053 1054 unsigned short getSubclassDataFromValue() const { 1055 return Value::getSubclassDataFromValue(); 1056 } 1057 1058 protected: 1059 // Instruction subclasses can stick up to 15 bits of stuff into the 1060 // SubclassData field of instruction with these members. 1061 1062 template <typename BitfieldElement> 1063 typename BitfieldElement::Type getSubclassData() const { 1064 static_assert( 1065 std::is_same<BitfieldElement, HasMetadataField>::value || 1066 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 1067 "Must not overlap with the metadata bit"); 1068 return Bitfield::get<BitfieldElement>(getSubclassDataFromValue()); 1069 } 1070 1071 template <typename BitfieldElement> 1072 void setSubclassData(typename BitfieldElement::Type Value) { 1073 static_assert( 1074 std::is_same<BitfieldElement, HasMetadataField>::value || 1075 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 1076 "Must not overlap with the metadata bit"); 1077 auto Storage = getSubclassDataFromValue(); 1078 Bitfield::set<BitfieldElement>(Storage, Value); 1079 setValueSubclassData(Storage); 1080 } 1081 1082 Instruction(Type *Ty, unsigned iType, AllocInfo AllocInfo, 1083 InsertPosition InsertBefore = nullptr); 1084 1085 private: 1086 /// Create a copy of this instruction. 1087 Instruction *cloneImpl() const; 1088 }; 1089 1090 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) { 1091 V->deleteValue(); 1092 } 1093 1094 } // end namespace llvm 1095 1096 #endif // LLVM_IR_INSTRUCTION_H 1097