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