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/Optional.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/IR/Attributes.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/OperandTraits.h"
31 //===----------------------------------------------------------------------===//
32 // TerminatorInst Class
33 //===----------------------------------------------------------------------===//
35 /// Subclasses of this class are all able to terminate a basic
36 /// block. Thus, these are all the flow control type of operations.
38 class TerminatorInst : public Instruction {
40 TerminatorInst(Type *Ty, Instruction::TermOps iType,
41 Use *Ops, unsigned NumOps,
42 Instruction *InsertBefore = nullptr)
43 : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
45 TerminatorInst(Type *Ty, Instruction::TermOps iType,
46 Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
47 : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
49 // Out of line virtual method, so the vtable, etc has a home.
50 ~TerminatorInst() override;
52 /// Virtual methods - Terminators should overload these and provide inline
53 /// overrides of non-V methods.
54 virtual BasicBlock *getSuccessorV(unsigned idx) const = 0;
55 virtual unsigned getNumSuccessorsV() const = 0;
56 virtual void setSuccessorV(unsigned idx, BasicBlock *B) = 0;
59 /// Return the number of successors that this terminator has.
60 unsigned getNumSuccessors() const {
61 return getNumSuccessorsV();
64 /// Return the specified successor.
65 BasicBlock *getSuccessor(unsigned idx) const {
66 return getSuccessorV(idx);
69 /// Update the specified successor to point at the provided block.
70 void setSuccessor(unsigned idx, BasicBlock *B) {
71 setSuccessorV(idx, B);
74 // Methods for support type inquiry through isa, cast, and dyn_cast:
75 static inline bool classof(const Instruction *I) {
76 return I->isTerminator();
78 static inline bool classof(const Value *V) {
79 return isa<Instruction>(V) && classof(cast<Instruction>(V));
82 // \brief Returns true if this terminator relates to exception handling.
83 bool isExceptional() const {
84 switch (getOpcode()) {
85 case Instruction::CatchSwitch:
86 case Instruction::CatchRet:
87 case Instruction::CleanupRet:
88 case Instruction::Invoke:
89 case Instruction::Resume:
90 case Instruction::TerminatePad:
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,
104 typedef std::iterator<std::random_access_iterator_tag, BB, int, BB *, BB *>
108 typedef typename super::pointer pointer;
109 typedef typename super::reference reference;
114 typedef SuccIterator<Term, BB> Self;
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 typedef SuccIterator<TerminatorInst *, BasicBlock> succ_iterator;
251 typedef SuccIterator<const TerminatorInst *, const BasicBlock>
253 typedef llvm::iterator_range<succ_iterator> succ_range;
254 typedef llvm::iterator_range<succ_const_iterator> succ_const_range;
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 {
280 void *operator new(size_t, unsigned) = delete;
283 UnaryInstruction(Type *Ty, unsigned iType, Value *V,
284 Instruction *IB = nullptr)
285 : Instruction(Ty, iType, &Op<0>(), 1, IB) {
288 UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
289 : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
294 // allocate space for exactly one operand
295 void *operator new(size_t s) {
296 return User::operator new(s, 1);
299 // Out of line virtual method, so the vtable, etc has a home.
300 ~UnaryInstruction() override;
302 /// Transparently provide more efficient getOperand methods.
303 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
305 // Methods for support type inquiry through isa, cast, and dyn_cast:
306 static inline bool classof(const Instruction *I) {
307 return I->getOpcode() == Instruction::Alloca ||
308 I->getOpcode() == Instruction::Load ||
309 I->getOpcode() == Instruction::VAArg ||
310 I->getOpcode() == Instruction::ExtractValue ||
311 (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
313 static inline bool classof(const Value *V) {
314 return isa<Instruction>(V) && classof(cast<Instruction>(V));
319 struct OperandTraits<UnaryInstruction> :
320 public FixedNumOperandTraits<UnaryInstruction, 1> {
323 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
325 //===----------------------------------------------------------------------===//
326 // BinaryOperator Class
327 //===----------------------------------------------------------------------===//
329 class BinaryOperator : public Instruction {
330 void *operator new(size_t, unsigned) = delete;
333 void init(BinaryOps iType);
334 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
335 const Twine &Name, Instruction *InsertBefore);
336 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
337 const Twine &Name, BasicBlock *InsertAtEnd);
339 // Note: Instruction needs to be a friend here to call cloneImpl.
340 friend class Instruction;
341 BinaryOperator *cloneImpl() const;
344 // allocate space for exactly two operands
345 void *operator new(size_t s) {
346 return User::operator new(s, 2);
349 /// Transparently provide more efficient getOperand methods.
350 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
352 /// Construct a binary instruction, given the opcode and the two
353 /// operands. Optionally (if InstBefore is specified) insert the instruction
354 /// into a BasicBlock right before the specified instruction. The specified
355 /// Instruction is allowed to be a dereferenced end iterator.
357 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
358 const Twine &Name = Twine(),
359 Instruction *InsertBefore = nullptr);
361 /// Construct a binary instruction, given the opcode and the two
362 /// operands. Also automatically insert this instruction to the end of the
363 /// BasicBlock specified.
365 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
366 const Twine &Name, BasicBlock *InsertAtEnd);
368 /// These methods just forward to Create, and are useful when you
369 /// statically know what type of instruction you're going to create. These
370 /// helpers just save some typing.
371 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
372 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
373 const Twine &Name = "") {\
374 return Create(Instruction::OPC, V1, V2, Name);\
376 #include "llvm/IR/Instruction.def"
377 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
378 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
379 const Twine &Name, BasicBlock *BB) {\
380 return Create(Instruction::OPC, V1, V2, Name, BB);\
382 #include "llvm/IR/Instruction.def"
383 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
384 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
385 const Twine &Name, Instruction *I) {\
386 return Create(Instruction::OPC, V1, V2, Name, I);\
388 #include "llvm/IR/Instruction.def"
390 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
391 const Twine &Name = "") {
392 BinaryOperator *BO = Create(Opc, V1, V2, Name);
393 BO->setHasNoSignedWrap(true);
396 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
397 const Twine &Name, BasicBlock *BB) {
398 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
399 BO->setHasNoSignedWrap(true);
402 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
403 const Twine &Name, Instruction *I) {
404 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
405 BO->setHasNoSignedWrap(true);
409 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
410 const Twine &Name = "") {
411 BinaryOperator *BO = Create(Opc, V1, V2, Name);
412 BO->setHasNoUnsignedWrap(true);
415 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
416 const Twine &Name, BasicBlock *BB) {
417 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
418 BO->setHasNoUnsignedWrap(true);
421 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
422 const Twine &Name, Instruction *I) {
423 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
424 BO->setHasNoUnsignedWrap(true);
428 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
429 const Twine &Name = "") {
430 BinaryOperator *BO = Create(Opc, V1, V2, Name);
431 BO->setIsExact(true);
434 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
435 const Twine &Name, BasicBlock *BB) {
436 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
437 BO->setIsExact(true);
440 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
441 const Twine &Name, Instruction *I) {
442 BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
443 BO->setIsExact(true);
447 #define DEFINE_HELPERS(OPC, NUWNSWEXACT) \
448 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \
449 const Twine &Name = "") { \
450 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \
452 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
453 Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \
454 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \
456 static BinaryOperator *Create##NUWNSWEXACT##OPC( \
457 Value *V1, Value *V2, const Twine &Name, Instruction *I) { \
458 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \
461 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
462 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
463 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
464 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
465 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
466 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
467 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
468 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
470 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv
471 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv
472 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr
473 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr
475 #undef DEFINE_HELPERS
477 /// Helper functions to construct and inspect unary operations (NEG and NOT)
478 /// via binary operators SUB and XOR:
480 /// Create the NEG and NOT instructions out of SUB and XOR instructions.
482 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
483 Instruction *InsertBefore = nullptr);
484 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
485 BasicBlock *InsertAtEnd);
486 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
487 Instruction *InsertBefore = nullptr);
488 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
489 BasicBlock *InsertAtEnd);
490 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
491 Instruction *InsertBefore = nullptr);
492 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
493 BasicBlock *InsertAtEnd);
494 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
495 Instruction *InsertBefore = nullptr);
496 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
497 BasicBlock *InsertAtEnd);
498 static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
499 Instruction *InsertBefore = nullptr);
500 static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
501 BasicBlock *InsertAtEnd);
503 /// Check if the given Value is a NEG, FNeg, or NOT instruction.
505 static bool isNeg(const Value *V);
506 static bool isFNeg(const Value *V, bool IgnoreZeroSign=false);
507 static bool isNot(const Value *V);
509 /// Helper functions to extract the unary argument of a NEG, FNEG or NOT
510 /// operation implemented via Sub, FSub, or Xor.
512 static const Value *getNegArgument(const Value *BinOp);
513 static Value *getNegArgument( Value *BinOp);
514 static const Value *getFNegArgument(const Value *BinOp);
515 static Value *getFNegArgument( Value *BinOp);
516 static const Value *getNotArgument(const Value *BinOp);
517 static Value *getNotArgument( Value *BinOp);
519 BinaryOps getOpcode() const {
520 return static_cast<BinaryOps>(Instruction::getOpcode());
523 /// Exchange the two operands to this instruction.
524 /// This instruction is safe to use on any binary instruction and
525 /// does not modify the semantics of the instruction. If the instruction
526 /// cannot be reversed (ie, it's a Div), then return true.
530 /// Set or clear the nsw flag on this instruction, which must be an operator
531 /// which supports this flag. See LangRef.html for the meaning of this flag.
532 void setHasNoUnsignedWrap(bool b = true);
534 /// Set or clear the nsw flag on this instruction, which must be an operator
535 /// which supports this flag. See LangRef.html for the meaning of this flag.
536 void setHasNoSignedWrap(bool b = true);
538 /// Set or clear the exact flag on this instruction, which must be an operator
539 /// which supports this flag. See LangRef.html for the meaning of this flag.
540 void setIsExact(bool b = true);
542 /// Determine whether the no unsigned wrap flag is set.
543 bool hasNoUnsignedWrap() const;
545 /// Determine whether the no signed wrap flag is set.
546 bool hasNoSignedWrap() const;
548 /// Determine whether the exact flag is set.
549 bool isExact() const;
551 /// Convenience method to copy supported wrapping, exact, and fast-math flags
552 /// from V to this instruction.
553 void copyIRFlags(const Value *V);
555 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
556 /// V and this instruction.
557 void andIRFlags(const Value *V);
559 // Methods for support type inquiry through isa, cast, and dyn_cast:
560 static inline bool classof(const Instruction *I) {
561 return I->isBinaryOp();
563 static inline bool classof(const Value *V) {
564 return isa<Instruction>(V) && classof(cast<Instruction>(V));
569 struct OperandTraits<BinaryOperator> :
570 public FixedNumOperandTraits<BinaryOperator, 2> {
573 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
575 //===----------------------------------------------------------------------===//
577 //===----------------------------------------------------------------------===//
579 /// This is the base class for all instructions that perform data
580 /// casts. It is simply provided so that instruction category testing
581 /// can be performed with code like:
583 /// if (isa<CastInst>(Instr)) { ... }
584 /// @brief Base class of casting instructions.
585 class CastInst : public UnaryInstruction {
586 void anchor() override;
589 /// @brief Constructor with insert-before-instruction semantics for subclasses
590 CastInst(Type *Ty, unsigned iType, Value *S,
591 const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
592 : UnaryInstruction(Ty, iType, S, InsertBefore) {
595 /// @brief Constructor with insert-at-end-of-block semantics for subclasses
596 CastInst(Type *Ty, unsigned iType, Value *S,
597 const Twine &NameStr, BasicBlock *InsertAtEnd)
598 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
603 /// Provides a way to construct any of the CastInst subclasses using an
604 /// opcode instead of the subclass's constructor. The opcode must be in the
605 /// CastOps category (Instruction::isCast(opcode) returns true). This
606 /// constructor has insert-before-instruction semantics to automatically
607 /// insert the new CastInst before InsertBefore (if it is non-null).
608 /// @brief Construct any of the CastInst subclasses
609 static CastInst *Create(
610 Instruction::CastOps, ///< The opcode of the cast instruction
611 Value *S, ///< The value to be casted (operand 0)
612 Type *Ty, ///< The type to which cast should be made
613 const Twine &Name = "", ///< Name for the instruction
614 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
616 /// Provides a way to construct any of the CastInst subclasses using an
617 /// opcode instead of the subclass's constructor. The opcode must be in the
618 /// CastOps category. This constructor has insert-at-end-of-block semantics
619 /// to automatically insert the new CastInst at the end of InsertAtEnd (if
621 /// @brief Construct any of the CastInst subclasses
622 static CastInst *Create(
623 Instruction::CastOps, ///< The opcode for the cast instruction
624 Value *S, ///< The value to be casted (operand 0)
625 Type *Ty, ///< The type to which operand is casted
626 const Twine &Name, ///< The name for the instruction
627 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
630 /// @brief Create a ZExt or BitCast cast instruction
631 static CastInst *CreateZExtOrBitCast(
632 Value *S, ///< The value to be casted (operand 0)
633 Type *Ty, ///< The type to which cast should be made
634 const Twine &Name = "", ///< Name for the instruction
635 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
638 /// @brief Create a ZExt or BitCast cast instruction
639 static CastInst *CreateZExtOrBitCast(
640 Value *S, ///< The value to be casted (operand 0)
641 Type *Ty, ///< The type to which operand is casted
642 const Twine &Name, ///< The name for the instruction
643 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
646 /// @brief Create a SExt or BitCast cast instruction
647 static CastInst *CreateSExtOrBitCast(
648 Value *S, ///< The value to be casted (operand 0)
649 Type *Ty, ///< The type to which cast should be made
650 const Twine &Name = "", ///< Name for the instruction
651 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
654 /// @brief Create a SExt or BitCast cast instruction
655 static CastInst *CreateSExtOrBitCast(
656 Value *S, ///< The value to be casted (operand 0)
657 Type *Ty, ///< The type to which operand is casted
658 const Twine &Name, ///< The name for the instruction
659 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
662 /// @brief Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
663 static CastInst *CreatePointerCast(
664 Value *S, ///< The pointer value to be casted (operand 0)
665 Type *Ty, ///< The type to which operand is casted
666 const Twine &Name, ///< The name for the instruction
667 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
670 /// @brief Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
671 static CastInst *CreatePointerCast(
672 Value *S, ///< The pointer value to be casted (operand 0)
673 Type *Ty, ///< The type to which cast should be made
674 const Twine &Name = "", ///< Name for the instruction
675 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
678 /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
679 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
680 Value *S, ///< The pointer value to be casted (operand 0)
681 Type *Ty, ///< The type to which operand is casted
682 const Twine &Name, ///< The name for the instruction
683 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
686 /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
687 static CastInst *CreatePointerBitCastOrAddrSpaceCast(
688 Value *S, ///< The pointer value to be casted (operand 0)
689 Type *Ty, ///< The type to which cast should be made
690 const Twine &Name = "", ///< Name for the instruction
691 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
694 /// @brief Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
696 /// If the value is a pointer type and the destination an integer type,
697 /// creates a PtrToInt cast. If the value is an integer type and the
698 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
700 static CastInst *CreateBitOrPointerCast(
701 Value *S, ///< The pointer value to be casted (operand 0)
702 Type *Ty, ///< The type to which cast should be made
703 const Twine &Name = "", ///< Name for the instruction
704 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
707 /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
708 static CastInst *CreateIntegerCast(
709 Value *S, ///< The pointer value to be casted (operand 0)
710 Type *Ty, ///< The type to which cast should be made
711 bool isSigned, ///< Whether to regard S as signed or not
712 const Twine &Name = "", ///< Name for the instruction
713 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
716 /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
717 static CastInst *CreateIntegerCast(
718 Value *S, ///< The integer value to be casted (operand 0)
719 Type *Ty, ///< The integer type to which operand is casted
720 bool isSigned, ///< Whether to regard S as signed or not
721 const Twine &Name, ///< The name for the instruction
722 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
725 /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
726 static CastInst *CreateFPCast(
727 Value *S, ///< The floating point value to be casted
728 Type *Ty, ///< The floating point type to cast to
729 const Twine &Name = "", ///< Name for the instruction
730 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
733 /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
734 static CastInst *CreateFPCast(
735 Value *S, ///< The floating point value to be casted
736 Type *Ty, ///< The floating point type to cast to
737 const Twine &Name, ///< The name for the instruction
738 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
741 /// @brief Create a Trunc or BitCast cast instruction
742 static CastInst *CreateTruncOrBitCast(
743 Value *S, ///< The value to be casted (operand 0)
744 Type *Ty, ///< The type to which cast should be made
745 const Twine &Name = "", ///< Name for the instruction
746 Instruction *InsertBefore = nullptr ///< Place to insert the instruction
749 /// @brief Create a Trunc or BitCast cast instruction
750 static CastInst *CreateTruncOrBitCast(
751 Value *S, ///< The value to be casted (operand 0)
752 Type *Ty, ///< The type to which operand is casted
753 const Twine &Name, ///< The name for the instruction
754 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
757 /// @brief Check whether it is valid to call getCastOpcode for these types.
758 static bool isCastable(
759 Type *SrcTy, ///< The Type from which the value should be cast.
760 Type *DestTy ///< The Type to which the value should be cast.
763 /// @brief Check whether a bitcast between these types is valid
764 static bool isBitCastable(
765 Type *SrcTy, ///< The Type from which the value should be cast.
766 Type *DestTy ///< The Type to which the value should be cast.
769 /// @brief Check whether a bitcast, inttoptr, or ptrtoint cast between these
770 /// types is valid and a no-op.
772 /// This ensures that any pointer<->integer cast has enough bits in the
773 /// integer and any other cast is a bitcast.
774 static bool isBitOrNoopPointerCastable(
775 Type *SrcTy, ///< The Type from which the value should be cast.
776 Type *DestTy, ///< The Type to which the value should be cast.
777 const DataLayout &DL);
779 /// Returns the opcode necessary to cast Val into Ty using usual casting
781 /// @brief Infer the opcode for cast operand and type
782 static Instruction::CastOps getCastOpcode(
783 const Value *Val, ///< The value to cast
784 bool SrcIsSigned, ///< Whether to treat the source as signed
785 Type *Ty, ///< The Type to which the value should be casted
786 bool DstIsSigned ///< Whether to treate the dest. as signed
789 /// There are several places where we need to know if a cast instruction
790 /// only deals with integer source and destination types. To simplify that
791 /// logic, this method is provided.
792 /// @returns true iff the cast has only integral typed operand and dest type.
793 /// @brief Determine if this is an integer-only cast.
794 bool isIntegerCast() const;
796 /// A lossless cast is one that does not alter the basic value. It implies
797 /// a no-op cast but is more stringent, preventing things like int->float,
798 /// long->double, or int->ptr.
799 /// @returns true iff the cast is lossless.
800 /// @brief Determine if this is a lossless cast.
801 bool isLosslessCast() const;
803 /// A no-op cast is one that can be effected without changing any bits.
804 /// It implies that the source and destination types are the same size. The
805 /// IntPtrTy argument is used to make accurate determinations for casts
806 /// involving Integer and Pointer types. They are no-op casts if the integer
807 /// is the same size as the pointer. However, pointer size varies with
808 /// platform. Generally, the result of DataLayout::getIntPtrType() should be
809 /// passed in. If that's not available, use Type::Int64Ty, which will make
810 /// the isNoopCast call conservative.
811 /// @brief Determine if the described cast is a no-op cast.
812 static bool isNoopCast(
813 Instruction::CastOps Opcode, ///< Opcode of cast
814 Type *SrcTy, ///< SrcTy of cast
815 Type *DstTy, ///< DstTy of cast
816 Type *IntPtrTy ///< Integer type corresponding to Ptr types
819 /// @brief Determine if this cast is a no-op cast.
821 Type *IntPtrTy ///< Integer type corresponding to pointer
824 /// @brief Determine if this cast is a no-op cast.
826 /// \param DL is the DataLayout to get the Int Ptr type from.
827 bool isNoopCast(const DataLayout &DL) const;
829 /// Determine how a pair of casts can be eliminated, if they can be at all.
830 /// This is a helper function for both CastInst and ConstantExpr.
831 /// @returns 0 if the CastInst pair can't be eliminated, otherwise
832 /// returns Instruction::CastOps value for a cast that can replace
833 /// the pair, casting SrcTy to DstTy.
834 /// @brief Determine if a cast pair is eliminable
835 static unsigned isEliminableCastPair(
836 Instruction::CastOps firstOpcode, ///< Opcode of first cast
837 Instruction::CastOps secondOpcode, ///< Opcode of second cast
838 Type *SrcTy, ///< SrcTy of 1st cast
839 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
840 Type *DstTy, ///< DstTy of 2nd cast
841 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
842 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
843 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null
846 /// @brief Return the opcode of this CastInst
847 Instruction::CastOps getOpcode() const {
848 return Instruction::CastOps(Instruction::getOpcode());
851 /// @brief Return the source type, as a convenience
852 Type* getSrcTy() const { return getOperand(0)->getType(); }
853 /// @brief Return the destination type, as a convenience
854 Type* getDestTy() const { return getType(); }
856 /// This method can be used to determine if a cast from S to DstTy using
857 /// Opcode op is valid or not.
858 /// @returns true iff the proposed cast is valid.
859 /// @brief Determine if a cast is valid without creating one.
860 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
862 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
863 static inline bool classof(const Instruction *I) {
866 static inline bool classof(const Value *V) {
867 return isa<Instruction>(V) && classof(cast<Instruction>(V));
871 //===----------------------------------------------------------------------===//
873 //===----------------------------------------------------------------------===//
875 /// This class is the base class for the comparison instructions.
876 /// @brief Abstract base class of comparison instructions.
877 class CmpInst : public Instruction {
878 void *operator new(size_t, unsigned) = delete;
882 CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
883 Value *LHS, Value *RHS, const Twine &Name = "",
884 Instruction *InsertBefore = nullptr);
886 CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
887 Value *LHS, Value *RHS, const Twine &Name,
888 BasicBlock *InsertAtEnd);
890 void anchor() override; // Out of line virtual method.
893 /// This enumeration lists the possible predicates for CmpInst subclasses.
894 /// Values in the range 0-31 are reserved for FCmpInst, while values in the
895 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
896 /// predicate values are not overlapping between the classes.
898 // Opcode U L G E Intuitive operation
899 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
900 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
901 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
902 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
903 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
904 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
905 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
906 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
907 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
908 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
909 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
910 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
911 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
912 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
913 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
914 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
915 FIRST_FCMP_PREDICATE = FCMP_FALSE,
916 LAST_FCMP_PREDICATE = FCMP_TRUE,
917 BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
918 ICMP_EQ = 32, ///< equal
919 ICMP_NE = 33, ///< not equal
920 ICMP_UGT = 34, ///< unsigned greater than
921 ICMP_UGE = 35, ///< unsigned greater or equal
922 ICMP_ULT = 36, ///< unsigned less than
923 ICMP_ULE = 37, ///< unsigned less or equal
924 ICMP_SGT = 38, ///< signed greater than
925 ICMP_SGE = 39, ///< signed greater or equal
926 ICMP_SLT = 40, ///< signed less than
927 ICMP_SLE = 41, ///< signed less or equal
928 FIRST_ICMP_PREDICATE = ICMP_EQ,
929 LAST_ICMP_PREDICATE = ICMP_SLE,
930 BAD_ICMP_PREDICATE = ICMP_SLE + 1
933 // allocate space for exactly two operands
934 void *operator new(size_t s) {
935 return User::operator new(s, 2);
937 /// Construct a compare instruction, given the opcode, the predicate and
938 /// the two operands. Optionally (if InstBefore is specified) insert the
939 /// instruction into a BasicBlock right before the specified instruction.
940 /// The specified Instruction is allowed to be a dereferenced end iterator.
941 /// @brief Create a CmpInst
942 static CmpInst *Create(OtherOps Op,
943 unsigned short predicate, Value *S1,
944 Value *S2, const Twine &Name = "",
945 Instruction *InsertBefore = nullptr);
947 /// Construct a compare instruction, given the opcode, the predicate and the
948 /// two operands. Also automatically insert this instruction to the end of
949 /// the BasicBlock specified.
950 /// @brief Create a CmpInst
951 static CmpInst *Create(OtherOps Op, unsigned short predicate, Value *S1,
952 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
954 /// @brief Get the opcode casted to the right type
955 OtherOps getOpcode() const {
956 return static_cast<OtherOps>(Instruction::getOpcode());
959 /// @brief Return the predicate for this instruction.
960 Predicate getPredicate() const {
961 return Predicate(getSubclassDataFromInstruction());
964 /// @brief Set the predicate for this instruction to the specified value.
965 void setPredicate(Predicate P) { setInstructionSubclassData(P); }
967 static bool isFPPredicate(Predicate P) {
968 return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
971 static bool isIntPredicate(Predicate P) {
972 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
975 bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
976 bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
978 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
979 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
980 /// @returns the inverse predicate for the instruction's current predicate.
981 /// @brief Return the inverse of the instruction's predicate.
982 Predicate getInversePredicate() const {
983 return getInversePredicate(getPredicate());
986 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
987 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
988 /// @returns the inverse predicate for predicate provided in \p pred.
989 /// @brief Return the inverse of a given predicate
990 static Predicate getInversePredicate(Predicate pred);
992 /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
993 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
994 /// @returns the predicate that would be the result of exchanging the two
995 /// operands of the CmpInst instruction without changing the result
997 /// @brief Return the predicate as if the operands were swapped
998 Predicate getSwappedPredicate() const {
999 return getSwappedPredicate(getPredicate());
1002 /// This is a static version that you can use without an instruction
1004 /// @brief Return the predicate as if the operands were swapped.
1005 static Predicate getSwappedPredicate(Predicate pred);
1007 /// @brief Provide more efficient getOperand methods.
1008 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1010 /// This is just a convenience that dispatches to the subclasses.
1011 /// @brief Swap the operands and adjust predicate accordingly to retain
1012 /// the same comparison.
1013 void swapOperands();
1015 /// This is just a convenience that dispatches to the subclasses.
1016 /// @brief Determine if this CmpInst is commutative.
1017 bool isCommutative() const;
1019 /// This is just a convenience that dispatches to the subclasses.
1020 /// @brief Determine if this is an equals/not equals predicate.
1021 bool isEquality() const;
1023 /// @returns true if the comparison is signed, false otherwise.
1024 /// @brief Determine if this instruction is using a signed comparison.
1025 bool isSigned() const {
1026 return isSigned(getPredicate());
1029 /// @returns true if the comparison is unsigned, false otherwise.
1030 /// @brief Determine if this instruction is using an unsigned comparison.
1031 bool isUnsigned() const {
1032 return isUnsigned(getPredicate());
1035 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1036 /// @returns the signed version of the unsigned predicate pred.
1037 /// @brief return the signed version of a predicate
1038 static Predicate getSignedPredicate(Predicate pred);
1040 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1041 /// @returns the signed version of the predicate for this instruction (which
1042 /// has to be an unsigned predicate).
1043 /// @brief return the signed version of a predicate
1044 Predicate getSignedPredicate() {
1045 return getSignedPredicate(getPredicate());
1048 /// This is just a convenience.
1049 /// @brief Determine if this is true when both operands are the same.
1050 bool isTrueWhenEqual() const {
1051 return isTrueWhenEqual(getPredicate());
1054 /// This is just a convenience.
1055 /// @brief Determine if this is false when both operands are the same.
1056 bool isFalseWhenEqual() const {
1057 return isFalseWhenEqual(getPredicate());
1060 /// @returns true if the predicate is unsigned, false otherwise.
1061 /// @brief Determine if the predicate is an unsigned operation.
1062 static bool isUnsigned(unsigned short predicate);
1064 /// @returns true if the predicate is signed, false otherwise.
1065 /// @brief Determine if the predicate is an signed operation.
1066 static bool isSigned(unsigned short predicate);
1068 /// @brief Determine if the predicate is an ordered operation.
1069 static bool isOrdered(unsigned short predicate);
1071 /// @brief Determine if the predicate is an unordered operation.
1072 static bool isUnordered(unsigned short predicate);
1074 /// Determine if the predicate is true when comparing a value with itself.
1075 static bool isTrueWhenEqual(unsigned short predicate);
1077 /// Determine if the predicate is false when comparing a value with itself.
1078 static bool isFalseWhenEqual(unsigned short predicate);
1080 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1081 static inline bool classof(const Instruction *I) {
1082 return I->getOpcode() == Instruction::ICmp ||
1083 I->getOpcode() == Instruction::FCmp;
1085 static inline bool classof(const Value *V) {
1086 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1089 /// @brief Create a result type for fcmp/icmp
1090 static Type* makeCmpResultType(Type* opnd_type) {
1091 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1092 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1093 vt->getNumElements());
1095 return Type::getInt1Ty(opnd_type->getContext());
1099 // Shadow Value::setValueSubclassData with a private forwarding method so that
1100 // subclasses cannot accidentally use it.
1101 void setValueSubclassData(unsigned short D) {
1102 Value::setValueSubclassData(D);
1106 // FIXME: these are redundant if CmpInst < BinaryOperator
1108 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1111 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1113 //===----------------------------------------------------------------------===//
1114 // FuncletPadInst Class
1115 //===----------------------------------------------------------------------===//
1116 class FuncletPadInst : public Instruction {
1118 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
1120 FuncletPadInst(const FuncletPadInst &CPI);
1122 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1123 ArrayRef<Value *> Args, unsigned Values,
1124 const Twine &NameStr, Instruction *InsertBefore);
1125 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1126 ArrayRef<Value *> Args, unsigned Values,
1127 const Twine &NameStr, BasicBlock *InsertAtEnd);
1130 // Note: Instruction needs to be a friend here to call cloneImpl.
1131 friend class Instruction;
1132 friend class CatchPadInst;
1133 friend class CleanupPadInst;
1134 FuncletPadInst *cloneImpl() const;
1137 /// Provide fast operand accessors
1138 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1140 /// getNumArgOperands - Return the number of funcletpad arguments.
1142 unsigned getNumArgOperands() const { return getNumOperands() - 1; }
1144 /// Convenience accessors
1146 /// \brief Return the outer EH-pad this funclet is nested within.
1148 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
1149 /// is a CatchPadInst.
1150 Value *getParentPad() const { return Op<-1>(); }
1151 void setParentPad(Value *ParentPad) {
1153 Op<-1>() = ParentPad;
1156 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
1158 Value *getArgOperand(unsigned i) const { return getOperand(i); }
1159 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
1161 /// arg_operands - iteration adapter for range-for loops.
1162 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
1164 /// arg_operands - iteration adapter for range-for loops.
1165 const_op_range arg_operands() const {
1166 return const_op_range(op_begin(), op_end() - 1);
1169 // Methods for support type inquiry through isa, cast, and dyn_cast:
1170 static inline bool classof(const Instruction *I) { return I->isFuncletPad(); }
1171 static inline bool classof(const Value *V) {
1172 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1177 struct OperandTraits<FuncletPadInst>
1178 : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
1180 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
1182 /// \brief A lightweight accessor for an operand bundle meant to be passed
1183 /// around by value.
1184 struct OperandBundleUse {
1185 ArrayRef<Use> Inputs;
1187 OperandBundleUse() {}
1188 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1189 : Inputs(Inputs), Tag(Tag) {}
1191 /// \brief Return true if the operand at index \p Idx in this operand bundle
1192 /// has the attribute A.
1193 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
1194 if (isDeoptOperandBundle())
1195 if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
1196 return Inputs[Idx]->getType()->isPointerTy();
1198 // Conservative answer: no operands have any attributes.
1202 /// \brief Return the tag of this operand bundle as a string.
1203 StringRef getTagName() const {
1204 return Tag->getKey();
1207 /// \brief Return the tag of this operand bundle as an integer.
1209 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1210 /// and this function returns the unique integer getOrInsertBundleTag
1211 /// associated the tag of this operand bundle to.
1212 uint32_t getTagID() const {
1213 return Tag->getValue();
1216 /// \brief Return true if this is a "deopt" operand bundle.
1217 bool isDeoptOperandBundle() const {
1218 return getTagID() == LLVMContext::OB_deopt;
1222 /// \brief Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1223 StringMapEntry<uint32_t> *Tag;
1226 /// \brief A container for an operand bundle being viewed as a set of values
1227 /// rather than a set of uses.
1229 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1230 /// so it is possible to create and pass around "self-contained" instances of
1231 /// OperandBundleDef and ConstOperandBundleDef.
1232 template <typename InputTy> class OperandBundleDefT {
1234 std::vector<InputTy> Inputs;
1237 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1238 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1240 explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1241 Tag = OBU.getTagName();
1242 Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1245 ArrayRef<InputTy> inputs() const { return Inputs; }
1247 typedef typename std::vector<InputTy>::const_iterator input_iterator;
1248 size_t input_size() const { return Inputs.size(); }
1249 input_iterator input_begin() const { return Inputs.begin(); }
1250 input_iterator input_end() const { return Inputs.end(); }
1252 StringRef getTag() const { return Tag; }
1255 typedef OperandBundleDefT<Value *> OperandBundleDef;
1256 typedef OperandBundleDefT<const Value *> ConstOperandBundleDef;
1258 /// \brief A mixin to add operand bundle functionality to llvm instruction
1261 /// OperandBundleUser uses the descriptor area co-allocated with the host User
1262 /// to store some meta information about which operands are "normal" operands,
1263 /// and which ones belong to some operand bundle.
1265 /// The layout of an operand bundle user is
1267 /// +-----------uint32_t End-------------------------------------+
1269 /// | +--------uint32_t Begin--------------------+ |
1272 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1273 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1274 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1277 /// | +--------uint32_t Begin------------+ |
1279 /// +-----------uint32_t End-----------------------------+
1282 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use list.
1283 /// These descriptions are installed and managed by this class, and they're all
1284 /// instances of OperandBundleUser<T>::BundleOpInfo.
1286 /// DU is an additional descriptor installed by User's 'operator new' to keep
1287 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not
1288 /// access or modify DU in any way, it's an implementation detail private to
1291 /// The regular Use& vector for the User starts at U0. The operand bundle uses
1292 /// are part of the Use& vector, just like normal uses. In the diagram above,
1293 /// the operand bundle uses start at BOI0_U0. Each instance of BundleOpInfo has
1294 /// information about a contiguous set of uses constituting an operand bundle,
1295 /// and the total set of operand bundle uses themselves form a contiguous set of
1296 /// uses (i.e. there are no gaps between uses corresponding to individual
1297 /// operand bundles).
1299 /// This class does not know the location of the set of operand bundle uses
1300 /// within the use list -- that is decided by the User using this class via the
1301 /// BeginIdx argument in populateBundleOperandInfos.
1303 /// Currently operand bundle users with hung-off operands are not supported.
1304 template <typename InstrTy, typename OpIteratorTy> class OperandBundleUser {
1306 /// \brief Return the number of operand bundles associated with this User.
1307 unsigned getNumOperandBundles() const {
1308 return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1311 /// \brief Return true if this User has any operand bundles.
1312 bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1314 /// \brief Return the index of the first bundle operand in the Use array.
1315 unsigned getBundleOperandsStartIndex() const {
1316 assert(hasOperandBundles() && "Don't call otherwise!");
1317 return bundle_op_info_begin()->Begin;
1320 /// \brief Return the index of the last bundle operand in the Use array.
1321 unsigned getBundleOperandsEndIndex() const {
1322 assert(hasOperandBundles() && "Don't call otherwise!");
1323 return bundle_op_info_end()[-1].End;
1326 /// \brief Return the total number operands (not operand bundles) used by
1327 /// every operand bundle in this OperandBundleUser.
1328 unsigned getNumTotalBundleOperands() const {
1329 if (!hasOperandBundles())
1332 unsigned Begin = getBundleOperandsStartIndex();
1333 unsigned End = getBundleOperandsEndIndex();
1335 assert(Begin <= End && "Should be!");
1339 /// \brief Return the operand bundle at a specific index.
1340 OperandBundleUse getOperandBundleAt(unsigned Index) const {
1341 assert(Index < getNumOperandBundles() && "Index out of bounds!");
1342 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1345 /// \brief Return the number of operand bundles with the tag Name attached to
1346 /// this instruction.
1347 unsigned countOperandBundlesOfType(StringRef Name) const {
1349 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1350 if (getOperandBundleAt(i).getTagName() == Name)
1356 /// \brief Return the number of operand bundles with the tag ID attached to
1357 /// this instruction.
1358 unsigned countOperandBundlesOfType(uint32_t ID) const {
1360 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1361 if (getOperandBundleAt(i).getTagID() == ID)
1367 /// \brief Return an operand bundle by name, if present.
1369 /// It is an error to call this for operand bundle types that may have
1370 /// multiple instances of them on the same instruction.
1371 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1372 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1374 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1375 OperandBundleUse U = getOperandBundleAt(i);
1376 if (U.getTagName() == Name)
1383 /// \brief Return an operand bundle by tag ID, if present.
1385 /// It is an error to call this for operand bundle types that may have
1386 /// multiple instances of them on the same instruction.
1387 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1388 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1390 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1391 OperandBundleUse U = getOperandBundleAt(i);
1392 if (U.getTagID() == ID)
1399 /// \brief Return the list of operand bundles attached to this instruction as
1400 /// a vector of OperandBundleDefs.
1402 /// This function copies the OperandBundeUse instances associated with this
1403 /// OperandBundleUser to a vector of OperandBundleDefs. Note:
1404 /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1405 /// representations of operand bundles (see documentation above).
1406 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1407 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1408 Defs.emplace_back(getOperandBundleAt(i));
1411 /// \brief Return the operand bundle for the operand at index OpIdx.
1413 /// It is an error to call this with an OpIdx that does not correspond to an
1415 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1416 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1419 /// \brief Return true if this operand bundle user has operand bundles that
1420 /// may read from the heap.
1421 bool hasReadingOperandBundles() const {
1422 // Implementation note: this is a conservative implementation of operand
1423 // bundle semantics, where *any* operand bundle forces a callsite to be at
1425 return hasOperandBundles();
1428 /// \brief Return true if this operand bundle user has operand bundles that
1429 /// may write to the heap.
1430 bool hasClobberingOperandBundles() const {
1431 for (auto &BOI : bundle_op_infos()) {
1432 if (BOI.Tag->second == LLVMContext::OB_deopt)
1435 // This instruction has an operand bundle that is not a "deopt" operand
1436 // bundle. 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);
1452 /// \brief Is the function attribute S disallowed by some operand bundle on
1453 /// this operand bundle user?
1454 bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1455 // Operand bundles only possibly disallow readnone, readonly and argmenonly
1456 // attributes. All String attributes are fine.
1460 /// \brief Is the function attribute A disallowed by some operand bundle on
1461 /// this operand bundle user?
1462 bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1467 case Attribute::ArgMemOnly:
1468 return hasReadingOperandBundles();
1470 case Attribute::ReadNone:
1471 return hasReadingOperandBundles();
1473 case Attribute::ReadOnly:
1474 return hasClobberingOperandBundles();
1477 llvm_unreachable("switch has a default case!");
1480 /// \brief Used to keep track of an operand bundle. See the main comment on
1481 /// OperandBundleUser above.
1482 struct BundleOpInfo {
1483 /// \brief The operand bundle tag, interned by
1484 /// LLVMContextImpl::getOrInsertBundleTag.
1485 StringMapEntry<uint32_t> *Tag;
1487 /// \brief The index in the Use& vector where operands for this operand
1491 /// \brief The index in the Use& vector where operands for this operand
1496 /// \brief Simple helper function to map a BundleOpInfo to an
1497 /// OperandBundleUse.
1499 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1500 auto op_begin = static_cast<const InstrTy *>(this)->op_begin();
1501 ArrayRef<Use> Inputs(op_begin + BOI.Begin, op_begin + BOI.End);
1502 return OperandBundleUse(BOI.Tag, Inputs);
1505 typedef BundleOpInfo *bundle_op_iterator;
1506 typedef const BundleOpInfo *const_bundle_op_iterator;
1508 /// \brief Return the start of the list of BundleOpInfo instances associated
1509 /// with this OperandBundleUser.
1510 bundle_op_iterator bundle_op_info_begin() {
1511 if (!static_cast<InstrTy *>(this)->hasDescriptor())
1514 uint8_t *BytesBegin = static_cast<InstrTy *>(this)->getDescriptor().begin();
1515 return reinterpret_cast<bundle_op_iterator>(BytesBegin);
1518 /// \brief Return the start of the list of BundleOpInfo instances associated
1519 /// with this OperandBundleUser.
1520 const_bundle_op_iterator bundle_op_info_begin() const {
1521 auto *NonConstThis =
1522 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1523 return NonConstThis->bundle_op_info_begin();
1526 /// \brief Return the end of the list of BundleOpInfo instances associated
1527 /// with this OperandBundleUser.
1528 bundle_op_iterator bundle_op_info_end() {
1529 if (!static_cast<InstrTy *>(this)->hasDescriptor())
1532 uint8_t *BytesEnd = static_cast<InstrTy *>(this)->getDescriptor().end();
1533 return reinterpret_cast<bundle_op_iterator>(BytesEnd);
1536 /// \brief Return the end of the list of BundleOpInfo instances associated
1537 /// with this OperandBundleUser.
1538 const_bundle_op_iterator bundle_op_info_end() const {
1539 auto *NonConstThis =
1540 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1541 return NonConstThis->bundle_op_info_end();
1544 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1545 iterator_range<bundle_op_iterator> bundle_op_infos() {
1546 return make_range(bundle_op_info_begin(), bundle_op_info_end());
1549 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1550 iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
1551 return make_range(bundle_op_info_begin(), bundle_op_info_end());
1554 /// \brief Populate the BundleOpInfo instances and the Use& vector from \p
1555 /// Bundles. Return the op_iterator pointing to the Use& one past the last
1556 /// last bundle operand use.
1558 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
1559 /// instance allocated in this User's descriptor.
1560 OpIteratorTy populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
1561 const unsigned BeginIndex) {
1562 auto It = static_cast<InstrTy *>(this)->op_begin() + BeginIndex;
1563 for (auto &B : Bundles)
1564 It = std::copy(B.input_begin(), B.input_end(), It);
1566 auto *ContextImpl = static_cast<InstrTy *>(this)->getContext().pImpl;
1567 auto BI = Bundles.begin();
1568 unsigned CurrentIndex = BeginIndex;
1570 for (auto &BOI : bundle_op_infos()) {
1571 assert(BI != Bundles.end() && "Incorrect allocation?");
1573 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
1574 BOI.Begin = CurrentIndex;
1575 BOI.End = CurrentIndex + BI->input_size();
1576 CurrentIndex = BOI.End;
1580 assert(BI == Bundles.end() && "Incorrect allocation?");
1585 /// \brief Return the BundleOpInfo for the operand at index OpIdx.
1587 /// It is an error to call this with an OpIdx that does not correspond to an
1589 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
1590 for (auto &BOI : bundle_op_infos())
1591 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
1594 llvm_unreachable("Did not find operand bundle for operand!");
1597 /// \brief Return the total number of values used in \p Bundles.
1598 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
1600 for (auto &B : Bundles)
1601 Total += B.input_size();
1606 } // end llvm namespace
1608 #endif // LLVM_IR_INSTRTYPES_H