[OperandBundles] Extract duplicated code into a helper function, NFC
[oota-llvm.git] / include / llvm / IR / InstrTypes.h
1 //===-- llvm/InstrTypes.h - Important Instruction subclasses ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines various meta classes of instructions that exist in the VM
11 // representation.  Specific concrete subclasses of these may be found in the
12 // i*.h files...
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_INSTRTYPES_H
17 #define LLVM_IR_INSTRTYPES_H
18
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/OperandTraits.h"
25
26 namespace llvm {
27
28 class LLVMContext;
29
30 //===----------------------------------------------------------------------===//
31 //                            TerminatorInst Class
32 //===----------------------------------------------------------------------===//
33
34 /// Subclasses of this class are all able to terminate a basic
35 /// block. Thus, these are all the flow control type of operations.
36 ///
37 class TerminatorInst : public Instruction {
38 protected:
39   TerminatorInst(Type *Ty, Instruction::TermOps iType,
40                  Use *Ops, unsigned NumOps,
41                  Instruction *InsertBefore = nullptr)
42     : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
43
44   TerminatorInst(Type *Ty, Instruction::TermOps iType,
45                  Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
46     : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
47
48   // Out of line virtual method, so the vtable, etc has a home.
49   ~TerminatorInst() override;
50
51   /// Virtual methods - Terminators should overload these and provide inline
52   /// overrides of non-V methods.
53   virtual BasicBlock *getSuccessorV(unsigned idx) const = 0;
54   virtual unsigned getNumSuccessorsV() const = 0;
55   virtual void setSuccessorV(unsigned idx, BasicBlock *B) = 0;
56
57 public:
58   /// Return the number of successors that this terminator has.
59   unsigned getNumSuccessors() const {
60     return getNumSuccessorsV();
61   }
62
63   /// Return the specified successor.
64   BasicBlock *getSuccessor(unsigned idx) const {
65     return getSuccessorV(idx);
66   }
67
68   /// Update the specified successor to point at the provided block.
69   void setSuccessor(unsigned idx, BasicBlock *B) {
70     setSuccessorV(idx, B);
71   }
72
73   // Methods for support type inquiry through isa, cast, and dyn_cast:
74   static inline bool classof(const Instruction *I) {
75     return I->isTerminator();
76   }
77   static inline bool classof(const Value *V) {
78     return isa<Instruction>(V) && classof(cast<Instruction>(V));
79   }
80
81   // \brief Returns true if this terminator relates to exception handling.
82   bool isExceptional() const {
83     switch (getOpcode()) {
84     case Instruction::CatchPad:
85     case Instruction::CatchEndPad:
86     case Instruction::CatchRet:
87     case Instruction::CleanupEndPad:
88     case Instruction::CleanupRet:
89     case Instruction::Invoke:
90     case Instruction::Resume:
91     case Instruction::TerminatePad:
92       return true;
93     default:
94       return false;
95     }
96   }
97
98   //===--------------------------------------------------------------------===//
99   // succ_iterator definition
100   //===--------------------------------------------------------------------===//
101
102   template <class Term, class BB> // Successor Iterator
103   class SuccIterator : public std::iterator<std::random_access_iterator_tag, BB,
104                                             int, BB *, BB *> {
105     typedef std::iterator<std::random_access_iterator_tag, BB, int, BB *, BB *>
106         super;
107
108   public:
109     typedef typename super::pointer pointer;
110     typedef typename super::reference reference;
111
112   private:
113     Term TermInst;
114     unsigned idx;
115     typedef SuccIterator<Term, BB> Self;
116
117     inline bool index_is_valid(unsigned idx) {
118       return idx < TermInst->getNumSuccessors();
119     }
120
121     /// \brief Proxy object to allow write access in operator[]
122     class SuccessorProxy {
123       Self it;
124
125     public:
126       explicit SuccessorProxy(const Self &it) : it(it) {}
127
128       SuccessorProxy(const SuccessorProxy &) = default;
129
130       SuccessorProxy &operator=(SuccessorProxy r) {
131         *this = reference(r);
132         return *this;
133       }
134
135       SuccessorProxy &operator=(reference r) {
136         it.TermInst->setSuccessor(it.idx, r);
137         return *this;
138       }
139
140       operator reference() const { return *it; }
141     };
142
143   public:
144     // begin iterator
145     explicit inline SuccIterator(Term T) : TermInst(T), idx(0) {}
146     // end iterator
147     inline SuccIterator(Term T, bool) : TermInst(T) {
148       if (TermInst)
149         idx = TermInst->getNumSuccessors();
150       else
151         // Term == NULL happens, if a basic block is not fully constructed and
152         // consequently getTerminator() returns NULL. In this case we construct
153         // a SuccIterator which describes a basic block that has zero
154         // successors.
155         // Defining SuccIterator for incomplete and malformed CFGs is especially
156         // useful for debugging.
157         idx = 0;
158     }
159
160     /// This is used to interface between code that wants to
161     /// operate on terminator instructions directly.
162     unsigned getSuccessorIndex() const { return idx; }
163
164     inline bool operator==(const Self &x) const { return idx == x.idx; }
165     inline bool operator!=(const Self &x) const { return !operator==(x); }
166
167     inline reference operator*() const { return TermInst->getSuccessor(idx); }
168     inline pointer operator->() const { return operator*(); }
169
170     inline Self &operator++() {
171       ++idx;
172       return *this;
173     } // Preincrement
174
175     inline Self operator++(int) { // Postincrement
176       Self tmp = *this;
177       ++*this;
178       return tmp;
179     }
180
181     inline Self &operator--() {
182       --idx;
183       return *this;
184     }                             // Predecrement
185     inline Self operator--(int) { // Postdecrement
186       Self tmp = *this;
187       --*this;
188       return tmp;
189     }
190
191     inline bool operator<(const Self &x) const {
192       assert(TermInst == x.TermInst &&
193              "Cannot compare iterators of different blocks!");
194       return idx < x.idx;
195     }
196
197     inline bool operator<=(const Self &x) const {
198       assert(TermInst == x.TermInst &&
199              "Cannot compare iterators of different blocks!");
200       return idx <= x.idx;
201     }
202     inline bool operator>=(const Self &x) const {
203       assert(TermInst == x.TermInst &&
204              "Cannot compare iterators of different blocks!");
205       return idx >= x.idx;
206     }
207
208     inline bool operator>(const Self &x) const {
209       assert(TermInst == x.TermInst &&
210              "Cannot compare iterators of different blocks!");
211       return idx > x.idx;
212     }
213
214     inline Self &operator+=(int Right) {
215       unsigned new_idx = idx + Right;
216       assert(index_is_valid(new_idx) && "Iterator index out of bound");
217       idx = new_idx;
218       return *this;
219     }
220
221     inline Self operator+(int Right) const {
222       Self tmp = *this;
223       tmp += Right;
224       return tmp;
225     }
226
227     inline Self &operator-=(int Right) { return operator+=(-Right); }
228
229     inline Self operator-(int Right) const { return operator+(-Right); }
230
231     inline int operator-(const Self &x) const {
232       assert(TermInst == x.TermInst &&
233              "Cannot work on iterators of different blocks!");
234       int distance = idx - x.idx;
235       return distance;
236     }
237
238     inline SuccessorProxy operator[](int offset) {
239       Self tmp = *this;
240       tmp += offset;
241       return SuccessorProxy(tmp);
242     }
243
244     /// Get the source BB of this iterator.
245     inline BB *getSource() {
246       assert(TermInst && "Source not available, if basic block was malformed");
247       return TermInst->getParent();
248     }
249   };
250
251   typedef SuccIterator<TerminatorInst *, BasicBlock> succ_iterator;
252   typedef SuccIterator<const TerminatorInst *, const BasicBlock>
253       succ_const_iterator;
254   typedef llvm::iterator_range<succ_iterator> succ_range;
255   typedef llvm::iterator_range<succ_const_iterator> succ_const_range;
256
257 private:
258   inline succ_iterator succ_begin() { return succ_iterator(this); }
259   inline succ_const_iterator succ_begin() const {
260     return succ_const_iterator(this);
261   }
262   inline succ_iterator succ_end() { return succ_iterator(this, true); }
263   inline succ_const_iterator succ_end() const {
264     return succ_const_iterator(this, true);
265   }
266
267 public:
268   inline succ_range successors() {
269     return succ_range(succ_begin(), succ_end());
270   }
271   inline succ_const_range successors() const {
272     return succ_const_range(succ_begin(), succ_end());
273   }
274 };
275
276 //===----------------------------------------------------------------------===//
277 //                          UnaryInstruction Class
278 //===----------------------------------------------------------------------===//
279
280 class UnaryInstruction : public Instruction {
281   void *operator new(size_t, unsigned) = delete;
282
283 protected:
284   UnaryInstruction(Type *Ty, unsigned iType, Value *V,
285                    Instruction *IB = nullptr)
286     : Instruction(Ty, iType, &Op<0>(), 1, IB) {
287     Op<0>() = V;
288   }
289   UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
290     : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
291     Op<0>() = V;
292   }
293
294 public:
295   // allocate space for exactly one operand
296   void *operator new(size_t s) {
297     return User::operator new(s, 1);
298   }
299
300   // Out of line virtual method, so the vtable, etc has a home.
301   ~UnaryInstruction() override;
302
303   /// Transparently provide more efficient getOperand methods.
304   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
305
306   // Methods for support type inquiry through isa, cast, and dyn_cast:
307   static inline bool classof(const Instruction *I) {
308     return I->getOpcode() == Instruction::Alloca ||
309            I->getOpcode() == Instruction::Load ||
310            I->getOpcode() == Instruction::VAArg ||
311            I->getOpcode() == Instruction::ExtractValue ||
312            (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
313   }
314   static inline bool classof(const Value *V) {
315     return isa<Instruction>(V) && classof(cast<Instruction>(V));
316   }
317 };
318
319 template <>
320 struct OperandTraits<UnaryInstruction> :
321   public FixedNumOperandTraits<UnaryInstruction, 1> {
322 };
323
324 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
325
326 //===----------------------------------------------------------------------===//
327 //                           BinaryOperator Class
328 //===----------------------------------------------------------------------===//
329
330 class BinaryOperator : public Instruction {
331   void *operator new(size_t, unsigned) = delete;
332
333 protected:
334   void init(BinaryOps iType);
335   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
336                  const Twine &Name, Instruction *InsertBefore);
337   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
338                  const Twine &Name, BasicBlock *InsertAtEnd);
339
340   // Note: Instruction needs to be a friend here to call cloneImpl.
341   friend class Instruction;
342   BinaryOperator *cloneImpl() const;
343
344 public:
345   // allocate space for exactly two operands
346   void *operator new(size_t s) {
347     return User::operator new(s, 2);
348   }
349
350   /// Transparently provide more efficient getOperand methods.
351   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
352
353   /// Construct a binary instruction, given the opcode and the two
354   /// operands.  Optionally (if InstBefore is specified) insert the instruction
355   /// into a BasicBlock right before the specified instruction.  The specified
356   /// Instruction is allowed to be a dereferenced end iterator.
357   ///
358   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
359                                 const Twine &Name = Twine(),
360                                 Instruction *InsertBefore = nullptr);
361
362   /// Construct a binary instruction, given the opcode and the two
363   /// operands.  Also automatically insert this instruction to the end of the
364   /// BasicBlock specified.
365   ///
366   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
367                                 const Twine &Name, BasicBlock *InsertAtEnd);
368
369   /// These methods just forward to Create, and are useful when you
370   /// statically know what type of instruction you're going to create.  These
371   /// helpers just save some typing.
372 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
373   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
374                                      const Twine &Name = "") {\
375     return Create(Instruction::OPC, V1, V2, Name);\
376   }
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, BasicBlock *BB) {\
381     return Create(Instruction::OPC, V1, V2, Name, BB);\
382   }
383 #include "llvm/IR/Instruction.def"
384 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
385   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
386                                      const Twine &Name, Instruction *I) {\
387     return Create(Instruction::OPC, V1, V2, Name, I);\
388   }
389 #include "llvm/IR/Instruction.def"
390
391   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
392                                    const Twine &Name = "") {
393     BinaryOperator *BO = Create(Opc, V1, V2, Name);
394     BO->setHasNoSignedWrap(true);
395     return BO;
396   }
397   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
398                                    const Twine &Name, BasicBlock *BB) {
399     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
400     BO->setHasNoSignedWrap(true);
401     return BO;
402   }
403   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
404                                    const Twine &Name, Instruction *I) {
405     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
406     BO->setHasNoSignedWrap(true);
407     return BO;
408   }
409
410   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
411                                    const Twine &Name = "") {
412     BinaryOperator *BO = Create(Opc, V1, V2, Name);
413     BO->setHasNoUnsignedWrap(true);
414     return BO;
415   }
416   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
417                                    const Twine &Name, BasicBlock *BB) {
418     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
419     BO->setHasNoUnsignedWrap(true);
420     return BO;
421   }
422   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
423                                    const Twine &Name, Instruction *I) {
424     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
425     BO->setHasNoUnsignedWrap(true);
426     return BO;
427   }
428
429   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
430                                      const Twine &Name = "") {
431     BinaryOperator *BO = Create(Opc, V1, V2, Name);
432     BO->setIsExact(true);
433     return BO;
434   }
435   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
436                                      const Twine &Name, BasicBlock *BB) {
437     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
438     BO->setIsExact(true);
439     return BO;
440   }
441   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
442                                      const Twine &Name, Instruction *I) {
443     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
444     BO->setIsExact(true);
445     return BO;
446   }
447
448 #define DEFINE_HELPERS(OPC, NUWNSWEXACT)                                       \
449   static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2,        \
450                                                   const Twine &Name = "") {    \
451     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name);                \
452   }                                                                            \
453   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
454       Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) {               \
455     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB);            \
456   }                                                                            \
457   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
458       Value *V1, Value *V2, const Twine &Name, Instruction *I) {               \
459     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I);             \
460   }
461
462   DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
463   DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
464   DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
465   DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
466   DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
467   DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
468   DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
469   DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
470
471   DEFINE_HELPERS(SDiv, Exact)  // CreateExactSDiv
472   DEFINE_HELPERS(UDiv, Exact)  // CreateExactUDiv
473   DEFINE_HELPERS(AShr, Exact)  // CreateExactAShr
474   DEFINE_HELPERS(LShr, Exact)  // CreateExactLShr
475
476 #undef DEFINE_HELPERS
477
478   /// Helper functions to construct and inspect unary operations (NEG and NOT)
479   /// via binary operators SUB and XOR:
480   ///
481   /// Create the NEG and NOT instructions out of SUB and XOR instructions.
482   ///
483   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
484                                    Instruction *InsertBefore = nullptr);
485   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
486                                    BasicBlock *InsertAtEnd);
487   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
488                                       Instruction *InsertBefore = nullptr);
489   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
490                                       BasicBlock *InsertAtEnd);
491   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
492                                       Instruction *InsertBefore = nullptr);
493   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
494                                       BasicBlock *InsertAtEnd);
495   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
496                                     Instruction *InsertBefore = nullptr);
497   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
498                                     BasicBlock *InsertAtEnd);
499   static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
500                                    Instruction *InsertBefore = nullptr);
501   static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
502                                    BasicBlock *InsertAtEnd);
503
504   /// Check if the given Value is a NEG, FNeg, or NOT instruction.
505   ///
506   static bool isNeg(const Value *V);
507   static bool isFNeg(const Value *V, bool IgnoreZeroSign=false);
508   static bool isNot(const Value *V);
509
510   /// Helper functions to extract the unary argument of a NEG, FNEG or NOT
511   /// operation implemented via Sub, FSub, or Xor.
512   ///
513   static const Value *getNegArgument(const Value *BinOp);
514   static       Value *getNegArgument(      Value *BinOp);
515   static const Value *getFNegArgument(const Value *BinOp);
516   static       Value *getFNegArgument(      Value *BinOp);
517   static const Value *getNotArgument(const Value *BinOp);
518   static       Value *getNotArgument(      Value *BinOp);
519
520   BinaryOps getOpcode() const {
521     return static_cast<BinaryOps>(Instruction::getOpcode());
522   }
523
524   /// Exchange the two operands to this instruction.
525   /// This instruction is safe to use on any binary instruction and
526   /// does not modify the semantics of the instruction.  If the instruction
527   /// cannot be reversed (ie, it's a Div), then return true.
528   ///
529   bool swapOperands();
530
531   /// Set or clear the nsw flag on this instruction, which must be an operator
532   /// which supports this flag. See LangRef.html for the meaning of this flag.
533   void setHasNoUnsignedWrap(bool b = true);
534
535   /// Set or clear the nsw flag on this instruction, which must be an operator
536   /// which supports this flag. See LangRef.html for the meaning of this flag.
537   void setHasNoSignedWrap(bool b = true);
538
539   /// Set or clear the exact flag on this instruction, which must be an operator
540   /// which supports this flag. See LangRef.html for the meaning of this flag.
541   void setIsExact(bool b = true);
542
543   /// Determine whether the no unsigned wrap flag is set.
544   bool hasNoUnsignedWrap() const;
545
546   /// Determine whether the no signed wrap flag is set.
547   bool hasNoSignedWrap() const;
548
549   /// Determine whether the exact flag is set.
550   bool isExact() const;
551
552   /// Convenience method to copy supported wrapping, exact, and fast-math flags
553   /// from V to this instruction.
554   void copyIRFlags(const Value *V);
555
556   /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
557   /// V and this instruction.
558   void andIRFlags(const Value *V);
559
560   // Methods for support type inquiry through isa, cast, and dyn_cast:
561   static inline bool classof(const Instruction *I) {
562     return I->isBinaryOp();
563   }
564   static inline bool classof(const Value *V) {
565     return isa<Instruction>(V) && classof(cast<Instruction>(V));
566   }
567 };
568
569 template <>
570 struct OperandTraits<BinaryOperator> :
571   public FixedNumOperandTraits<BinaryOperator, 2> {
572 };
573
574 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
575
576 //===----------------------------------------------------------------------===//
577 //                               CastInst Class
578 //===----------------------------------------------------------------------===//
579
580 /// This is the base class for all instructions that perform data
581 /// casts. It is simply provided so that instruction category testing
582 /// can be performed with code like:
583 ///
584 /// if (isa<CastInst>(Instr)) { ... }
585 /// @brief Base class of casting instructions.
586 class CastInst : public UnaryInstruction {
587   void anchor() override;
588
589 protected:
590   /// @brief Constructor with insert-before-instruction semantics for subclasses
591   CastInst(Type *Ty, unsigned iType, Value *S,
592            const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
593     : UnaryInstruction(Ty, iType, S, InsertBefore) {
594     setName(NameStr);
595   }
596   /// @brief Constructor with insert-at-end-of-block semantics for subclasses
597   CastInst(Type *Ty, unsigned iType, Value *S,
598            const Twine &NameStr, BasicBlock *InsertAtEnd)
599     : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
600     setName(NameStr);
601   }
602
603 public:
604   /// Provides a way to construct any of the CastInst subclasses using an
605   /// opcode instead of the subclass's constructor. The opcode must be in the
606   /// CastOps category (Instruction::isCast(opcode) returns true). This
607   /// constructor has insert-before-instruction semantics to automatically
608   /// insert the new CastInst before InsertBefore (if it is non-null).
609   /// @brief Construct any of the CastInst subclasses
610   static CastInst *Create(
611     Instruction::CastOps,    ///< The opcode of the cast instruction
612     Value *S,                ///< The value to be casted (operand 0)
613     Type *Ty,          ///< The type to which cast should be made
614     const Twine &Name = "", ///< Name for the instruction
615     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
616   );
617   /// Provides a way to construct any of the CastInst subclasses using an
618   /// opcode instead of the subclass's constructor. The opcode must be in the
619   /// CastOps category. This constructor has insert-at-end-of-block semantics
620   /// to automatically insert the new CastInst at the end of InsertAtEnd (if
621   /// its non-null).
622   /// @brief Construct any of the CastInst subclasses
623   static CastInst *Create(
624     Instruction::CastOps,    ///< The opcode for the cast instruction
625     Value *S,                ///< The value to be casted (operand 0)
626     Type *Ty,          ///< The type to which operand is casted
627     const Twine &Name, ///< The name for the instruction
628     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
629   );
630
631   /// @brief Create a ZExt or BitCast cast instruction
632   static CastInst *CreateZExtOrBitCast(
633     Value *S,                ///< The value to be casted (operand 0)
634     Type *Ty,          ///< The type to which cast should be made
635     const Twine &Name = "", ///< Name for the instruction
636     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
637   );
638
639   /// @brief Create a ZExt or BitCast cast instruction
640   static CastInst *CreateZExtOrBitCast(
641     Value *S,                ///< The value to be casted (operand 0)
642     Type *Ty,          ///< The type to which operand is casted
643     const Twine &Name, ///< The name for the instruction
644     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
645   );
646
647   /// @brief Create a SExt or BitCast cast instruction
648   static CastInst *CreateSExtOrBitCast(
649     Value *S,                ///< The value to be casted (operand 0)
650     Type *Ty,          ///< The type to which cast should be made
651     const Twine &Name = "", ///< Name for the instruction
652     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
653   );
654
655   /// @brief Create a SExt or BitCast cast instruction
656   static CastInst *CreateSExtOrBitCast(
657     Value *S,                ///< The value to be casted (operand 0)
658     Type *Ty,          ///< The type to which operand is casted
659     const Twine &Name, ///< The name for the instruction
660     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
661   );
662
663   /// @brief Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
664   static CastInst *CreatePointerCast(
665     Value *S,                ///< The pointer value to be casted (operand 0)
666     Type *Ty,          ///< The type to which operand is casted
667     const Twine &Name, ///< The name for the instruction
668     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
669   );
670
671   /// @brief Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
672   static CastInst *CreatePointerCast(
673     Value *S,                ///< The pointer value to be casted (operand 0)
674     Type *Ty,          ///< The type to which cast should be made
675     const Twine &Name = "", ///< Name for the instruction
676     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
677   );
678
679   /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
680   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
681     Value *S,                ///< The pointer value to be casted (operand 0)
682     Type *Ty,          ///< The type to which operand is casted
683     const Twine &Name, ///< The name for the instruction
684     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
685   );
686
687   /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
688   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
689     Value *S,                ///< The pointer value to be casted (operand 0)
690     Type *Ty,          ///< The type to which cast should be made
691     const Twine &Name = "", ///< Name for the instruction
692     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
693   );
694
695   /// @brief Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
696   ///
697   /// If the value is a pointer type and the destination an integer type,
698   /// creates a PtrToInt cast. If the value is an integer type and the
699   /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
700   /// a bitcast.
701   static CastInst *CreateBitOrPointerCast(
702     Value *S,                ///< The pointer value to be casted (operand 0)
703     Type *Ty,          ///< The type to which cast should be made
704     const Twine &Name = "", ///< Name for the instruction
705     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
706   );
707
708   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
709   static CastInst *CreateIntegerCast(
710     Value *S,                ///< The pointer value to be casted (operand 0)
711     Type *Ty,          ///< The type to which cast should be made
712     bool isSigned,           ///< Whether to regard S as signed or not
713     const Twine &Name = "", ///< Name for the instruction
714     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
715   );
716
717   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
718   static CastInst *CreateIntegerCast(
719     Value *S,                ///< The integer value to be casted (operand 0)
720     Type *Ty,          ///< The integer type to which operand is casted
721     bool isSigned,           ///< Whether to regard S as signed or not
722     const Twine &Name, ///< The name for the instruction
723     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
724   );
725
726   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
727   static CastInst *CreateFPCast(
728     Value *S,                ///< The floating point value to be casted
729     Type *Ty,          ///< The floating point type to cast to
730     const Twine &Name = "", ///< Name for the instruction
731     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
732   );
733
734   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
735   static CastInst *CreateFPCast(
736     Value *S,                ///< The floating point value to be casted
737     Type *Ty,          ///< The floating point type to cast to
738     const Twine &Name, ///< The name for the instruction
739     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
740   );
741
742   /// @brief Create a Trunc or BitCast cast instruction
743   static CastInst *CreateTruncOrBitCast(
744     Value *S,                ///< The value to be casted (operand 0)
745     Type *Ty,          ///< The type to which cast should be made
746     const Twine &Name = "", ///< Name for the instruction
747     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
748   );
749
750   /// @brief Create a Trunc or BitCast cast instruction
751   static CastInst *CreateTruncOrBitCast(
752     Value *S,                ///< The value to be casted (operand 0)
753     Type *Ty,          ///< The type to which operand is casted
754     const Twine &Name, ///< The name for the instruction
755     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
756   );
757
758   /// @brief Check whether it is valid to call getCastOpcode for these types.
759   static bool isCastable(
760     Type *SrcTy, ///< The Type from which the value should be cast.
761     Type *DestTy ///< The Type to which the value should be cast.
762   );
763
764   /// @brief Check whether a bitcast between these types is valid
765   static bool isBitCastable(
766     Type *SrcTy, ///< The Type from which the value should be cast.
767     Type *DestTy ///< The Type to which the value should be cast.
768   );
769
770   /// @brief Check whether a bitcast, inttoptr, or ptrtoint cast between these
771   /// types is valid and a no-op.
772   ///
773   /// This ensures that any pointer<->integer cast has enough bits in the
774   /// integer and any other cast is a bitcast.
775   static bool isBitOrNoopPointerCastable(
776       Type *SrcTy,  ///< The Type from which the value should be cast.
777       Type *DestTy, ///< The Type to which the value should be cast.
778       const DataLayout &DL);
779
780   /// Returns the opcode necessary to cast Val into Ty using usual casting
781   /// rules.
782   /// @brief Infer the opcode for cast operand and type
783   static Instruction::CastOps getCastOpcode(
784     const Value *Val, ///< The value to cast
785     bool SrcIsSigned, ///< Whether to treat the source as signed
786     Type *Ty,   ///< The Type to which the value should be casted
787     bool DstIsSigned  ///< Whether to treate the dest. as signed
788   );
789
790   /// There are several places where we need to know if a cast instruction
791   /// only deals with integer source and destination types. To simplify that
792   /// logic, this method is provided.
793   /// @returns true iff the cast has only integral typed operand and dest type.
794   /// @brief Determine if this is an integer-only cast.
795   bool isIntegerCast() const;
796
797   /// A lossless cast is one that does not alter the basic value. It implies
798   /// a no-op cast but is more stringent, preventing things like int->float,
799   /// long->double, or int->ptr.
800   /// @returns true iff the cast is lossless.
801   /// @brief Determine if this is a lossless cast.
802   bool isLosslessCast() const;
803
804   /// A no-op cast is one that can be effected without changing any bits.
805   /// It implies that the source and destination types are the same size. The
806   /// IntPtrTy argument is used to make accurate determinations for casts
807   /// involving Integer and Pointer types. They are no-op casts if the integer
808   /// is the same size as the pointer. However, pointer size varies with
809   /// platform. Generally, the result of DataLayout::getIntPtrType() should be
810   /// passed in. If that's not available, use Type::Int64Ty, which will make
811   /// the isNoopCast call conservative.
812   /// @brief Determine if the described cast is a no-op cast.
813   static bool isNoopCast(
814     Instruction::CastOps Opcode,  ///< Opcode of cast
815     Type *SrcTy,   ///< SrcTy of cast
816     Type *DstTy,   ///< DstTy of cast
817     Type *IntPtrTy ///< Integer type corresponding to Ptr types
818   );
819
820   /// @brief Determine if this cast is a no-op cast.
821   bool isNoopCast(
822     Type *IntPtrTy ///< Integer type corresponding to pointer
823   ) const;
824
825   /// @brief Determine if this cast is a no-op cast.
826   ///
827   /// \param DL is the DataLayout to get the Int Ptr type from.
828   bool isNoopCast(const DataLayout &DL) const;
829
830   /// Determine how a pair of casts can be eliminated, if they can be at all.
831   /// This is a helper function for both CastInst and ConstantExpr.
832   /// @returns 0 if the CastInst pair can't be eliminated, otherwise
833   /// returns Instruction::CastOps value for a cast that can replace
834   /// the pair, casting SrcTy to DstTy.
835   /// @brief Determine if a cast pair is eliminable
836   static unsigned isEliminableCastPair(
837     Instruction::CastOps firstOpcode,  ///< Opcode of first cast
838     Instruction::CastOps secondOpcode, ///< Opcode of second cast
839     Type *SrcTy, ///< SrcTy of 1st cast
840     Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
841     Type *DstTy, ///< DstTy of 2nd cast
842     Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
843     Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
844     Type *DstIntPtrTy  ///< Integer type corresponding to Ptr DstTy, or null
845   );
846
847   /// @brief Return the opcode of this CastInst
848   Instruction::CastOps getOpcode() const {
849     return Instruction::CastOps(Instruction::getOpcode());
850   }
851
852   /// @brief Return the source type, as a convenience
853   Type* getSrcTy() const { return getOperand(0)->getType(); }
854   /// @brief Return the destination type, as a convenience
855   Type* getDestTy() const { return getType(); }
856
857   /// This method can be used to determine if a cast from S to DstTy using
858   /// Opcode op is valid or not.
859   /// @returns true iff the proposed cast is valid.
860   /// @brief Determine if a cast is valid without creating one.
861   static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
862
863   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
864   static inline bool classof(const Instruction *I) {
865     return I->isCast();
866   }
867   static inline bool classof(const Value *V) {
868     return isa<Instruction>(V) && classof(cast<Instruction>(V));
869   }
870 };
871
872 //===----------------------------------------------------------------------===//
873 //                               CmpInst Class
874 //===----------------------------------------------------------------------===//
875
876 /// This class is the base class for the comparison instructions.
877 /// @brief Abstract base class of comparison instructions.
878 class CmpInst : public Instruction {
879   void *operator new(size_t, unsigned) = delete;
880   CmpInst() = delete;
881
882 protected:
883   CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
884           Value *LHS, Value *RHS, const Twine &Name = "",
885           Instruction *InsertBefore = nullptr);
886
887   CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
888           Value *LHS, Value *RHS, const Twine &Name,
889           BasicBlock *InsertAtEnd);
890
891   void anchor() override; // Out of line virtual method.
892
893 public:
894   /// This enumeration lists the possible predicates for CmpInst subclasses.
895   /// Values in the range 0-31 are reserved for FCmpInst, while values in the
896   /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
897   /// predicate values are not overlapping between the classes.
898   enum Predicate {
899     // Opcode              U L G E    Intuitive operation
900     FCMP_FALSE =  0,  ///< 0 0 0 0    Always false (always folded)
901     FCMP_OEQ   =  1,  ///< 0 0 0 1    True if ordered and equal
902     FCMP_OGT   =  2,  ///< 0 0 1 0    True if ordered and greater than
903     FCMP_OGE   =  3,  ///< 0 0 1 1    True if ordered and greater than or equal
904     FCMP_OLT   =  4,  ///< 0 1 0 0    True if ordered and less than
905     FCMP_OLE   =  5,  ///< 0 1 0 1    True if ordered and less than or equal
906     FCMP_ONE   =  6,  ///< 0 1 1 0    True if ordered and operands are unequal
907     FCMP_ORD   =  7,  ///< 0 1 1 1    True if ordered (no nans)
908     FCMP_UNO   =  8,  ///< 1 0 0 0    True if unordered: isnan(X) | isnan(Y)
909     FCMP_UEQ   =  9,  ///< 1 0 0 1    True if unordered or equal
910     FCMP_UGT   = 10,  ///< 1 0 1 0    True if unordered or greater than
911     FCMP_UGE   = 11,  ///< 1 0 1 1    True if unordered, greater than, or equal
912     FCMP_ULT   = 12,  ///< 1 1 0 0    True if unordered or less than
913     FCMP_ULE   = 13,  ///< 1 1 0 1    True if unordered, less than, or equal
914     FCMP_UNE   = 14,  ///< 1 1 1 0    True if unordered or not equal
915     FCMP_TRUE  = 15,  ///< 1 1 1 1    Always true (always folded)
916     FIRST_FCMP_PREDICATE = FCMP_FALSE,
917     LAST_FCMP_PREDICATE = FCMP_TRUE,
918     BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
919     ICMP_EQ    = 32,  ///< equal
920     ICMP_NE    = 33,  ///< not equal
921     ICMP_UGT   = 34,  ///< unsigned greater than
922     ICMP_UGE   = 35,  ///< unsigned greater or equal
923     ICMP_ULT   = 36,  ///< unsigned less than
924     ICMP_ULE   = 37,  ///< unsigned less or equal
925     ICMP_SGT   = 38,  ///< signed greater than
926     ICMP_SGE   = 39,  ///< signed greater or equal
927     ICMP_SLT   = 40,  ///< signed less than
928     ICMP_SLE   = 41,  ///< signed less or equal
929     FIRST_ICMP_PREDICATE = ICMP_EQ,
930     LAST_ICMP_PREDICATE = ICMP_SLE,
931     BAD_ICMP_PREDICATE = ICMP_SLE + 1
932   };
933
934   // allocate space for exactly two operands
935   void *operator new(size_t s) {
936     return User::operator new(s, 2);
937   }
938   /// Construct a compare instruction, given the opcode, the predicate and
939   /// the two operands.  Optionally (if InstBefore is specified) insert the
940   /// instruction into a BasicBlock right before the specified instruction.
941   /// The specified Instruction is allowed to be a dereferenced end iterator.
942   /// @brief Create a CmpInst
943   static CmpInst *Create(OtherOps Op,
944                          unsigned short predicate, Value *S1,
945                          Value *S2, const Twine &Name = "",
946                          Instruction *InsertBefore = nullptr);
947
948   /// Construct a compare instruction, given the opcode, the predicate and the
949   /// two operands.  Also automatically insert this instruction to the end of
950   /// the BasicBlock specified.
951   /// @brief Create a CmpInst
952   static CmpInst *Create(OtherOps Op, unsigned short predicate, Value *S1,
953                          Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
954
955   /// @brief Get the opcode casted to the right type
956   OtherOps getOpcode() const {
957     return static_cast<OtherOps>(Instruction::getOpcode());
958   }
959
960   /// @brief Return the predicate for this instruction.
961   Predicate getPredicate() const {
962     return Predicate(getSubclassDataFromInstruction());
963   }
964
965   /// @brief Set the predicate for this instruction to the specified value.
966   void setPredicate(Predicate P) { setInstructionSubclassData(P); }
967
968   static bool isFPPredicate(Predicate P) {
969     return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
970   }
971
972   static bool isIntPredicate(Predicate P) {
973     return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
974   }
975
976   bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
977   bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
978
979   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
980   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
981   /// @returns the inverse predicate for the instruction's current predicate.
982   /// @brief Return the inverse of the instruction's predicate.
983   Predicate getInversePredicate() const {
984     return getInversePredicate(getPredicate());
985   }
986
987   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
988   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
989   /// @returns the inverse predicate for predicate provided in \p pred.
990   /// @brief Return the inverse of a given predicate
991   static Predicate getInversePredicate(Predicate pred);
992
993   /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
994   ///              OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
995   /// @returns the predicate that would be the result of exchanging the two
996   /// operands of the CmpInst instruction without changing the result
997   /// produced.
998   /// @brief Return the predicate as if the operands were swapped
999   Predicate getSwappedPredicate() const {
1000     return getSwappedPredicate(getPredicate());
1001   }
1002
1003   /// This is a static version that you can use without an instruction
1004   /// available.
1005   /// @brief Return the predicate as if the operands were swapped.
1006   static Predicate getSwappedPredicate(Predicate pred);
1007
1008   /// @brief Provide more efficient getOperand methods.
1009   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1010
1011   /// This is just a convenience that dispatches to the subclasses.
1012   /// @brief Swap the operands and adjust predicate accordingly to retain
1013   /// the same comparison.
1014   void swapOperands();
1015
1016   /// This is just a convenience that dispatches to the subclasses.
1017   /// @brief Determine if this CmpInst is commutative.
1018   bool isCommutative() const;
1019
1020   /// This is just a convenience that dispatches to the subclasses.
1021   /// @brief Determine if this is an equals/not equals predicate.
1022   bool isEquality() const;
1023
1024   /// @returns true if the comparison is signed, false otherwise.
1025   /// @brief Determine if this instruction is using a signed comparison.
1026   bool isSigned() const {
1027     return isSigned(getPredicate());
1028   }
1029
1030   /// @returns true if the comparison is unsigned, false otherwise.
1031   /// @brief Determine if this instruction is using an unsigned comparison.
1032   bool isUnsigned() const {
1033     return isUnsigned(getPredicate());
1034   }
1035
1036   /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1037   /// @returns the signed version of the unsigned predicate pred.
1038   /// @brief return the signed version of a predicate
1039   static Predicate getSignedPredicate(Predicate pred);
1040
1041   /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert
1042   /// @returns the signed version of the predicate for this instruction (which
1043   /// has to be an unsigned predicate).
1044   /// @brief return the signed version of a predicate
1045   Predicate getSignedPredicate() {
1046     return getSignedPredicate(getPredicate());
1047   }
1048
1049   /// This is just a convenience.
1050   /// @brief Determine if this is true when both operands are the same.
1051   bool isTrueWhenEqual() const {
1052     return isTrueWhenEqual(getPredicate());
1053   }
1054
1055   /// This is just a convenience.
1056   /// @brief Determine if this is false when both operands are the same.
1057   bool isFalseWhenEqual() const {
1058     return isFalseWhenEqual(getPredicate());
1059   }
1060
1061   /// @returns true if the predicate is unsigned, false otherwise.
1062   /// @brief Determine if the predicate is an unsigned operation.
1063   static bool isUnsigned(unsigned short predicate);
1064
1065   /// @returns true if the predicate is signed, false otherwise.
1066   /// @brief Determine if the predicate is an signed operation.
1067   static bool isSigned(unsigned short predicate);
1068
1069   /// @brief Determine if the predicate is an ordered operation.
1070   static bool isOrdered(unsigned short predicate);
1071
1072   /// @brief Determine if the predicate is an unordered operation.
1073   static bool isUnordered(unsigned short predicate);
1074
1075   /// Determine if the predicate is true when comparing a value with itself.
1076   static bool isTrueWhenEqual(unsigned short predicate);
1077
1078   /// Determine if the predicate is false when comparing a value with itself.
1079   static bool isFalseWhenEqual(unsigned short predicate);
1080
1081   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1082   static inline bool classof(const Instruction *I) {
1083     return I->getOpcode() == Instruction::ICmp ||
1084            I->getOpcode() == Instruction::FCmp;
1085   }
1086   static inline bool classof(const Value *V) {
1087     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1088   }
1089
1090   /// @brief Create a result type for fcmp/icmp
1091   static Type* makeCmpResultType(Type* opnd_type) {
1092     if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1093       return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1094                              vt->getNumElements());
1095     }
1096     return Type::getInt1Ty(opnd_type->getContext());
1097   }
1098
1099 private:
1100   // Shadow Value::setValueSubclassData with a private forwarding method so that
1101   // subclasses cannot accidentally use it.
1102   void setValueSubclassData(unsigned short D) {
1103     Value::setValueSubclassData(D);
1104   }
1105 };
1106
1107 // FIXME: these are redundant if CmpInst < BinaryOperator
1108 template <>
1109 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1110 };
1111
1112 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1113
1114 /// \brief A lightweight accessor for an operand bundle meant to be passed
1115 /// around by value.
1116 struct OperandBundleUse {
1117   ArrayRef<Use> Inputs;
1118
1119   OperandBundleUse() {}
1120   explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1121       : Inputs(Inputs), Tag(Tag) {}
1122
1123   /// \brief Return true if all the operands in this operand bundle have the
1124   /// attribute A.
1125   ///
1126   /// Currently there is no way to have attributes on operand bundles differ on
1127   /// a per operand granularity.
1128   bool operandsHaveAttr(Attribute::AttrKind A) const {
1129     // Conservative answer:  no operands have any attributes.
1130     return false;
1131   };
1132
1133   /// \brief Return the tag of this operand bundle as a string.
1134   StringRef getTagName() const {
1135     return Tag->getKey();
1136   }
1137
1138   /// \brief Return the tag of this operand bundle as an integer.
1139   ///
1140   /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1141   /// and this function returns the unique integer getOrInsertBundleTag
1142   /// associated the tag of this operand bundle to.
1143   uint32_t getTagID() const {
1144     return Tag->getValue();
1145   }
1146
1147 private:
1148   /// \brief Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1149   StringMapEntry<uint32_t> *Tag;
1150 };
1151
1152 /// \brief A container for an operand bundle being viewed as a set of values
1153 /// rather than a set of uses.
1154 ///
1155 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1156 /// so it is possible to create and pass around "self-contained" instances of
1157 /// OperandBundleDef and ConstOperandBundleDef.
1158 template <typename InputTy> class OperandBundleDefT {
1159   std::string Tag;
1160   std::vector<InputTy> Inputs;
1161
1162 public:
1163   explicit OperandBundleDefT(StringRef Tag, std::vector<InputTy> Inputs)
1164       : Tag(Tag), Inputs(std::move(Inputs)) {}
1165
1166   explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1167       : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1168
1169   explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1170     Tag = OBU.getTagName();
1171     Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end());
1172   }
1173
1174   ArrayRef<InputTy> inputs() const { return Inputs; }
1175
1176   typedef typename std::vector<InputTy>::const_iterator input_iterator;
1177   size_t input_size() const { return Inputs.size(); }
1178   input_iterator input_begin() const { return Inputs.begin(); }
1179   input_iterator input_end() const { return Inputs.end(); }
1180
1181   StringRef getTag() const { return Tag; }
1182 };
1183
1184 typedef OperandBundleDefT<Value *> OperandBundleDef;
1185 typedef OperandBundleDefT<const Value *> ConstOperandBundleDef;
1186
1187 /// \brief A mixin to add operand bundle functionality to llvm instruction
1188 /// classes.
1189 ///
1190 /// OperandBundleUser uses the descriptor area co-allocated with the host User
1191 /// to store some meta information about which operands are "normal" operands,
1192 /// and which ones belong to some operand bundle.
1193 ///
1194 /// The layout of an operand bundle user is
1195 ///
1196 ///          +-----------uint32_t End-------------------------------------+
1197 ///          |                                                            |
1198 ///          |  +--------uint32_t Begin--------------------+              |
1199 ///          |  |                                          |              |
1200 ///          ^  ^                                          v              v
1201 ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
1202 ///  | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
1203 ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
1204 ///   v  v                                  ^              ^
1205 ///   |  |                                  |              |
1206 ///   |  +--------uint32_t Begin------------+              |
1207 ///   |                                                    |
1208 ///   +-----------uint32_t End-----------------------------+
1209 ///
1210 ///
1211 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use list.
1212 /// These descriptions are installed and managed by this class, and they're all
1213 /// instances of OperandBundleUser<T>::BundleOpInfo.
1214 ///
1215 /// DU is an additional descriptor installed by User's 'operator new' to keep
1216 /// track of the 'BOI0 ... BOIN' co-allocation.  OperandBundleUser does not
1217 /// access or modify DU in any way, it's an implementation detail private to
1218 /// User.
1219 ///
1220 /// The regular Use& vector for the User starts at U0.  The operand bundle uses
1221 /// are part of the Use& vector, just like normal uses.  In the diagram above,
1222 /// the operand bundle uses start at BOI0_U0.  Each instance of BundleOpInfo has
1223 /// information about a contiguous set of uses constituting an operand bundle,
1224 /// and the total set of operand bundle uses themselves form a contiguous set of
1225 /// uses (i.e. there are no gaps between uses corresponding to individual
1226 /// operand bundles).
1227 ///
1228 /// This class does not know the location of the set of operand bundle uses
1229 /// within the use list -- that is decided by the User using this class via the
1230 /// BeginIdx argument in populateBundleOperandInfos.
1231 ///
1232 /// Currently operand bundle users with hung-off operands are not supported.
1233 template <typename InstrTy, typename OpIteratorTy> class OperandBundleUser {
1234 public:
1235   /// \brief Return the number of operand bundles associated with this User.
1236   unsigned getNumOperandBundles() const {
1237     return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1238   }
1239
1240   /// \brief Return true if this User has any operand bundles.
1241   bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1242
1243   /// \brief Return the index of the first bundle operand in the Use array.
1244   unsigned getBundleOperandsStartIndex() const {
1245     assert(hasOperandBundles() && "Don't call otherwise!");
1246     return bundle_op_info_begin()->Begin;
1247   }
1248
1249   /// \brief Return the index of the last bundle operand in the Use array.
1250   unsigned getBundleOperandsEndIndex() const {
1251     assert(hasOperandBundles() && "Don't call otherwise!");
1252     return bundle_op_info_end()[-1].End;
1253   }
1254
1255   /// \brief Return the total number operands (not operand bundles) used by
1256   /// every operand bundle in this OperandBundleUser.
1257   unsigned getNumTotalBundleOperands() const {
1258     if (!hasOperandBundles())
1259       return 0;
1260
1261     unsigned Begin = getBundleOperandsStartIndex();
1262     unsigned End = getBundleOperandsEndIndex();
1263
1264     assert(Begin <= End && "Should be!");
1265     return End - Begin;
1266   }
1267
1268   /// \brief Return the operand bundle at a specific index.
1269   OperandBundleUse getOperandBundleAt(unsigned Index) const {
1270     assert(Index < getNumOperandBundles() && "Index out of bounds!");
1271     return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
1272   }
1273
1274   /// \brief Return the number of operand bundles with the tag Name attached to
1275   /// this instruction.
1276   unsigned countOperandBundlesOfType(StringRef Name) const {
1277     unsigned Count = 0;
1278     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1279       if (getOperandBundleAt(i).getTagName() == Name)
1280         Count++;
1281
1282     return Count;
1283   }
1284
1285   /// \brief Return the number of operand bundles with the tag ID attached to
1286   /// this instruction.
1287   unsigned countOperandBundlesOfType(uint32_t ID) const {
1288     unsigned Count = 0;
1289     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1290       if (getOperandBundleAt(i).getTagID() == ID)
1291         Count++;
1292
1293     return Count;
1294   }
1295
1296   /// \brief Return an operand bundle by name, if present.
1297   ///
1298   /// It is an error to call this for operand bundle types that may have
1299   /// multiple instances of them on the same instruction.
1300   Optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
1301     assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
1302
1303     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1304       OperandBundleUse U = getOperandBundleAt(i);
1305       if (U.getTagName() == Name)
1306         return U;
1307     }
1308
1309     return None;
1310   }
1311
1312   /// \brief Return an operand bundle by tag ID, if present.
1313   ///
1314   /// It is an error to call this for operand bundle types that may have
1315   /// multiple instances of them on the same instruction.
1316   Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
1317     assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
1318
1319     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
1320       OperandBundleUse U = getOperandBundleAt(i);
1321       if (U.getTagID() == ID)
1322         return U;
1323     }
1324
1325     return None;
1326   }
1327
1328   /// \brief Return the list of operand bundles attached to this instruction as
1329   /// a vector of OperandBundleDefs.
1330   ///
1331   /// This function copies the OperandBundeUse instances associated with this
1332   /// OperandBundleUser to a vector of OperandBundleDefs.  Note:
1333   /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
1334   /// representations of operand bundles (see documentation above).
1335   void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const {
1336     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
1337       Defs.emplace_back(getOperandBundleAt(i));
1338   }
1339
1340   /// \brief Return the operand bundle for the operand at index OpIdx.
1341   ///
1342   /// It is an error to call this with an OpIdx that does not correspond to an
1343   /// bundle operand.
1344   OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
1345     for (auto &BOI : bundle_op_infos())
1346       if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
1347         return operandBundleFromBundleOpInfo(BOI);
1348
1349     llvm_unreachable("Did not find operand bundle for operand!");
1350   }
1351
1352   /// \brief Return true if this operand bundle user has operand bundles that
1353   /// may read from the heap.
1354   bool hasReadingOperandBundles() const {
1355     // Implementation note: this is a conservative implementation of operand
1356     // bundle semantics, where *any* operand bundle forces a callsite to be at
1357     // least readonly.
1358     return hasOperandBundles();
1359   }
1360
1361   /// \brief Return true if this operand bundle user has operand bundles that
1362   /// may write to the heap.
1363   bool hasClobberingOperandBundles() const {
1364     // Implementation note: this is a conservative implementation of operand
1365     // bundle semantics, where *any* operand bundle forces a callsite to be
1366     // read-write.
1367     return hasOperandBundles();
1368   }
1369
1370 protected:
1371   /// \brief Is the function attribute S disallowed by some operand bundle on
1372   /// this operand bundle user?
1373   bool isFnAttrDisallowedByOpBundle(StringRef S) const {
1374     // Operand bundles only possibly disallow readnone, readonly and argmenonly
1375     // attributes.  All String attributes are fine.
1376     return false;
1377   }
1378
1379   /// \brief Is the function attribute A disallowed by some operand bundle on
1380   /// this operand bundle user?
1381   bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const {
1382     switch (A) {
1383     default:
1384       return false;
1385
1386     case Attribute::ArgMemOnly:
1387       return hasReadingOperandBundles();
1388
1389     case Attribute::ReadNone:
1390       return hasReadingOperandBundles();
1391
1392     case Attribute::ReadOnly:
1393       return hasClobberingOperandBundles();
1394     }
1395
1396     llvm_unreachable("switch has a default case!");
1397   }
1398
1399   /// \brief Used to keep track of an operand bundle.  See the main comment on
1400   /// OperandBundleUser above.
1401   struct BundleOpInfo {
1402     /// \brief The operand bundle tag, interned by
1403     /// LLVMContextImpl::getOrInsertBundleTag.
1404     StringMapEntry<uint32_t> *Tag;
1405
1406     /// \brief The index in the Use& vector where operands for this operand
1407     /// bundle starts.
1408     uint32_t Begin;
1409
1410     /// \brief The index in the Use& vector where operands for this operand
1411     /// bundle ends.
1412     uint32_t End;
1413   };
1414
1415   /// \brief Simple helper function to map a BundleOpInfo to an
1416   /// OperandBundleUse.
1417   OperandBundleUse
1418   operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
1419     auto op_begin = static_cast<const InstrTy *>(this)->op_begin();
1420     ArrayRef<Use> Inputs(op_begin + BOI.Begin, op_begin + BOI.End);
1421     return OperandBundleUse(BOI.Tag, Inputs);
1422   }
1423
1424   typedef BundleOpInfo *bundle_op_iterator;
1425   typedef const BundleOpInfo *const_bundle_op_iterator;
1426
1427   /// \brief Return the start of the list of BundleOpInfo instances associated
1428   /// with this OperandBundleUser.
1429   bundle_op_iterator bundle_op_info_begin() {
1430     if (!static_cast<InstrTy *>(this)->hasDescriptor())
1431       return nullptr;
1432
1433     uint8_t *BytesBegin = static_cast<InstrTy *>(this)->getDescriptor().begin();
1434     return reinterpret_cast<bundle_op_iterator>(BytesBegin);
1435   }
1436
1437   /// \brief Return the start of the list of BundleOpInfo instances associated
1438   /// with this OperandBundleUser.
1439   const_bundle_op_iterator bundle_op_info_begin() const {
1440     auto *NonConstThis =
1441         const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1442     return NonConstThis->bundle_op_info_begin();
1443   }
1444
1445   /// \brief Return the end of the list of BundleOpInfo instances associated
1446   /// with this OperandBundleUser.
1447   bundle_op_iterator bundle_op_info_end() {
1448     if (!static_cast<InstrTy *>(this)->hasDescriptor())
1449       return nullptr;
1450
1451     uint8_t *BytesEnd = static_cast<InstrTy *>(this)->getDescriptor().end();
1452     return reinterpret_cast<bundle_op_iterator>(BytesEnd);
1453   }
1454
1455   /// \brief Return the end of the list of BundleOpInfo instances associated
1456   /// with this OperandBundleUser.
1457   const_bundle_op_iterator bundle_op_info_end() const {
1458     auto *NonConstThis =
1459         const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this);
1460     return NonConstThis->bundle_op_info_end();
1461   }
1462
1463   /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1464   iterator_range<bundle_op_iterator> bundle_op_infos() {
1465     return iterator_range<bundle_op_iterator>(bundle_op_info_begin(),
1466                                               bundle_op_info_end());
1467   }
1468
1469   /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
1470   iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
1471     return iterator_range<const_bundle_op_iterator>(bundle_op_info_begin(),
1472                                                     bundle_op_info_end());
1473   }
1474
1475   /// \brief Populate the BundleOpInfo instances and the Use& vector from \p
1476   /// Bundles.  Return the op_iterator pointing to the Use& one past the last
1477   /// last bundle operand use.
1478   ///
1479   /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
1480   /// instance allocated in this User's descriptor.
1481   OpIteratorTy populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
1482                                           const unsigned BeginIndex) {
1483     auto It = static_cast<InstrTy *>(this)->op_begin() + BeginIndex;
1484     for (auto &B : Bundles)
1485       It = std::copy(B.input_begin(), B.input_end(), It);
1486
1487     auto *ContextImpl = static_cast<InstrTy *>(this)->getContext().pImpl;
1488     auto BI = Bundles.begin();
1489     unsigned CurrentIndex = BeginIndex;
1490
1491     for (auto &BOI : bundle_op_infos()) {
1492       assert(BI != Bundles.end() && "Incorrect allocation?");
1493
1494       BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
1495       BOI.Begin = CurrentIndex;
1496       BOI.End = CurrentIndex + BI->input_size();
1497       CurrentIndex = BOI.End;
1498       BI++;
1499     }
1500
1501     assert(BI == Bundles.end() && "Incorrect allocation?");
1502
1503     return It;
1504   }
1505
1506   /// \brief Return the total number of values used in \p Bundles.
1507   static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
1508     unsigned Total = 0;
1509     for (auto &B : Bundles)
1510       Total += B.input_size();
1511     return Total;
1512   }
1513 };
1514
1515 } // end llvm namespace
1516
1517 #endif // LLVM_IR_INSTRTYPES_H