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