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 bool classof(const Instruction *I) {
77 return I->isTerminator();
79 static 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 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 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 {
328 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
329 const Twine &Name, Instruction *InsertBefore);
330 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
331 const Twine &Name, BasicBlock *InsertAtEnd);
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 bool classof(const Instruction *I) {
536 return I->isBinaryOp();
538 static 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 /// DataLayout argument is to determine the pointer size when examining 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
782 /// @brief Determine if the described cast is a no-op cast.
783 static bool isNoopCast(
784 Instruction::CastOps Opcode, ///< Opcode of cast
785 Type *SrcTy, ///< SrcTy of cast
786 Type *DstTy, ///< DstTy of cast
787 const DataLayout &DL ///< DataLayout to get the Int Ptr type from.
790 /// @brief Determine if this cast is a no-op cast.
792 /// \param DL is the DataLayout to determine pointer size.
793 bool isNoopCast(const DataLayout &DL) const;
795 /// Determine how a pair of casts can be eliminated, if they can be at all.
796 /// This is a helper function for both CastInst and ConstantExpr.
797 /// @returns 0 if the CastInst pair can't be eliminated, otherwise
798 /// returns Instruction::CastOps value for a cast that can replace
799 /// the pair, casting SrcTy to DstTy.
800 /// @brief Determine if a cast pair is eliminable
801 static unsigned isEliminableCastPair(
802 Instruction::CastOps firstOpcode, ///< Opcode of first cast
803 Instruction::CastOps secondOpcode, ///< Opcode of second cast
804 Type *SrcTy, ///< SrcTy of 1st cast
805 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
806 Type *DstTy, ///< DstTy of 2nd cast
807 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
808 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
809 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null
812 /// @brief Return the opcode of this CastInst
813 Instruction::CastOps getOpcode() const {
814 return Instruction::CastOps(Instruction::getOpcode());
817 /// @brief Return the source type, as a convenience
818 Type* getSrcTy() const { return getOperand(0)->getType(); }
819 /// @brief Return the destination type, as a convenience
820 Type* getDestTy() const { return getType(); }
822 /// This method can be used to determine if a cast from S to DstTy using
823 /// Opcode op is valid or not.
824 /// @returns true iff the proposed cast is valid.
825 /// @brief Determine if a cast is valid without creating one.
826 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
828 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
829 static bool classof(const Instruction *I) {
832 static bool classof(const Value *V) {
833 return isa<Instruction>(V) && classof(cast<Instruction>(V));
837 //===----------------------------------------------------------------------===//
839 //===----------------------------------------------------------------------===//
841 /// This class is the base class for the comparison instructions.
842 /// @brief Abstract base class of comparison instructions.
843 class CmpInst : public Instruction {
845 /// This enumeration lists the possible predicates for CmpInst subclasses.
846 /// Values in the range 0-31 are reserved for FCmpInst, while values in the
847 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
848 /// predicate values are not overlapping between the classes.
850 /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
851 /// FCMP_* values. Changing the bit patterns requires a potential change to
854 // Opcode U L G E Intuitive operation
855 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
856 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
857 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
858 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
859 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
860 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
861 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
862 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
863 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
864 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
865 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
866 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
867 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
868 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
869 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
870 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
871 FIRST_FCMP_PREDICATE = FCMP_FALSE,
872 LAST_FCMP_PREDICATE = FCMP_TRUE,
873 BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
874 ICMP_EQ = 32, ///< equal
875 ICMP_NE = 33, ///< not equal
876 ICMP_UGT = 34, ///< unsigned greater than
877 ICMP_UGE = 35, ///< unsigned greater or equal
878 ICMP_ULT = 36, ///< unsigned less than
879 ICMP_ULE = 37, ///< unsigned less or equal
880 ICMP_SGT = 38, ///< signed greater than
881 ICMP_SGE = 39, ///< signed greater or equal
882 ICMP_SLT = 40, ///< signed less than
883 ICMP_SLE = 41, ///< signed less or equal
884 FIRST_ICMP_PREDICATE = ICMP_EQ,
885 LAST_ICMP_PREDICATE = ICMP_SLE,
886 BAD_ICMP_PREDICATE = ICMP_SLE + 1
890 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
891 Value *LHS, Value *RHS, const Twine &Name = "",
892 Instruction *InsertBefore = nullptr);
894 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred,
895 Value *LHS, Value *RHS, const Twine &Name,
896 BasicBlock *InsertAtEnd);
899 // allocate space for exactly two operands
900 void *operator new(size_t s) {
901 return User::operator new(s, 2);
904 /// Construct a compare instruction, given the opcode, the predicate and
905 /// the two operands. Optionally (if InstBefore is specified) insert the
906 /// instruction into a BasicBlock right before the specified instruction.
907 /// The specified Instruction is allowed to be a dereferenced end iterator.
908 /// @brief Create a CmpInst
909 static CmpInst *Create(OtherOps Op,
910 Predicate predicate, Value *S1,
911 Value *S2, const Twine &Name = "",
912 Instruction *InsertBefore = nullptr);
914 /// Construct a compare instruction, given the opcode, the predicate and the
915 /// two operands. Also automatically insert this instruction to the end of
916 /// the BasicBlock specified.
917 /// @brief Create a CmpInst
918 static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1,
919 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
921 /// @brief Get the opcode casted to the right type
922 OtherOps getOpcode() const {
923 return static_cast<OtherOps>(Instruction::getOpcode());
926 /// @brief Return the predicate for this instruction.
927 Predicate getPredicate() const {
928 return Predicate(getSubclassDataFromInstruction());
931 /// @brief Set the predicate for this instruction to the specified value.
932 void setPredicate(Predicate P) { setInstructionSubclassData(P); }
934 static bool isFPPredicate(Predicate P) {
935 return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
938 static bool isIntPredicate(Predicate P) {
939 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
942 static StringRef getPredicateName(Predicate P);
944 bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
945 bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
947 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
948 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
949 /// @returns the inverse predicate for the instruction's current predicate.
950 /// @brief Return the inverse of the instruction's predicate.
951 Predicate getInversePredicate() const {
952 return getInversePredicate(getPredicate());
955 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
956 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
957 /// @returns the inverse predicate for predicate provided in \p pred.
958 /// @brief Return the inverse of a given predicate
959 static Predicate getInversePredicate(Predicate pred);
961 /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
962 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
963 /// @returns the predicate that would be the result of exchanging the two
964 /// operands of the CmpInst instruction without changing the result
966 /// @brief Return the predicate as if the operands were swapped
967 Predicate getSwappedPredicate() const {
968 return getSwappedPredicate(getPredicate());
971 /// This is a static version that you can use without an instruction
973 /// @brief Return the predicate as if the operands were swapped.
974 static Predicate getSwappedPredicate(Predicate pred);
976 /// @brief Provide more efficient getOperand methods.
977 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
979 /// This is just a convenience that dispatches to the subclasses.
980 /// @brief Swap the operands and adjust predicate accordingly to retain
981 /// the same comparison.
984 /// This is just a convenience that dispatches to the subclasses.
985 /// @brief Determine if this CmpInst is commutative.
986 bool isCommutative() const;
988 /// This is just a convenience that dispatches to the subclasses.
989 /// @brief Determine if this is an equals/not equals predicate.
990 bool isEquality() const;
992 /// @returns true if the comparison is signed, false otherwise.
993 /// @brief Determine if this instruction is using a signed comparison.
994 bool isSigned() const {
995 return isSigned(getPredicate());
998 /// @returns true if the comparison is unsigned, false otherwise.
999 /// @brief Determine if this instruction is using an unsigned comparison.
1000 bool isUnsigned() const {
1001 return isUnsigned(getPredicate());
1004 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1005 /// @returns the signed version of the unsigned predicate pred.
1006 /// @brief return the signed version of a predicate
1007 static Predicate getSignedPredicate(Predicate pred);
1009 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1010 /// @returns the signed version of the predicate for this instruction (which
1011 /// has to be an unsigned predicate).
1012 /// @brief return the signed version of a predicate
1013 Predicate getSignedPredicate() {
1014 return getSignedPredicate(getPredicate());
1017 /// This is just a convenience.
1018 /// @brief Determine if this is true when both operands are the same.
1019 bool isTrueWhenEqual() const {
1020 return isTrueWhenEqual(getPredicate());
1023 /// This is just a convenience.
1024 /// @brief Determine if this is false when both operands are the same.
1025 bool isFalseWhenEqual() const {
1026 return isFalseWhenEqual(getPredicate());
1029 /// @returns true if the predicate is unsigned, false otherwise.
1030 /// @brief Determine if the predicate is an unsigned operation.
1031 static bool isUnsigned(Predicate predicate);
1033 /// @returns true if the predicate is signed, false otherwise.
1034 /// @brief Determine if the predicate is an signed operation.
1035 static bool isSigned(Predicate predicate);
1037 /// @brief Determine if the predicate is an ordered operation.
1038 static bool isOrdered(Predicate predicate);
1040 /// @brief Determine if the predicate is an unordered operation.
1041 static bool isUnordered(Predicate predicate);
1043 /// Determine if the predicate is true when comparing a value with itself.
1044 static bool isTrueWhenEqual(Predicate predicate);
1046 /// Determine if the predicate is false when comparing a value with itself.
1047 static bool isFalseWhenEqual(Predicate predicate);
1049 /// Determine if Pred1 implies Pred2 is true when two compares have matching
1051 static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2);
1053 /// Determine if Pred1 implies Pred2 is false when two compares have matching
1055 static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2);
1057 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1058 static bool classof(const Instruction *I) {
1059 return I->getOpcode() == Instruction::ICmp ||
1060 I->getOpcode() == Instruction::FCmp;
1062 static bool classof(const Value *V) {
1063 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1066 /// @brief Create a result type for fcmp/icmp
1067 static Type* makeCmpResultType(Type* opnd_type) {
1068 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1069 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1070 vt->getNumElements());
1072 return Type::getInt1Ty(opnd_type->getContext());
1076 // Shadow Value::setValueSubclassData with a private forwarding method so that
1077 // subclasses cannot accidentally use it.
1078 void setValueSubclassData(unsigned short D) {
1079 Value::setValueSubclassData(D);
1083 // FIXME: these are redundant if CmpInst < BinaryOperator
1085 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1088 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1090 //===----------------------------------------------------------------------===//
1091 // FuncletPadInst Class
1092 //===----------------------------------------------------------------------===//
1093 class FuncletPadInst : public Instruction {
1095 FuncletPadInst(const FuncletPadInst &CPI);
1097 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1098 ArrayRef<Value *> Args, unsigned Values,
1099 const Twine &NameStr, Instruction *InsertBefore);
1100 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1101 ArrayRef<Value *> Args, unsigned Values,
1102 const Twine &NameStr, BasicBlock *InsertAtEnd);
1104 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
1107 // Note: Instruction needs to be a friend here to call cloneImpl.
1108 friend class Instruction;
1109 friend class CatchPadInst;
1110 friend class CleanupPadInst;
1112 FuncletPadInst *cloneImpl() const;
1115 /// Provide fast operand accessors
1116 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1118 /// getNumArgOperands - Return the number of funcletpad arguments.
1120 unsigned getNumArgOperands() const { return getNumOperands() - 1; }
1122 /// Convenience accessors
1124 /// \brief Return the outer EH-pad this funclet is nested within.
1126 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
1127 /// is a CatchPadInst.
1128 Value *getParentPad() const { return Op<-1>(); }
1129 void setParentPad(Value *ParentPad) {
1131 Op<-1>() = ParentPad;
1134 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
1136 Value *getArgOperand(unsigned i) const { return getOperand(i); }
1137 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
1139 /// arg_operands - iteration adapter for range-for loops.
1140 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
1142 /// arg_operands - iteration adapter for range-for loops.
1143 const_op_range arg_operands() const {
1144 return const_op_range(op_begin(), op_end() - 1);
1147 // Methods for support type inquiry through isa, cast, and dyn_cast:
1148 static bool classof(const Instruction *I) { return I->isFuncletPad(); }
1149 static bool classof(const Value *V) {
1150 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1155 struct OperandTraits<FuncletPadInst>
1156 : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {};
1158 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
1160 /// \brief A lightweight accessor for an operand bundle meant to be passed
1161 /// around by value.
1162 struct OperandBundleUse {
1163 ArrayRef<Use> Inputs;
1165 OperandBundleUse() = default;
1166 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1167 : Inputs(Inputs), Tag(Tag) {}
1169 /// \brief Return true if the operand at index \p Idx in this operand bundle
1170 /// has the attribute A.
1171 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
1172 if (isDeoptOperandBundle())
1173 if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
1174 return Inputs[Idx]->getType()->isPointerTy();
1176 // Conservative answer: no operands have any attributes.
1180 /// \brief Return the tag of this operand bundle as a string.
1181 StringRef getTagName() const {
1182 return Tag->getKey();
1185 /// \brief Return the tag of this operand bundle as an integer.
1187 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1188 /// and this function returns the unique integer getOrInsertBundleTag
1189 /// associated the tag of this operand bundle to.
1190 uint32_t getTagID() const {
1191 return Tag->getValue();
1194 /// \brief Return true if this is a "deopt" operand bundle.
1195 bool isDeoptOperandBundle() const {
1196 return getTagID() == LLVMContext::OB_deopt;
1199 /// \brief Return true if this is a "funclet" operand bundle.
1200 bool isFuncletOperandBundle() const {
1201 return getTagID() == LLVMContext::OB_funclet;
1205 /// \brief Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1206 StringMapEntry<uint32_t> *Tag;
1209 /// \brief A container for an operand bundle being viewed as a set of values
1210 /// rather than a set of uses.
1212 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1213 /// so it is possible to create and pass around "self-contained" instances of
1214 /// OperandBundleDef and ConstOperandBundleDef.
1215 template <typename InputTy> class OperandBundleDefT {
1217 std::vector<InputTy> Inputs;
1220 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1221 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1222 explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
1223 : Tag(std::move(Tag)), Inputs(Inputs) {}
1225 explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1226 Tag = OBU.getTagName();
1227 Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1230 ArrayRef<InputTy> inputs() const { return Inputs; }
1232 using input_iterator = typename std::vector<InputTy>::const_iterator;
1234 size_t input_size() const { return Inputs.size(); }
1235 input_iterator input_begin() const { return Inputs.begin(); }
1236 input_iterator input_end() const { return Inputs.end(); }
1238 StringRef getTag() const { return Tag; }
1241 using OperandBundleDef = OperandBundleDefT<Value *>;
1242 using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
1244 /// \brief A mixin to add operand bundle functionality to llvm instruction
1247 /// OperandBundleUser uses the descriptor area co-allocated with the host User
1248 /// to store some meta information about which operands are "normal" operands,
1249 /// and which ones belong to some operand bundle.
1251 /// The layout of an operand bundle user is
1253 /// +-----------uint32_t End-------------------------------------+
1255 /// | +--------uint32_t Begin--------------------+ |
1258 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1259 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1260 /// |------|------|----|----|----|----|----|---------|----|---------|----|-----
1263 /// | +--------uint32_t Begin------------+ |
1265 /// +-----------uint32_t End-----------------------------+
1268 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use list.
1269 /// These descriptions are installed and managed by this class, and they're all
1270 /// instances of OperandBundleUser<T>::BundleOpInfo.
1272 /// DU is an additional descriptor installed by User's 'operator new' to keep
1273 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not
1274 /// access or modify DU in any way, it's an implementation detail private to
1277 /// The regular Use& vector for the User starts at U0. The operand bundle uses
1278 /// are part of the Use& vector, just like normal uses. In the diagram above,
1279 /// the operand bundle uses start at BOI0_U0. Each instance of BundleOpInfo has
1280 /// information about a contiguous set of uses constituting an operand bundle,
1281 /// and the total set of operand bundle uses themselves form a contiguous set of
1282 /// uses (i.e. there are no gaps between uses corresponding to individual
1283 /// operand bundles).
1285 /// This class does not know the location of the set of operand bundle uses
1286 /// within the use list -- that is decided by the User using this class via the
1287 /// BeginIdx argument in populateBundleOperandInfos.
1289 /// Currently operand bundle users with hung-off operands are not supported.
1290 template <typename InstrTy, typename OpIteratorTy> class OperandBundleUser {
1292 /// \brief Return the number of operand bundles associated with this User.
1293 unsigned getNumOperandBundles() const {
1294 return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1297 /// \brief Return true if this User has any operand bundles.
1298 bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1300 /// \brief Return the index of the first bundle operand in the Use array.
1301 unsigned getBundleOperandsStartIndex() const {
1302 assert(hasOperandBundles() && "Don't call otherwise!");
1303 return bundle_op_info_begin()->Begin;
1306 /// \brief Return the index of the last bundle operand in the Use array.
1307 unsigned getBundleOperandsEndIndex() const {
1308 assert(hasOperandBundles() && "Don't call otherwise!");
1309 return bundle_op_info_end()[-1].End;
1312 /// Return true if the operand at index \p Idx is a bundle operand.
1313 bool isBundleOperand(unsigned Idx) const {
1314 return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1315 Idx < getBundleOperandsEndIndex();
1318 /// \brief Return the total number operands (not operand bundles) used by
1319 /// every operand bundle in this OperandBundleUser.
1320 unsigned getNumTotalBundleOperands() const {
1321 if (!hasOperandBundles())
1324 unsigned Begin = getBundleOperandsStartIndex();
1325 unsigned End = getBundleOperandsEndIndex();
1327 assert(Begin <= End && "Should be!");
1331 /// \brief Return the operand bundle at a specific index.
1332 OperandBundleUse getOperandBundleAt(unsigned Index) const {
1333 assert(Index < getNumOperandBundles() && "Index out of bounds!");
1334 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1337 /// \brief Return the number of operand bundles with the tag Name attached to
1338 /// this instruction.
1339 unsigned countOperandBundlesOfType(StringRef Name) const {
1341 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1342 if (getOperandBundleAt(i).getTagName() == Name)
1348 /// \brief Return the number of operand bundles with the tag ID attached to
1349 /// this instruction.
1350 unsigned countOperandBundlesOfType(uint32_t ID) const {
1352 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1353 if (getOperandBundleAt(i).getTagID() == ID)
1359 /// \brief Return an operand bundle by name, if present.
1361 /// It is an error to call this for operand bundle types that may have
1362 /// multiple instances of them on the same instruction.
1363 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1364 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1366 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1367 OperandBundleUse U = getOperandBundleAt(i);
1368 if (U.getTagName() == Name)
1375 /// \brief Return an operand bundle by tag ID, if present.
1377 /// It is an error to call this for operand bundle types that may have
1378 /// multiple instances of them on the same instruction.
1379 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1380 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1382 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1383 OperandBundleUse U = getOperandBundleAt(i);
1384 if (U.getTagID() == ID)
1391 /// \brief Return the list of operand bundles attached to this instruction as
1392 /// a vector of OperandBundleDefs.
1394 /// This function copies the OperandBundeUse instances associated with this
1395 /// OperandBundleUser to a vector of OperandBundleDefs. Note:
1396 /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1397 /// representations of operand bundles (see documentation above).
1398 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1399 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1400 Defs.emplace_back(getOperandBundleAt(i));
1403 /// \brief Return the operand bundle for the operand at index OpIdx.
1405 /// It is an error to call this with an OpIdx that does not correspond to an
1407 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1408 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
1411 /// \brief Return true if this operand bundle user has operand bundles that
1412 /// may read from the heap.
1413 bool hasReadingOperandBundles() const {
1414 // Implementation note: this is a conservative implementation of operand
1415 // bundle semantics, where *any* operand bundle forces a callsite to be at
1417 return hasOperandBundles();
1420 /// \brief Return true if this operand bundle user has operand bundles that
1421 /// may write to the heap.
1422 bool hasClobberingOperandBundles() const {
1423 for (auto &BOI : bundle_op_infos()) {
1424 if (BOI.Tag->second == LLVMContext::OB_deopt ||
1425 BOI.Tag->second == LLVMContext::OB_funclet)
1428 // This instruction has an operand bundle that is not known to us.
1429 // Assume the worst.
1436 /// \brief Return true if the bundle operand at index \p OpIdx has the
1438 bool bundleOperandHasAttr(unsigned OpIdx, Attribute::AttrKind A) const {
1439 auto &BOI = getBundleOpInfoForOperand(OpIdx);
1440 auto OBU = operandBundleFromBundleOpInfo(BOI);
1441 return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
1444 /// \brief Return true if \p Other has the same sequence of operand bundle
1445 /// tags with the same number of operands on each one of them as this
1446 /// OperandBundleUser.
1447 bool hasIdenticalOperandBundleSchema(
1448 const OperandBundleUser<InstrTy, OpIteratorTy> &Other) const {
1449 if (getNumOperandBundles() != Other.getNumOperandBundles())
1452 return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
1453 Other.bundle_op_info_begin());
1456 /// \brief Return true if this operand bundle user contains operand bundles
1457 /// with tags other than those specified in \p IDs.
1458 bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
1459 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1460 uint32_t ID = getOperandBundleAt(i).getTagID();
1461 if (!is_contained(IDs, ID))
1468 /// \brief Is the function attribute S disallowed by some operand bundle on
1469 /// this operand bundle user?
1470 bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1471 // Operand bundles only possibly disallow readnone, readonly and argmenonly
1472 // attributes. All String attributes are fine.
1476 /// \brief Is the function attribute A disallowed by some operand bundle on
1477 /// this operand bundle user?
1478 bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1483 case Attribute::InaccessibleMemOrArgMemOnly:
1484 return hasReadingOperandBundles();
1486 case Attribute::InaccessibleMemOnly:
1487 return hasReadingOperandBundles();
1489 case Attribute::ArgMemOnly:
1490 return hasReadingOperandBundles();
1492 case Attribute::ReadNone:
1493 return hasReadingOperandBundles();
1495 case Attribute::ReadOnly:
1496 return hasClobberingOperandBundles();
1499 llvm_unreachable("switch has a default case!");
1502 /// \brief Used to keep track of an operand bundle. See the main comment on
1503 /// OperandBundleUser above.
1504 struct BundleOpInfo {
1505 /// \brief The operand bundle tag, interned by
1506 /// LLVMContextImpl::getOrInsertBundleTag.
1507 StringMapEntry<uint32_t> *Tag;
1509 /// \brief The index in the Use& vector where operands for this operand
1513 /// \brief The index in the Use& vector where operands for this operand
1517 bool operator==(const BundleOpInfo &Other) const {
1518 return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
1522 /// \brief Simple helper function to map a BundleOpInfo to an
1523 /// OperandBundleUse.
1525 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1526 auto op_begin = static_cast<const InstrTy *>(this)->op_begin();
1527 ArrayRef<Use> Inputs(op_begin + BOI.Begin, op_begin + BOI.End);
1528 return OperandBundleUse(BOI.Tag, Inputs);
1531 using bundle_op_iterator = BundleOpInfo *;
1532 using const_bundle_op_iterator = const BundleOpInfo *;
1534 /// \brief Return the start of the list of BundleOpInfo instances associated
1535 /// with this OperandBundleUser.
1536 bundle_op_iterator bundle_op_info_begin() {
1537 if (!static_cast<InstrTy *>(this)->hasDescriptor())
1540 uint8_t *BytesBegin = static_cast<InstrTy *>(this)->getDescriptor().begin();
1541 return reinterpret_cast<bundle_op_iterator>(BytesBegin);
1544 /// \brief Return the start of the list of BundleOpInfo instances associated
1545 /// with this OperandBundleUser.
1546 const_bundle_op_iterator bundle_op_info_begin() const {
1547 auto *NonConstThis =
1548 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1549 return NonConstThis->bundle_op_info_begin();
1552 /// \brief Return the end of the list of BundleOpInfo instances associated
1553 /// with this OperandBundleUser.
1554 bundle_op_iterator bundle_op_info_end() {
1555 if (!static_cast<InstrTy *>(this)->hasDescriptor())
1558 uint8_t *BytesEnd = static_cast<InstrTy *>(this)->getDescriptor().end();
1559 return reinterpret_cast<bundle_op_iterator>(BytesEnd);
1562 /// \brief Return the end of the list of BundleOpInfo instances associated
1563 /// with this OperandBundleUser.
1564 const_bundle_op_iterator bundle_op_info_end() const {
1565 auto *NonConstThis =
1566 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1567 return NonConstThis->bundle_op_info_end();
1570 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1571 iterator_range<bundle_op_iterator> bundle_op_infos() {
1572 return make_range(bundle_op_info_begin(), bundle_op_info_end());
1575 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1576 iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
1577 return make_range(bundle_op_info_begin(), bundle_op_info_end());
1580 /// \brief Populate the BundleOpInfo instances and the Use& vector from \p
1581 /// Bundles. Return the op_iterator pointing to the Use& one past the last
1582 /// last bundle operand use.
1584 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
1585 /// instance allocated in this User's descriptor.
1586 OpIteratorTy populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
1587 const unsigned BeginIndex) {
1588 auto It = static_cast<InstrTy *>(this)->op_begin() + BeginIndex;
1589 for (auto &B : Bundles)
1590 It = std::copy(B.input_begin(), B.input_end(), It);
1592 auto *ContextImpl = static_cast<InstrTy *>(this)->getContext().pImpl;
1593 auto BI = Bundles.begin();
1594 unsigned CurrentIndex = BeginIndex;
1596 for (auto &BOI : bundle_op_infos()) {
1597 assert(BI != Bundles.end() && "Incorrect allocation?");
1599 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
1600 BOI.Begin = CurrentIndex;
1601 BOI.End = CurrentIndex + BI->input_size();
1602 CurrentIndex = BOI.End;
1606 assert(BI == Bundles.end() && "Incorrect allocation?");
1611 /// \brief Return the BundleOpInfo for the operand at index OpIdx.
1613 /// It is an error to call this with an OpIdx that does not correspond to an
1615 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
1616 for (auto &BOI : bundle_op_infos())
1617 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
1620 llvm_unreachable("Did not find operand bundle for operand!");
1623 /// \brief Return the total number of values used in \p Bundles.
1624 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
1626 for (auto &B : Bundles)
1627 Total += B.input_size();
1632 } // end namespace llvm
1634 #endif // LLVM_IR_INSTRTYPES_H