1 //===- llvm/InstrTypes.h - Important Instruction subclasses -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines various meta classes of instructions that exist in the VM
11 // representation. Specific concrete subclasses of these may be found in the
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_IR_INSTRTYPES_H
17 #define LLVM_IR_INSTRTYPES_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/OperandTraits.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/User.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/ErrorHandling.h"
47 //===----------------------------------------------------------------------===//
48 // TerminatorInst Class
49 //===----------------------------------------------------------------------===//
51 /// Subclasses of this class are all able to terminate a basic
52 /// block. Thus, these are all the flow control type of operations.
54 class TerminatorInst : public Instruction {
56 TerminatorInst(Type *Ty, Instruction::TermOps iType,
57 Use *Ops, unsigned NumOps,
58 Instruction *InsertBefore = nullptr)
59 : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
61 TerminatorInst(Type *Ty, Instruction::TermOps iType,
62 Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
63 : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
66 /// Return the number of successors that this terminator has.
67 unsigned getNumSuccessors() const;
69 /// Return the specified successor.
70 BasicBlock *getSuccessor(unsigned idx) const;
72 /// Update the specified successor to point at the provided block.
73 void setSuccessor(unsigned idx, BasicBlock *B);
75 // Methods for support type inquiry through isa, cast, and dyn_cast:
76 static inline bool classof(const Instruction *I) {
77 return I->isTerminator();
79 static inline bool classof(const Value *V) {
80 return isa<Instruction>(V) && classof(cast<Instruction>(V));
83 // \brief Returns true if this terminator relates to exception handling.
84 bool isExceptional() const {
85 switch (getOpcode()) {
86 case Instruction::CatchSwitch:
87 case Instruction::CatchRet:
88 case Instruction::CleanupRet:
89 case Instruction::Invoke:
90 case Instruction::Resume:
97 //===--------------------------------------------------------------------===//
98 // succ_iterator definition
99 //===--------------------------------------------------------------------===//
101 template <class Term, class BB> // Successor Iterator
102 class SuccIterator : public std::iterator<std::random_access_iterator_tag, BB,
105 std::iterator<std::random_access_iterator_tag, BB, int, BB *, BB *>;
108 using pointer = typename super::pointer;
109 using reference = typename super::reference;
114 using Self = SuccIterator<Term, BB>;
116 inline bool index_is_valid(unsigned idx) {
117 return idx < TermInst->getNumSuccessors();
120 /// \brief Proxy object to allow write access in operator[]
121 class SuccessorProxy {
125 explicit SuccessorProxy(const Self &it) : it(it) {}
127 SuccessorProxy(const SuccessorProxy &) = default;
129 SuccessorProxy &operator=(SuccessorProxy r) {
130 *this = reference(r);
134 SuccessorProxy &operator=(reference r) {
135 it.TermInst->setSuccessor(it.idx, r);
139 operator reference() const { return *it; }
144 explicit inline SuccIterator(Term T) : TermInst(T), idx(0) {}
146 inline SuccIterator(Term T, bool) : TermInst(T) {
148 idx = TermInst->getNumSuccessors();
150 // Term == NULL happens, if a basic block is not fully constructed and
151 // consequently getTerminator() returns NULL. In this case we construct
152 // a SuccIterator which describes a basic block that has zero
154 // Defining SuccIterator for incomplete and malformed CFGs is especially
155 // useful for debugging.
159 /// This is used to interface between code that wants to
160 /// operate on terminator instructions directly.
161 unsigned getSuccessorIndex() const { return idx; }
163 inline bool operator==(const Self &x) const { return idx == x.idx; }
164 inline bool operator!=(const Self &x) const { return !operator==(x); }
166 inline reference operator*() const { return TermInst->getSuccessor(idx); }
167 inline pointer operator->() const { return operator*(); }
169 inline Self &operator++() {
174 inline Self operator++(int) { // Postincrement
180 inline Self &operator--() {
184 inline Self operator--(int) { // Postdecrement
190 inline bool operator<(const Self &x) const {
191 assert(TermInst == x.TermInst &&
192 "Cannot compare iterators of different blocks!");
196 inline bool operator<=(const Self &x) const {
197 assert(TermInst == x.TermInst &&
198 "Cannot compare iterators of different blocks!");
201 inline bool operator>=(const Self &x) const {
202 assert(TermInst == x.TermInst &&
203 "Cannot compare iterators of different blocks!");
207 inline bool operator>(const Self &x) const {
208 assert(TermInst == x.TermInst &&
209 "Cannot compare iterators of different blocks!");
213 inline Self &operator+=(int Right) {
214 unsigned new_idx = idx + Right;
215 assert(index_is_valid(new_idx) && "Iterator index out of bound");
220 inline Self operator+(int Right) const {
226 inline Self &operator-=(int Right) { return operator+=(-Right); }
228 inline Self operator-(int Right) const { return operator+(-Right); }
230 inline int operator-(const Self &x) const {
231 assert(TermInst == x.TermInst &&
232 "Cannot work on iterators of different blocks!");
233 int distance = idx - x.idx;
237 inline SuccessorProxy operator[](int offset) {
240 return SuccessorProxy(tmp);
243 /// Get the source BB of this iterator.
244 inline BB *getSource() {
245 assert(TermInst && "Source not available, if basic block was malformed");
246 return TermInst->getParent();
250 using succ_iterator = SuccIterator<TerminatorInst *, BasicBlock>;
251 using succ_const_iterator =
252 SuccIterator<const TerminatorInst *, const BasicBlock>;
253 using succ_range = iterator_range<succ_iterator>;
254 using succ_const_range = iterator_range<succ_const_iterator>;
257 inline succ_iterator succ_begin() { return succ_iterator(this); }
258 inline succ_const_iterator succ_begin() const {
259 return succ_const_iterator(this);
261 inline succ_iterator succ_end() { return succ_iterator(this, true); }
262 inline succ_const_iterator succ_end() const {
263 return succ_const_iterator(this, true);
267 inline succ_range successors() {
268 return succ_range(succ_begin(), succ_end());
270 inline succ_const_range successors() const {
271 return succ_const_range(succ_begin(), succ_end());
275 //===----------------------------------------------------------------------===//
276 // UnaryInstruction Class
277 //===----------------------------------------------------------------------===//
279 class UnaryInstruction : public Instruction {
281 UnaryInstruction(Type *Ty, unsigned iType, Value *V,
282 Instruction *IB = nullptr)
283 : Instruction(Ty, iType, &Op<0>(), 1, IB) {
286 UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
287 : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
292 // allocate space for exactly one operand
293 void *operator new(size_t s) {
294 return User::operator new(s, 1);
297 /// Transparently provide more efficient getOperand methods.
298 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
300 // Methods for support type inquiry through isa, cast, and dyn_cast:
301 static inline bool classof(const Instruction *I) {
302 return I->getOpcode() == Instruction::Alloca ||
303 I->getOpcode() == Instruction::Load ||
304 I->getOpcode() == Instruction::VAArg ||
305 I->getOpcode() == Instruction::ExtractValue ||
306 (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
308 static inline bool classof(const Value *V) {
309 return isa<Instruction>(V) && classof(cast<Instruction>(V));
314 struct OperandTraits<UnaryInstruction> :
315 public FixedNumOperandTraits<UnaryInstruction, 1> {
318 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
320 //===----------------------------------------------------------------------===//
321 // BinaryOperator Class
322 //===----------------------------------------------------------------------===//
324 class BinaryOperator : public Instruction {
326 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
327 const Twine &Name, Instruction *InsertBefore);
328 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
329 const Twine &Name, BasicBlock *InsertAtEnd);
331 void init(BinaryOps iType);
333 // Note: Instruction needs to be a friend here to call cloneImpl.
334 friend class Instruction;
336 BinaryOperator *cloneImpl() const;
339 // allocate space for exactly two operands
340 void *operator new(size_t s) {
341 return User::operator new(s, 2);
344 /// Transparently provide more efficient getOperand methods.
345 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
347 /// Construct a binary instruction, given the opcode and the two
348 /// operands. Optionally (if InstBefore is specified) insert the instruction
349 /// into a BasicBlock right before the specified instruction. The specified
350 /// Instruction is allowed to be a dereferenced end iterator.
352 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
353 const Twine &Name = Twine(),
354 Instruction *InsertBefore = nullptr);
356 /// Construct a binary instruction, given the opcode and the two
357 /// operands. Also automatically insert this instruction to the end of the
358 /// BasicBlock specified.
360 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
361 const Twine &Name, BasicBlock *InsertAtEnd);
363 /// These methods just forward to Create, and are useful when you
364 /// statically know what type of instruction you're going to create. These
365 /// helpers just save some typing.
366 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
367 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
368 const Twine &Name = "") {\
369 return Create(Instruction::OPC, V1, V2, Name);\
371 #include "llvm/IR/Instruction.def"
372 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
373 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
374 const Twine &Name, BasicBlock *BB) {\
375 return Create(Instruction::OPC, V1, V2, Name, BB);\
377 #include "llvm/IR/Instruction.def"
378 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
379 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
380 const Twine &Name, Instruction *I) {\
381 return Create(Instruction::OPC, V1, V2, Name, I);\
383 #include "llvm/IR/Instruction.def"
385 static BinaryOperator *CreateWithCopiedFlags(BinaryOps Opc,
386 Value *V1, Value *V2,
387 BinaryOperator *CopyBO,
388 const Twine &Name = "") {
389 BinaryOperator *BO = Create(Opc, V1, V2, Name);
390 BO->copyIRFlags(CopyBO);
394 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
395 const Twine &Name = "") {
396 BinaryOperator *BO = Create(Opc, V1, V2, Name);
397 BO->setHasNoSignedWrap(true);
400 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
401 const Twine &Name, BasicBlock *BB) {
402 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
403 BO->setHasNoSignedWrap(true);
406 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
407 const Twine &Name, Instruction *I) {
408 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
409 BO->setHasNoSignedWrap(true);
413 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
414 const Twine &Name = "") {
415 BinaryOperator *BO = Create(Opc, V1, V2, Name);
416 BO->setHasNoUnsignedWrap(true);
419 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
420 const Twine &Name, BasicBlock *BB) {
421 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
422 BO->setHasNoUnsignedWrap(true);
425 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
426 const Twine &Name, Instruction *I) {
427 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
428 BO->setHasNoUnsignedWrap(true);
432 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
433 const Twine &Name = "") {
434 BinaryOperator *BO = Create(Opc, V1, V2, Name);
435 BO->setIsExact(true);
438 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
439 const Twine &Name, BasicBlock *BB) {
440 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
441 BO->setIsExact(true);
444 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
445 const Twine &Name, Instruction *I) {
446 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
447 BO->setIsExact(true);
451 #define DEFINE_HELPERS(OPC, NUWNSWEXACT) \
452 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \
453 const Twine &Name = "") { \
454 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \
456 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
457 Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \
458 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \
460 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
461 Value *V1, Value *V2, const Twine &Name, Instruction *I) { \
462 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \
465 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
466 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
467 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
468 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
469 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
470 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
471 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
472 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
474 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv
475 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv
476 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr
477 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr
479 #undef DEFINE_HELPERS
481 /// Helper functions to construct and inspect unary operations (NEG and NOT)
482 /// via binary operators SUB and XOR:
484 /// Create the NEG and NOT instructions out of SUB and XOR instructions.
486 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
487 Instruction *InsertBefore = nullptr);
488 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
489 BasicBlock *InsertAtEnd);
490 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
491 Instruction *InsertBefore = nullptr);
492 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
493 BasicBlock *InsertAtEnd);
494 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
495 Instruction *InsertBefore = nullptr);
496 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
497 BasicBlock *InsertAtEnd);
498 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
499 Instruction *InsertBefore = nullptr);
500 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
501 BasicBlock *InsertAtEnd);
502 static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
503 Instruction *InsertBefore = nullptr);
504 static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
505 BasicBlock *InsertAtEnd);
507 /// Check if the given Value is a NEG, FNeg, or NOT instruction.
509 static bool isNeg(const Value *V);
510 static bool isFNeg(const Value *V, bool IgnoreZeroSign=false);
511 static bool isNot(const Value *V);
513 /// Helper functions to extract the unary argument of a NEG, FNEG or NOT
514 /// operation implemented via Sub, FSub, or Xor.
516 static const Value *getNegArgument(const Value *BinOp);
517 static Value *getNegArgument( Value *BinOp);
518 static const Value *getFNegArgument(const Value *BinOp);
519 static Value *getFNegArgument( Value *BinOp);
520 static const Value *getNotArgument(const Value *BinOp);
521 static Value *getNotArgument( Value *BinOp);
523 BinaryOps getOpcode() const {
524 return static_cast<BinaryOps>(Instruction::getOpcode());
527 /// Exchange the two operands to this instruction.
528 /// This instruction is safe to use on any binary instruction and
529 /// does not modify the semantics of the instruction. If the instruction
530 /// cannot be reversed (ie, it's a Div), then return true.
534 // Methods for support type inquiry through isa, cast, and dyn_cast:
535 static inline bool classof(const Instruction *I) {
536 return I->isBinaryOp();
538 static inline bool classof(const Value *V) {
539 return isa<Instruction>(V) && classof(cast<Instruction>(V));
544 struct OperandTraits<BinaryOperator> :
545 public FixedNumOperandTraits<BinaryOperator, 2> {
548 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
550 //===----------------------------------------------------------------------===//
552 //===----------------------------------------------------------------------===//
554 /// This is the base class for all instructions that perform data
555 /// casts. It is simply provided so that instruction category testing
556 /// can be performed with code like:
558 /// if (isa<CastInst>(Instr)) { ... }
559 /// @brief Base class of casting instructions.
560 class CastInst : public UnaryInstruction {
562 /// @brief Constructor with insert-before-instruction semantics for subclasses
563 CastInst(Type *Ty, unsigned iType, Value *S,
564 const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
565 : UnaryInstruction(Ty, iType, S, InsertBefore) {
568 /// @brief Constructor with insert-at-end-of-block semantics for subclasses
569 CastInst(Type *Ty, unsigned iType, Value *S,
570 const Twine &NameStr, BasicBlock *InsertAtEnd)
571 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
576 /// Provides a way to construct any of the CastInst subclasses using an
577 /// opcode instead of the subclass's constructor. The opcode must be in the
578 /// CastOps category (Instruction::isCast(opcode) returns true). This
579 /// constructor has insert-before-instruction semantics to automatically
580 /// insert the new CastInst before InsertBefore (if it is non-null).
581 /// @brief Construct any of the CastInst subclasses
582 static CastInst *Create(
583 Instruction::CastOps, ///< The opcode of the cast instruction
584 Value *S, ///< The value to be casted (operand 0)
585 Type *Ty, ///< The type to which cast should be made
586 const Twine &Name = "", ///< Name for the instruction
587 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
589 /// Provides a way to construct any of the CastInst subclasses using an
590 /// opcode instead of the subclass's constructor. The opcode must be in the
591 /// CastOps category. This constructor has insert-at-end-of-block semantics
592 /// to automatically insert the new CastInst at the end of InsertAtEnd (if
594 /// @brief Construct any of the CastInst subclasses
595 static CastInst *Create(
596 Instruction::CastOps, ///< The opcode for the cast instruction
597 Value *S, ///< The value to be casted (operand 0)
598 Type *Ty, ///< The type to which operand is casted
599 const Twine &Name, ///< The name for the instruction
600 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
603 /// @brief Create a ZExt or BitCast cast instruction
604 static CastInst *CreateZExtOrBitCast(
605 Value *S, ///< The value to be casted (operand 0)
606 Type *Ty, ///< The type to which cast should be made
607 const Twine &Name = "", ///< Name for the instruction
608 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
611 /// @brief Create a ZExt or BitCast cast instruction
612 static CastInst *CreateZExtOrBitCast(
613 Value *S, ///< The value to be casted (operand 0)
614 Type *Ty, ///< The type to which operand is casted
615 const Twine &Name, ///< The name for the instruction
616 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
619 /// @brief Create a SExt or BitCast cast instruction
620 static CastInst *CreateSExtOrBitCast(
621 Value *S, ///< The value to be casted (operand 0)
622 Type *Ty, ///< The type to which cast should be made
623 const Twine &Name = "", ///< Name for the instruction
624 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
627 /// @brief Create a SExt or BitCast cast instruction
628 static CastInst *CreateSExtOrBitCast(
629 Value *S, ///< The value to be casted (operand 0)
630 Type *Ty, ///< The type to which operand is casted
631 const Twine &Name, ///< The name for the instruction
632 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
635 /// @brief Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
636 static CastInst *CreatePointerCast(
637 Value *S, ///< The pointer value to be casted (operand 0)
638 Type *Ty, ///< The type to which operand is casted
639 const Twine &Name, ///< The name for the instruction
640 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
643 /// @brief Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
644 static CastInst *CreatePointerCast(
645 Value *S, ///< The pointer value to be casted (operand 0)
646 Type *Ty, ///< The type to which cast should be made
647 const Twine &Name = "", ///< Name for the instruction
648 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
651 /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
652 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
653 Value *S, ///< The pointer value to be casted (operand 0)
654 Type *Ty, ///< The type to which operand is casted
655 const Twine &Name, ///< The name for the instruction
656 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
659 /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
660 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
661 Value *S, ///< The pointer value to be casted (operand 0)
662 Type *Ty, ///< The type to which cast should be made
663 const Twine &Name = "", ///< Name for the instruction
664 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
667 /// @brief Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
669 /// If the value is a pointer type and the destination an integer type,
670 /// creates a PtrToInt cast. If the value is an integer type and the
671 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
673 static CastInst *CreateBitOrPointerCast(
674 Value *S, ///< The pointer value to be casted (operand 0)
675 Type *Ty, ///< The type to which cast should be made
676 const Twine &Name = "", ///< Name for the instruction
677 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
680 /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
681 static CastInst *CreateIntegerCast(
682 Value *S, ///< The pointer value to be casted (operand 0)
683 Type *Ty, ///< The type to which cast should be made
684 bool isSigned, ///< Whether to regard S as signed or not
685 const Twine &Name = "", ///< Name for the instruction
686 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
689 /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
690 static CastInst *CreateIntegerCast(
691 Value *S, ///< The integer value to be casted (operand 0)
692 Type *Ty, ///< The integer type to which operand is casted
693 bool isSigned, ///< Whether to regard S as signed or not
694 const Twine &Name, ///< The name for the instruction
695 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
698 /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
699 static CastInst *CreateFPCast(
700 Value *S, ///< The floating point value to be casted
701 Type *Ty, ///< The floating point type to cast to
702 const Twine &Name = "", ///< Name for the instruction
703 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
706 /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
707 static CastInst *CreateFPCast(
708 Value *S, ///< The floating point value to be casted
709 Type *Ty, ///< The floating point type to cast to
710 const Twine &Name, ///< The name for the instruction
711 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
714 /// @brief Create a Trunc or BitCast cast instruction
715 static CastInst *CreateTruncOrBitCast(
716 Value *S, ///< The value to be casted (operand 0)
717 Type *Ty, ///< The type to which cast should be made
718 const Twine &Name = "", ///< Name for the instruction
719 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
722 /// @brief Create a Trunc or BitCast cast instruction
723 static CastInst *CreateTruncOrBitCast(
724 Value *S, ///< The value to be casted (operand 0)
725 Type *Ty, ///< The type to which operand is casted
726 const Twine &Name, ///< The name for the instruction
727 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
730 /// @brief Check whether it is valid to call getCastOpcode for these types.
731 static bool isCastable(
732 Type *SrcTy, ///< The Type from which the value should be cast.
733 Type *DestTy ///< The Type to which the value should be cast.
736 /// @brief Check whether a bitcast between these types is valid
737 static bool isBitCastable(
738 Type *SrcTy, ///< The Type from which the value should be cast.
739 Type *DestTy ///< The Type to which the value should be cast.
742 /// @brief Check whether a bitcast, inttoptr, or ptrtoint cast between these
743 /// types is valid and a no-op.
745 /// This ensures that any pointer<->integer cast has enough bits in the
746 /// integer and any other cast is a bitcast.
747 static bool isBitOrNoopPointerCastable(
748 Type *SrcTy, ///< The Type from which the value should be cast.
749 Type *DestTy, ///< The Type to which the value should be cast.
750 const DataLayout &DL);
752 /// Returns the opcode necessary to cast Val into Ty using usual casting
754 /// @brief Infer the opcode for cast operand and type
755 static Instruction::CastOps getCastOpcode(
756 const Value *Val, ///< The value to cast
757 bool SrcIsSigned, ///< Whether to treat the source as signed
758 Type *Ty, ///< The Type to which the value should be casted
759 bool DstIsSigned ///< Whether to treate the dest. as signed
762 /// There are several places where we need to know if a cast instruction
763 /// only deals with integer source and destination types. To simplify that
764 /// logic, this method is provided.
765 /// @returns true iff the cast has only integral typed operand and dest type.
766 /// @brief Determine if this is an integer-only cast.
767 bool isIntegerCast() const;
769 /// A lossless cast is one that does not alter the basic value. It implies
770 /// a no-op cast but is more stringent, preventing things like int->float,
771 /// long->double, or int->ptr.
772 /// @returns true iff the cast is lossless.
773 /// @brief Determine if this is a lossless cast.
774 bool isLosslessCast() const;
776 /// A no-op cast is one that can be effected without changing any bits.
777 /// It implies that the source and destination types are the same size. The
778 /// IntPtrTy argument is used to make accurate determinations for casts
779 /// involving Integer and Pointer types. They are no-op casts if the integer
780 /// is the same size as the pointer. However, pointer size varies with
781 /// platform. Generally, the result of DataLayout::getIntPtrType() should be
782 /// passed in. If that's not available, use Type::Int64Ty, which will make
783 /// the isNoopCast call conservative.
784 /// @brief Determine if the described cast is a no-op cast.
785 static bool isNoopCast(
786 Instruction::CastOps Opcode, ///< Opcode of cast
787 Type *SrcTy, ///< SrcTy of cast
788 Type *DstTy, ///< DstTy of cast
789 Type *IntPtrTy ///< Integer type corresponding to Ptr types
792 /// @brief Determine if this cast is a no-op cast.
794 Type *IntPtrTy ///< Integer type corresponding to pointer
797 /// @brief Determine if this cast is a no-op cast.
799 /// \param DL is the DataLayout to get the Int Ptr type from.
800 bool isNoopCast(const DataLayout &DL) const;
802 /// Determine how a pair of casts can be eliminated, if they can be at all.
803 /// This is a helper function for both CastInst and ConstantExpr.
804 /// @returns 0 if the CastInst pair can't be eliminated, otherwise
805 /// returns Instruction::CastOps value for a cast that can replace
806 /// the pair, casting SrcTy to DstTy.
807 /// @brief Determine if a cast pair is eliminable
808 static unsigned isEliminableCastPair(
809 Instruction::CastOps firstOpcode, ///< Opcode of first cast
810 Instruction::CastOps secondOpcode, ///< Opcode of second cast
811 Type *SrcTy, ///< SrcTy of 1st cast
812 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
813 Type *DstTy, ///< DstTy of 2nd cast
814 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
815 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
816 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null
819 /// @brief Return the opcode of this CastInst
820 Instruction::CastOps getOpcode() const {
821 return Instruction::CastOps(Instruction::getOpcode());
824 /// @brief Return the source type, as a convenience
825 Type* getSrcTy() const { return getOperand(0)->getType(); }
826 /// @brief Return the destination type, as a convenience
827 Type* getDestTy() const { return getType(); }
829 /// This method can be used to determine if a cast from S to DstTy using
830 /// Opcode op is valid or not.
831 /// @returns true iff the proposed cast is valid.
832 /// @brief Determine if a cast is valid without creating one.
833 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
835 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
836 static inline bool classof(const Instruction *I) {
839 static inline bool classof(const Value *V) {
840 return isa<Instruction>(V) && classof(cast<Instruction>(V));
844 //===----------------------------------------------------------------------===//
846 //===----------------------------------------------------------------------===//
848 /// This class is the base class for the comparison instructions.
849 /// @brief Abstract base class of comparison instructions.
850 class CmpInst : public Instruction {
852 /// This enumeration lists the possible predicates for CmpInst subclasses.
853 /// Values in the range 0-31 are reserved for FCmpInst, while values in the
854 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
855 /// predicate values are not overlapping between the classes.
857 /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
858 /// FCMP_* values. Changing the bit patterns requires a potential change to
861 // Opcode U L G E Intuitive operation
862 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
863 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
864 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
865 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
866 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
867 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
868 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
869 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
870 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
871 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
872 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
873 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
874 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
875 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
876 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
877 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
878 FIRST_FCMP_PREDICATE = FCMP_FALSE,
879 LAST_FCMP_PREDICATE = FCMP_TRUE,
880 BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
881 ICMP_EQ = 32, ///< equal
882 ICMP_NE = 33, ///< not equal
883 ICMP_UGT = 34, ///< unsigned greater than
884 ICMP_UGE = 35, ///< unsigned greater or equal
885 ICMP_ULT = 36, ///< unsigned less than
886 ICMP_ULE = 37, ///< unsigned less or equal
887 ICMP_SGT = 38, ///< signed greater than
888 ICMP_SGE = 39, ///< signed greater or equal
889 ICMP_SLT = 40, ///< signed less than
890 ICMP_SLE = 41, ///< signed less or equal
891 FIRST_ICMP_PREDICATE = ICMP_EQ,
892 LAST_ICMP_PREDICATE = ICMP_SLE,
893 BAD_ICMP_PREDICATE = ICMP_SLE + 1
897 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
898 Value *LHS, Value *RHS, const Twine &Name = "",
899 Instruction *InsertBefore = nullptr);
901 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
902 Value *LHS, Value *RHS, const Twine &Name,
903 BasicBlock *InsertAtEnd);
906 // allocate space for exactly two operands
907 void *operator new(size_t s) {
908 return User::operator new(s, 2);
911 /// Construct a compare instruction, given the opcode, the predicate and
912 /// the two operands. Optionally (if InstBefore is specified) insert the
913 /// instruction into a BasicBlock right before the specified instruction.
914 /// The specified Instruction is allowed to be a dereferenced end iterator.
915 /// @brief Create a CmpInst
916 static CmpInst *Create(OtherOps Op,
917 Predicate predicate, Value *S1,
918 Value *S2, const Twine &Name = "",
919 Instruction *InsertBefore = nullptr);
921 /// Construct a compare instruction, given the opcode, the predicate and the
922 /// two operands. Also automatically insert this instruction to the end of
923 /// the BasicBlock specified.
924 /// @brief Create a CmpInst
925 static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1,
926 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
928 /// @brief Get the opcode casted to the right type
929 OtherOps getOpcode() const {
930 return static_cast<OtherOps>(Instruction::getOpcode());
933 /// @brief Return the predicate for this instruction.
934 Predicate getPredicate() const {
935 return Predicate(getSubclassDataFromInstruction());
938 /// @brief Set the predicate for this instruction to the specified value.
939 void setPredicate(Predicate P) { setInstructionSubclassData(P); }
941 static bool isFPPredicate(Predicate P) {
942 return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
945 static bool isIntPredicate(Predicate P) {
946 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
949 static StringRef getPredicateName(Predicate P);
951 bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
952 bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
954 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
955 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
956 /// @returns the inverse predicate for the instruction's current predicate.
957 /// @brief Return the inverse of the instruction's predicate.
958 Predicate getInversePredicate() const {
959 return getInversePredicate(getPredicate());
962 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
963 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
964 /// @returns the inverse predicate for predicate provided in \p pred.
965 /// @brief Return the inverse of a given predicate
966 static Predicate getInversePredicate(Predicate pred);
968 /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
969 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
970 /// @returns the predicate that would be the result of exchanging the two
971 /// operands of the CmpInst instruction without changing the result
973 /// @brief Return the predicate as if the operands were swapped
974 Predicate getSwappedPredicate() const {
975 return getSwappedPredicate(getPredicate());
978 /// This is a static version that you can use without an instruction
980 /// @brief Return the predicate as if the operands were swapped.
981 static Predicate getSwappedPredicate(Predicate pred);
983 /// @brief Provide more efficient getOperand methods.
984 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
986 /// This is just a convenience that dispatches to the subclasses.
987 /// @brief Swap the operands and adjust predicate accordingly to retain
988 /// the same comparison.
991 /// This is just a convenience that dispatches to the subclasses.
992 /// @brief Determine if this CmpInst is commutative.
993 bool isCommutative() const;
995 /// This is just a convenience that dispatches to the subclasses.
996 /// @brief Determine if this is an equals/not equals predicate.
997 bool isEquality() const;
999 /// @returns true if the comparison is signed, false otherwise.
1000 /// @brief Determine if this instruction is using a signed comparison.
1001 bool isSigned() const {
1002 return isSigned(getPredicate());
1005 /// @returns true if the comparison is unsigned, false otherwise.
1006 /// @brief Determine if this instruction is using an unsigned comparison.
1007 bool isUnsigned() const {
1008 return isUnsigned(getPredicate());
1011 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1012 /// @returns the signed version of the unsigned predicate pred.
1013 /// @brief return the signed version of a predicate
1014 static Predicate getSignedPredicate(Predicate pred);
1016 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1017 /// @returns the signed version of the predicate for this instruction (which
1018 /// has to be an unsigned predicate).
1019 /// @brief return the signed version of a predicate
1020 Predicate getSignedPredicate() {
1021 return getSignedPredicate(getPredicate());
1024 /// This is just a convenience.
1025 /// @brief Determine if this is true when both operands are the same.
1026 bool isTrueWhenEqual() const {
1027 return isTrueWhenEqual(getPredicate());
1030 /// This is just a convenience.
1031 /// @brief Determine if this is false when both operands are the same.
1032 bool isFalseWhenEqual() const {
1033 return isFalseWhenEqual(getPredicate());
1036 /// @returns true if the predicate is unsigned, false otherwise.
1037 /// @brief Determine if the predicate is an unsigned operation.
1038 static bool isUnsigned(Predicate predicate);
1040 /// @returns true if the predicate is signed, false otherwise.
1041 /// @brief Determine if the predicate is an signed operation.
1042 static bool isSigned(Predicate predicate);
1044 /// @brief Determine if the predicate is an ordered operation.
1045 static bool isOrdered(Predicate predicate);
1047 /// @brief Determine if the predicate is an unordered operation.
1048 static bool isUnordered(Predicate predicate);
1050 /// Determine if the predicate is true when comparing a value with itself.
1051 static bool isTrueWhenEqual(Predicate predicate);
1053 /// Determine if the predicate is false when comparing a value with itself.
1054 static bool isFalseWhenEqual(Predicate predicate);
1056 /// Determine if Pred1 implies Pred2 is true when two compares have matching
1058 static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2);
1060 /// Determine if Pred1 implies Pred2 is false when two compares have matching
1062 static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2);
1064 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1065 static inline bool classof(const Instruction *I) {
1066 return I->getOpcode() == Instruction::ICmp ||
1067 I->getOpcode() == Instruction::FCmp;
1069 static inline bool classof(const Value *V) {
1070 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1073 /// @brief Create a result type for fcmp/icmp
1074 static Type* makeCmpResultType(Type* opnd_type) {
1075 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1076 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1077 vt->getNumElements());
1079 return Type::getInt1Ty(opnd_type->getContext());
1083 // Shadow Value::setValueSubclassData with a private forwarding method so that
1084 // subclasses cannot accidentally use it.
1085 void setValueSubclassData(unsigned short D) {
1086 Value::setValueSubclassData(D);
1090 // FIXME: these are redundant if CmpInst < BinaryOperator
1092 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1095 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1097 //===----------------------------------------------------------------------===//
1098 // FuncletPadInst Class
1099 //===----------------------------------------------------------------------===//
1100 class FuncletPadInst : public Instruction {
1102 FuncletPadInst(const FuncletPadInst &CPI);
1104 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1105 ArrayRef<Value *> Args, unsigned Values,
1106 const Twine &NameStr, Instruction *InsertBefore);
1107 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1108 ArrayRef<Value *> Args, unsigned Values,
1109 const Twine &NameStr, BasicBlock *InsertAtEnd);
1111 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
1114 // Note: Instruction needs to be a friend here to call cloneImpl.
1115 friend class Instruction;
1116 friend class CatchPadInst;
1117 friend class CleanupPadInst;
1119 FuncletPadInst *cloneImpl() const;
1122 /// Provide fast operand accessors
1123 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1125 /// getNumArgOperands - Return the number of funcletpad arguments.
1127 unsigned getNumArgOperands() const { return getNumOperands() - 1; }
1129 /// Convenience accessors
1131 /// \brief Return the outer EH-pad this funclet is nested within.
1133 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
1134 /// is a CatchPadInst.
1135 Value *getParentPad() const { return Op<-1>(); }
1136 void setParentPad(Value *ParentPad) {
1138 Op<-1>() = ParentPad;
1141 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
1143 Value *getArgOperand(unsigned i) const { return getOperand(i); }
1144 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
1146 /// arg_operands - iteration adapter for range-for loops.
1147 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
1149 /// arg_operands - iteration adapter for range-for loops.
1150 const_op_range arg_operands() const {
1151 return const_op_range(op_begin(), op_end() - 1);
1154 // Methods for support type inquiry through isa, cast, and dyn_cast:
1155 static inline bool classof(const Instruction *I) { return I->isFuncletPad(); }
1156 static inline bool classof(const Value *V) {
1157 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1162 struct OperandTraits<FuncletPadInst>
1163 : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
1165 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
1167 /// \brief A lightweight accessor for an operand bundle meant to be passed
1168 /// around by value.
1169 struct OperandBundleUse {
1170 ArrayRef<Use> Inputs;
1172 OperandBundleUse() = default;
1173 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1174 : Inputs(Inputs), Tag(Tag) {}
1176 /// \brief Return true if the operand at index \p Idx in this operand bundle
1177 /// has the attribute A.
1178 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
1179 if (isDeoptOperandBundle())
1180 if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
1181 return Inputs[Idx]->getType()->isPointerTy();
1183 // Conservative answer: no operands have any attributes.
1187 /// \brief Return the tag of this operand bundle as a string.
1188 StringRef getTagName() const {
1189 return Tag->getKey();
1192 /// \brief Return the tag of this operand bundle as an integer.
1194 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1195 /// and this function returns the unique integer getOrInsertBundleTag
1196 /// associated the tag of this operand bundle to.
1197 uint32_t getTagID() const {
1198 return Tag->getValue();
1201 /// \brief Return true if this is a "deopt" operand bundle.
1202 bool isDeoptOperandBundle() const {
1203 return getTagID() == LLVMContext::OB_deopt;
1206 /// \brief Return true if this is a "funclet" operand bundle.
1207 bool isFuncletOperandBundle() const {
1208 return getTagID() == LLVMContext::OB_funclet;
1212 /// \brief Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1213 StringMapEntry<uint32_t> *Tag;
1216 /// \brief A container for an operand bundle being viewed as a set of values
1217 /// rather than a set of uses.
1219 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1220 /// so it is possible to create and pass around "self-contained" instances of
1221 /// OperandBundleDef and ConstOperandBundleDef.
1222 template <typename InputTy> class OperandBundleDefT {
1224 std::vector<InputTy> Inputs;
1227 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1228 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1229 explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
1230 : Tag(std::move(Tag)), Inputs(Inputs) {}
1232 explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1233 Tag = OBU.getTagName();
1234 Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1237 ArrayRef<InputTy> inputs() const { return Inputs; }
1239 using input_iterator = typename std::vector<InputTy>::const_iterator;
1241 size_t input_size() const { return Inputs.size(); }
1242 input_iterator input_begin() const { return Inputs.begin(); }
1243 input_iterator input_end() const { return Inputs.end(); }
1245 StringRef getTag() const { return Tag; }
1248 using OperandBundleDef = OperandBundleDefT<Value *>;
1249 using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
1251 /// \brief A mixin to add operand bundle functionality to llvm instruction
1254 /// OperandBundleUser uses the descriptor area co-allocated with the host User
1255 /// to store some meta information about which operands are "normal" operands,
1256 /// and which ones belong to some operand bundle.
1258 /// The layout of an operand bundle user is
1260 /// +-----------uint32_t End-------------------------------------+
1262 /// | +--------uint32_t Begin--------------------+ |
1265 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1266 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1267 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1270 /// | +--------uint32_t Begin------------+ |
1272 /// +-----------uint32_t End-----------------------------+
1275 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use list.
1276 /// These descriptions are installed and managed by this class, and they're all
1277 /// instances of OperandBundleUser<T>::BundleOpInfo.
1279 /// DU is an additional descriptor installed by User's 'operator new' to keep
1280 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not
1281 /// access or modify DU in any way, it's an implementation detail private to
1284 /// The regular Use& vector for the User starts at U0. The operand bundle uses
1285 /// are part of the Use& vector, just like normal uses. In the diagram above,
1286 /// the operand bundle uses start at BOI0_U0. Each instance of BundleOpInfo has
1287 /// information about a contiguous set of uses constituting an operand bundle,
1288 /// and the total set of operand bundle uses themselves form a contiguous set of
1289 /// uses (i.e. there are no gaps between uses corresponding to individual
1290 /// operand bundles).
1292 /// This class does not know the location of the set of operand bundle uses
1293 /// within the use list -- that is decided by the User using this class via the
1294 /// BeginIdx argument in populateBundleOperandInfos.
1296 /// Currently operand bundle users with hung-off operands are not supported.
1297 template <typename InstrTy, typename OpIteratorTy> class OperandBundleUser {
1299 /// \brief Return the number of operand bundles associated with this User.
1300 unsigned getNumOperandBundles() const {
1301 return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1304 /// \brief Return true if this User has any operand bundles.
1305 bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1307 /// \brief Return the index of the first bundle operand in the Use array.
1308 unsigned getBundleOperandsStartIndex() const {
1309 assert(hasOperandBundles() && "Don't call otherwise!");
1310 return bundle_op_info_begin()->Begin;
1313 /// \brief Return the index of the last bundle operand in the Use array.
1314 unsigned getBundleOperandsEndIndex() const {
1315 assert(hasOperandBundles() && "Don't call otherwise!");
1316 return bundle_op_info_end()[-1].End;
1319 /// Return true if the operand at index \p Idx is a bundle operand.
1320 bool isBundleOperand(unsigned Idx) const {
1321 return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1322 Idx < getBundleOperandsEndIndex();
1325 /// \brief Return the total number operands (not operand bundles) used by
1326 /// every operand bundle in this OperandBundleUser.
1327 unsigned getNumTotalBundleOperands() const {
1328 if (!hasOperandBundles())
1331 unsigned Begin = getBundleOperandsStartIndex();
1332 unsigned End = getBundleOperandsEndIndex();
1334 assert(Begin <= End && "Should be!");
1338 /// \brief Return the operand bundle at a specific index.
1339 OperandBundleUse getOperandBundleAt(unsigned Index) const {
1340 assert(Index < getNumOperandBundles() && "Index out of bounds!");
1341 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1344 /// \brief Return the number of operand bundles with the tag Name attached to
1345 /// this instruction.
1346 unsigned countOperandBundlesOfType(StringRef Name) const {
1348 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1349 if (getOperandBundleAt(i).getTagName() == Name)
1355 /// \brief Return the number of operand bundles with the tag ID attached to
1356 /// this instruction.
1357 unsigned countOperandBundlesOfType(uint32_t ID) const {
1359 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1360 if (getOperandBundleAt(i).getTagID() == ID)
1366 /// \brief Return an operand bundle by name, if present.
1368 /// It is an error to call this for operand bundle types that may have
1369 /// multiple instances of them on the same instruction.
1370 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1371 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1373 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1374 OperandBundleUse U = getOperandBundleAt(i);
1375 if (U.getTagName() == Name)
1382 /// \brief Return an operand bundle by tag ID, if present.
1384 /// It is an error to call this for operand bundle types that may have
1385 /// multiple instances of them on the same instruction.
1386 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1387 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1389 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1390 OperandBundleUse U = getOperandBundleAt(i);
1391 if (U.getTagID() == ID)
1398 /// \brief Return the list of operand bundles attached to this instruction as
1399 /// a vector of OperandBundleDefs.
1401 /// This function copies the OperandBundeUse instances associated with this
1402 /// OperandBundleUser to a vector of OperandBundleDefs. Note:
1403 /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1404 /// representations of operand bundles (see documentation above).
1405 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1406 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1407 Defs.emplace_back(getOperandBundleAt(i));
1410 /// \brief Return the operand bundle for the operand at index OpIdx.
1412 /// It is an error to call this with an OpIdx that does not correspond to an
1414 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1415 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1418 /// \brief Return true if this operand bundle user has operand bundles that
1419 /// may read from the heap.
1420 bool hasReadingOperandBundles() const {
1421 // Implementation note: this is a conservative implementation of operand
1422 // bundle semantics, where *any* operand bundle forces a callsite to be at
1424 return hasOperandBundles();
1427 /// \brief Return true if this operand bundle user has operand bundles that
1428 /// may write to the heap.
1429 bool hasClobberingOperandBundles() const {
1430 for (auto &BOI : bundle_op_infos()) {
1431 if (BOI.Tag->second == LLVMContext::OB_deopt ||
1432 BOI.Tag->second == LLVMContext::OB_funclet)
1435 // This instruction has an operand bundle that is not known to us.
1436 // Assume the worst.
1443 /// \brief Return true if the bundle operand at index \p OpIdx has the
1445 bool bundleOperandHasAttr(unsigned OpIdx, Attribute::AttrKind A) const {
1446 auto &BOI = getBundleOpInfoForOperand(OpIdx);
1447 auto OBU = operandBundleFromBundleOpInfo(BOI);
1448 return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
1451 /// \brief Return true if \p Other has the same sequence of operand bundle
1452 /// tags with the same number of operands on each one of them as this
1453 /// OperandBundleUser.
1454 bool hasIdenticalOperandBundleSchema(
1455 const OperandBundleUser<InstrTy, OpIteratorTy> &Other) const {
1456 if (getNumOperandBundles() != Other.getNumOperandBundles())
1459 return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
1460 Other.bundle_op_info_begin());
1463 /// \brief Return true if this operand bundle user contains operand bundles
1464 /// with tags other than those specified in \p IDs.
1465 bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
1466 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1467 uint32_t ID = getOperandBundleAt(i).getTagID();
1468 if (!is_contained(IDs, ID))
1475 /// \brief Is the function attribute S disallowed by some operand bundle on
1476 /// this operand bundle user?
1477 bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1478 // Operand bundles only possibly disallow readnone, readonly and argmenonly
1479 // attributes. All String attributes are fine.
1483 /// \brief Is the function attribute A disallowed by some operand bundle on
1484 /// this operand bundle user?
1485 bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1490 case Attribute::ArgMemOnly:
1491 return hasReadingOperandBundles();
1493 case Attribute::ReadNone:
1494 return hasReadingOperandBundles();
1496 case Attribute::ReadOnly:
1497 return hasClobberingOperandBundles();
1500 llvm_unreachable("switch has a default case!");
1503 /// \brief Used to keep track of an operand bundle. See the main comment on
1504 /// OperandBundleUser above.
1505 struct BundleOpInfo {
1506 /// \brief The operand bundle tag, interned by
1507 /// LLVMContextImpl::getOrInsertBundleTag.
1508 StringMapEntry<uint32_t> *Tag;
1510 /// \brief The index in the Use& vector where operands for this operand
1514 /// \brief The index in the Use& vector where operands for this operand
1518 bool operator==(const BundleOpInfo &Other) const {
1519 return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
1523 /// \brief Simple helper function to map a BundleOpInfo to an
1524 /// OperandBundleUse.
1526 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1527 auto op_begin = static_cast<const InstrTy *>(this)->op_begin();
1528 ArrayRef<Use> Inputs(op_begin + BOI.Begin, op_begin + BOI.End);
1529 return OperandBundleUse(BOI.Tag, Inputs);
1532 using bundle_op_iterator = BundleOpInfo *;
1533 using const_bundle_op_iterator = const BundleOpInfo *;
1535 /// \brief Return the start of the list of BundleOpInfo instances associated
1536 /// with this OperandBundleUser.
1537 bundle_op_iterator bundle_op_info_begin() {
1538 if (!static_cast<InstrTy *>(this)->hasDescriptor())
1541 uint8_t *BytesBegin = static_cast<InstrTy *>(this)->getDescriptor().begin();
1542 return reinterpret_cast<bundle_op_iterator>(BytesBegin);
1545 /// \brief Return the start of the list of BundleOpInfo instances associated
1546 /// with this OperandBundleUser.
1547 const_bundle_op_iterator bundle_op_info_begin() const {
1548 auto *NonConstThis =
1549 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1550 return NonConstThis->bundle_op_info_begin();
1553 /// \brief Return the end of the list of BundleOpInfo instances associated
1554 /// with this OperandBundleUser.
1555 bundle_op_iterator bundle_op_info_end() {
1556 if (!static_cast<InstrTy *>(this)->hasDescriptor())
1559 uint8_t *BytesEnd = static_cast<InstrTy *>(this)->getDescriptor().end();
1560 return reinterpret_cast<bundle_op_iterator>(BytesEnd);
1563 /// \brief Return the end of the list of BundleOpInfo instances associated
1564 /// with this OperandBundleUser.
1565 const_bundle_op_iterator bundle_op_info_end() const {
1566 auto *NonConstThis =
1567 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1568 return NonConstThis->bundle_op_info_end();
1571 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1572 iterator_range<bundle_op_iterator> bundle_op_infos() {
1573 return make_range(bundle_op_info_begin(), bundle_op_info_end());
1576 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1577 iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
1578 return make_range(bundle_op_info_begin(), bundle_op_info_end());
1581 /// \brief Populate the BundleOpInfo instances and the Use& vector from \p
1582 /// Bundles. Return the op_iterator pointing to the Use& one past the last
1583 /// last bundle operand use.
1585 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
1586 /// instance allocated in this User's descriptor.
1587 OpIteratorTy populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
1588 const unsigned BeginIndex) {
1589 auto It = static_cast<InstrTy *>(this)->op_begin() + BeginIndex;
1590 for (auto &B : Bundles)
1591 It = std::copy(B.input_begin(), B.input_end(), It);
1593 auto *ContextImpl = static_cast<InstrTy *>(this)->getContext().pImpl;
1594 auto BI = Bundles.begin();
1595 unsigned CurrentIndex = BeginIndex;
1597 for (auto &BOI : bundle_op_infos()) {
1598 assert(BI != Bundles.end() && "Incorrect allocation?");
1600 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
1601 BOI.Begin = CurrentIndex;
1602 BOI.End = CurrentIndex + BI->input_size();
1603 CurrentIndex = BOI.End;
1607 assert(BI == Bundles.end() && "Incorrect allocation?");
1612 /// \brief Return the BundleOpInfo for the operand at index OpIdx.
1614 /// It is an error to call this with an OpIdx that does not correspond to an
1616 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
1617 for (auto &BOI : bundle_op_infos())
1618 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
1621 llvm_unreachable("Did not find operand bundle for operand!");
1624 /// \brief Return the total number of values used in \p Bundles.
1625 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
1627 for (auto &B : Bundles)
1628 Total += B.input_size();
1633 } // end namespace llvm
1635 #endif // LLVM_IR_INSTRTYPES_H