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