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