Reformat.
[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/Twine.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/IR/OperandTraits.h"
23
24 namespace llvm {
25
26 class LLVMContext;
27
28 //===----------------------------------------------------------------------===//
29 //                            TerminatorInst Class
30 //===----------------------------------------------------------------------===//
31
32 /// Subclasses of this class are all able to terminate a basic
33 /// block. Thus, these are all the flow control type of operations.
34 ///
35 class TerminatorInst : public Instruction {
36 protected:
37   TerminatorInst(Type *Ty, Instruction::TermOps iType,
38                  Use *Ops, unsigned NumOps,
39                  Instruction *InsertBefore = nullptr)
40     : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
41
42   TerminatorInst(Type *Ty, Instruction::TermOps iType,
43                  Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
44     : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
45
46   // Out of line virtual method, so the vtable, etc has a home.
47   ~TerminatorInst() override;
48
49   /// Virtual methods - Terminators should overload these and provide inline
50   /// overrides of non-V methods.
51   virtual BasicBlock *getSuccessorV(unsigned idx) const = 0;
52   virtual unsigned getNumSuccessorsV() const = 0;
53   virtual void setSuccessorV(unsigned idx, BasicBlock *B) = 0;
54 public:
55
56   /// Return the number of successors that this terminator has.
57   unsigned getNumSuccessors() const {
58     return getNumSuccessorsV();
59   }
60
61   /// Return the specified successor.
62   BasicBlock *getSuccessor(unsigned idx) const {
63     return getSuccessorV(idx);
64   }
65
66   /// Update the specified successor to point at the provided block.
67   void setSuccessor(unsigned idx, BasicBlock *B) {
68     setSuccessorV(idx, B);
69   }
70
71   // Methods for support type inquiry through isa, cast, and dyn_cast:
72   static inline bool classof(const Instruction *I) {
73     return I->isTerminator();
74   }
75   static inline bool classof(const Value *V) {
76     return isa<Instruction>(V) && classof(cast<Instruction>(V));
77   }
78
79   // \brief Returns true if this terminator relates to exception handling.
80   bool isExceptional() const {
81     switch (getOpcode()) {
82     case Instruction::CatchPad:
83     case Instruction::CatchEndPad:
84     case Instruction::CatchRet:
85     case Instruction::CleanupEndPad:
86     case Instruction::CleanupRet:
87     case Instruction::Invoke:
88     case Instruction::Resume:
89     case Instruction::TerminatePad:
90       return true;
91     default:
92       return false;
93     }
94   }
95
96   //===--------------------------------------------------------------------===//
97   // succ_iterator definition
98   //===--------------------------------------------------------------------===//
99
100   template <class Term, class BB> // Successor Iterator
101   class SuccIterator : public std::iterator<std::random_access_iterator_tag, BB,
102                                             int, BB *, BB *> {
103     typedef std::iterator<std::random_access_iterator_tag, BB, int, BB *, BB *>
104         super;
105
106   public:
107     typedef typename super::pointer pointer;
108     typedef typename super::reference reference;
109
110   private:
111     Term TermInst;
112     unsigned idx;
113     typedef SuccIterator<Term, BB> Self;
114
115     inline bool index_is_valid(unsigned idx) {
116       return idx < TermInst->getNumSuccessors();
117     }
118
119     /// \brief Proxy object to allow write access in operator[]
120     class SuccessorProxy {
121       Self it;
122
123     public:
124       explicit SuccessorProxy(const Self &it) : it(it) {}
125
126       SuccessorProxy(const SuccessorProxy &) = default;
127
128       SuccessorProxy &operator=(SuccessorProxy r) {
129         *this = reference(r);
130         return *this;
131       }
132
133       SuccessorProxy &operator=(reference r) {
134         it.TermInst->setSuccessor(it.idx, r);
135         return *this;
136       }
137
138       operator reference() const { return *it; }
139     };
140
141   public:
142     // begin iterator
143     explicit inline SuccIterator(Term T) : TermInst(T), idx(0) {}
144     // end iterator
145     inline SuccIterator(Term T, bool) : TermInst(T) {
146       if (TermInst)
147         idx = TermInst->getNumSuccessors();
148       else
149         // Term == NULL happens, if a basic block is not fully constructed and
150         // consequently getTerminator() returns NULL. In this case we construct
151         // a SuccIterator which describes a basic block that has zero
152         // successors.
153         // Defining SuccIterator for incomplete and malformed CFGs is especially
154         // useful for debugging.
155         idx = 0;
156     }
157
158     /// This is used to interface between code that wants to
159     /// operate on terminator instructions directly.
160     unsigned getSuccessorIndex() const { return idx; }
161
162     inline bool operator==(const Self &x) const { return idx == x.idx; }
163     inline bool operator!=(const Self &x) const { return !operator==(x); }
164
165     inline reference operator*() const { return TermInst->getSuccessor(idx); }
166     inline pointer operator->() const { return operator*(); }
167
168     inline Self &operator++() {
169       ++idx;
170       return *this;
171     } // Preincrement
172
173     inline Self operator++(int) { // Postincrement
174       Self tmp = *this;
175       ++*this;
176       return tmp;
177     }
178
179     inline Self &operator--() {
180       --idx;
181       return *this;
182     }                             // Predecrement
183     inline Self operator--(int) { // Postdecrement
184       Self tmp = *this;
185       --*this;
186       return tmp;
187     }
188
189     inline bool operator<(const Self &x) const {
190       assert(TermInst == x.TermInst &&
191              "Cannot compare iterators of different blocks!");
192       return idx < x.idx;
193     }
194
195     inline bool operator<=(const Self &x) const {
196       assert(TermInst == x.TermInst &&
197              "Cannot compare iterators of different blocks!");
198       return idx <= x.idx;
199     }
200     inline bool operator>=(const Self &x) const {
201       assert(TermInst == x.TermInst &&
202              "Cannot compare iterators of different blocks!");
203       return idx >= x.idx;
204     }
205
206     inline bool operator>(const Self &x) const {
207       assert(TermInst == x.TermInst &&
208              "Cannot compare iterators of different blocks!");
209       return idx > x.idx;
210     }
211
212     inline Self &operator+=(int Right) {
213       unsigned new_idx = idx + Right;
214       assert(index_is_valid(new_idx) && "Iterator index out of bound");
215       idx = new_idx;
216       return *this;
217     }
218
219     inline Self operator+(int Right) const {
220       Self tmp = *this;
221       tmp += Right;
222       return tmp;
223     }
224
225     inline Self &operator-=(int Right) { return operator+=(-Right); }
226
227     inline Self operator-(int Right) const { return operator+(-Right); }
228
229     inline int operator-(const Self &x) const {
230       assert(TermInst == x.TermInst &&
231              "Cannot work on iterators of different blocks!");
232       int distance = idx - x.idx;
233       return distance;
234     }
235
236     inline SuccessorProxy operator[](int offset) {
237       Self tmp = *this;
238       tmp += offset;
239       return SuccessorProxy(tmp);
240     }
241
242     /// Get the source BB of this iterator.
243     inline BB *getSource() {
244       assert(TermInst && "Source not available, if basic block was malformed");
245       return TermInst->getParent();
246     }
247   };
248
249   typedef SuccIterator<TerminatorInst *, BasicBlock> succ_iterator;
250   typedef SuccIterator<const TerminatorInst *, const BasicBlock>
251       succ_const_iterator;
252   typedef llvm::iterator_range<succ_iterator> succ_range;
253   typedef llvm::iterator_range<succ_const_iterator> succ_const_range;
254
255 private:
256   inline succ_iterator succ_begin() { return succ_iterator(this); }
257   inline succ_const_iterator succ_begin() const {
258     return succ_const_iterator(this);
259   }
260   inline succ_iterator succ_end() { return succ_iterator(this, true); }
261   inline succ_const_iterator succ_end() const {
262     return succ_const_iterator(this, true);
263   }
264
265 public:
266   inline succ_range successors() {
267     return succ_range(succ_begin(), succ_end());
268   }
269   inline succ_const_range successors() const {
270     return succ_const_range(succ_begin(), succ_end());
271   }
272 };
273
274
275 //===----------------------------------------------------------------------===//
276 //                          UnaryInstruction Class
277 //===----------------------------------------------------------------------===//
278
279 class UnaryInstruction : public Instruction {
280   void *operator new(size_t, unsigned) = delete;
281
282 protected:
283   UnaryInstruction(Type *Ty, unsigned iType, Value *V,
284                    Instruction *IB = nullptr)
285     : Instruction(Ty, iType, &Op<0>(), 1, IB) {
286     Op<0>() = V;
287   }
288   UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
289     : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
290     Op<0>() = V;
291   }
292 public:
293   // allocate space for exactly one operand
294   void *operator new(size_t s) {
295     return User::operator new(s, 1);
296   }
297
298   // Out of line virtual method, so the vtable, etc has a home.
299   ~UnaryInstruction() override;
300
301   /// Transparently provide more efficient getOperand methods.
302   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
303
304   // Methods for support type inquiry through isa, cast, and dyn_cast:
305   static inline bool classof(const Instruction *I) {
306     return I->getOpcode() == Instruction::Alloca ||
307            I->getOpcode() == Instruction::Load ||
308            I->getOpcode() == Instruction::VAArg ||
309            I->getOpcode() == Instruction::ExtractValue ||
310            (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
311   }
312   static inline bool classof(const Value *V) {
313     return isa<Instruction>(V) && classof(cast<Instruction>(V));
314   }
315 };
316
317 template <>
318 struct OperandTraits<UnaryInstruction> :
319   public FixedNumOperandTraits<UnaryInstruction, 1> {
320 };
321
322 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
323
324 //===----------------------------------------------------------------------===//
325 //                           BinaryOperator Class
326 //===----------------------------------------------------------------------===//
327
328 class BinaryOperator : public Instruction {
329   void *operator new(size_t, unsigned) = delete;
330 protected:
331   void init(BinaryOps iType);
332   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
333                  const Twine &Name, Instruction *InsertBefore);
334   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
335                  const Twine &Name, BasicBlock *InsertAtEnd);
336
337   // Note: Instruction needs to be a friend here to call cloneImpl.
338   friend class Instruction;
339   BinaryOperator *cloneImpl() const;
340
341 public:
342   // allocate space for exactly two operands
343   void *operator new(size_t s) {
344     return User::operator new(s, 2);
345   }
346
347   /// Transparently provide more efficient getOperand methods.
348   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
349
350   /// Construct a binary instruction, given the opcode and the two
351   /// operands.  Optionally (if InstBefore is specified) insert the instruction
352   /// into a BasicBlock right before the specified instruction.  The specified
353   /// Instruction is allowed to be a dereferenced end iterator.
354   ///
355   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
356                                 const Twine &Name = Twine(),
357                                 Instruction *InsertBefore = nullptr);
358
359   /// Construct a binary instruction, given the opcode and the two
360   /// operands.  Also automatically insert this instruction to the end of the
361   /// BasicBlock specified.
362   ///
363   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
364                                 const Twine &Name, BasicBlock *InsertAtEnd);
365
366   /// These methods just forward to Create, and are useful when you
367   /// statically know what type of instruction you're going to create.  These
368   /// helpers just save some typing.
369 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
370   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
371                                      const Twine &Name = "") {\
372     return Create(Instruction::OPC, V1, V2, Name);\
373   }
374 #include "llvm/IR/Instruction.def"
375 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
376   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
377                                      const Twine &Name, BasicBlock *BB) {\
378     return Create(Instruction::OPC, V1, V2, Name, BB);\
379   }
380 #include "llvm/IR/Instruction.def"
381 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
382   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
383                                      const Twine &Name, Instruction *I) {\
384     return Create(Instruction::OPC, V1, V2, Name, I);\
385   }
386 #include "llvm/IR/Instruction.def"
387
388   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
389                                    const Twine &Name = "") {
390     BinaryOperator *BO = Create(Opc, V1, V2, Name);
391     BO->setHasNoSignedWrap(true);
392     return BO;
393   }
394   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
395                                    const Twine &Name, BasicBlock *BB) {
396     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
397     BO->setHasNoSignedWrap(true);
398     return BO;
399   }
400   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
401                                    const Twine &Name, Instruction *I) {
402     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
403     BO->setHasNoSignedWrap(true);
404     return BO;
405   }
406   
407   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
408                                    const Twine &Name = "") {
409     BinaryOperator *BO = Create(Opc, V1, V2, Name);
410     BO->setHasNoUnsignedWrap(true);
411     return BO;
412   }
413   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
414                                    const Twine &Name, BasicBlock *BB) {
415     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
416     BO->setHasNoUnsignedWrap(true);
417     return BO;
418   }
419   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
420                                    const Twine &Name, Instruction *I) {
421     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
422     BO->setHasNoUnsignedWrap(true);
423     return BO;
424   }
425   
426   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
427                                      const Twine &Name = "") {
428     BinaryOperator *BO = Create(Opc, V1, V2, Name);
429     BO->setIsExact(true);
430     return BO;
431   }
432   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
433                                      const Twine &Name, BasicBlock *BB) {
434     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
435     BO->setIsExact(true);
436     return BO;
437   }
438   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
439                                      const Twine &Name, Instruction *I) {
440     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
441     BO->setIsExact(true);
442     return BO;
443   }
444
445 #define DEFINE_HELPERS(OPC, NUWNSWEXACT)                                       \
446   static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2,        \
447                                                   const Twine &Name = "") {    \
448     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name);                \
449   }                                                                            \
450   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
451       Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) {               \
452     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB);            \
453   }                                                                            \
454   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
455       Value *V1, Value *V2, const Twine &Name, Instruction *I) {               \
456     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I);             \
457   }
458
459   DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
460   DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
461   DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
462   DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
463   DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
464   DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
465   DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
466   DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
467
468   DEFINE_HELPERS(SDiv, Exact)  // CreateExactSDiv
469   DEFINE_HELPERS(UDiv, Exact)  // CreateExactUDiv
470   DEFINE_HELPERS(AShr, Exact)  // CreateExactAShr
471   DEFINE_HELPERS(LShr, Exact)  // CreateExactLShr
472
473 #undef DEFINE_HELPERS
474   
475   /// Helper functions to construct and inspect unary operations (NEG and NOT)
476   /// via binary operators SUB and XOR:
477   ///
478   /// Create the NEG and NOT instructions out of SUB and XOR instructions.
479   ///
480   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
481                                    Instruction *InsertBefore = nullptr);
482   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
483                                    BasicBlock *InsertAtEnd);
484   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
485                                       Instruction *InsertBefore = nullptr);
486   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
487                                       BasicBlock *InsertAtEnd);
488   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
489                                       Instruction *InsertBefore = nullptr);
490   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
491                                       BasicBlock *InsertAtEnd);
492   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
493                                     Instruction *InsertBefore = nullptr);
494   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
495                                     BasicBlock *InsertAtEnd);
496   static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
497                                    Instruction *InsertBefore = nullptr);
498   static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
499                                    BasicBlock *InsertAtEnd);
500
501   /// Check if the given Value is a NEG, FNeg, or NOT instruction.
502   ///
503   static bool isNeg(const Value *V);
504   static bool isFNeg(const Value *V, bool IgnoreZeroSign=false);
505   static bool isNot(const Value *V);
506
507   /// Helper functions to extract the unary argument of a NEG, FNEG or NOT
508   /// operation implemented via Sub, FSub, or Xor.
509   ///
510   static const Value *getNegArgument(const Value *BinOp);
511   static       Value *getNegArgument(      Value *BinOp);
512   static const Value *getFNegArgument(const Value *BinOp);
513   static       Value *getFNegArgument(      Value *BinOp);
514   static const Value *getNotArgument(const Value *BinOp);
515   static       Value *getNotArgument(      Value *BinOp);
516
517   BinaryOps getOpcode() const {
518     return static_cast<BinaryOps>(Instruction::getOpcode());
519   }
520
521   /// Exchange the two operands to this instruction.
522   /// This instruction is safe to use on any binary instruction and
523   /// does not modify the semantics of the instruction.  If the instruction
524   /// cannot be reversed (ie, it's a Div), then return true.
525   ///
526   bool swapOperands();
527
528   /// Set or clear the nsw flag on this instruction, which must be an operator
529   /// which supports this flag. See LangRef.html for the meaning of this flag.
530   void setHasNoUnsignedWrap(bool b = true);
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 setHasNoSignedWrap(bool b = true);
535
536   /// Set or clear the exact 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 setIsExact(bool b = true);
539
540   /// Determine whether the no unsigned wrap flag is set.
541   bool hasNoUnsignedWrap() const;
542
543   /// Determine whether the no signed wrap flag is set.
544   bool hasNoSignedWrap() const;
545
546   /// Determine whether the exact flag is set.
547   bool isExact() const;
548
549   /// Convenience method to copy supported wrapping, exact, and fast-math flags
550   /// from V to this instruction.
551   void copyIRFlags(const Value *V);
552   
553   /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
554   /// V and this instruction.
555   void andIRFlags(const Value *V);
556
557   // Methods for support type inquiry through isa, cast, and dyn_cast:
558   static inline bool classof(const Instruction *I) {
559     return I->isBinaryOp();
560   }
561   static inline bool classof(const Value *V) {
562     return isa<Instruction>(V) && classof(cast<Instruction>(V));
563   }
564 };
565
566 template <>
567 struct OperandTraits<BinaryOperator> :
568   public FixedNumOperandTraits<BinaryOperator, 2> {
569 };
570
571 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
572
573 //===----------------------------------------------------------------------===//
574 //                               CastInst Class
575 //===----------------------------------------------------------------------===//
576
577 /// This is the base class for all instructions that perform data
578 /// casts. It is simply provided so that instruction category testing
579 /// can be performed with code like:
580 ///
581 /// if (isa<CastInst>(Instr)) { ... }
582 /// @brief Base class of casting instructions.
583 class CastInst : public UnaryInstruction {
584   void anchor() override;
585 protected:
586   /// @brief Constructor with insert-before-instruction semantics for subclasses
587   CastInst(Type *Ty, unsigned iType, Value *S,
588            const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
589     : UnaryInstruction(Ty, iType, S, InsertBefore) {
590     setName(NameStr);
591   }
592   /// @brief Constructor with insert-at-end-of-block semantics for subclasses
593   CastInst(Type *Ty, unsigned iType, Value *S,
594            const Twine &NameStr, BasicBlock *InsertAtEnd)
595     : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
596     setName(NameStr);
597   }
598 public:
599   /// Provides a way to construct any of the CastInst subclasses using an
600   /// opcode instead of the subclass's constructor. The opcode must be in the
601   /// CastOps category (Instruction::isCast(opcode) returns true). This
602   /// constructor has insert-before-instruction semantics to automatically
603   /// insert the new CastInst before InsertBefore (if it is non-null).
604   /// @brief Construct any of the CastInst subclasses
605   static CastInst *Create(
606     Instruction::CastOps,    ///< The opcode of the cast instruction
607     Value *S,                ///< The value to be casted (operand 0)
608     Type *Ty,          ///< The type to which cast should be made
609     const Twine &Name = "", ///< Name for the instruction
610     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
611   );
612   /// Provides a way to construct any of the CastInst subclasses using an
613   /// opcode instead of the subclass's constructor. The opcode must be in the
614   /// CastOps category. This constructor has insert-at-end-of-block semantics
615   /// to automatically insert the new CastInst at the end of InsertAtEnd (if
616   /// its non-null).
617   /// @brief Construct any of the CastInst subclasses
618   static CastInst *Create(
619     Instruction::CastOps,    ///< The opcode for the cast instruction
620     Value *S,                ///< The value to be casted (operand 0)
621     Type *Ty,          ///< The type to which operand is casted
622     const Twine &Name, ///< The name for the instruction
623     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
624   );
625
626   /// @brief Create a ZExt or BitCast cast instruction
627   static CastInst *CreateZExtOrBitCast(
628     Value *S,                ///< The value to be casted (operand 0)
629     Type *Ty,          ///< The type to which cast should be made
630     const Twine &Name = "", ///< Name for the instruction
631     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
632   );
633
634   /// @brief Create a ZExt or BitCast cast instruction
635   static CastInst *CreateZExtOrBitCast(
636     Value *S,                ///< The value to be casted (operand 0)
637     Type *Ty,          ///< The type to which operand is casted
638     const Twine &Name, ///< The name for the instruction
639     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
640   );
641
642   /// @brief Create a SExt or BitCast cast instruction
643   static CastInst *CreateSExtOrBitCast(
644     Value *S,                ///< The value to be casted (operand 0)
645     Type *Ty,          ///< The type to which cast should be made
646     const Twine &Name = "", ///< Name for the instruction
647     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
648   );
649
650   /// @brief Create a SExt or BitCast cast instruction
651   static CastInst *CreateSExtOrBitCast(
652     Value *S,                ///< The value to be casted (operand 0)
653     Type *Ty,          ///< The type to which operand is casted
654     const Twine &Name, ///< The name for the instruction
655     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
656   );
657
658   /// @brief Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
659   static CastInst *CreatePointerCast(
660     Value *S,                ///< The pointer value to be casted (operand 0)
661     Type *Ty,          ///< The type to which operand is casted
662     const Twine &Name, ///< The name for the instruction
663     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
664   );
665
666   /// @brief Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
667   static CastInst *CreatePointerCast(
668     Value *S,                ///< The pointer value to be casted (operand 0)
669     Type *Ty,          ///< The type to which cast should be made
670     const Twine &Name = "", ///< Name for the instruction
671     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
672   );
673
674   /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
675   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
676     Value *S,                ///< The pointer value to be casted (operand 0)
677     Type *Ty,          ///< The type to which operand is casted
678     const Twine &Name, ///< The name for the instruction
679     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
680   );
681
682   /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
683   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
684     Value *S,                ///< The pointer value to be casted (operand 0)
685     Type *Ty,          ///< The type to which cast should be made
686     const Twine &Name = "", ///< Name for the instruction
687     Instruction *InsertBefore = 0 ///< Place to insert the instruction
688   );
689
690   /// @brief Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
691   ///
692   /// If the value is a pointer type and the destination an integer type,
693   /// creates a PtrToInt cast. If the value is an integer type and the
694   /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
695   /// a bitcast.
696   static CastInst *CreateBitOrPointerCast(
697     Value *S,                ///< The pointer value to be casted (operand 0)
698     Type *Ty,          ///< The type to which cast should be made
699     const Twine &Name = "", ///< Name for the instruction
700     Instruction *InsertBefore = 0 ///< Place to insert the instruction
701   );
702
703   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
704   static CastInst *CreateIntegerCast(
705     Value *S,                ///< The pointer value to be casted (operand 0)
706     Type *Ty,          ///< The type to which cast should be made
707     bool isSigned,           ///< Whether to regard S as signed or not
708     const Twine &Name = "", ///< Name for the instruction
709     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
710   );
711
712   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
713   static CastInst *CreateIntegerCast(
714     Value *S,                ///< The integer value to be casted (operand 0)
715     Type *Ty,          ///< The integer type to which operand is casted
716     bool isSigned,           ///< Whether to regard S as signed or not
717     const Twine &Name, ///< The name for the instruction
718     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
719   );
720
721   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
722   static CastInst *CreateFPCast(
723     Value *S,                ///< The floating point value to be casted
724     Type *Ty,          ///< The floating point type to cast to
725     const Twine &Name = "", ///< Name for the instruction
726     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
727   );
728
729   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
730   static CastInst *CreateFPCast(
731     Value *S,                ///< The floating point value to be casted
732     Type *Ty,          ///< The floating point type to cast to
733     const Twine &Name, ///< The name for the instruction
734     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
735   );
736
737   /// @brief Create a Trunc or BitCast cast instruction
738   static CastInst *CreateTruncOrBitCast(
739     Value *S,                ///< The value to be casted (operand 0)
740     Type *Ty,          ///< The type to which cast should be made
741     const Twine &Name = "", ///< Name for the instruction
742     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
743   );
744
745   /// @brief Create a Trunc or BitCast cast instruction
746   static CastInst *CreateTruncOrBitCast(
747     Value *S,                ///< The value to be casted (operand 0)
748     Type *Ty,          ///< The type to which operand is casted
749     const Twine &Name, ///< The name for the instruction
750     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
751   );
752
753   /// @brief Check whether it is valid to call getCastOpcode for these types.
754   static bool isCastable(
755     Type *SrcTy, ///< The Type from which the value should be cast.
756     Type *DestTy ///< The Type to which the value should be cast.
757   );
758
759   /// @brief Check whether a bitcast between these types is valid
760   static bool isBitCastable(
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, inttoptr, or ptrtoint cast between these
766   /// types is valid and a no-op.
767   ///
768   /// This ensures that any pointer<->integer cast has enough bits in the
769   /// integer and any other cast is a bitcast.
770   static bool isBitOrNoopPointerCastable(
771       Type *SrcTy,  ///< The Type from which the value should be cast.
772       Type *DestTy, ///< The Type to which the value should be cast.
773       const DataLayout &DL);
774
775   /// Returns the opcode necessary to cast Val into Ty using usual casting
776   /// rules.
777   /// @brief Infer the opcode for cast operand and type
778   static Instruction::CastOps getCastOpcode(
779     const Value *Val, ///< The value to cast
780     bool SrcIsSigned, ///< Whether to treat the source as signed
781     Type *Ty,   ///< The Type to which the value should be casted
782     bool DstIsSigned  ///< Whether to treate the dest. as signed
783   );
784
785   /// There are several places where we need to know if a cast instruction
786   /// only deals with integer source and destination types. To simplify that
787   /// logic, this method is provided.
788   /// @returns true iff the cast has only integral typed operand and dest type.
789   /// @brief Determine if this is an integer-only cast.
790   bool isIntegerCast() const;
791
792   /// A lossless cast is one that does not alter the basic value. It implies
793   /// a no-op cast but is more stringent, preventing things like int->float,
794   /// long->double, or int->ptr.
795   /// @returns true iff the cast is lossless.
796   /// @brief Determine if this is a lossless cast.
797   bool isLosslessCast() const;
798
799   /// A no-op cast is one that can be effected without changing any bits.
800   /// It implies that the source and destination types are the same size. The
801   /// IntPtrTy argument is used to make accurate determinations for casts
802   /// involving Integer and Pointer types. They are no-op casts if the integer
803   /// is the same size as the pointer. However, pointer size varies with
804   /// platform. Generally, the result of DataLayout::getIntPtrType() should be
805   /// passed in. If that's not available, use Type::Int64Ty, which will make
806   /// the isNoopCast call conservative.
807   /// @brief Determine if the described cast is a no-op cast.
808   static bool isNoopCast(
809     Instruction::CastOps Opcode,  ///< Opcode of cast
810     Type *SrcTy,   ///< SrcTy of cast
811     Type *DstTy,   ///< DstTy of cast
812     Type *IntPtrTy ///< Integer type corresponding to Ptr types
813   );
814
815   /// @brief Determine if this cast is a no-op cast.
816   bool isNoopCast(
817     Type *IntPtrTy ///< Integer type corresponding to pointer
818   ) const;
819
820   /// @brief Determine if this cast is a no-op cast.
821   ///
822   /// \param DL is the DataLayout to get the Int Ptr type from.
823   bool isNoopCast(const DataLayout &DL) const;
824
825   /// Determine how a pair of casts can be eliminated, if they can be at all.
826   /// This is a helper function for both CastInst and ConstantExpr.
827   /// @returns 0 if the CastInst pair can't be eliminated, otherwise
828   /// returns Instruction::CastOps value for a cast that can replace
829   /// the pair, casting SrcTy to DstTy.
830   /// @brief Determine if a cast pair is eliminable
831   static unsigned isEliminableCastPair(
832     Instruction::CastOps firstOpcode,  ///< Opcode of first cast
833     Instruction::CastOps secondOpcode, ///< Opcode of second cast
834     Type *SrcTy, ///< SrcTy of 1st cast
835     Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
836     Type *DstTy, ///< DstTy of 2nd cast
837     Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
838     Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
839     Type *DstIntPtrTy  ///< Integer type corresponding to Ptr DstTy, or null
840   );
841
842   /// @brief Return the opcode of this CastInst
843   Instruction::CastOps getOpcode() const {
844     return Instruction::CastOps(Instruction::getOpcode());
845   }
846
847   /// @brief Return the source type, as a convenience
848   Type* getSrcTy() const { return getOperand(0)->getType(); }
849   /// @brief Return the destination type, as a convenience
850   Type* getDestTy() const { return getType(); }
851
852   /// This method can be used to determine if a cast from S to DstTy using
853   /// Opcode op is valid or not.
854   /// @returns true iff the proposed cast is valid.
855   /// @brief Determine if a cast is valid without creating one.
856   static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
857
858   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
859   static inline bool classof(const Instruction *I) {
860     return I->isCast();
861   }
862   static inline bool classof(const Value *V) {
863     return isa<Instruction>(V) && classof(cast<Instruction>(V));
864   }
865 };
866
867 //===----------------------------------------------------------------------===//
868 //                               CmpInst Class
869 //===----------------------------------------------------------------------===//
870
871 /// This class is the base class for the comparison instructions.
872 /// @brief Abstract base class of comparison instructions.
873 class CmpInst : public Instruction {
874   void *operator new(size_t, unsigned) = delete;
875   CmpInst() = delete;
876 protected:
877   CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
878           Value *LHS, Value *RHS, const Twine &Name = "",
879           Instruction *InsertBefore = nullptr);
880
881   CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
882           Value *LHS, Value *RHS, const Twine &Name,
883           BasicBlock *InsertAtEnd);
884
885   void anchor() override; // Out of line virtual method.
886 public:
887   /// This enumeration lists the possible predicates for CmpInst subclasses.
888   /// Values in the range 0-31 are reserved for FCmpInst, while values in the
889   /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
890   /// predicate values are not overlapping between the classes.
891   enum Predicate {
892     // Opcode              U L G E    Intuitive operation
893     FCMP_FALSE =  0,  ///< 0 0 0 0    Always false (always folded)
894     FCMP_OEQ   =  1,  ///< 0 0 0 1    True if ordered and equal
895     FCMP_OGT   =  2,  ///< 0 0 1 0    True if ordered and greater than
896     FCMP_OGE   =  3,  ///< 0 0 1 1    True if ordered and greater than or equal
897     FCMP_OLT   =  4,  ///< 0 1 0 0    True if ordered and less than
898     FCMP_OLE   =  5,  ///< 0 1 0 1    True if ordered and less than or equal
899     FCMP_ONE   =  6,  ///< 0 1 1 0    True if ordered and operands are unequal
900     FCMP_ORD   =  7,  ///< 0 1 1 1    True if ordered (no nans)
901     FCMP_UNO   =  8,  ///< 1 0 0 0    True if unordered: isnan(X) | isnan(Y)
902     FCMP_UEQ   =  9,  ///< 1 0 0 1    True if unordered or equal
903     FCMP_UGT   = 10,  ///< 1 0 1 0    True if unordered or greater than
904     FCMP_UGE   = 11,  ///< 1 0 1 1    True if unordered, greater than, or equal
905     FCMP_ULT   = 12,  ///< 1 1 0 0    True if unordered or less than
906     FCMP_ULE   = 13,  ///< 1 1 0 1    True if unordered, less than, or equal
907     FCMP_UNE   = 14,  ///< 1 1 1 0    True if unordered or not equal
908     FCMP_TRUE  = 15,  ///< 1 1 1 1    Always true (always folded)
909     FIRST_FCMP_PREDICATE = FCMP_FALSE,
910     LAST_FCMP_PREDICATE = FCMP_TRUE,
911     BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
912     ICMP_EQ    = 32,  ///< equal
913     ICMP_NE    = 33,  ///< not equal
914     ICMP_UGT   = 34,  ///< unsigned greater than
915     ICMP_UGE   = 35,  ///< unsigned greater or equal
916     ICMP_ULT   = 36,  ///< unsigned less than
917     ICMP_ULE   = 37,  ///< unsigned less or equal
918     ICMP_SGT   = 38,  ///< signed greater than
919     ICMP_SGE   = 39,  ///< signed greater or equal
920     ICMP_SLT   = 40,  ///< signed less than
921     ICMP_SLE   = 41,  ///< signed less or equal
922     FIRST_ICMP_PREDICATE = ICMP_EQ,
923     LAST_ICMP_PREDICATE = ICMP_SLE,
924     BAD_ICMP_PREDICATE = ICMP_SLE + 1
925   };
926
927   // allocate space for exactly two operands
928   void *operator new(size_t s) {
929     return User::operator new(s, 2);
930   }
931   /// Construct a compare instruction, given the opcode, the predicate and
932   /// the two operands.  Optionally (if InstBefore is specified) insert the
933   /// instruction into a BasicBlock right before the specified instruction.
934   /// The specified Instruction is allowed to be a dereferenced end iterator.
935   /// @brief Create a CmpInst
936   static CmpInst *Create(OtherOps Op,
937                          unsigned short predicate, Value *S1,
938                          Value *S2, const Twine &Name = "",
939                          Instruction *InsertBefore = nullptr);
940
941   /// Construct a compare instruction, given the opcode, the predicate and the
942   /// two operands.  Also automatically insert this instruction to the end of
943   /// the BasicBlock specified.
944   /// @brief Create a CmpInst
945   static CmpInst *Create(OtherOps Op, unsigned short predicate, Value *S1,
946                          Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
947
948   /// @brief Get the opcode casted to the right type
949   OtherOps getOpcode() const {
950     return static_cast<OtherOps>(Instruction::getOpcode());
951   }
952
953   /// @brief Return the predicate for this instruction.
954   Predicate getPredicate() const {
955     return Predicate(getSubclassDataFromInstruction());
956   }
957
958   /// @brief Set the predicate for this instruction to the specified value.
959   void setPredicate(Predicate P) { setInstructionSubclassData(P); }
960
961   static bool isFPPredicate(Predicate P) {
962     return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
963   }
964
965   static bool isIntPredicate(Predicate P) {
966     return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
967   }
968
969   bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
970   bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
971
972
973   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
974   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
975   /// @returns the inverse predicate for the instruction's current predicate.
976   /// @brief Return the inverse of the instruction's predicate.
977   Predicate getInversePredicate() const {
978     return getInversePredicate(getPredicate());
979   }
980
981   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
982   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
983   /// @returns the inverse predicate for predicate provided in \p pred.
984   /// @brief Return the inverse of a given predicate
985   static Predicate getInversePredicate(Predicate pred);
986
987   /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
988   ///              OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
989   /// @returns the predicate that would be the result of exchanging the two
990   /// operands of the CmpInst instruction without changing the result
991   /// produced.
992   /// @brief Return the predicate as if the operands were swapped
993   Predicate getSwappedPredicate() const {
994     return getSwappedPredicate(getPredicate());
995   }
996
997   /// This is a static version that you can use without an instruction
998   /// available.
999   /// @brief Return the predicate as if the operands were swapped.
1000   static Predicate getSwappedPredicate(Predicate pred);
1001
1002   /// @brief Provide more efficient getOperand methods.
1003   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1004
1005   /// This is just a convenience that dispatches to the subclasses.
1006   /// @brief Swap the operands and adjust predicate accordingly to retain
1007   /// the same comparison.
1008   void swapOperands();
1009
1010   /// This is just a convenience that dispatches to the subclasses.
1011   /// @brief Determine if this CmpInst is commutative.
1012   bool isCommutative() const;
1013
1014   /// This is just a convenience that dispatches to the subclasses.
1015   /// @brief Determine if this is an equals/not equals predicate.
1016   bool isEquality() const;
1017
1018   /// @returns true if the comparison is signed, false otherwise.
1019   /// @brief Determine if this instruction is using a signed comparison.
1020   bool isSigned() const {
1021     return isSigned(getPredicate());
1022   }
1023
1024   /// @returns true if the comparison is unsigned, false otherwise.
1025   /// @brief Determine if this instruction is using an unsigned comparison.
1026   bool isUnsigned() const {
1027     return isUnsigned(getPredicate());
1028   }
1029
1030   /// This is just a convenience.
1031   /// @brief Determine if this is true when both operands are the same.
1032   bool isTrueWhenEqual() const {
1033     return isTrueWhenEqual(getPredicate());
1034   }
1035
1036   /// This is just a convenience.
1037   /// @brief Determine if this is false when both operands are the same.
1038   bool isFalseWhenEqual() const {
1039     return isFalseWhenEqual(getPredicate());
1040   }
1041
1042   /// @returns true if the predicate is unsigned, false otherwise.
1043   /// @brief Determine if the predicate is an unsigned operation.
1044   static bool isUnsigned(unsigned short predicate);
1045
1046   /// @returns true if the predicate is signed, false otherwise.
1047   /// @brief Determine if the predicate is an signed operation.
1048   static bool isSigned(unsigned short predicate);
1049
1050   /// @brief Determine if the predicate is an ordered operation.
1051   static bool isOrdered(unsigned short predicate);
1052
1053   /// @brief Determine if the predicate is an unordered operation.
1054   static bool isUnordered(unsigned short predicate);
1055
1056   /// Determine if the predicate is true when comparing a value with itself.
1057   static bool isTrueWhenEqual(unsigned short predicate);
1058
1059   /// Determine if the predicate is false when comparing a value with itself.
1060   static bool isFalseWhenEqual(unsigned short predicate);
1061
1062   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1063   static inline bool classof(const Instruction *I) {
1064     return I->getOpcode() == Instruction::ICmp ||
1065            I->getOpcode() == Instruction::FCmp;
1066   }
1067   static inline bool classof(const Value *V) {
1068     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1069   }
1070
1071   /// @brief Create a result type for fcmp/icmp
1072   static Type* makeCmpResultType(Type* opnd_type) {
1073     if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1074       return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1075                              vt->getNumElements());
1076     }
1077     return Type::getInt1Ty(opnd_type->getContext());
1078   }
1079 private:
1080   // Shadow Value::setValueSubclassData with a private forwarding method so that
1081   // subclasses cannot accidentally use it.
1082   void setValueSubclassData(unsigned short D) {
1083     Value::setValueSubclassData(D);
1084   }
1085 };
1086
1087
1088 // FIXME: these are redundant if CmpInst < BinaryOperator
1089 template <>
1090 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1091 };
1092
1093 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1094
1095 } // End llvm namespace
1096
1097 #endif