Reformat blank lines.
[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
55 public:
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 //                          UnaryInstruction Class
276 //===----------------------------------------------------------------------===//
277
278 class UnaryInstruction : public Instruction {
279   void *operator new(size_t, unsigned) = delete;
280
281 protected:
282   UnaryInstruction(Type *Ty, unsigned iType, Value *V,
283                    Instruction *IB = nullptr)
284     : Instruction(Ty, iType, &Op<0>(), 1, IB) {
285     Op<0>() = V;
286   }
287   UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
288     : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
289     Op<0>() = V;
290   }
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
331 protected:
332   void init(BinaryOps iType);
333   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
334                  const Twine &Name, Instruction *InsertBefore);
335   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
336                  const Twine &Name, BasicBlock *InsertAtEnd);
337
338   // Note: Instruction needs to be a friend here to call cloneImpl.
339   friend class Instruction;
340   BinaryOperator *cloneImpl() const;
341
342 public:
343   // allocate space for exactly two operands
344   void *operator new(size_t s) {
345     return User::operator new(s, 2);
346   }
347
348   /// Transparently provide more efficient getOperand methods.
349   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
350
351   /// Construct a binary instruction, given the opcode and the two
352   /// operands.  Optionally (if InstBefore is specified) insert the instruction
353   /// into a BasicBlock right before the specified instruction.  The specified
354   /// Instruction is allowed to be a dereferenced end iterator.
355   ///
356   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
357                                 const Twine &Name = Twine(),
358                                 Instruction *InsertBefore = nullptr);
359
360   /// Construct a binary instruction, given the opcode and the two
361   /// operands.  Also automatically insert this instruction to the end of the
362   /// BasicBlock specified.
363   ///
364   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
365                                 const Twine &Name, BasicBlock *InsertAtEnd);
366
367   /// These methods just forward to Create, and are useful when you
368   /// statically know what type of instruction you're going to create.  These
369   /// helpers just save some typing.
370 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
371   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
372                                      const Twine &Name = "") {\
373     return Create(Instruction::OPC, V1, V2, Name);\
374   }
375 #include "llvm/IR/Instruction.def"
376 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
377   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
378                                      const Twine &Name, BasicBlock *BB) {\
379     return Create(Instruction::OPC, V1, V2, Name, BB);\
380   }
381 #include "llvm/IR/Instruction.def"
382 #define HANDLE_BINARY_INST(N, OPC, CLASS) \
383   static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
384                                      const Twine &Name, Instruction *I) {\
385     return Create(Instruction::OPC, V1, V2, Name, I);\
386   }
387 #include "llvm/IR/Instruction.def"
388
389   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
390                                    const Twine &Name = "") {
391     BinaryOperator *BO = Create(Opc, V1, V2, Name);
392     BO->setHasNoSignedWrap(true);
393     return BO;
394   }
395   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
396                                    const Twine &Name, BasicBlock *BB) {
397     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
398     BO->setHasNoSignedWrap(true);
399     return BO;
400   }
401   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
402                                    const Twine &Name, Instruction *I) {
403     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
404     BO->setHasNoSignedWrap(true);
405     return BO;
406   }
407
408   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
409                                    const Twine &Name = "") {
410     BinaryOperator *BO = Create(Opc, V1, V2, Name);
411     BO->setHasNoUnsignedWrap(true);
412     return BO;
413   }
414   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
415                                    const Twine &Name, BasicBlock *BB) {
416     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
417     BO->setHasNoUnsignedWrap(true);
418     return BO;
419   }
420   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
421                                    const Twine &Name, Instruction *I) {
422     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
423     BO->setHasNoUnsignedWrap(true);
424     return BO;
425   }
426
427   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
428                                      const Twine &Name = "") {
429     BinaryOperator *BO = Create(Opc, V1, V2, Name);
430     BO->setIsExact(true);
431     return BO;
432   }
433   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
434                                      const Twine &Name, BasicBlock *BB) {
435     BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
436     BO->setIsExact(true);
437     return BO;
438   }
439   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
440                                      const Twine &Name, Instruction *I) {
441     BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
442     BO->setIsExact(true);
443     return BO;
444   }
445
446 #define DEFINE_HELPERS(OPC, NUWNSWEXACT)                                       \
447   static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2,        \
448                                                   const Twine &Name = "") {    \
449     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name);                \
450   }                                                                            \
451   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
452       Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) {               \
453     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB);            \
454   }                                                                            \
455   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
456       Value *V1, Value *V2, const Twine &Name, Instruction *I) {               \
457     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I);             \
458   }
459
460   DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
461   DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
462   DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
463   DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
464   DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
465   DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
466   DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
467   DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
468
469   DEFINE_HELPERS(SDiv, Exact)  // CreateExactSDiv
470   DEFINE_HELPERS(UDiv, Exact)  // CreateExactUDiv
471   DEFINE_HELPERS(AShr, Exact)  // CreateExactAShr
472   DEFINE_HELPERS(LShr, Exact)  // CreateExactLShr
473
474 #undef DEFINE_HELPERS
475
476   /// Helper functions to construct and inspect unary operations (NEG and NOT)
477   /// via binary operators SUB and XOR:
478   ///
479   /// Create the NEG and NOT instructions out of SUB and XOR instructions.
480   ///
481   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
482                                    Instruction *InsertBefore = nullptr);
483   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
484                                    BasicBlock *InsertAtEnd);
485   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
486                                       Instruction *InsertBefore = nullptr);
487   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
488                                       BasicBlock *InsertAtEnd);
489   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
490                                       Instruction *InsertBefore = nullptr);
491   static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
492                                       BasicBlock *InsertAtEnd);
493   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
494                                     Instruction *InsertBefore = nullptr);
495   static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
496                                     BasicBlock *InsertAtEnd);
497   static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
498                                    Instruction *InsertBefore = nullptr);
499   static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
500                                    BasicBlock *InsertAtEnd);
501
502   /// Check if the given Value is a NEG, FNeg, or NOT instruction.
503   ///
504   static bool isNeg(const Value *V);
505   static bool isFNeg(const Value *V, bool IgnoreZeroSign=false);
506   static bool isNot(const Value *V);
507
508   /// Helper functions to extract the unary argument of a NEG, FNEG or NOT
509   /// operation implemented via Sub, FSub, or Xor.
510   ///
511   static const Value *getNegArgument(const Value *BinOp);
512   static       Value *getNegArgument(      Value *BinOp);
513   static const Value *getFNegArgument(const Value *BinOp);
514   static       Value *getFNegArgument(      Value *BinOp);
515   static const Value *getNotArgument(const Value *BinOp);
516   static       Value *getNotArgument(      Value *BinOp);
517
518   BinaryOps getOpcode() const {
519     return static_cast<BinaryOps>(Instruction::getOpcode());
520   }
521
522   /// Exchange the two operands to this instruction.
523   /// This instruction is safe to use on any binary instruction and
524   /// does not modify the semantics of the instruction.  If the instruction
525   /// cannot be reversed (ie, it's a Div), then return true.
526   ///
527   bool swapOperands();
528
529   /// Set or clear the nsw flag on this instruction, which must be an operator
530   /// which supports this flag. See LangRef.html for the meaning of this flag.
531   void setHasNoUnsignedWrap(bool b = true);
532
533   /// Set or clear the nsw flag on this instruction, which must be an operator
534   /// which supports this flag. See LangRef.html for the meaning of this flag.
535   void setHasNoSignedWrap(bool b = true);
536
537   /// Set or clear the exact flag on this instruction, which must be an operator
538   /// which supports this flag. See LangRef.html for the meaning of this flag.
539   void setIsExact(bool b = true);
540
541   /// Determine whether the no unsigned wrap flag is set.
542   bool hasNoUnsignedWrap() const;
543
544   /// Determine whether the no signed wrap flag is set.
545   bool hasNoSignedWrap() const;
546
547   /// Determine whether the exact flag is set.
548   bool isExact() const;
549
550   /// Convenience method to copy supported wrapping, exact, and fast-math flags
551   /// from V to this instruction.
552   void copyIRFlags(const Value *V);
553
554   /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
555   /// V and this instruction.
556   void andIRFlags(const Value *V);
557
558   // Methods for support type inquiry through isa, cast, and dyn_cast:
559   static inline bool classof(const Instruction *I) {
560     return I->isBinaryOp();
561   }
562   static inline bool classof(const Value *V) {
563     return isa<Instruction>(V) && classof(cast<Instruction>(V));
564   }
565 };
566
567 template <>
568 struct OperandTraits<BinaryOperator> :
569   public FixedNumOperandTraits<BinaryOperator, 2> {
570 };
571
572 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
573
574 //===----------------------------------------------------------------------===//
575 //                               CastInst Class
576 //===----------------------------------------------------------------------===//
577
578 /// This is the base class for all instructions that perform data
579 /// casts. It is simply provided so that instruction category testing
580 /// can be performed with code like:
581 ///
582 /// if (isa<CastInst>(Instr)) { ... }
583 /// @brief Base class of casting instructions.
584 class CastInst : public UnaryInstruction {
585   void anchor() override;
586
587 protected:
588   /// @brief Constructor with insert-before-instruction semantics for subclasses
589   CastInst(Type *Ty, unsigned iType, Value *S,
590            const Twine &NameStr = "", Instruction *InsertBefore = nullptr)
591     : UnaryInstruction(Ty, iType, S, InsertBefore) {
592     setName(NameStr);
593   }
594   /// @brief Constructor with insert-at-end-of-block semantics for subclasses
595   CastInst(Type *Ty, unsigned iType, Value *S,
596            const Twine &NameStr, BasicBlock *InsertAtEnd)
597     : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
598     setName(NameStr);
599   }
600
601 public:
602   /// Provides a way to construct any of the CastInst subclasses using an
603   /// opcode instead of the subclass's constructor. The opcode must be in the
604   /// CastOps category (Instruction::isCast(opcode) returns true). This
605   /// constructor has insert-before-instruction semantics to automatically
606   /// insert the new CastInst before InsertBefore (if it is non-null).
607   /// @brief Construct any of the CastInst subclasses
608   static CastInst *Create(
609     Instruction::CastOps,    ///< The opcode of the cast instruction
610     Value *S,                ///< The value to be casted (operand 0)
611     Type *Ty,          ///< The type to which cast should be made
612     const Twine &Name = "", ///< Name for the instruction
613     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
614   );
615   /// Provides a way to construct any of the CastInst subclasses using an
616   /// opcode instead of the subclass's constructor. The opcode must be in the
617   /// CastOps category. This constructor has insert-at-end-of-block semantics
618   /// to automatically insert the new CastInst at the end of InsertAtEnd (if
619   /// its non-null).
620   /// @brief Construct any of the CastInst subclasses
621   static CastInst *Create(
622     Instruction::CastOps,    ///< The opcode for the cast instruction
623     Value *S,                ///< The value to be casted (operand 0)
624     Type *Ty,          ///< The type to which operand is casted
625     const Twine &Name, ///< The name for the instruction
626     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
627   );
628
629   /// @brief Create a ZExt or BitCast cast instruction
630   static CastInst *CreateZExtOrBitCast(
631     Value *S,                ///< The value to be casted (operand 0)
632     Type *Ty,          ///< The type to which cast should be made
633     const Twine &Name = "", ///< Name for the instruction
634     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
635   );
636
637   /// @brief Create a ZExt or BitCast cast instruction
638   static CastInst *CreateZExtOrBitCast(
639     Value *S,                ///< The value to be casted (operand 0)
640     Type *Ty,          ///< The type to which operand is casted
641     const Twine &Name, ///< The name for the instruction
642     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
643   );
644
645   /// @brief Create a SExt or BitCast cast instruction
646   static CastInst *CreateSExtOrBitCast(
647     Value *S,                ///< The value to be casted (operand 0)
648     Type *Ty,          ///< The type to which cast should be made
649     const Twine &Name = "", ///< Name for the instruction
650     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
651   );
652
653   /// @brief Create a SExt or BitCast cast instruction
654   static CastInst *CreateSExtOrBitCast(
655     Value *S,                ///< The value to be casted (operand 0)
656     Type *Ty,          ///< The type to which operand is casted
657     const Twine &Name, ///< The name for the instruction
658     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
659   );
660
661   /// @brief Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
662   static CastInst *CreatePointerCast(
663     Value *S,                ///< The pointer value to be casted (operand 0)
664     Type *Ty,          ///< The type to which operand is casted
665     const Twine &Name, ///< The name for the instruction
666     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
667   );
668
669   /// @brief Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
670   static CastInst *CreatePointerCast(
671     Value *S,                ///< The pointer value to be casted (operand 0)
672     Type *Ty,          ///< The type to which cast should be made
673     const Twine &Name = "", ///< Name for the instruction
674     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
675   );
676
677   /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
678   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
679     Value *S,                ///< The pointer value to be casted (operand 0)
680     Type *Ty,          ///< The type to which operand is casted
681     const Twine &Name, ///< The name for the instruction
682     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
683   );
684
685   /// @brief Create a BitCast or an AddrSpaceCast cast instruction.
686   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
687     Value *S,                ///< The pointer value to be casted (operand 0)
688     Type *Ty,          ///< The type to which cast should be made
689     const Twine &Name = "", ///< Name for the instruction
690     Instruction *InsertBefore = 0 ///< Place to insert the instruction
691   );
692
693   /// @brief Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
694   ///
695   /// If the value is a pointer type and the destination an integer type,
696   /// creates a PtrToInt cast. If the value is an integer type and the
697   /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
698   /// a bitcast.
699   static CastInst *CreateBitOrPointerCast(
700     Value *S,                ///< The pointer value to be casted (operand 0)
701     Type *Ty,          ///< The type to which cast should be made
702     const Twine &Name = "", ///< Name for the instruction
703     Instruction *InsertBefore = 0 ///< Place to insert the instruction
704   );
705
706   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
707   static CastInst *CreateIntegerCast(
708     Value *S,                ///< The pointer value to be casted (operand 0)
709     Type *Ty,          ///< The type to which cast should be made
710     bool isSigned,           ///< Whether to regard S as signed or not
711     const Twine &Name = "", ///< Name for the instruction
712     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
713   );
714
715   /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
716   static CastInst *CreateIntegerCast(
717     Value *S,                ///< The integer value to be casted (operand 0)
718     Type *Ty,          ///< The integer type to which operand is casted
719     bool isSigned,           ///< Whether to regard S as signed or not
720     const Twine &Name, ///< The name for the instruction
721     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
722   );
723
724   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
725   static CastInst *CreateFPCast(
726     Value *S,                ///< The floating point value to be casted
727     Type *Ty,          ///< The floating point type to cast to
728     const Twine &Name = "", ///< Name for the instruction
729     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
730   );
731
732   /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
733   static CastInst *CreateFPCast(
734     Value *S,                ///< The floating point value to be casted
735     Type *Ty,          ///< The floating point type to cast to
736     const Twine &Name, ///< The name for the instruction
737     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
738   );
739
740   /// @brief Create a Trunc or BitCast cast instruction
741   static CastInst *CreateTruncOrBitCast(
742     Value *S,                ///< The value to be casted (operand 0)
743     Type *Ty,          ///< The type to which cast should be made
744     const Twine &Name = "", ///< Name for the instruction
745     Instruction *InsertBefore = nullptr ///< Place to insert the instruction
746   );
747
748   /// @brief Create a Trunc or BitCast cast instruction
749   static CastInst *CreateTruncOrBitCast(
750     Value *S,                ///< The value to be casted (operand 0)
751     Type *Ty,          ///< The type to which operand is casted
752     const Twine &Name, ///< The name for the instruction
753     BasicBlock *InsertAtEnd  ///< The block to insert the instruction into
754   );
755
756   /// @brief Check whether it is valid to call getCastOpcode for these types.
757   static bool isCastable(
758     Type *SrcTy, ///< The Type from which the value should be cast.
759     Type *DestTy ///< The Type to which the value should be cast.
760   );
761
762   /// @brief Check whether a bitcast between these types is valid
763   static bool isBitCastable(
764     Type *SrcTy, ///< The Type from which the value should be cast.
765     Type *DestTy ///< The Type to which the value should be cast.
766   );
767
768   /// @brief Check whether a bitcast, inttoptr, or ptrtoint cast between these
769   /// types is valid and a no-op.
770   ///
771   /// This ensures that any pointer<->integer cast has enough bits in the
772   /// integer and any other cast is a bitcast.
773   static bool isBitOrNoopPointerCastable(
774       Type *SrcTy,  ///< The Type from which the value should be cast.
775       Type *DestTy, ///< The Type to which the value should be cast.
776       const DataLayout &DL);
777
778   /// Returns the opcode necessary to cast Val into Ty using usual casting
779   /// rules.
780   /// @brief Infer the opcode for cast operand and type
781   static Instruction::CastOps getCastOpcode(
782     const Value *Val, ///< The value to cast
783     bool SrcIsSigned, ///< Whether to treat the source as signed
784     Type *Ty,   ///< The Type to which the value should be casted
785     bool DstIsSigned  ///< Whether to treate the dest. as signed
786   );
787
788   /// There are several places where we need to know if a cast instruction
789   /// only deals with integer source and destination types. To simplify that
790   /// logic, this method is provided.
791   /// @returns true iff the cast has only integral typed operand and dest type.
792   /// @brief Determine if this is an integer-only cast.
793   bool isIntegerCast() const;
794
795   /// A lossless cast is one that does not alter the basic value. It implies
796   /// a no-op cast but is more stringent, preventing things like int->float,
797   /// long->double, or int->ptr.
798   /// @returns true iff the cast is lossless.
799   /// @brief Determine if this is a lossless cast.
800   bool isLosslessCast() const;
801
802   /// A no-op cast is one that can be effected without changing any bits.
803   /// It implies that the source and destination types are the same size. The
804   /// IntPtrTy argument is used to make accurate determinations for casts
805   /// involving Integer and Pointer types. They are no-op casts if the integer
806   /// is the same size as the pointer. However, pointer size varies with
807   /// platform. Generally, the result of DataLayout::getIntPtrType() should be
808   /// passed in. If that's not available, use Type::Int64Ty, which will make
809   /// the isNoopCast call conservative.
810   /// @brief Determine if the described cast is a no-op cast.
811   static bool isNoopCast(
812     Instruction::CastOps Opcode,  ///< Opcode of cast
813     Type *SrcTy,   ///< SrcTy of cast
814     Type *DstTy,   ///< DstTy of cast
815     Type *IntPtrTy ///< Integer type corresponding to Ptr types
816   );
817
818   /// @brief Determine if this cast is a no-op cast.
819   bool isNoopCast(
820     Type *IntPtrTy ///< Integer type corresponding to pointer
821   ) const;
822
823   /// @brief Determine if this cast is a no-op cast.
824   ///
825   /// \param DL is the DataLayout to get the Int Ptr type from.
826   bool isNoopCast(const DataLayout &DL) const;
827
828   /// Determine how a pair of casts can be eliminated, if they can be at all.
829   /// This is a helper function for both CastInst and ConstantExpr.
830   /// @returns 0 if the CastInst pair can't be eliminated, otherwise
831   /// returns Instruction::CastOps value for a cast that can replace
832   /// the pair, casting SrcTy to DstTy.
833   /// @brief Determine if a cast pair is eliminable
834   static unsigned isEliminableCastPair(
835     Instruction::CastOps firstOpcode,  ///< Opcode of first cast
836     Instruction::CastOps secondOpcode, ///< Opcode of second cast
837     Type *SrcTy, ///< SrcTy of 1st cast
838     Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
839     Type *DstTy, ///< DstTy of 2nd cast
840     Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
841     Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
842     Type *DstIntPtrTy  ///< Integer type corresponding to Ptr DstTy, or null
843   );
844
845   /// @brief Return the opcode of this CastInst
846   Instruction::CastOps getOpcode() const {
847     return Instruction::CastOps(Instruction::getOpcode());
848   }
849
850   /// @brief Return the source type, as a convenience
851   Type* getSrcTy() const { return getOperand(0)->getType(); }
852   /// @brief Return the destination type, as a convenience
853   Type* getDestTy() const { return getType(); }
854
855   /// This method can be used to determine if a cast from S to DstTy using
856   /// Opcode op is valid or not.
857   /// @returns true iff the proposed cast is valid.
858   /// @brief Determine if a cast is valid without creating one.
859   static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
860
861   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
862   static inline bool classof(const Instruction *I) {
863     return I->isCast();
864   }
865   static inline bool classof(const Value *V) {
866     return isa<Instruction>(V) && classof(cast<Instruction>(V));
867   }
868 };
869
870 //===----------------------------------------------------------------------===//
871 //                               CmpInst Class
872 //===----------------------------------------------------------------------===//
873
874 /// This class is the base class for the comparison instructions.
875 /// @brief Abstract base class of comparison instructions.
876 class CmpInst : public Instruction {
877   void *operator new(size_t, unsigned) = delete;
878   CmpInst() = delete;
879
880 protected:
881   CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
882           Value *LHS, Value *RHS, const Twine &Name = "",
883           Instruction *InsertBefore = nullptr);
884
885   CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
886           Value *LHS, Value *RHS, const Twine &Name,
887           BasicBlock *InsertAtEnd);
888
889   void anchor() override; // Out of line virtual method.
890
891 public:
892   /// This enumeration lists the possible predicates for CmpInst subclasses.
893   /// Values in the range 0-31 are reserved for FCmpInst, while values in the
894   /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
895   /// predicate values are not overlapping between the classes.
896   enum Predicate {
897     // Opcode              U L G E    Intuitive operation
898     FCMP_FALSE =  0,  ///< 0 0 0 0    Always false (always folded)
899     FCMP_OEQ   =  1,  ///< 0 0 0 1    True if ordered and equal
900     FCMP_OGT   =  2,  ///< 0 0 1 0    True if ordered and greater than
901     FCMP_OGE   =  3,  ///< 0 0 1 1    True if ordered and greater than or equal
902     FCMP_OLT   =  4,  ///< 0 1 0 0    True if ordered and less than
903     FCMP_OLE   =  5,  ///< 0 1 0 1    True if ordered and less than or equal
904     FCMP_ONE   =  6,  ///< 0 1 1 0    True if ordered and operands are unequal
905     FCMP_ORD   =  7,  ///< 0 1 1 1    True if ordered (no nans)
906     FCMP_UNO   =  8,  ///< 1 0 0 0    True if unordered: isnan(X) | isnan(Y)
907     FCMP_UEQ   =  9,  ///< 1 0 0 1    True if unordered or equal
908     FCMP_UGT   = 10,  ///< 1 0 1 0    True if unordered or greater than
909     FCMP_UGE   = 11,  ///< 1 0 1 1    True if unordered, greater than, or equal
910     FCMP_ULT   = 12,  ///< 1 1 0 0    True if unordered or less than
911     FCMP_ULE   = 13,  ///< 1 1 0 1    True if unordered, less than, or equal
912     FCMP_UNE   = 14,  ///< 1 1 1 0    True if unordered or not equal
913     FCMP_TRUE  = 15,  ///< 1 1 1 1    Always true (always folded)
914     FIRST_FCMP_PREDICATE = FCMP_FALSE,
915     LAST_FCMP_PREDICATE = FCMP_TRUE,
916     BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
917     ICMP_EQ    = 32,  ///< equal
918     ICMP_NE    = 33,  ///< not equal
919     ICMP_UGT   = 34,  ///< unsigned greater than
920     ICMP_UGE   = 35,  ///< unsigned greater or equal
921     ICMP_ULT   = 36,  ///< unsigned less than
922     ICMP_ULE   = 37,  ///< unsigned less or equal
923     ICMP_SGT   = 38,  ///< signed greater than
924     ICMP_SGE   = 39,  ///< signed greater or equal
925     ICMP_SLT   = 40,  ///< signed less than
926     ICMP_SLE   = 41,  ///< signed less or equal
927     FIRST_ICMP_PREDICATE = ICMP_EQ,
928     LAST_ICMP_PREDICATE = ICMP_SLE,
929     BAD_ICMP_PREDICATE = ICMP_SLE + 1
930   };
931
932   // allocate space for exactly two operands
933   void *operator new(size_t s) {
934     return User::operator new(s, 2);
935   }
936   /// Construct a compare instruction, given the opcode, the predicate and
937   /// the two operands.  Optionally (if InstBefore is specified) insert the
938   /// instruction into a BasicBlock right before the specified instruction.
939   /// The specified Instruction is allowed to be a dereferenced end iterator.
940   /// @brief Create a CmpInst
941   static CmpInst *Create(OtherOps Op,
942                          unsigned short predicate, Value *S1,
943                          Value *S2, const Twine &Name = "",
944                          Instruction *InsertBefore = nullptr);
945
946   /// Construct a compare instruction, given the opcode, the predicate and the
947   /// two operands.  Also automatically insert this instruction to the end of
948   /// the BasicBlock specified.
949   /// @brief Create a CmpInst
950   static CmpInst *Create(OtherOps Op, unsigned short predicate, Value *S1,
951                          Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
952
953   /// @brief Get the opcode casted to the right type
954   OtherOps getOpcode() const {
955     return static_cast<OtherOps>(Instruction::getOpcode());
956   }
957
958   /// @brief Return the predicate for this instruction.
959   Predicate getPredicate() const {
960     return Predicate(getSubclassDataFromInstruction());
961   }
962
963   /// @brief Set the predicate for this instruction to the specified value.
964   void setPredicate(Predicate P) { setInstructionSubclassData(P); }
965
966   static bool isFPPredicate(Predicate P) {
967     return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
968   }
969
970   static bool isIntPredicate(Predicate P) {
971     return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
972   }
973
974   bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
975   bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
976
977   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
978   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
979   /// @returns the inverse predicate for the instruction's current predicate.
980   /// @brief Return the inverse of the instruction's predicate.
981   Predicate getInversePredicate() const {
982     return getInversePredicate(getPredicate());
983   }
984
985   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
986   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
987   /// @returns the inverse predicate for predicate provided in \p pred.
988   /// @brief Return the inverse of a given predicate
989   static Predicate getInversePredicate(Predicate pred);
990
991   /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
992   ///              OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
993   /// @returns the predicate that would be the result of exchanging the two
994   /// operands of the CmpInst instruction without changing the result
995   /// produced.
996   /// @brief Return the predicate as if the operands were swapped
997   Predicate getSwappedPredicate() const {
998     return getSwappedPredicate(getPredicate());
999   }
1000
1001   /// This is a static version that you can use without an instruction
1002   /// available.
1003   /// @brief Return the predicate as if the operands were swapped.
1004   static Predicate getSwappedPredicate(Predicate pred);
1005
1006   /// @brief Provide more efficient getOperand methods.
1007   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1008
1009   /// This is just a convenience that dispatches to the subclasses.
1010   /// @brief Swap the operands and adjust predicate accordingly to retain
1011   /// the same comparison.
1012   void swapOperands();
1013
1014   /// This is just a convenience that dispatches to the subclasses.
1015   /// @brief Determine if this CmpInst is commutative.
1016   bool isCommutative() const;
1017
1018   /// This is just a convenience that dispatches to the subclasses.
1019   /// @brief Determine if this is an equals/not equals predicate.
1020   bool isEquality() const;
1021
1022   /// @returns true if the comparison is signed, false otherwise.
1023   /// @brief Determine if this instruction is using a signed comparison.
1024   bool isSigned() const {
1025     return isSigned(getPredicate());
1026   }
1027
1028   /// @returns true if the comparison is unsigned, false otherwise.
1029   /// @brief Determine if this instruction is using an unsigned comparison.
1030   bool isUnsigned() const {
1031     return isUnsigned(getPredicate());
1032   }
1033
1034   /// This is just a convenience.
1035   /// @brief Determine if this is true when both operands are the same.
1036   bool isTrueWhenEqual() const {
1037     return isTrueWhenEqual(getPredicate());
1038   }
1039
1040   /// This is just a convenience.
1041   /// @brief Determine if this is false when both operands are the same.
1042   bool isFalseWhenEqual() const {
1043     return isFalseWhenEqual(getPredicate());
1044   }
1045
1046   /// @returns true if the predicate is unsigned, false otherwise.
1047   /// @brief Determine if the predicate is an unsigned operation.
1048   static bool isUnsigned(unsigned short predicate);
1049
1050   /// @returns true if the predicate is signed, false otherwise.
1051   /// @brief Determine if the predicate is an signed operation.
1052   static bool isSigned(unsigned short predicate);
1053
1054   /// @brief Determine if the predicate is an ordered operation.
1055   static bool isOrdered(unsigned short predicate);
1056
1057   /// @brief Determine if the predicate is an unordered operation.
1058   static bool isUnordered(unsigned short predicate);
1059
1060   /// Determine if the predicate is true when comparing a value with itself.
1061   static bool isTrueWhenEqual(unsigned short predicate);
1062
1063   /// Determine if the predicate is false when comparing a value with itself.
1064   static bool isFalseWhenEqual(unsigned short predicate);
1065
1066   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1067   static inline bool classof(const Instruction *I) {
1068     return I->getOpcode() == Instruction::ICmp ||
1069            I->getOpcode() == Instruction::FCmp;
1070   }
1071   static inline bool classof(const Value *V) {
1072     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1073   }
1074
1075   /// @brief Create a result type for fcmp/icmp
1076   static Type* makeCmpResultType(Type* opnd_type) {
1077     if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
1078       return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
1079                              vt->getNumElements());
1080     }
1081     return Type::getInt1Ty(opnd_type->getContext());
1082   }
1083
1084 private:
1085   // Shadow Value::setValueSubclassData with a private forwarding method so that
1086   // subclasses cannot accidentally use it.
1087   void setValueSubclassData(unsigned short D) {
1088     Value::setValueSubclassData(D);
1089   }
1090 };
1091
1092 // FIXME: these are redundant if CmpInst < BinaryOperator
1093 template <>
1094 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
1095 };
1096
1097 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1098
1099 } // End llvm namespace
1100
1101 #endif