1 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the declaration of the Instruction class, which is the 11 // base class for all of the LLVM instructions. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_IR_INSTRUCTION_H 16 #define LLVM_IR_INSTRUCTION_H 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/ilist_node.h" 20 #include "llvm/IR/DebugLoc.h" 21 #include "llvm/IR/User.h" 22 23 namespace llvm { 24 25 class FastMathFlags; 26 class LLVMContext; 27 class MDNode; 28 struct AAMDNodes; 29 30 template<typename ValueSubClass, typename ItemParentClass> 31 class SymbolTableListTraits; 32 33 class Instruction : public User, public ilist_node<Instruction> { 34 void operator=(const Instruction &) LLVM_DELETED_FUNCTION; 35 Instruction(const Instruction &) LLVM_DELETED_FUNCTION; 36 37 BasicBlock *Parent; 38 DebugLoc DbgLoc; // 'dbg' Metadata cache. 39 40 enum { 41 /// HasMetadataBit - This is a bit stored in the SubClassData field which 42 /// indicates whether this instruction has metadata attached to it or not. 43 HasMetadataBit = 1 << 15 44 }; 45 public: 46 // Out of line virtual method, so the vtable, etc has a home. 47 ~Instruction(); 48 49 /// user_back - Specialize the methods defined in Value, as we know that an 50 /// instruction can only be used by other instructions. user_back()51 Instruction *user_back() { return cast<Instruction>(*user_begin());} user_back()52 const Instruction *user_back() const { return cast<Instruction>(*user_begin());} 53 getParent()54 inline const BasicBlock *getParent() const { return Parent; } getParent()55 inline BasicBlock *getParent() { return Parent; } 56 57 const DataLayout *getDataLayout() const; 58 59 /// removeFromParent - This method unlinks 'this' from the containing basic 60 /// block, but does not delete it. 61 /// 62 void removeFromParent(); 63 64 /// eraseFromParent - This method unlinks 'this' from the containing basic 65 /// block and deletes it. 66 /// 67 void eraseFromParent(); 68 69 /// insertBefore - Insert an unlinked instructions into a basic block 70 /// immediately before the specified instruction. 71 void insertBefore(Instruction *InsertPos); 72 73 /// insertAfter - Insert an unlinked instructions into a basic block 74 /// immediately after the specified instruction. 75 void insertAfter(Instruction *InsertPos); 76 77 /// moveBefore - Unlink this instruction from its current basic block and 78 /// insert it into the basic block that MovePos lives in, right before 79 /// MovePos. 80 void moveBefore(Instruction *MovePos); 81 82 //===--------------------------------------------------------------------===// 83 // Subclass classification. 84 //===--------------------------------------------------------------------===// 85 86 /// getOpcode() returns a member of one of the enums like Instruction::Add. getOpcode()87 unsigned getOpcode() const { return getValueID() - InstructionVal; } 88 getOpcodeName()89 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); } isTerminator()90 bool isTerminator() const { return isTerminator(getOpcode()); } isBinaryOp()91 bool isBinaryOp() const { return isBinaryOp(getOpcode()); } isShift()92 bool isShift() { return isShift(getOpcode()); } isCast()93 bool isCast() const { return isCast(getOpcode()); } 94 95 static const char* getOpcodeName(unsigned OpCode); 96 isTerminator(unsigned OpCode)97 static inline bool isTerminator(unsigned OpCode) { 98 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd; 99 } 100 isBinaryOp(unsigned Opcode)101 static inline bool isBinaryOp(unsigned Opcode) { 102 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd; 103 } 104 105 /// @brief Determine if the Opcode is one of the shift instructions. isShift(unsigned Opcode)106 static inline bool isShift(unsigned Opcode) { 107 return Opcode >= Shl && Opcode <= AShr; 108 } 109 110 /// isLogicalShift - Return true if this is a logical shift left or a logical 111 /// shift right. isLogicalShift()112 inline bool isLogicalShift() const { 113 return getOpcode() == Shl || getOpcode() == LShr; 114 } 115 116 /// isArithmeticShift - Return true if this is an arithmetic shift right. isArithmeticShift()117 inline bool isArithmeticShift() const { 118 return getOpcode() == AShr; 119 } 120 121 /// @brief Determine if the OpCode is one of the CastInst instructions. isCast(unsigned OpCode)122 static inline bool isCast(unsigned OpCode) { 123 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd; 124 } 125 126 //===--------------------------------------------------------------------===// 127 // Metadata manipulation. 128 //===--------------------------------------------------------------------===// 129 130 /// hasMetadata() - Return true if this instruction has any metadata attached 131 /// to it. hasMetadata()132 bool hasMetadata() const { 133 return !DbgLoc.isUnknown() || hasMetadataHashEntry(); 134 } 135 136 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has 137 /// metadata attached to it other than a debug location. hasMetadataOtherThanDebugLoc()138 bool hasMetadataOtherThanDebugLoc() const { 139 return hasMetadataHashEntry(); 140 } 141 142 /// getMetadata - Get the metadata of given kind attached to this Instruction. 143 /// If the metadata is not found then return null. getMetadata(unsigned KindID)144 MDNode *getMetadata(unsigned KindID) const { 145 if (!hasMetadata()) return nullptr; 146 return getMetadataImpl(KindID); 147 } 148 149 /// getMetadata - Get the metadata of given kind attached to this Instruction. 150 /// If the metadata is not found then return null. getMetadata(StringRef Kind)151 MDNode *getMetadata(StringRef Kind) const { 152 if (!hasMetadata()) return nullptr; 153 return getMetadataImpl(Kind); 154 } 155 156 /// getAllMetadata - Get all metadata attached to this Instruction. The first 157 /// element of each pair returned is the KindID, the second element is the 158 /// metadata value. This list is returned sorted by the KindID. 159 void getAllMetadata(SmallVectorImpl<std::pair<unsigned,MDNode * >> & MDs)160 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 161 if (hasMetadata()) 162 getAllMetadataImpl(MDs); 163 } 164 165 /// getAllMetadataOtherThanDebugLoc - This does the same thing as 166 /// getAllMetadata, except that it filters out the debug location. getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,MDNode * >> & MDs)167 void getAllMetadataOtherThanDebugLoc( 168 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 169 if (hasMetadataOtherThanDebugLoc()) 170 getAllMetadataOtherThanDebugLocImpl(MDs); 171 } 172 173 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from 174 /// this instruction. When Merge is true, the existing AA metadata is 175 /// merged with that from this instruction providing the most-general result. 176 void getAAMetadata(AAMDNodes &N, bool Merge = false) const; 177 178 /// setMetadata - Set the metadata of the specified kind to the specified 179 /// node. This updates/replaces metadata if already present, or removes it if 180 /// Node is null. 181 void setMetadata(unsigned KindID, MDNode *Node); 182 void setMetadata(StringRef Kind, MDNode *Node); 183 184 /// \brief Drop unknown metadata. 185 /// Passes are required to drop metadata they don't understand. This is a 186 /// convenience method for passes to do so. 187 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs); dropUnknownMetadata()188 void dropUnknownMetadata() { 189 return dropUnknownMetadata(None); 190 } dropUnknownMetadata(unsigned ID1)191 void dropUnknownMetadata(unsigned ID1) { 192 return dropUnknownMetadata(makeArrayRef(ID1)); 193 } dropUnknownMetadata(unsigned ID1,unsigned ID2)194 void dropUnknownMetadata(unsigned ID1, unsigned ID2) { 195 unsigned IDs[] = {ID1, ID2}; 196 return dropUnknownMetadata(IDs); 197 } 198 199 /// setAAMetadata - Sets the metadata on this instruction from the 200 /// AAMDNodes structure. 201 void setAAMetadata(const AAMDNodes &N); 202 203 /// setDebugLoc - Set the debug location information for this instruction. setDebugLoc(const DebugLoc & Loc)204 void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; } 205 206 /// getDebugLoc - Return the debug location for this node as a DebugLoc. getDebugLoc()207 const DebugLoc &getDebugLoc() const { return DbgLoc; } 208 209 /// Set or clear the unsafe-algebra flag on this instruction, which must be an 210 /// operator which supports this flag. See LangRef.html for the meaning of 211 /// this flag. 212 void setHasUnsafeAlgebra(bool B); 213 214 /// Set or clear the no-nans flag on this instruction, which must be an 215 /// operator which supports this flag. See LangRef.html for the meaning of 216 /// this flag. 217 void setHasNoNaNs(bool B); 218 219 /// Set or clear the no-infs flag on this instruction, which must be an 220 /// operator which supports this flag. See LangRef.html for the meaning of 221 /// this flag. 222 void setHasNoInfs(bool B); 223 224 /// Set or clear the no-signed-zeros flag on this instruction, which must be 225 /// an operator which supports this flag. See LangRef.html for the meaning of 226 /// this flag. 227 void setHasNoSignedZeros(bool B); 228 229 /// Set or clear the allow-reciprocal flag on this instruction, which must be 230 /// an operator which supports this flag. See LangRef.html for the meaning of 231 /// this flag. 232 void setHasAllowReciprocal(bool B); 233 234 /// Convenience function for setting multiple fast-math flags on this 235 /// instruction, which must be an operator which supports these flags. See 236 /// LangRef.html for the meaning of these flags. 237 void setFastMathFlags(FastMathFlags FMF); 238 239 /// Convenience function for transferring all fast-math flag values to this 240 /// instruction, which must be an operator which supports these flags. See 241 /// LangRef.html for the meaning of these flags. 242 void copyFastMathFlags(FastMathFlags FMF); 243 244 /// Determine whether the unsafe-algebra flag is set. 245 bool hasUnsafeAlgebra() const; 246 247 /// Determine whether the no-NaNs flag is set. 248 bool hasNoNaNs() const; 249 250 /// Determine whether the no-infs flag is set. 251 bool hasNoInfs() const; 252 253 /// Determine whether the no-signed-zeros flag is set. 254 bool hasNoSignedZeros() const; 255 256 /// Determine whether the allow-reciprocal flag is set. 257 bool hasAllowReciprocal() const; 258 259 /// Convenience function for getting all the fast-math flags, which must be an 260 /// operator which supports these flags. See LangRef.html for the meaning of 261 /// these flags. 262 FastMathFlags getFastMathFlags() const; 263 264 /// Copy I's fast-math flags 265 void copyFastMathFlags(const Instruction *I); 266 267 private: 268 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side 269 /// metadata hash. hasMetadataHashEntry()270 bool hasMetadataHashEntry() const { 271 return (getSubclassDataFromValue() & HasMetadataBit) != 0; 272 } 273 274 // These are all implemented in Metadata.cpp. 275 MDNode *getMetadataImpl(unsigned KindID) const; 276 MDNode *getMetadataImpl(StringRef Kind) const; 277 void 278 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 279 void getAllMetadataOtherThanDebugLocImpl( 280 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 281 void clearMetadataHashEntries(); 282 public: 283 //===--------------------------------------------------------------------===// 284 // Predicates and helper methods. 285 //===--------------------------------------------------------------------===// 286 287 288 /// isAssociative - Return true if the instruction is associative: 289 /// 290 /// Associative operators satisfy: x op (y op z) === (x op y) op z 291 /// 292 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. 293 /// 294 bool isAssociative() const; 295 static bool isAssociative(unsigned op); 296 297 /// isCommutative - Return true if the instruction is commutative: 298 /// 299 /// Commutative operators satisfy: (x op y) === (y op x) 300 /// 301 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when 302 /// applied to any type. 303 /// isCommutative()304 bool isCommutative() const { return isCommutative(getOpcode()); } 305 static bool isCommutative(unsigned op); 306 307 /// isIdempotent - Return true if the instruction is idempotent: 308 /// 309 /// Idempotent operators satisfy: x op x === x 310 /// 311 /// In LLVM, the And and Or operators are idempotent. 312 /// isIdempotent()313 bool isIdempotent() const { return isIdempotent(getOpcode()); } 314 static bool isIdempotent(unsigned op); 315 316 /// isNilpotent - Return true if the instruction is nilpotent: 317 /// 318 /// Nilpotent operators satisfy: x op x === Id, 319 /// 320 /// where Id is the identity for the operator, i.e. a constant such that 321 /// x op Id === x and Id op x === x for all x. 322 /// 323 /// In LLVM, the Xor operator is nilpotent. 324 /// isNilpotent()325 bool isNilpotent() const { return isNilpotent(getOpcode()); } 326 static bool isNilpotent(unsigned op); 327 328 /// mayWriteToMemory - Return true if this instruction may modify memory. 329 /// 330 bool mayWriteToMemory() const; 331 332 /// mayReadFromMemory - Return true if this instruction may read memory. 333 /// 334 bool mayReadFromMemory() const; 335 336 /// mayReadOrWriteMemory - Return true if this instruction may read or 337 /// write memory. 338 /// mayReadOrWriteMemory()339 bool mayReadOrWriteMemory() const { 340 return mayReadFromMemory() || mayWriteToMemory(); 341 } 342 343 /// isAtomic - Return true if this instruction has an 344 /// AtomicOrdering of unordered or higher. 345 /// 346 bool isAtomic() const; 347 348 /// mayThrow - Return true if this instruction may throw an exception. 349 /// 350 bool mayThrow() const; 351 352 /// mayReturn - Return true if this is a function that may return. 353 /// this is true for all normal instructions. The only exception 354 /// is functions that are marked with the 'noreturn' attribute. 355 /// 356 bool mayReturn() const; 357 358 /// mayHaveSideEffects - Return true if the instruction may have side effects. 359 /// 360 /// Note that this does not consider malloc and alloca to have side 361 /// effects because the newly allocated memory is completely invisible to 362 /// instructions which don't used the returned value. For cases where this 363 /// matters, isSafeToSpeculativelyExecute may be more appropriate. mayHaveSideEffects()364 bool mayHaveSideEffects() const { 365 return mayWriteToMemory() || mayThrow() || !mayReturn(); 366 } 367 368 /// clone() - Create a copy of 'this' instruction that is identical in all 369 /// ways except the following: 370 /// * The instruction has no parent 371 /// * The instruction has no name 372 /// 373 Instruction *clone() const; 374 375 /// isIdenticalTo - Return true if the specified instruction is exactly 376 /// identical to the current one. This means that all operands match and any 377 /// extra information (e.g. load is volatile) agree. 378 bool isIdenticalTo(const Instruction *I) const; 379 380 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it 381 /// ignores the SubclassOptionalData flags, which specify conditions 382 /// under which the instruction's result is undefined. 383 bool isIdenticalToWhenDefined(const Instruction *I) const; 384 385 /// When checking for operation equivalence (using isSameOperationAs) it is 386 /// sometimes useful to ignore certain attributes. 387 enum OperationEquivalenceFlags { 388 /// Check for equivalence ignoring load/store alignment. 389 CompareIgnoringAlignment = 1<<0, 390 /// Check for equivalence treating a type and a vector of that type 391 /// as equivalent. 392 CompareUsingScalarTypes = 1<<1 393 }; 394 395 /// This function determines if the specified instruction executes the same 396 /// operation as the current one. This means that the opcodes, type, operand 397 /// types and any other factors affecting the operation must be the same. This 398 /// is similar to isIdenticalTo except the operands themselves don't have to 399 /// be identical. 400 /// @returns true if the specified instruction is the same operation as 401 /// the current one. 402 /// @brief Determine if one instruction is the same operation as another. 403 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const; 404 405 /// isUsedOutsideOfBlock - Return true if there are any uses of this 406 /// instruction in blocks other than the specified block. Note that PHI nodes 407 /// are considered to evaluate their operands in the corresponding predecessor 408 /// block. 409 bool isUsedOutsideOfBlock(const BasicBlock *BB) const; 410 411 412 /// Methods for support type inquiry through isa, cast, and dyn_cast: classof(const Value * V)413 static inline bool classof(const Value *V) { 414 return V->getValueID() >= Value::InstructionVal; 415 } 416 417 //---------------------------------------------------------------------- 418 // Exported enumerations. 419 // 420 enum TermOps { // These terminate basic blocks 421 #define FIRST_TERM_INST(N) TermOpsBegin = N, 422 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N, 423 #define LAST_TERM_INST(N) TermOpsEnd = N+1 424 #include "llvm/IR/Instruction.def" 425 }; 426 427 enum BinaryOps { 428 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N, 429 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N, 430 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1 431 #include "llvm/IR/Instruction.def" 432 }; 433 434 enum MemoryOps { 435 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N, 436 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N, 437 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1 438 #include "llvm/IR/Instruction.def" 439 }; 440 441 enum CastOps { 442 #define FIRST_CAST_INST(N) CastOpsBegin = N, 443 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N, 444 #define LAST_CAST_INST(N) CastOpsEnd = N+1 445 #include "llvm/IR/Instruction.def" 446 }; 447 448 enum OtherOps { 449 #define FIRST_OTHER_INST(N) OtherOpsBegin = N, 450 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N, 451 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 452 #include "llvm/IR/Instruction.def" 453 }; 454 private: 455 // Shadow Value::setValueSubclassData with a private forwarding method so that 456 // subclasses cannot accidentally use it. setValueSubclassData(unsigned short D)457 void setValueSubclassData(unsigned short D) { 458 Value::setValueSubclassData(D); 459 } getSubclassDataFromValue()460 unsigned short getSubclassDataFromValue() const { 461 return Value::getSubclassDataFromValue(); 462 } 463 setHasMetadataHashEntry(bool V)464 void setHasMetadataHashEntry(bool V) { 465 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) | 466 (V ? HasMetadataBit : 0)); 467 } 468 469 friend class SymbolTableListTraits<Instruction, BasicBlock>; 470 void setParent(BasicBlock *P); 471 protected: 472 // Instruction subclasses can stick up to 15 bits of stuff into the 473 // SubclassData field of instruction with these members. 474 475 // Verify that only the low 15 bits are used. setInstructionSubclassData(unsigned short D)476 void setInstructionSubclassData(unsigned short D) { 477 assert((D & HasMetadataBit) == 0 && "Out of range value put into field"); 478 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D); 479 } 480 getSubclassDataFromInstruction()481 unsigned getSubclassDataFromInstruction() const { 482 return getSubclassDataFromValue() & ~HasMetadataBit; 483 } 484 485 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 486 Instruction *InsertBefore = nullptr); 487 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 488 BasicBlock *InsertAtEnd); 489 virtual Instruction *clone_impl() const = 0; 490 491 }; 492 493 // Instruction* is only 4-byte aligned. 494 template<> 495 class PointerLikeTypeTraits<Instruction*> { 496 typedef Instruction* PT; 497 public: getAsVoidPointer(PT P)498 static inline void *getAsVoidPointer(PT P) { return P; } getFromVoidPointer(void * P)499 static inline PT getFromVoidPointer(void *P) { 500 return static_cast<PT>(P); 501 } 502 enum { NumLowBitsAvailable = 2 }; 503 }; 504 505 } // End llvm namespace 506 507 #endif 508