[NFC] Fix typo in comment.
[oota-llvm.git] / include / llvm / IR / Instructions.h
1 //===-- llvm/Instructions.h - Instruction subclass definitions --*- 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 exposes the class definitions of all of the subclasses of the
11 // Instruction class.  This is meant to be an easy way to get access to all
12 // instruction subclasses.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_INSTRUCTIONS_H
17 #define LLVM_IR_INSTRUCTIONS_H
18
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/CallingConv.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/InstrTypes.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <iterator>
28
29 namespace llvm {
30
31 class APInt;
32 class ConstantInt;
33 class ConstantRange;
34 class DataLayout;
35 class LLVMContext;
36
37 enum AtomicOrdering {
38   NotAtomic = 0,
39   Unordered = 1,
40   Monotonic = 2,
41   // Consume = 3,  // Not specified yet.
42   Acquire = 4,
43   Release = 5,
44   AcquireRelease = 6,
45   SequentiallyConsistent = 7
46 };
47
48 enum SynchronizationScope {
49   SingleThread = 0,
50   CrossThread = 1
51 };
52
53 /// Returns true if the ordering is at least as strong as acquire
54 /// (i.e. acquire, acq_rel or seq_cst)
55 inline bool isAtLeastAcquire(AtomicOrdering Ord) {
56    return (Ord == Acquire ||
57     Ord == AcquireRelease ||
58     Ord == SequentiallyConsistent);
59 }
60
61 /// Returns true if the ordering is at least as strong as release
62 /// (i.e. release, acq_rel or seq_cst)
63 inline bool isAtLeastRelease(AtomicOrdering Ord) {
64 return (Ord == Release ||
65     Ord == AcquireRelease ||
66     Ord == SequentiallyConsistent);
67 }
68
69 //===----------------------------------------------------------------------===//
70 //                                AllocaInst Class
71 //===----------------------------------------------------------------------===//
72
73 /// AllocaInst - an instruction to allocate memory on the stack
74 ///
75 class AllocaInst : public UnaryInstruction {
76 protected:
77   AllocaInst *clone_impl() const override;
78 public:
79   explicit AllocaInst(Type *Ty, Value *ArraySize = nullptr,
80                       const Twine &Name = "",
81                       Instruction *InsertBefore = nullptr);
82   AllocaInst(Type *Ty, Value *ArraySize,
83              const Twine &Name, BasicBlock *InsertAtEnd);
84
85   AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore = nullptr);
86   AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd);
87
88   AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
89              const Twine &Name = "", Instruction *InsertBefore = nullptr);
90   AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
91              const Twine &Name, BasicBlock *InsertAtEnd);
92
93   // Out of line virtual method, so the vtable, etc. has a home.
94   virtual ~AllocaInst();
95
96   /// isArrayAllocation - Return true if there is an allocation size parameter
97   /// to the allocation instruction that is not 1.
98   ///
99   bool isArrayAllocation() const;
100
101   /// getArraySize - Get the number of elements allocated. For a simple
102   /// allocation of a single element, this will return a constant 1 value.
103   ///
104   const Value *getArraySize() const { return getOperand(0); }
105   Value *getArraySize() { return getOperand(0); }
106
107   /// getType - Overload to return most specific pointer type
108   ///
109   PointerType *getType() const {
110     return cast<PointerType>(Instruction::getType());
111   }
112
113   /// getAllocatedType - Return the type that is being allocated by the
114   /// instruction.
115   ///
116   Type *getAllocatedType() const;
117
118   /// getAlignment - Return the alignment of the memory that is being allocated
119   /// by the instruction.
120   ///
121   unsigned getAlignment() const {
122     return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
123   }
124   void setAlignment(unsigned Align);
125
126   /// isStaticAlloca - Return true if this alloca is in the entry block of the
127   /// function and is a constant size.  If so, the code generator will fold it
128   /// into the prolog/epilog code, so it is basically free.
129   bool isStaticAlloca() const;
130
131   /// \brief Return true if this alloca is used as an inalloca argument to a
132   /// call.  Such allocas are never considered static even if they are in the
133   /// entry block.
134   bool isUsedWithInAlloca() const {
135     return getSubclassDataFromInstruction() & 32;
136   }
137
138   /// \brief Specify whether this alloca is used to represent the arguments to
139   /// a call.
140   void setUsedWithInAlloca(bool V) {
141     setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
142                                (V ? 32 : 0));
143   }
144
145   // Methods for support type inquiry through isa, cast, and dyn_cast:
146   static inline bool classof(const Instruction *I) {
147     return (I->getOpcode() == Instruction::Alloca);
148   }
149   static inline bool classof(const Value *V) {
150     return isa<Instruction>(V) && classof(cast<Instruction>(V));
151   }
152 private:
153   // Shadow Instruction::setInstructionSubclassData with a private forwarding
154   // method so that subclasses cannot accidentally use it.
155   void setInstructionSubclassData(unsigned short D) {
156     Instruction::setInstructionSubclassData(D);
157   }
158 };
159
160
161 //===----------------------------------------------------------------------===//
162 //                                LoadInst Class
163 //===----------------------------------------------------------------------===//
164
165 /// LoadInst - an instruction for reading from memory.  This uses the
166 /// SubclassData field in Value to store whether or not the load is volatile.
167 ///
168 class LoadInst : public UnaryInstruction {
169   void AssertOK();
170 protected:
171   LoadInst *clone_impl() const override;
172 public:
173   LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
174   LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
175   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
176            Instruction *InsertBefore = nullptr);
177   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
178            BasicBlock *InsertAtEnd);
179   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
180            unsigned Align, Instruction *InsertBefore = nullptr);
181   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
182            unsigned Align, BasicBlock *InsertAtEnd);
183   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
184            unsigned Align, AtomicOrdering Order,
185            SynchronizationScope SynchScope = CrossThread,
186            Instruction *InsertBefore = nullptr);
187   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
188            unsigned Align, AtomicOrdering Order,
189            SynchronizationScope SynchScope,
190            BasicBlock *InsertAtEnd);
191
192   LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
193   LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
194   explicit LoadInst(Value *Ptr, const char *NameStr = nullptr,
195                     bool isVolatile = false,
196                     Instruction *InsertBefore = nullptr);
197   LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
198            BasicBlock *InsertAtEnd);
199
200   /// isVolatile - Return true if this is a load from a volatile memory
201   /// location.
202   ///
203   bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
204
205   /// setVolatile - Specify whether this is a volatile load or not.
206   ///
207   void setVolatile(bool V) {
208     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
209                                (V ? 1 : 0));
210   }
211
212   /// getAlignment - Return the alignment of the access that is being performed
213   ///
214   unsigned getAlignment() const {
215     return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
216   }
217
218   void setAlignment(unsigned Align);
219
220   /// Returns the ordering effect of this fence.
221   AtomicOrdering getOrdering() const {
222     return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
223   }
224
225   /// Set the ordering constraint on this load. May not be Release or
226   /// AcquireRelease.
227   void setOrdering(AtomicOrdering Ordering) {
228     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
229                                (Ordering << 7));
230   }
231
232   SynchronizationScope getSynchScope() const {
233     return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
234   }
235
236   /// Specify whether this load is ordered with respect to all
237   /// concurrently executing threads, or only with respect to signal handlers
238   /// executing in the same thread.
239   void setSynchScope(SynchronizationScope xthread) {
240     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
241                                (xthread << 6));
242   }
243
244   void setAtomic(AtomicOrdering Ordering,
245                  SynchronizationScope SynchScope = CrossThread) {
246     setOrdering(Ordering);
247     setSynchScope(SynchScope);
248   }
249
250   bool isSimple() const { return !isAtomic() && !isVolatile(); }
251   bool isUnordered() const {
252     return getOrdering() <= Unordered && !isVolatile();
253   }
254
255   Value *getPointerOperand() { return getOperand(0); }
256   const Value *getPointerOperand() const { return getOperand(0); }
257   static unsigned getPointerOperandIndex() { return 0U; }
258
259   /// \brief Returns the address space of the pointer operand.
260   unsigned getPointerAddressSpace() const {
261     return getPointerOperand()->getType()->getPointerAddressSpace();
262   }
263
264
265   // Methods for support type inquiry through isa, cast, and dyn_cast:
266   static inline bool classof(const Instruction *I) {
267     return I->getOpcode() == Instruction::Load;
268   }
269   static inline bool classof(const Value *V) {
270     return isa<Instruction>(V) && classof(cast<Instruction>(V));
271   }
272 private:
273   // Shadow Instruction::setInstructionSubclassData with a private forwarding
274   // method so that subclasses cannot accidentally use it.
275   void setInstructionSubclassData(unsigned short D) {
276     Instruction::setInstructionSubclassData(D);
277   }
278 };
279
280
281 //===----------------------------------------------------------------------===//
282 //                                StoreInst Class
283 //===----------------------------------------------------------------------===//
284
285 /// StoreInst - an instruction for storing to memory
286 ///
287 class StoreInst : public Instruction {
288   void *operator new(size_t, unsigned) = delete;
289   void AssertOK();
290 protected:
291   StoreInst *clone_impl() const override;
292 public:
293   // allocate space for exactly two operands
294   void *operator new(size_t s) {
295     return User::operator new(s, 2);
296   }
297   StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
298   StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
299   StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
300             Instruction *InsertBefore = nullptr);
301   StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
302   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
303             unsigned Align, Instruction *InsertBefore = nullptr);
304   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
305             unsigned Align, BasicBlock *InsertAtEnd);
306   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
307             unsigned Align, AtomicOrdering Order,
308             SynchronizationScope SynchScope = CrossThread,
309             Instruction *InsertBefore = nullptr);
310   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
311             unsigned Align, AtomicOrdering Order,
312             SynchronizationScope SynchScope,
313             BasicBlock *InsertAtEnd);
314
315
316   /// isVolatile - Return true if this is a store to a volatile memory
317   /// location.
318   ///
319   bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
320
321   /// setVolatile - Specify whether this is a volatile store or not.
322   ///
323   void setVolatile(bool V) {
324     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
325                                (V ? 1 : 0));
326   }
327
328   /// Transparently provide more efficient getOperand methods.
329   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
330
331   /// getAlignment - Return the alignment of the access that is being performed
332   ///
333   unsigned getAlignment() const {
334     return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
335   }
336
337   void setAlignment(unsigned Align);
338
339   /// Returns the ordering effect of this store.
340   AtomicOrdering getOrdering() const {
341     return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
342   }
343
344   /// Set the ordering constraint on this store.  May not be Acquire or
345   /// AcquireRelease.
346   void setOrdering(AtomicOrdering Ordering) {
347     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
348                                (Ordering << 7));
349   }
350
351   SynchronizationScope getSynchScope() const {
352     return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
353   }
354
355   /// Specify whether this store instruction is ordered with respect to all
356   /// concurrently executing threads, or only with respect to signal handlers
357   /// executing in the same thread.
358   void setSynchScope(SynchronizationScope xthread) {
359     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
360                                (xthread << 6));
361   }
362
363   void setAtomic(AtomicOrdering Ordering,
364                  SynchronizationScope SynchScope = CrossThread) {
365     setOrdering(Ordering);
366     setSynchScope(SynchScope);
367   }
368
369   bool isSimple() const { return !isAtomic() && !isVolatile(); }
370   bool isUnordered() const {
371     return getOrdering() <= Unordered && !isVolatile();
372   }
373
374   Value *getValueOperand() { return getOperand(0); }
375   const Value *getValueOperand() const { return getOperand(0); }
376
377   Value *getPointerOperand() { return getOperand(1); }
378   const Value *getPointerOperand() const { return getOperand(1); }
379   static unsigned getPointerOperandIndex() { return 1U; }
380
381   /// \brief Returns the address space of the pointer operand.
382   unsigned getPointerAddressSpace() const {
383     return getPointerOperand()->getType()->getPointerAddressSpace();
384   }
385
386   // Methods for support type inquiry through isa, cast, and dyn_cast:
387   static inline bool classof(const Instruction *I) {
388     return I->getOpcode() == Instruction::Store;
389   }
390   static inline bool classof(const Value *V) {
391     return isa<Instruction>(V) && classof(cast<Instruction>(V));
392   }
393 private:
394   // Shadow Instruction::setInstructionSubclassData with a private forwarding
395   // method so that subclasses cannot accidentally use it.
396   void setInstructionSubclassData(unsigned short D) {
397     Instruction::setInstructionSubclassData(D);
398   }
399 };
400
401 template <>
402 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
403 };
404
405 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
406
407 //===----------------------------------------------------------------------===//
408 //                                FenceInst Class
409 //===----------------------------------------------------------------------===//
410
411 /// FenceInst - an instruction for ordering other memory operations
412 ///
413 class FenceInst : public Instruction {
414   void *operator new(size_t, unsigned) = delete;
415   void Init(AtomicOrdering Ordering, SynchronizationScope SynchScope);
416 protected:
417   FenceInst *clone_impl() const override;
418 public:
419   // allocate space for exactly zero operands
420   void *operator new(size_t s) {
421     return User::operator new(s, 0);
422   }
423
424   // Ordering may only be Acquire, Release, AcquireRelease, or
425   // SequentiallyConsistent.
426   FenceInst(LLVMContext &C, AtomicOrdering Ordering,
427             SynchronizationScope SynchScope = CrossThread,
428             Instruction *InsertBefore = nullptr);
429   FenceInst(LLVMContext &C, AtomicOrdering Ordering,
430             SynchronizationScope SynchScope,
431             BasicBlock *InsertAtEnd);
432
433   /// Returns the ordering effect of this fence.
434   AtomicOrdering getOrdering() const {
435     return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
436   }
437
438   /// Set the ordering constraint on this fence.  May only be Acquire, Release,
439   /// AcquireRelease, or SequentiallyConsistent.
440   void setOrdering(AtomicOrdering Ordering) {
441     setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
442                                (Ordering << 1));
443   }
444
445   SynchronizationScope getSynchScope() const {
446     return SynchronizationScope(getSubclassDataFromInstruction() & 1);
447   }
448
449   /// Specify whether this fence orders other operations with respect to all
450   /// concurrently executing threads, or only with respect to signal handlers
451   /// executing in the same thread.
452   void setSynchScope(SynchronizationScope xthread) {
453     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
454                                xthread);
455   }
456
457   // Methods for support type inquiry through isa, cast, and dyn_cast:
458   static inline bool classof(const Instruction *I) {
459     return I->getOpcode() == Instruction::Fence;
460   }
461   static inline bool classof(const Value *V) {
462     return isa<Instruction>(V) && classof(cast<Instruction>(V));
463   }
464 private:
465   // Shadow Instruction::setInstructionSubclassData with a private forwarding
466   // method so that subclasses cannot accidentally use it.
467   void setInstructionSubclassData(unsigned short D) {
468     Instruction::setInstructionSubclassData(D);
469   }
470 };
471
472 //===----------------------------------------------------------------------===//
473 //                                AtomicCmpXchgInst Class
474 //===----------------------------------------------------------------------===//
475
476 /// AtomicCmpXchgInst - an instruction that atomically checks whether a
477 /// specified value is in a memory location, and, if it is, stores a new value
478 /// there.  Returns the value that was loaded.
479 ///
480 class AtomicCmpXchgInst : public Instruction {
481   void *operator new(size_t, unsigned) = delete;
482   void Init(Value *Ptr, Value *Cmp, Value *NewVal,
483             AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
484             SynchronizationScope SynchScope);
485 protected:
486   AtomicCmpXchgInst *clone_impl() const override;
487 public:
488   // allocate space for exactly three operands
489   void *operator new(size_t s) {
490     return User::operator new(s, 3);
491   }
492   AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
493                     AtomicOrdering SuccessOrdering,
494                     AtomicOrdering FailureOrdering,
495                     SynchronizationScope SynchScope,
496                     Instruction *InsertBefore = nullptr);
497   AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
498                     AtomicOrdering SuccessOrdering,
499                     AtomicOrdering FailureOrdering,
500                     SynchronizationScope SynchScope,
501                     BasicBlock *InsertAtEnd);
502
503   /// isVolatile - Return true if this is a cmpxchg from a volatile memory
504   /// location.
505   ///
506   bool isVolatile() const {
507     return getSubclassDataFromInstruction() & 1;
508   }
509
510   /// setVolatile - Specify whether this is a volatile cmpxchg.
511   ///
512   void setVolatile(bool V) {
513      setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
514                                 (unsigned)V);
515   }
516
517   /// Return true if this cmpxchg may spuriously fail.
518   bool isWeak() const {
519     return getSubclassDataFromInstruction() & 0x100;
520   }
521
522   void setWeak(bool IsWeak) {
523     setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
524                                (IsWeak << 8));
525   }
526
527   /// Transparently provide more efficient getOperand methods.
528   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
529
530   /// Set the ordering constraint on this cmpxchg.
531   void setSuccessOrdering(AtomicOrdering Ordering) {
532     assert(Ordering != NotAtomic &&
533            "CmpXchg instructions can only be atomic.");
534     setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
535                                (Ordering << 2));
536   }
537
538   void setFailureOrdering(AtomicOrdering Ordering) {
539     assert(Ordering != NotAtomic &&
540            "CmpXchg instructions can only be atomic.");
541     setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
542                                (Ordering << 5));
543   }
544
545   /// Specify whether this cmpxchg is atomic and orders other operations with
546   /// respect to all concurrently executing threads, or only with respect to
547   /// signal handlers executing in the same thread.
548   void setSynchScope(SynchronizationScope SynchScope) {
549     setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
550                                (SynchScope << 1));
551   }
552
553   /// Returns the ordering constraint on this cmpxchg.
554   AtomicOrdering getSuccessOrdering() const {
555     return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
556   }
557
558   /// Returns the ordering constraint on this cmpxchg.
559   AtomicOrdering getFailureOrdering() const {
560     return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
561   }
562
563   /// Returns whether this cmpxchg is atomic between threads or only within a
564   /// single thread.
565   SynchronizationScope getSynchScope() const {
566     return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
567   }
568
569   Value *getPointerOperand() { return getOperand(0); }
570   const Value *getPointerOperand() const { return getOperand(0); }
571   static unsigned getPointerOperandIndex() { return 0U; }
572
573   Value *getCompareOperand() { return getOperand(1); }
574   const Value *getCompareOperand() const { return getOperand(1); }
575
576   Value *getNewValOperand() { return getOperand(2); }
577   const Value *getNewValOperand() const { return getOperand(2); }
578
579   /// \brief Returns the address space of the pointer operand.
580   unsigned getPointerAddressSpace() const {
581     return getPointerOperand()->getType()->getPointerAddressSpace();
582   }
583
584   /// \brief Returns the strongest permitted ordering on failure, given the
585   /// desired ordering on success.
586   ///
587   /// If the comparison in a cmpxchg operation fails, there is no atomic store
588   /// so release semantics cannot be provided. So this function drops explicit
589   /// Release requests from the AtomicOrdering. A SequentiallyConsistent
590   /// operation would remain SequentiallyConsistent.
591   static AtomicOrdering
592   getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
593     switch (SuccessOrdering) {
594     default: llvm_unreachable("invalid cmpxchg success ordering");
595     case Release:
596     case Monotonic:
597       return Monotonic;
598     case AcquireRelease:
599     case Acquire:
600       return Acquire;
601     case SequentiallyConsistent:
602       return SequentiallyConsistent;
603     }
604   }
605
606   // Methods for support type inquiry through isa, cast, and dyn_cast:
607   static inline bool classof(const Instruction *I) {
608     return I->getOpcode() == Instruction::AtomicCmpXchg;
609   }
610   static inline bool classof(const Value *V) {
611     return isa<Instruction>(V) && classof(cast<Instruction>(V));
612   }
613 private:
614   // Shadow Instruction::setInstructionSubclassData with a private forwarding
615   // method so that subclasses cannot accidentally use it.
616   void setInstructionSubclassData(unsigned short D) {
617     Instruction::setInstructionSubclassData(D);
618   }
619 };
620
621 template <>
622 struct OperandTraits<AtomicCmpXchgInst> :
623     public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
624 };
625
626 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
627
628 //===----------------------------------------------------------------------===//
629 //                                AtomicRMWInst Class
630 //===----------------------------------------------------------------------===//
631
632 /// AtomicRMWInst - an instruction that atomically reads a memory location,
633 /// combines it with another value, and then stores the result back.  Returns
634 /// the old value.
635 ///
636 class AtomicRMWInst : public Instruction {
637   void *operator new(size_t, unsigned) = delete;
638 protected:
639   AtomicRMWInst *clone_impl() const override;
640 public:
641   /// This enumeration lists the possible modifications atomicrmw can make.  In
642   /// the descriptions, 'p' is the pointer to the instruction's memory location,
643   /// 'old' is the initial value of *p, and 'v' is the other value passed to the
644   /// instruction.  These instructions always return 'old'.
645   enum BinOp {
646     /// *p = v
647     Xchg,
648     /// *p = old + v
649     Add,
650     /// *p = old - v
651     Sub,
652     /// *p = old & v
653     And,
654     /// *p = ~(old & v)
655     Nand,
656     /// *p = old | v
657     Or,
658     /// *p = old ^ v
659     Xor,
660     /// *p = old >signed v ? old : v
661     Max,
662     /// *p = old <signed v ? old : v
663     Min,
664     /// *p = old >unsigned v ? old : v
665     UMax,
666     /// *p = old <unsigned v ? old : v
667     UMin,
668
669     FIRST_BINOP = Xchg,
670     LAST_BINOP = UMin,
671     BAD_BINOP
672   };
673
674   // allocate space for exactly two operands
675   void *operator new(size_t s) {
676     return User::operator new(s, 2);
677   }
678   AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
679                 AtomicOrdering Ordering, SynchronizationScope SynchScope,
680                 Instruction *InsertBefore = nullptr);
681   AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
682                 AtomicOrdering Ordering, SynchronizationScope SynchScope,
683                 BasicBlock *InsertAtEnd);
684
685   BinOp getOperation() const {
686     return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
687   }
688
689   void setOperation(BinOp Operation) {
690     unsigned short SubclassData = getSubclassDataFromInstruction();
691     setInstructionSubclassData((SubclassData & 31) |
692                                (Operation << 5));
693   }
694
695   /// isVolatile - Return true if this is a RMW on a volatile memory location.
696   ///
697   bool isVolatile() const {
698     return getSubclassDataFromInstruction() & 1;
699   }
700
701   /// setVolatile - Specify whether this is a volatile RMW or not.
702   ///
703   void setVolatile(bool V) {
704      setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
705                                 (unsigned)V);
706   }
707
708   /// Transparently provide more efficient getOperand methods.
709   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
710
711   /// Set the ordering constraint on this RMW.
712   void setOrdering(AtomicOrdering Ordering) {
713     assert(Ordering != NotAtomic &&
714            "atomicrmw instructions can only be atomic.");
715     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
716                                (Ordering << 2));
717   }
718
719   /// Specify whether this RMW orders other operations with respect to all
720   /// concurrently executing threads, or only with respect to signal handlers
721   /// executing in the same thread.
722   void setSynchScope(SynchronizationScope SynchScope) {
723     setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
724                                (SynchScope << 1));
725   }
726
727   /// Returns the ordering constraint on this RMW.
728   AtomicOrdering getOrdering() const {
729     return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
730   }
731
732   /// Returns whether this RMW is atomic between threads or only within a
733   /// single thread.
734   SynchronizationScope getSynchScope() const {
735     return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
736   }
737
738   Value *getPointerOperand() { return getOperand(0); }
739   const Value *getPointerOperand() const { return getOperand(0); }
740   static unsigned getPointerOperandIndex() { return 0U; }
741
742   Value *getValOperand() { return getOperand(1); }
743   const Value *getValOperand() const { return getOperand(1); }
744
745   /// \brief Returns the address space of the pointer operand.
746   unsigned getPointerAddressSpace() const {
747     return getPointerOperand()->getType()->getPointerAddressSpace();
748   }
749
750   // Methods for support type inquiry through isa, cast, and dyn_cast:
751   static inline bool classof(const Instruction *I) {
752     return I->getOpcode() == Instruction::AtomicRMW;
753   }
754   static inline bool classof(const Value *V) {
755     return isa<Instruction>(V) && classof(cast<Instruction>(V));
756   }
757 private:
758   void Init(BinOp Operation, Value *Ptr, Value *Val,
759             AtomicOrdering Ordering, SynchronizationScope SynchScope);
760   // Shadow Instruction::setInstructionSubclassData with a private forwarding
761   // method so that subclasses cannot accidentally use it.
762   void setInstructionSubclassData(unsigned short D) {
763     Instruction::setInstructionSubclassData(D);
764   }
765 };
766
767 template <>
768 struct OperandTraits<AtomicRMWInst>
769     : public FixedNumOperandTraits<AtomicRMWInst,2> {
770 };
771
772 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
773
774 //===----------------------------------------------------------------------===//
775 //                             GetElementPtrInst Class
776 //===----------------------------------------------------------------------===//
777
778 // checkGEPType - Simple wrapper function to give a better assertion failure
779 // message on bad indexes for a gep instruction.
780 //
781 inline Type *checkGEPType(Type *Ty) {
782   assert(Ty && "Invalid GetElementPtrInst indices for type!");
783   return Ty;
784 }
785
786 /// GetElementPtrInst - an instruction for type-safe pointer arithmetic to
787 /// access elements of arrays and structs
788 ///
789 class GetElementPtrInst : public Instruction {
790   GetElementPtrInst(const GetElementPtrInst &GEPI);
791   void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
792
793   /// Constructors - Create a getelementptr instruction with a base pointer an
794   /// list of indices. The first ctor can optionally insert before an existing
795   /// instruction, the second appends the new instruction to the specified
796   /// BasicBlock.
797   inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
798                            ArrayRef<Value *> IdxList, unsigned Values,
799                            const Twine &NameStr, Instruction *InsertBefore);
800   inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
801                            ArrayRef<Value *> IdxList, unsigned Values,
802                            const Twine &NameStr, BasicBlock *InsertAtEnd);
803
804 protected:
805   GetElementPtrInst *clone_impl() const override;
806 public:
807   static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
808                                    ArrayRef<Value *> IdxList,
809                                    const Twine &NameStr = "",
810                                    Instruction *InsertBefore = nullptr) {
811     unsigned Values = 1 + unsigned(IdxList.size());
812     return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
813                                           NameStr, InsertBefore);
814   }
815   static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
816                                    ArrayRef<Value *> IdxList,
817                                    const Twine &NameStr,
818                                    BasicBlock *InsertAtEnd) {
819     unsigned Values = 1 + unsigned(IdxList.size());
820     return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
821                                           NameStr, InsertAtEnd);
822   }
823
824   /// Create an "inbounds" getelementptr. See the documentation for the
825   /// "inbounds" flag in LangRef.html for details.
826   static GetElementPtrInst *CreateInBounds(Value *Ptr,
827                                            ArrayRef<Value *> IdxList,
828                                            const Twine &NameStr = "",
829                                            Instruction *InsertBefore = nullptr){
830     return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
831   }
832   static GetElementPtrInst *
833   CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
834                  const Twine &NameStr = "",
835                  Instruction *InsertBefore = nullptr) {
836     GetElementPtrInst *GEP =
837         Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
838     GEP->setIsInBounds(true);
839     return GEP;
840   }
841   static GetElementPtrInst *CreateInBounds(Value *Ptr,
842                                            ArrayRef<Value *> IdxList,
843                                            const Twine &NameStr,
844                                            BasicBlock *InsertAtEnd) {
845     return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
846   }
847   static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
848                                            ArrayRef<Value *> IdxList,
849                                            const Twine &NameStr,
850                                            BasicBlock *InsertAtEnd) {
851     GetElementPtrInst *GEP =
852         Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
853     GEP->setIsInBounds(true);
854     return GEP;
855   }
856
857   /// Transparently provide more efficient getOperand methods.
858   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
859
860   // getType - Overload to return most specific sequential type.
861   SequentialType *getType() const {
862     return cast<SequentialType>(Instruction::getType());
863   }
864
865   Type *getSourceElementType() const {
866     return cast<SequentialType>(getPointerOperandType()->getScalarType())
867         ->getElementType();
868   }
869
870   Type *getResultElementType() const { return getType()->getElementType(); }
871
872   /// \brief Returns the address space of this instruction's pointer type.
873   unsigned getAddressSpace() const {
874     // Note that this is always the same as the pointer operand's address space
875     // and that is cheaper to compute, so cheat here.
876     return getPointerAddressSpace();
877   }
878
879   /// getIndexedType - Returns the type of the element that would be loaded with
880   /// a load instruction with the specified parameters.
881   ///
882   /// Null is returned if the indices are invalid for the specified
883   /// pointer type.
884   ///
885   static Type *getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList);
886   static Type *getIndexedType(Type *Ptr, ArrayRef<Constant *> IdxList);
887   static Type *getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList);
888
889   inline op_iterator       idx_begin()       { return op_begin()+1; }
890   inline const_op_iterator idx_begin() const { return op_begin()+1; }
891   inline op_iterator       idx_end()         { return op_end(); }
892   inline const_op_iterator idx_end()   const { return op_end(); }
893
894   Value *getPointerOperand() {
895     return getOperand(0);
896   }
897   const Value *getPointerOperand() const {
898     return getOperand(0);
899   }
900   static unsigned getPointerOperandIndex() {
901     return 0U;    // get index for modifying correct operand.
902   }
903
904   /// getPointerOperandType - Method to return the pointer operand as a
905   /// PointerType.
906   Type *getPointerOperandType() const {
907     return getPointerOperand()->getType();
908   }
909
910   /// \brief Returns the address space of the pointer operand.
911   unsigned getPointerAddressSpace() const {
912     return getPointerOperandType()->getPointerAddressSpace();
913   }
914
915   /// GetGEPReturnType - Returns the pointer type returned by the GEP
916   /// instruction, which may be a vector of pointers.
917   static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
918     Type *PtrTy = PointerType::get(checkGEPType(
919                                    getIndexedType(Ptr->getType(), IdxList)),
920                                    Ptr->getType()->getPointerAddressSpace());
921     // Vector GEP
922     if (Ptr->getType()->isVectorTy()) {
923       unsigned NumElem = cast<VectorType>(Ptr->getType())->getNumElements();
924       return VectorType::get(PtrTy, NumElem);
925     }
926
927     // Scalar GEP
928     return PtrTy;
929   }
930
931   unsigned getNumIndices() const {  // Note: always non-negative
932     return getNumOperands() - 1;
933   }
934
935   bool hasIndices() const {
936     return getNumOperands() > 1;
937   }
938
939   /// hasAllZeroIndices - Return true if all of the indices of this GEP are
940   /// zeros.  If so, the result pointer and the first operand have the same
941   /// value, just potentially different types.
942   bool hasAllZeroIndices() const;
943
944   /// hasAllConstantIndices - Return true if all of the indices of this GEP are
945   /// constant integers.  If so, the result pointer and the first operand have
946   /// a constant offset between them.
947   bool hasAllConstantIndices() const;
948
949   /// setIsInBounds - Set or clear the inbounds flag on this GEP instruction.
950   /// See LangRef.html for the meaning of inbounds on a getelementptr.
951   void setIsInBounds(bool b = true);
952
953   /// isInBounds - Determine whether the GEP has the inbounds flag.
954   bool isInBounds() const;
955
956   /// \brief Accumulate the constant address offset of this GEP if possible.
957   ///
958   /// This routine accepts an APInt into which it will accumulate the constant
959   /// offset of this GEP if the GEP is in fact constant. If the GEP is not
960   /// all-constant, it returns false and the value of the offset APInt is
961   /// undefined (it is *not* preserved!). The APInt passed into this routine
962   /// must be at least as wide as the IntPtr type for the address space of
963   /// the base GEP pointer.
964   bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
965
966   // Methods for support type inquiry through isa, cast, and dyn_cast:
967   static inline bool classof(const Instruction *I) {
968     return (I->getOpcode() == Instruction::GetElementPtr);
969   }
970   static inline bool classof(const Value *V) {
971     return isa<Instruction>(V) && classof(cast<Instruction>(V));
972   }
973 };
974
975 template <>
976 struct OperandTraits<GetElementPtrInst> :
977   public VariadicOperandTraits<GetElementPtrInst, 1> {
978 };
979
980 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
981                                      ArrayRef<Value *> IdxList, unsigned Values,
982                                      const Twine &NameStr,
983                                      Instruction *InsertBefore)
984     : Instruction(getGEPReturnType(Ptr, IdxList), GetElementPtr,
985                   OperandTraits<GetElementPtrInst>::op_end(this) - Values,
986                   Values, InsertBefore) {
987   init(Ptr, IdxList, NameStr);
988   assert(!PointeeType || PointeeType == getSourceElementType());
989 }
990 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
991                                      ArrayRef<Value *> IdxList, unsigned Values,
992                                      const Twine &NameStr,
993                                      BasicBlock *InsertAtEnd)
994     : Instruction(getGEPReturnType(Ptr, IdxList), GetElementPtr,
995                   OperandTraits<GetElementPtrInst>::op_end(this) - Values,
996                   Values, InsertAtEnd) {
997   init(Ptr, IdxList, NameStr);
998   assert(!PointeeType || PointeeType == getSourceElementType());
999 }
1000
1001
1002 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1003
1004
1005 //===----------------------------------------------------------------------===//
1006 //                               ICmpInst Class
1007 //===----------------------------------------------------------------------===//
1008
1009 /// This instruction compares its operands according to the predicate given
1010 /// to the constructor. It only operates on integers or pointers. The operands
1011 /// must be identical types.
1012 /// \brief Represent an integer comparison operator.
1013 class ICmpInst: public CmpInst {
1014   void AssertOK() {
1015     assert(getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1016            getPredicate() <= CmpInst::LAST_ICMP_PREDICATE &&
1017            "Invalid ICmp predicate value");
1018     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1019           "Both operands to ICmp instruction are not of the same type!");
1020     // Check that the operands are the right type
1021     assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1022             getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1023            "Invalid operand types for ICmp instruction");
1024   }
1025
1026 protected:
1027   /// \brief Clone an identical ICmpInst
1028   ICmpInst *clone_impl() const override;
1029 public:
1030   /// \brief Constructor with insert-before-instruction semantics.
1031   ICmpInst(
1032     Instruction *InsertBefore,  ///< Where to insert
1033     Predicate pred,  ///< The predicate to use for the comparison
1034     Value *LHS,      ///< The left-hand-side of the expression
1035     Value *RHS,      ///< The right-hand-side of the expression
1036     const Twine &NameStr = ""  ///< Name of the instruction
1037   ) : CmpInst(makeCmpResultType(LHS->getType()),
1038               Instruction::ICmp, pred, LHS, RHS, NameStr,
1039               InsertBefore) {
1040 #ifndef NDEBUG
1041   AssertOK();
1042 #endif
1043   }
1044
1045   /// \brief Constructor with insert-at-end semantics.
1046   ICmpInst(
1047     BasicBlock &InsertAtEnd, ///< Block to insert into.
1048     Predicate pred,  ///< The predicate to use for the comparison
1049     Value *LHS,      ///< The left-hand-side of the expression
1050     Value *RHS,      ///< The right-hand-side of the expression
1051     const Twine &NameStr = ""  ///< Name of the instruction
1052   ) : CmpInst(makeCmpResultType(LHS->getType()),
1053               Instruction::ICmp, pred, LHS, RHS, NameStr,
1054               &InsertAtEnd) {
1055 #ifndef NDEBUG
1056   AssertOK();
1057 #endif
1058   }
1059
1060   /// \brief Constructor with no-insertion semantics
1061   ICmpInst(
1062     Predicate pred, ///< The predicate to use for the comparison
1063     Value *LHS,     ///< The left-hand-side of the expression
1064     Value *RHS,     ///< The right-hand-side of the expression
1065     const Twine &NameStr = "" ///< Name of the instruction
1066   ) : CmpInst(makeCmpResultType(LHS->getType()),
1067               Instruction::ICmp, pred, LHS, RHS, NameStr) {
1068 #ifndef NDEBUG
1069   AssertOK();
1070 #endif
1071   }
1072
1073   /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1074   /// @returns the predicate that would be the result if the operand were
1075   /// regarded as signed.
1076   /// \brief Return the signed version of the predicate
1077   Predicate getSignedPredicate() const {
1078     return getSignedPredicate(getPredicate());
1079   }
1080
1081   /// This is a static version that you can use without an instruction.
1082   /// \brief Return the signed version of the predicate.
1083   static Predicate getSignedPredicate(Predicate pred);
1084
1085   /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1086   /// @returns the predicate that would be the result if the operand were
1087   /// regarded as unsigned.
1088   /// \brief Return the unsigned version of the predicate
1089   Predicate getUnsignedPredicate() const {
1090     return getUnsignedPredicate(getPredicate());
1091   }
1092
1093   /// This is a static version that you can use without an instruction.
1094   /// \brief Return the unsigned version of the predicate.
1095   static Predicate getUnsignedPredicate(Predicate pred);
1096
1097   /// isEquality - Return true if this predicate is either EQ or NE.  This also
1098   /// tests for commutativity.
1099   static bool isEquality(Predicate P) {
1100     return P == ICMP_EQ || P == ICMP_NE;
1101   }
1102
1103   /// isEquality - Return true if this predicate is either EQ or NE.  This also
1104   /// tests for commutativity.
1105   bool isEquality() const {
1106     return isEquality(getPredicate());
1107   }
1108
1109   /// @returns true if the predicate of this ICmpInst is commutative
1110   /// \brief Determine if this relation is commutative.
1111   bool isCommutative() const { return isEquality(); }
1112
1113   /// isRelational - Return true if the predicate is relational (not EQ or NE).
1114   ///
1115   bool isRelational() const {
1116     return !isEquality();
1117   }
1118
1119   /// isRelational - Return true if the predicate is relational (not EQ or NE).
1120   ///
1121   static bool isRelational(Predicate P) {
1122     return !isEquality(P);
1123   }
1124
1125   /// Initialize a set of values that all satisfy the predicate with C.
1126   /// \brief Make a ConstantRange for a relation with a constant value.
1127   static ConstantRange makeConstantRange(Predicate pred, const APInt &C);
1128
1129   /// Exchange the two operands to this instruction in such a way that it does
1130   /// not modify the semantics of the instruction. The predicate value may be
1131   /// changed to retain the same result if the predicate is order dependent
1132   /// (e.g. ult).
1133   /// \brief Swap operands and adjust predicate.
1134   void swapOperands() {
1135     setPredicate(getSwappedPredicate());
1136     Op<0>().swap(Op<1>());
1137   }
1138
1139   // Methods for support type inquiry through isa, cast, and dyn_cast:
1140   static inline bool classof(const Instruction *I) {
1141     return I->getOpcode() == Instruction::ICmp;
1142   }
1143   static inline bool classof(const Value *V) {
1144     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1145   }
1146
1147 };
1148
1149 //===----------------------------------------------------------------------===//
1150 //                               FCmpInst Class
1151 //===----------------------------------------------------------------------===//
1152
1153 /// This instruction compares its operands according to the predicate given
1154 /// to the constructor. It only operates on floating point values or packed
1155 /// vectors of floating point values. The operands must be identical types.
1156 /// \brief Represents a floating point comparison operator.
1157 class FCmpInst: public CmpInst {
1158 protected:
1159   /// \brief Clone an identical FCmpInst
1160   FCmpInst *clone_impl() const override;
1161 public:
1162   /// \brief Constructor with insert-before-instruction semantics.
1163   FCmpInst(
1164     Instruction *InsertBefore, ///< Where to insert
1165     Predicate pred,  ///< The predicate to use for the comparison
1166     Value *LHS,      ///< The left-hand-side of the expression
1167     Value *RHS,      ///< The right-hand-side of the expression
1168     const Twine &NameStr = ""  ///< Name of the instruction
1169   ) : CmpInst(makeCmpResultType(LHS->getType()),
1170               Instruction::FCmp, pred, LHS, RHS, NameStr,
1171               InsertBefore) {
1172     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1173            "Invalid FCmp predicate value");
1174     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1175            "Both operands to FCmp instruction are not of the same type!");
1176     // Check that the operands are the right type
1177     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1178            "Invalid operand types for FCmp instruction");
1179   }
1180
1181   /// \brief Constructor with insert-at-end semantics.
1182   FCmpInst(
1183     BasicBlock &InsertAtEnd, ///< Block to insert into.
1184     Predicate pred,  ///< The predicate to use for the comparison
1185     Value *LHS,      ///< The left-hand-side of the expression
1186     Value *RHS,      ///< The right-hand-side of the expression
1187     const Twine &NameStr = ""  ///< Name of the instruction
1188   ) : CmpInst(makeCmpResultType(LHS->getType()),
1189               Instruction::FCmp, pred, LHS, RHS, NameStr,
1190               &InsertAtEnd) {
1191     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1192            "Invalid FCmp predicate value");
1193     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1194            "Both operands to FCmp instruction are not of the same type!");
1195     // Check that the operands are the right type
1196     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1197            "Invalid operand types for FCmp instruction");
1198   }
1199
1200   /// \brief Constructor with no-insertion semantics
1201   FCmpInst(
1202     Predicate pred, ///< The predicate to use for the comparison
1203     Value *LHS,     ///< The left-hand-side of the expression
1204     Value *RHS,     ///< The right-hand-side of the expression
1205     const Twine &NameStr = "" ///< Name of the instruction
1206   ) : CmpInst(makeCmpResultType(LHS->getType()),
1207               Instruction::FCmp, pred, LHS, RHS, NameStr) {
1208     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1209            "Invalid FCmp predicate value");
1210     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1211            "Both operands to FCmp instruction are not of the same type!");
1212     // Check that the operands are the right type
1213     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1214            "Invalid operand types for FCmp instruction");
1215   }
1216
1217   /// @returns true if the predicate of this instruction is EQ or NE.
1218   /// \brief Determine if this is an equality predicate.
1219   static bool isEquality(Predicate Pred) {
1220     return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1221            Pred == FCMP_UNE;
1222   }
1223
1224   /// @returns true if the predicate of this instruction is EQ or NE.
1225   /// \brief Determine if this is an equality predicate.
1226   bool isEquality() const { return isEquality(getPredicate()); }
1227
1228   /// @returns true if the predicate of this instruction is commutative.
1229   /// \brief Determine if this is a commutative predicate.
1230   bool isCommutative() const {
1231     return isEquality() ||
1232            getPredicate() == FCMP_FALSE ||
1233            getPredicate() == FCMP_TRUE ||
1234            getPredicate() == FCMP_ORD ||
1235            getPredicate() == FCMP_UNO;
1236   }
1237
1238   /// @returns true if the predicate is relational (not EQ or NE).
1239   /// \brief Determine if this a relational predicate.
1240   bool isRelational() const { return !isEquality(); }
1241
1242   /// Exchange the two operands to this instruction in such a way that it does
1243   /// not modify the semantics of the instruction. The predicate value may be
1244   /// changed to retain the same result if the predicate is order dependent
1245   /// (e.g. ult).
1246   /// \brief Swap operands and adjust predicate.
1247   void swapOperands() {
1248     setPredicate(getSwappedPredicate());
1249     Op<0>().swap(Op<1>());
1250   }
1251
1252   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
1253   static inline bool classof(const Instruction *I) {
1254     return I->getOpcode() == Instruction::FCmp;
1255   }
1256   static inline bool classof(const Value *V) {
1257     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1258   }
1259 };
1260
1261 //===----------------------------------------------------------------------===//
1262 /// CallInst - This class represents a function call, abstracting a target
1263 /// machine's calling convention.  This class uses low bit of the SubClassData
1264 /// field to indicate whether or not this is a tail call.  The rest of the bits
1265 /// hold the calling convention of the call.
1266 ///
1267 class CallInst : public Instruction {
1268   AttributeSet AttributeList; ///< parameter attributes for call
1269   CallInst(const CallInst &CI);
1270   void init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr);
1271   void init(Value *Func, const Twine &NameStr);
1272
1273   /// Construct a CallInst given a range of arguments.
1274   /// \brief Construct a CallInst from a range of arguments
1275   inline CallInst(Value *Func, ArrayRef<Value *> Args,
1276                   const Twine &NameStr, Instruction *InsertBefore);
1277
1278   /// Construct a CallInst given a range of arguments.
1279   /// \brief Construct a CallInst from a range of arguments
1280   inline CallInst(Value *Func, ArrayRef<Value *> Args,
1281                   const Twine &NameStr, BasicBlock *InsertAtEnd);
1282
1283   explicit CallInst(Value *F, const Twine &NameStr,
1284                     Instruction *InsertBefore);
1285   CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1286 protected:
1287   CallInst *clone_impl() const override;
1288 public:
1289   static CallInst *Create(Value *Func,
1290                           ArrayRef<Value *> Args,
1291                           const Twine &NameStr = "",
1292                           Instruction *InsertBefore = nullptr) {
1293     return new(unsigned(Args.size() + 1))
1294       CallInst(Func, Args, NameStr, InsertBefore);
1295   }
1296   static CallInst *Create(Value *Func,
1297                           ArrayRef<Value *> Args,
1298                           const Twine &NameStr, BasicBlock *InsertAtEnd) {
1299     return new(unsigned(Args.size() + 1))
1300       CallInst(Func, Args, NameStr, InsertAtEnd);
1301   }
1302   static CallInst *Create(Value *F, const Twine &NameStr = "",
1303                           Instruction *InsertBefore = nullptr) {
1304     return new(1) CallInst(F, NameStr, InsertBefore);
1305   }
1306   static CallInst *Create(Value *F, const Twine &NameStr,
1307                           BasicBlock *InsertAtEnd) {
1308     return new(1) CallInst(F, NameStr, InsertAtEnd);
1309   }
1310   /// CreateMalloc - Generate the IR for a call to malloc:
1311   /// 1. Compute the malloc call's argument as the specified type's size,
1312   ///    possibly multiplied by the array size if the array size is not
1313   ///    constant 1.
1314   /// 2. Call malloc with that argument.
1315   /// 3. Bitcast the result of the malloc call to the specified type.
1316   static Instruction *CreateMalloc(Instruction *InsertBefore,
1317                                    Type *IntPtrTy, Type *AllocTy,
1318                                    Value *AllocSize, Value *ArraySize = nullptr,
1319                                    Function* MallocF = nullptr,
1320                                    const Twine &Name = "");
1321   static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1322                                    Type *IntPtrTy, Type *AllocTy,
1323                                    Value *AllocSize, Value *ArraySize = nullptr,
1324                                    Function* MallocF = nullptr,
1325                                    const Twine &Name = "");
1326   /// CreateFree - Generate the IR for a call to the builtin free function.
1327   static Instruction* CreateFree(Value* Source, Instruction *InsertBefore);
1328   static Instruction* CreateFree(Value* Source, BasicBlock *InsertAtEnd);
1329
1330   ~CallInst();
1331
1332   // Note that 'musttail' implies 'tail'.
1333   enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2 };
1334   TailCallKind getTailCallKind() const {
1335     return TailCallKind(getSubclassDataFromInstruction() & 3);
1336   }
1337   bool isTailCall() const {
1338     return (getSubclassDataFromInstruction() & 3) != TCK_None;
1339   }
1340   bool isMustTailCall() const {
1341     return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1342   }
1343   void setTailCall(bool isTC = true) {
1344     setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1345                                unsigned(isTC ? TCK_Tail : TCK_None));
1346   }
1347   void setTailCallKind(TailCallKind TCK) {
1348     setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1349                                unsigned(TCK));
1350   }
1351
1352   /// Provide fast operand accessors
1353   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1354
1355   /// getNumArgOperands - Return the number of call arguments.
1356   ///
1357   unsigned getNumArgOperands() const { return getNumOperands() - 1; }
1358
1359   /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1360   ///
1361   Value *getArgOperand(unsigned i) const { return getOperand(i); }
1362   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
1363
1364   /// arg_operands - iteration adapter for range-for loops.
1365   iterator_range<op_iterator> arg_operands() {
1366     // The last operand in the op list is the callee - it's not one of the args
1367     // so we don't want to iterate over it.
1368     return iterator_range<op_iterator>(op_begin(), op_end() - 1);
1369   }
1370
1371   /// arg_operands - iteration adapter for range-for loops.
1372   iterator_range<const_op_iterator> arg_operands() const {
1373     return iterator_range<const_op_iterator>(op_begin(), op_end() - 1);
1374   }
1375
1376   /// \brief Wrappers for getting the \c Use of a call argument.
1377   const Use &getArgOperandUse(unsigned i) const { return getOperandUse(i); }
1378   Use &getArgOperandUse(unsigned i) { return getOperandUse(i); }
1379
1380   /// getCallingConv/setCallingConv - Get or set the calling convention of this
1381   /// function call.
1382   CallingConv::ID getCallingConv() const {
1383     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1384   }
1385   void setCallingConv(CallingConv::ID CC) {
1386     setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1387                                (static_cast<unsigned>(CC) << 2));
1388   }
1389
1390   /// getAttributes - Return the parameter attributes for this call.
1391   ///
1392   const AttributeSet &getAttributes() const { return AttributeList; }
1393
1394   /// setAttributes - Set the parameter attributes for this call.
1395   ///
1396   void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
1397
1398   /// addAttribute - adds the attribute to the list of attributes.
1399   void addAttribute(unsigned i, Attribute::AttrKind attr);
1400
1401   /// removeAttribute - removes the attribute from the list of attributes.
1402   void removeAttribute(unsigned i, Attribute attr);
1403
1404   /// \brief adds the dereferenceable attribute to the list of attributes.
1405   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1406
1407   /// \brief Determine whether this call has the given attribute.
1408   bool hasFnAttr(Attribute::AttrKind A) const {
1409     assert(A != Attribute::NoBuiltin &&
1410            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1411     return hasFnAttrImpl(A);
1412   }
1413
1414   /// \brief Determine whether the call or the callee has the given attributes.
1415   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
1416
1417   /// \brief Extract the alignment for a call or parameter (0=unknown).
1418   unsigned getParamAlignment(unsigned i) const {
1419     return AttributeList.getParamAlignment(i);
1420   }
1421
1422   /// \brief Extract the number of dereferenceable bytes for a call or
1423   /// parameter (0=unknown).
1424   uint64_t getDereferenceableBytes(unsigned i) const {
1425     return AttributeList.getDereferenceableBytes(i);
1426   }
1427
1428   /// \brief Return true if the call should not be treated as a call to a
1429   /// builtin.
1430   bool isNoBuiltin() const {
1431     return hasFnAttrImpl(Attribute::NoBuiltin) &&
1432       !hasFnAttrImpl(Attribute::Builtin);
1433   }
1434
1435   /// \brief Return true if the call should not be inlined.
1436   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1437   void setIsNoInline() {
1438     addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
1439   }
1440
1441   /// \brief Return true if the call can return twice
1442   bool canReturnTwice() const {
1443     return hasFnAttr(Attribute::ReturnsTwice);
1444   }
1445   void setCanReturnTwice() {
1446     addAttribute(AttributeSet::FunctionIndex, Attribute::ReturnsTwice);
1447   }
1448
1449   /// \brief Determine if the call does not access memory.
1450   bool doesNotAccessMemory() const {
1451     return hasFnAttr(Attribute::ReadNone);
1452   }
1453   void setDoesNotAccessMemory() {
1454     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
1455   }
1456
1457   /// \brief Determine if the call does not access or only reads memory.
1458   bool onlyReadsMemory() const {
1459     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1460   }
1461   void setOnlyReadsMemory() {
1462     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
1463   }
1464
1465   /// \brief Determine if the call cannot return.
1466   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1467   void setDoesNotReturn() {
1468     addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
1469   }
1470
1471   /// \brief Determine if the call cannot unwind.
1472   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1473   void setDoesNotThrow() {
1474     addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
1475   }
1476
1477   /// \brief Determine if the call cannot be duplicated.
1478   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1479   void setCannotDuplicate() {
1480     addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
1481   }
1482
1483   /// \brief Determine if the call returns a structure through first
1484   /// pointer argument.
1485   bool hasStructRetAttr() const {
1486     // Be friendly and also check the callee.
1487     return paramHasAttr(1, Attribute::StructRet);
1488   }
1489
1490   /// \brief Determine if any call argument is an aggregate passed by value.
1491   bool hasByValArgument() const {
1492     return AttributeList.hasAttrSomewhere(Attribute::ByVal);
1493   }
1494
1495   /// getCalledFunction - Return the function called, or null if this is an
1496   /// indirect function invocation.
1497   ///
1498   Function *getCalledFunction() const {
1499     return dyn_cast<Function>(Op<-1>());
1500   }
1501
1502   /// getCalledValue - Get a pointer to the function that is invoked by this
1503   /// instruction.
1504   const Value *getCalledValue() const { return Op<-1>(); }
1505         Value *getCalledValue()       { return Op<-1>(); }
1506
1507   /// setCalledFunction - Set the function called.
1508   void setCalledFunction(Value* Fn) {
1509     Op<-1>() = Fn;
1510   }
1511
1512   /// isInlineAsm - Check if this call is an inline asm statement.
1513   bool isInlineAsm() const {
1514     return isa<InlineAsm>(Op<-1>());
1515   }
1516
1517   // Methods for support type inquiry through isa, cast, and dyn_cast:
1518   static inline bool classof(const Instruction *I) {
1519     return I->getOpcode() == Instruction::Call;
1520   }
1521   static inline bool classof(const Value *V) {
1522     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1523   }
1524 private:
1525
1526   bool hasFnAttrImpl(Attribute::AttrKind A) const;
1527
1528   // Shadow Instruction::setInstructionSubclassData with a private forwarding
1529   // method so that subclasses cannot accidentally use it.
1530   void setInstructionSubclassData(unsigned short D) {
1531     Instruction::setInstructionSubclassData(D);
1532   }
1533 };
1534
1535 template <>
1536 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1537 };
1538
1539 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1540                    const Twine &NameStr, BasicBlock *InsertAtEnd)
1541   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
1542                                    ->getElementType())->getReturnType(),
1543                 Instruction::Call,
1544                 OperandTraits<CallInst>::op_end(this) - (Args.size() + 1),
1545                 unsigned(Args.size() + 1), InsertAtEnd) {
1546   init(Func, Args, NameStr);
1547 }
1548
1549 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1550                    const Twine &NameStr, Instruction *InsertBefore)
1551   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
1552                                    ->getElementType())->getReturnType(),
1553                 Instruction::Call,
1554                 OperandTraits<CallInst>::op_end(this) - (Args.size() + 1),
1555                 unsigned(Args.size() + 1), InsertBefore) {
1556   init(Func, Args, NameStr);
1557 }
1558
1559
1560 // Note: if you get compile errors about private methods then
1561 //       please update your code to use the high-level operand
1562 //       interfaces. See line 943 above.
1563 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1564
1565 //===----------------------------------------------------------------------===//
1566 //                               SelectInst Class
1567 //===----------------------------------------------------------------------===//
1568
1569 /// SelectInst - This class represents the LLVM 'select' instruction.
1570 ///
1571 class SelectInst : public Instruction {
1572   void init(Value *C, Value *S1, Value *S2) {
1573     assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1574     Op<0>() = C;
1575     Op<1>() = S1;
1576     Op<2>() = S2;
1577   }
1578
1579   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1580              Instruction *InsertBefore)
1581     : Instruction(S1->getType(), Instruction::Select,
1582                   &Op<0>(), 3, InsertBefore) {
1583     init(C, S1, S2);
1584     setName(NameStr);
1585   }
1586   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1587              BasicBlock *InsertAtEnd)
1588     : Instruction(S1->getType(), Instruction::Select,
1589                   &Op<0>(), 3, InsertAtEnd) {
1590     init(C, S1, S2);
1591     setName(NameStr);
1592   }
1593 protected:
1594   SelectInst *clone_impl() const override;
1595 public:
1596   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1597                             const Twine &NameStr = "",
1598                             Instruction *InsertBefore = nullptr) {
1599     return new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1600   }
1601   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1602                             const Twine &NameStr,
1603                             BasicBlock *InsertAtEnd) {
1604     return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1605   }
1606
1607   const Value *getCondition() const { return Op<0>(); }
1608   const Value *getTrueValue() const { return Op<1>(); }
1609   const Value *getFalseValue() const { return Op<2>(); }
1610   Value *getCondition() { return Op<0>(); }
1611   Value *getTrueValue() { return Op<1>(); }
1612   Value *getFalseValue() { return Op<2>(); }
1613
1614   /// areInvalidOperands - Return a string if the specified operands are invalid
1615   /// for a select operation, otherwise return null.
1616   static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1617
1618   /// Transparently provide more efficient getOperand methods.
1619   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1620
1621   OtherOps getOpcode() const {
1622     return static_cast<OtherOps>(Instruction::getOpcode());
1623   }
1624
1625   // Methods for support type inquiry through isa, cast, and dyn_cast:
1626   static inline bool classof(const Instruction *I) {
1627     return I->getOpcode() == Instruction::Select;
1628   }
1629   static inline bool classof(const Value *V) {
1630     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1631   }
1632 };
1633
1634 template <>
1635 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1636 };
1637
1638 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1639
1640 //===----------------------------------------------------------------------===//
1641 //                                VAArgInst Class
1642 //===----------------------------------------------------------------------===//
1643
1644 /// VAArgInst - This class represents the va_arg llvm instruction, which returns
1645 /// an argument of the specified type given a va_list and increments that list
1646 ///
1647 class VAArgInst : public UnaryInstruction {
1648 protected:
1649   VAArgInst *clone_impl() const override;
1650
1651 public:
1652   VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1653              Instruction *InsertBefore = nullptr)
1654     : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1655     setName(NameStr);
1656   }
1657   VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1658             BasicBlock *InsertAtEnd)
1659     : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1660     setName(NameStr);
1661   }
1662
1663   Value *getPointerOperand() { return getOperand(0); }
1664   const Value *getPointerOperand() const { return getOperand(0); }
1665   static unsigned getPointerOperandIndex() { return 0U; }
1666
1667   // Methods for support type inquiry through isa, cast, and dyn_cast:
1668   static inline bool classof(const Instruction *I) {
1669     return I->getOpcode() == VAArg;
1670   }
1671   static inline bool classof(const Value *V) {
1672     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1673   }
1674 };
1675
1676 //===----------------------------------------------------------------------===//
1677 //                                ExtractElementInst Class
1678 //===----------------------------------------------------------------------===//
1679
1680 /// ExtractElementInst - This instruction extracts a single (scalar)
1681 /// element from a VectorType value
1682 ///
1683 class ExtractElementInst : public Instruction {
1684   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1685                      Instruction *InsertBefore = nullptr);
1686   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1687                      BasicBlock *InsertAtEnd);
1688 protected:
1689   ExtractElementInst *clone_impl() const override;
1690
1691 public:
1692   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1693                                    const Twine &NameStr = "",
1694                                    Instruction *InsertBefore = nullptr) {
1695     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1696   }
1697   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1698                                    const Twine &NameStr,
1699                                    BasicBlock *InsertAtEnd) {
1700     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1701   }
1702
1703   /// isValidOperands - Return true if an extractelement instruction can be
1704   /// formed with the specified operands.
1705   static bool isValidOperands(const Value *Vec, const Value *Idx);
1706
1707   Value *getVectorOperand() { return Op<0>(); }
1708   Value *getIndexOperand() { return Op<1>(); }
1709   const Value *getVectorOperand() const { return Op<0>(); }
1710   const Value *getIndexOperand() const { return Op<1>(); }
1711
1712   VectorType *getVectorOperandType() const {
1713     return cast<VectorType>(getVectorOperand()->getType());
1714   }
1715
1716
1717   /// Transparently provide more efficient getOperand methods.
1718   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1719
1720   // Methods for support type inquiry through isa, cast, and dyn_cast:
1721   static inline bool classof(const Instruction *I) {
1722     return I->getOpcode() == Instruction::ExtractElement;
1723   }
1724   static inline bool classof(const Value *V) {
1725     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1726   }
1727 };
1728
1729 template <>
1730 struct OperandTraits<ExtractElementInst> :
1731   public FixedNumOperandTraits<ExtractElementInst, 2> {
1732 };
1733
1734 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1735
1736 //===----------------------------------------------------------------------===//
1737 //                                InsertElementInst Class
1738 //===----------------------------------------------------------------------===//
1739
1740 /// InsertElementInst - This instruction inserts a single (scalar)
1741 /// element into a VectorType value
1742 ///
1743 class InsertElementInst : public Instruction {
1744   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1745                     const Twine &NameStr = "",
1746                     Instruction *InsertBefore = nullptr);
1747   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1748                     const Twine &NameStr, BasicBlock *InsertAtEnd);
1749 protected:
1750   InsertElementInst *clone_impl() const override;
1751
1752 public:
1753   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1754                                    const Twine &NameStr = "",
1755                                    Instruction *InsertBefore = nullptr) {
1756     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1757   }
1758   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1759                                    const Twine &NameStr,
1760                                    BasicBlock *InsertAtEnd) {
1761     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1762   }
1763
1764   /// isValidOperands - Return true if an insertelement instruction can be
1765   /// formed with the specified operands.
1766   static bool isValidOperands(const Value *Vec, const Value *NewElt,
1767                               const Value *Idx);
1768
1769   /// getType - Overload to return most specific vector type.
1770   ///
1771   VectorType *getType() const {
1772     return cast<VectorType>(Instruction::getType());
1773   }
1774
1775   /// Transparently provide more efficient getOperand methods.
1776   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1777
1778   // Methods for support type inquiry through isa, cast, and dyn_cast:
1779   static inline bool classof(const Instruction *I) {
1780     return I->getOpcode() == Instruction::InsertElement;
1781   }
1782   static inline bool classof(const Value *V) {
1783     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1784   }
1785 };
1786
1787 template <>
1788 struct OperandTraits<InsertElementInst> :
1789   public FixedNumOperandTraits<InsertElementInst, 3> {
1790 };
1791
1792 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1793
1794 //===----------------------------------------------------------------------===//
1795 //                           ShuffleVectorInst Class
1796 //===----------------------------------------------------------------------===//
1797
1798 /// ShuffleVectorInst - This instruction constructs a fixed permutation of two
1799 /// input vectors.
1800 ///
1801 class ShuffleVectorInst : public Instruction {
1802 protected:
1803   ShuffleVectorInst *clone_impl() const override;
1804
1805 public:
1806   // allocate space for exactly three operands
1807   void *operator new(size_t s) {
1808     return User::operator new(s, 3);
1809   }
1810   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1811                     const Twine &NameStr = "",
1812                     Instruction *InsertBefor = nullptr);
1813   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1814                     const Twine &NameStr, BasicBlock *InsertAtEnd);
1815
1816   /// isValidOperands - Return true if a shufflevector instruction can be
1817   /// formed with the specified operands.
1818   static bool isValidOperands(const Value *V1, const Value *V2,
1819                               const Value *Mask);
1820
1821   /// getType - Overload to return most specific vector type.
1822   ///
1823   VectorType *getType() const {
1824     return cast<VectorType>(Instruction::getType());
1825   }
1826
1827   /// Transparently provide more efficient getOperand methods.
1828   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1829
1830   Constant *getMask() const {
1831     return cast<Constant>(getOperand(2));
1832   }
1833
1834   /// getMaskValue - Return the index from the shuffle mask for the specified
1835   /// output result.  This is either -1 if the element is undef or a number less
1836   /// than 2*numelements.
1837   static int getMaskValue(Constant *Mask, unsigned i);
1838
1839   int getMaskValue(unsigned i) const {
1840     return getMaskValue(getMask(), i);
1841   }
1842
1843   /// getShuffleMask - Return the full mask for this instruction, where each
1844   /// element is the element number and undef's are returned as -1.
1845   static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
1846
1847   void getShuffleMask(SmallVectorImpl<int> &Result) const {
1848     return getShuffleMask(getMask(), Result);
1849   }
1850
1851   SmallVector<int, 16> getShuffleMask() const {
1852     SmallVector<int, 16> Mask;
1853     getShuffleMask(Mask);
1854     return Mask;
1855   }
1856
1857
1858   // Methods for support type inquiry through isa, cast, and dyn_cast:
1859   static inline bool classof(const Instruction *I) {
1860     return I->getOpcode() == Instruction::ShuffleVector;
1861   }
1862   static inline bool classof(const Value *V) {
1863     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1864   }
1865 };
1866
1867 template <>
1868 struct OperandTraits<ShuffleVectorInst> :
1869   public FixedNumOperandTraits<ShuffleVectorInst, 3> {
1870 };
1871
1872 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
1873
1874 //===----------------------------------------------------------------------===//
1875 //                                ExtractValueInst Class
1876 //===----------------------------------------------------------------------===//
1877
1878 /// ExtractValueInst - This instruction extracts a struct member or array
1879 /// element value from an aggregate value.
1880 ///
1881 class ExtractValueInst : public UnaryInstruction {
1882   SmallVector<unsigned, 4> Indices;
1883
1884   ExtractValueInst(const ExtractValueInst &EVI);
1885   void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
1886
1887   /// Constructors - Create a extractvalue instruction with a base aggregate
1888   /// value and a list of indices.  The first ctor can optionally insert before
1889   /// an existing instruction, the second appends the new instruction to the
1890   /// specified BasicBlock.
1891   inline ExtractValueInst(Value *Agg,
1892                           ArrayRef<unsigned> Idxs,
1893                           const Twine &NameStr,
1894                           Instruction *InsertBefore);
1895   inline ExtractValueInst(Value *Agg,
1896                           ArrayRef<unsigned> Idxs,
1897                           const Twine &NameStr, BasicBlock *InsertAtEnd);
1898
1899   // allocate space for exactly one operand
1900   void *operator new(size_t s) {
1901     return User::operator new(s, 1);
1902   }
1903 protected:
1904   ExtractValueInst *clone_impl() const override;
1905
1906 public:
1907   static ExtractValueInst *Create(Value *Agg,
1908                                   ArrayRef<unsigned> Idxs,
1909                                   const Twine &NameStr = "",
1910                                   Instruction *InsertBefore = nullptr) {
1911     return new
1912       ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
1913   }
1914   static ExtractValueInst *Create(Value *Agg,
1915                                   ArrayRef<unsigned> Idxs,
1916                                   const Twine &NameStr,
1917                                   BasicBlock *InsertAtEnd) {
1918     return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
1919   }
1920
1921   /// getIndexedType - Returns the type of the element that would be extracted
1922   /// with an extractvalue instruction with the specified parameters.
1923   ///
1924   /// Null is returned if the indices are invalid for the specified type.
1925   static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
1926
1927   typedef const unsigned* idx_iterator;
1928   inline idx_iterator idx_begin() const { return Indices.begin(); }
1929   inline idx_iterator idx_end()   const { return Indices.end(); }
1930   inline iterator_range<idx_iterator> indices() const {
1931     return iterator_range<idx_iterator>(idx_begin(), idx_end());
1932   }
1933
1934   Value *getAggregateOperand() {
1935     return getOperand(0);
1936   }
1937   const Value *getAggregateOperand() const {
1938     return getOperand(0);
1939   }
1940   static unsigned getAggregateOperandIndex() {
1941     return 0U;                      // get index for modifying correct operand
1942   }
1943
1944   ArrayRef<unsigned> getIndices() const {
1945     return Indices;
1946   }
1947
1948   unsigned getNumIndices() const {
1949     return (unsigned)Indices.size();
1950   }
1951
1952   bool hasIndices() const {
1953     return true;
1954   }
1955
1956   // Methods for support type inquiry through isa, cast, and dyn_cast:
1957   static inline bool classof(const Instruction *I) {
1958     return I->getOpcode() == Instruction::ExtractValue;
1959   }
1960   static inline bool classof(const Value *V) {
1961     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1962   }
1963 };
1964
1965 ExtractValueInst::ExtractValueInst(Value *Agg,
1966                                    ArrayRef<unsigned> Idxs,
1967                                    const Twine &NameStr,
1968                                    Instruction *InsertBefore)
1969   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
1970                      ExtractValue, Agg, InsertBefore) {
1971   init(Idxs, NameStr);
1972 }
1973 ExtractValueInst::ExtractValueInst(Value *Agg,
1974                                    ArrayRef<unsigned> Idxs,
1975                                    const Twine &NameStr,
1976                                    BasicBlock *InsertAtEnd)
1977   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
1978                      ExtractValue, Agg, InsertAtEnd) {
1979   init(Idxs, NameStr);
1980 }
1981
1982
1983 //===----------------------------------------------------------------------===//
1984 //                                InsertValueInst Class
1985 //===----------------------------------------------------------------------===//
1986
1987 /// InsertValueInst - This instruction inserts a struct field of array element
1988 /// value into an aggregate value.
1989 ///
1990 class InsertValueInst : public Instruction {
1991   SmallVector<unsigned, 4> Indices;
1992
1993   void *operator new(size_t, unsigned) = delete;
1994   InsertValueInst(const InsertValueInst &IVI);
1995   void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1996             const Twine &NameStr);
1997
1998   /// Constructors - Create a insertvalue instruction with a base aggregate
1999   /// value, a value to insert, and a list of indices.  The first ctor can
2000   /// optionally insert before an existing instruction, the second appends
2001   /// the new instruction to the specified BasicBlock.
2002   inline InsertValueInst(Value *Agg, Value *Val,
2003                          ArrayRef<unsigned> Idxs,
2004                          const Twine &NameStr,
2005                          Instruction *InsertBefore);
2006   inline InsertValueInst(Value *Agg, Value *Val,
2007                          ArrayRef<unsigned> Idxs,
2008                          const Twine &NameStr, BasicBlock *InsertAtEnd);
2009
2010   /// Constructors - These two constructors are convenience methods because one
2011   /// and two index insertvalue instructions are so common.
2012   InsertValueInst(Value *Agg, Value *Val,
2013                   unsigned Idx, const Twine &NameStr = "",
2014                   Instruction *InsertBefore = nullptr);
2015   InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2016                   const Twine &NameStr, BasicBlock *InsertAtEnd);
2017 protected:
2018   InsertValueInst *clone_impl() const override;
2019 public:
2020   // allocate space for exactly two operands
2021   void *operator new(size_t s) {
2022     return User::operator new(s, 2);
2023   }
2024
2025   static InsertValueInst *Create(Value *Agg, Value *Val,
2026                                  ArrayRef<unsigned> Idxs,
2027                                  const Twine &NameStr = "",
2028                                  Instruction *InsertBefore = nullptr) {
2029     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2030   }
2031   static InsertValueInst *Create(Value *Agg, Value *Val,
2032                                  ArrayRef<unsigned> Idxs,
2033                                  const Twine &NameStr,
2034                                  BasicBlock *InsertAtEnd) {
2035     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2036   }
2037
2038   /// Transparently provide more efficient getOperand methods.
2039   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2040
2041   typedef const unsigned* idx_iterator;
2042   inline idx_iterator idx_begin() const { return Indices.begin(); }
2043   inline idx_iterator idx_end()   const { return Indices.end(); }
2044   inline iterator_range<idx_iterator> indices() const {
2045     return iterator_range<idx_iterator>(idx_begin(), idx_end());
2046   }
2047
2048   Value *getAggregateOperand() {
2049     return getOperand(0);
2050   }
2051   const Value *getAggregateOperand() const {
2052     return getOperand(0);
2053   }
2054   static unsigned getAggregateOperandIndex() {
2055     return 0U;                      // get index for modifying correct operand
2056   }
2057
2058   Value *getInsertedValueOperand() {
2059     return getOperand(1);
2060   }
2061   const Value *getInsertedValueOperand() const {
2062     return getOperand(1);
2063   }
2064   static unsigned getInsertedValueOperandIndex() {
2065     return 1U;                      // get index for modifying correct operand
2066   }
2067
2068   ArrayRef<unsigned> getIndices() const {
2069     return Indices;
2070   }
2071
2072   unsigned getNumIndices() const {
2073     return (unsigned)Indices.size();
2074   }
2075
2076   bool hasIndices() const {
2077     return true;
2078   }
2079
2080   // Methods for support type inquiry through isa, cast, and dyn_cast:
2081   static inline bool classof(const Instruction *I) {
2082     return I->getOpcode() == Instruction::InsertValue;
2083   }
2084   static inline bool classof(const Value *V) {
2085     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2086   }
2087 };
2088
2089 template <>
2090 struct OperandTraits<InsertValueInst> :
2091   public FixedNumOperandTraits<InsertValueInst, 2> {
2092 };
2093
2094 InsertValueInst::InsertValueInst(Value *Agg,
2095                                  Value *Val,
2096                                  ArrayRef<unsigned> Idxs,
2097                                  const Twine &NameStr,
2098                                  Instruction *InsertBefore)
2099   : Instruction(Agg->getType(), InsertValue,
2100                 OperandTraits<InsertValueInst>::op_begin(this),
2101                 2, InsertBefore) {
2102   init(Agg, Val, Idxs, NameStr);
2103 }
2104 InsertValueInst::InsertValueInst(Value *Agg,
2105                                  Value *Val,
2106                                  ArrayRef<unsigned> Idxs,
2107                                  const Twine &NameStr,
2108                                  BasicBlock *InsertAtEnd)
2109   : Instruction(Agg->getType(), InsertValue,
2110                 OperandTraits<InsertValueInst>::op_begin(this),
2111                 2, InsertAtEnd) {
2112   init(Agg, Val, Idxs, NameStr);
2113 }
2114
2115 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2116
2117 //===----------------------------------------------------------------------===//
2118 //                               PHINode Class
2119 //===----------------------------------------------------------------------===//
2120
2121 // PHINode - The PHINode class is used to represent the magical mystical PHI
2122 // node, that can not exist in nature, but can be synthesized in a computer
2123 // scientist's overactive imagination.
2124 //
2125 class PHINode : public Instruction {
2126   void *operator new(size_t, unsigned) = delete;
2127   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2128   /// the number actually in use.
2129   unsigned ReservedSpace;
2130   PHINode(const PHINode &PN);
2131   // allocate space for exactly zero operands
2132   void *operator new(size_t s) {
2133     return User::operator new(s, 0);
2134   }
2135   explicit PHINode(Type *Ty, unsigned NumReservedValues,
2136                    const Twine &NameStr = "",
2137                    Instruction *InsertBefore = nullptr)
2138     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2139       ReservedSpace(NumReservedValues) {
2140     setName(NameStr);
2141     OperandList = allocHungoffUses(ReservedSpace);
2142   }
2143
2144   PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2145           BasicBlock *InsertAtEnd)
2146     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2147       ReservedSpace(NumReservedValues) {
2148     setName(NameStr);
2149     OperandList = allocHungoffUses(ReservedSpace);
2150   }
2151 protected:
2152   // allocHungoffUses - this is more complicated than the generic
2153   // User::allocHungoffUses, because we have to allocate Uses for the incoming
2154   // values and pointers to the incoming blocks, all in one allocation.
2155   Use *allocHungoffUses(unsigned) const;
2156
2157   PHINode *clone_impl() const override;
2158 public:
2159   /// Constructors - NumReservedValues is a hint for the number of incoming
2160   /// edges that this phi node will have (use 0 if you really have no idea).
2161   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2162                          const Twine &NameStr = "",
2163                          Instruction *InsertBefore = nullptr) {
2164     return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2165   }
2166   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2167                          const Twine &NameStr, BasicBlock *InsertAtEnd) {
2168     return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2169   }
2170   ~PHINode();
2171
2172   /// Provide fast operand accessors
2173   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2174
2175   // Block iterator interface. This provides access to the list of incoming
2176   // basic blocks, which parallels the list of incoming values.
2177
2178   typedef BasicBlock **block_iterator;
2179   typedef BasicBlock * const *const_block_iterator;
2180
2181   block_iterator block_begin() {
2182     Use::UserRef *ref =
2183       reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2184     return reinterpret_cast<block_iterator>(ref + 1);
2185   }
2186
2187   const_block_iterator block_begin() const {
2188     const Use::UserRef *ref =
2189       reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2190     return reinterpret_cast<const_block_iterator>(ref + 1);
2191   }
2192
2193   block_iterator block_end() {
2194     return block_begin() + getNumOperands();
2195   }
2196
2197   const_block_iterator block_end() const {
2198     return block_begin() + getNumOperands();
2199   }
2200
2201   op_range incoming_values() { return operands(); }
2202
2203   /// getNumIncomingValues - Return the number of incoming edges
2204   ///
2205   unsigned getNumIncomingValues() const { return getNumOperands(); }
2206
2207   /// getIncomingValue - Return incoming value number x
2208   ///
2209   Value *getIncomingValue(unsigned i) const {
2210     return getOperand(i);
2211   }
2212   void setIncomingValue(unsigned i, Value *V) {
2213     setOperand(i, V);
2214   }
2215   static unsigned getOperandNumForIncomingValue(unsigned i) {
2216     return i;
2217   }
2218   static unsigned getIncomingValueNumForOperand(unsigned i) {
2219     return i;
2220   }
2221
2222   /// getIncomingBlock - Return incoming basic block number @p i.
2223   ///
2224   BasicBlock *getIncomingBlock(unsigned i) const {
2225     return block_begin()[i];
2226   }
2227
2228   /// getIncomingBlock - Return incoming basic block corresponding
2229   /// to an operand of the PHI.
2230   ///
2231   BasicBlock *getIncomingBlock(const Use &U) const {
2232     assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2233     return getIncomingBlock(unsigned(&U - op_begin()));
2234   }
2235
2236   /// getIncomingBlock - Return incoming basic block corresponding
2237   /// to value use iterator.
2238   ///
2239   BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2240     return getIncomingBlock(I.getUse());
2241   }
2242
2243   void setIncomingBlock(unsigned i, BasicBlock *BB) {
2244     block_begin()[i] = BB;
2245   }
2246
2247   /// addIncoming - Add an incoming value to the end of the PHI list
2248   ///
2249   void addIncoming(Value *V, BasicBlock *BB) {
2250     assert(V && "PHI node got a null value!");
2251     assert(BB && "PHI node got a null basic block!");
2252     assert(getType() == V->getType() &&
2253            "All operands to PHI node must be the same type as the PHI node!");
2254     if (NumOperands == ReservedSpace)
2255       growOperands();  // Get more space!
2256     // Initialize some new operands.
2257     ++NumOperands;
2258     setIncomingValue(NumOperands - 1, V);
2259     setIncomingBlock(NumOperands - 1, BB);
2260   }
2261
2262   /// removeIncomingValue - Remove an incoming value.  This is useful if a
2263   /// predecessor basic block is deleted.  The value removed is returned.
2264   ///
2265   /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2266   /// is true), the PHI node is destroyed and any uses of it are replaced with
2267   /// dummy values.  The only time there should be zero incoming values to a PHI
2268   /// node is when the block is dead, so this strategy is sound.
2269   ///
2270   Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2271
2272   Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2273     int Idx = getBasicBlockIndex(BB);
2274     assert(Idx >= 0 && "Invalid basic block argument to remove!");
2275     return removeIncomingValue(Idx, DeletePHIIfEmpty);
2276   }
2277
2278   /// getBasicBlockIndex - Return the first index of the specified basic
2279   /// block in the value list for this PHI.  Returns -1 if no instance.
2280   ///
2281   int getBasicBlockIndex(const BasicBlock *BB) const {
2282     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2283       if (block_begin()[i] == BB)
2284         return i;
2285     return -1;
2286   }
2287
2288   Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2289     int Idx = getBasicBlockIndex(BB);
2290     assert(Idx >= 0 && "Invalid basic block argument!");
2291     return getIncomingValue(Idx);
2292   }
2293
2294   /// hasConstantValue - If the specified PHI node always merges together the
2295   /// same value, return the value, otherwise return null.
2296   Value *hasConstantValue() const;
2297
2298   /// Methods for support type inquiry through isa, cast, and dyn_cast:
2299   static inline bool classof(const Instruction *I) {
2300     return I->getOpcode() == Instruction::PHI;
2301   }
2302   static inline bool classof(const Value *V) {
2303     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2304   }
2305  private:
2306   void growOperands();
2307 };
2308
2309 template <>
2310 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2311 };
2312
2313 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2314
2315 //===----------------------------------------------------------------------===//
2316 //                           LandingPadInst Class
2317 //===----------------------------------------------------------------------===//
2318
2319 //===---------------------------------------------------------------------------
2320 /// LandingPadInst - The landingpad instruction holds all of the information
2321 /// necessary to generate correct exception handling. The landingpad instruction
2322 /// cannot be moved from the top of a landing pad block, which itself is
2323 /// accessible only from the 'unwind' edge of an invoke. This uses the
2324 /// SubclassData field in Value to store whether or not the landingpad is a
2325 /// cleanup.
2326 ///
2327 class LandingPadInst : public Instruction {
2328   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2329   /// the number actually in use.
2330   unsigned ReservedSpace;
2331   LandingPadInst(const LandingPadInst &LP);
2332 public:
2333   enum ClauseType { Catch, Filter };
2334 private:
2335   void *operator new(size_t, unsigned) = delete;
2336   // Allocate space for exactly zero operands.
2337   void *operator new(size_t s) {
2338     return User::operator new(s, 0);
2339   }
2340   void growOperands(unsigned Size);
2341   void init(Value *PersFn, unsigned NumReservedValues, const Twine &NameStr);
2342
2343   explicit LandingPadInst(Type *RetTy, Value *PersonalityFn,
2344                           unsigned NumReservedValues, const Twine &NameStr,
2345                           Instruction *InsertBefore);
2346   explicit LandingPadInst(Type *RetTy, Value *PersonalityFn,
2347                           unsigned NumReservedValues, const Twine &NameStr,
2348                           BasicBlock *InsertAtEnd);
2349 protected:
2350   LandingPadInst *clone_impl() const override;
2351 public:
2352   /// Constructors - NumReservedClauses is a hint for the number of incoming
2353   /// clauses that this landingpad will have (use 0 if you really have no idea).
2354   static LandingPadInst *Create(Type *RetTy, Value *PersonalityFn,
2355                                 unsigned NumReservedClauses,
2356                                 const Twine &NameStr = "",
2357                                 Instruction *InsertBefore = nullptr);
2358   static LandingPadInst *Create(Type *RetTy, Value *PersonalityFn,
2359                                 unsigned NumReservedClauses,
2360                                 const Twine &NameStr, BasicBlock *InsertAtEnd);
2361   ~LandingPadInst();
2362
2363   /// Provide fast operand accessors
2364   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2365
2366   /// getPersonalityFn - Get the personality function associated with this
2367   /// landing pad.
2368   Value *getPersonalityFn() const { return getOperand(0); }
2369
2370   /// isCleanup - Return 'true' if this landingpad instruction is a
2371   /// cleanup. I.e., it should be run when unwinding even if its landing pad
2372   /// doesn't catch the exception.
2373   bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2374
2375   /// setCleanup - Indicate that this landingpad instruction is a cleanup.
2376   void setCleanup(bool V) {
2377     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2378                                (V ? 1 : 0));
2379   }
2380
2381   /// Add a catch or filter clause to the landing pad.
2382   void addClause(Constant *ClauseVal);
2383
2384   /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2385   /// determine what type of clause this is.
2386   Constant *getClause(unsigned Idx) const {
2387     return cast<Constant>(OperandList[Idx + 1]);
2388   }
2389
2390   /// isCatch - Return 'true' if the clause and index Idx is a catch clause.
2391   bool isCatch(unsigned Idx) const {
2392     return !isa<ArrayType>(OperandList[Idx + 1]->getType());
2393   }
2394
2395   /// isFilter - Return 'true' if the clause and index Idx is a filter clause.
2396   bool isFilter(unsigned Idx) const {
2397     return isa<ArrayType>(OperandList[Idx + 1]->getType());
2398   }
2399
2400   /// getNumClauses - Get the number of clauses for this landing pad.
2401   unsigned getNumClauses() const { return getNumOperands() - 1; }
2402
2403   /// reserveClauses - Grow the size of the operand list to accommodate the new
2404   /// number of clauses.
2405   void reserveClauses(unsigned Size) { growOperands(Size); }
2406
2407   // Methods for support type inquiry through isa, cast, and dyn_cast:
2408   static inline bool classof(const Instruction *I) {
2409     return I->getOpcode() == Instruction::LandingPad;
2410   }
2411   static inline bool classof(const Value *V) {
2412     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2413   }
2414 };
2415
2416 template <>
2417 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<2> {
2418 };
2419
2420 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2421
2422 //===----------------------------------------------------------------------===//
2423 //                               ReturnInst Class
2424 //===----------------------------------------------------------------------===//
2425
2426 //===---------------------------------------------------------------------------
2427 /// ReturnInst - Return a value (possibly void), from a function.  Execution
2428 /// does not continue in this function any longer.
2429 ///
2430 class ReturnInst : public TerminatorInst {
2431   ReturnInst(const ReturnInst &RI);
2432
2433 private:
2434   // ReturnInst constructors:
2435   // ReturnInst()                  - 'ret void' instruction
2436   // ReturnInst(    null)          - 'ret void' instruction
2437   // ReturnInst(Value* X)          - 'ret X'    instruction
2438   // ReturnInst(    null, Inst *I) - 'ret void' instruction, insert before I
2439   // ReturnInst(Value* X, Inst *I) - 'ret X'    instruction, insert before I
2440   // ReturnInst(    null, BB *B)   - 'ret void' instruction, insert @ end of B
2441   // ReturnInst(Value* X, BB *B)   - 'ret X'    instruction, insert @ end of B
2442   //
2443   // NOTE: If the Value* passed is of type void then the constructor behaves as
2444   // if it was passed NULL.
2445   explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2446                       Instruction *InsertBefore = nullptr);
2447   ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2448   explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2449 protected:
2450   ReturnInst *clone_impl() const override;
2451 public:
2452   static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2453                             Instruction *InsertBefore = nullptr) {
2454     return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2455   }
2456   static ReturnInst* Create(LLVMContext &C, Value *retVal,
2457                             BasicBlock *InsertAtEnd) {
2458     return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2459   }
2460   static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2461     return new(0) ReturnInst(C, InsertAtEnd);
2462   }
2463   virtual ~ReturnInst();
2464
2465   /// Provide fast operand accessors
2466   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2467
2468   /// Convenience accessor. Returns null if there is no return value.
2469   Value *getReturnValue() const {
2470     return getNumOperands() != 0 ? getOperand(0) : nullptr;
2471   }
2472
2473   unsigned getNumSuccessors() const { return 0; }
2474
2475   // Methods for support type inquiry through isa, cast, and dyn_cast:
2476   static inline bool classof(const Instruction *I) {
2477     return (I->getOpcode() == Instruction::Ret);
2478   }
2479   static inline bool classof(const Value *V) {
2480     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2481   }
2482  private:
2483   BasicBlock *getSuccessorV(unsigned idx) const override;
2484   unsigned getNumSuccessorsV() const override;
2485   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2486 };
2487
2488 template <>
2489 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2490 };
2491
2492 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2493
2494 //===----------------------------------------------------------------------===//
2495 //                               BranchInst Class
2496 //===----------------------------------------------------------------------===//
2497
2498 //===---------------------------------------------------------------------------
2499 /// BranchInst - Conditional or Unconditional Branch instruction.
2500 ///
2501 class BranchInst : public TerminatorInst {
2502   /// Ops list - Branches are strange.  The operands are ordered:
2503   ///  [Cond, FalseDest,] TrueDest.  This makes some accessors faster because
2504   /// they don't have to check for cond/uncond branchness. These are mostly
2505   /// accessed relative from op_end().
2506   BranchInst(const BranchInst &BI);
2507   void AssertOK();
2508   // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2509   // BranchInst(BB *B)                           - 'br B'
2510   // BranchInst(BB* T, BB *F, Value *C)          - 'br C, T, F'
2511   // BranchInst(BB* B, Inst *I)                  - 'br B'        insert before I
2512   // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2513   // BranchInst(BB* B, BB *I)                    - 'br B'        insert at end
2514   // BranchInst(BB* T, BB *F, Value *C, BB *I)   - 'br C, T, F', insert at end
2515   explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2516   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2517              Instruction *InsertBefore = nullptr);
2518   BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2519   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2520              BasicBlock *InsertAtEnd);
2521 protected:
2522   BranchInst *clone_impl() const override;
2523 public:
2524   static BranchInst *Create(BasicBlock *IfTrue,
2525                             Instruction *InsertBefore = nullptr) {
2526     return new(1) BranchInst(IfTrue, InsertBefore);
2527   }
2528   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2529                             Value *Cond, Instruction *InsertBefore = nullptr) {
2530     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
2531   }
2532   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
2533     return new(1) BranchInst(IfTrue, InsertAtEnd);
2534   }
2535   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2536                             Value *Cond, BasicBlock *InsertAtEnd) {
2537     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
2538   }
2539
2540   /// Transparently provide more efficient getOperand methods.
2541   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2542
2543   bool isUnconditional() const { return getNumOperands() == 1; }
2544   bool isConditional()   const { return getNumOperands() == 3; }
2545
2546   Value *getCondition() const {
2547     assert(isConditional() && "Cannot get condition of an uncond branch!");
2548     return Op<-3>();
2549   }
2550
2551   void setCondition(Value *V) {
2552     assert(isConditional() && "Cannot set condition of unconditional branch!");
2553     Op<-3>() = V;
2554   }
2555
2556   unsigned getNumSuccessors() const { return 1+isConditional(); }
2557
2558   BasicBlock *getSuccessor(unsigned i) const {
2559     assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
2560     return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
2561   }
2562
2563   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2564     assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
2565     *(&Op<-1>() - idx) = (Value*)NewSucc;
2566   }
2567
2568   /// \brief Swap the successors of this branch instruction.
2569   ///
2570   /// Swaps the successors of the branch instruction. This also swaps any
2571   /// branch weight metadata associated with the instruction so that it
2572   /// continues to map correctly to each operand.
2573   void swapSuccessors();
2574
2575   // Methods for support type inquiry through isa, cast, and dyn_cast:
2576   static inline bool classof(const Instruction *I) {
2577     return (I->getOpcode() == Instruction::Br);
2578   }
2579   static inline bool classof(const Value *V) {
2580     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2581   }
2582 private:
2583   BasicBlock *getSuccessorV(unsigned idx) const override;
2584   unsigned getNumSuccessorsV() const override;
2585   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2586 };
2587
2588 template <>
2589 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
2590 };
2591
2592 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
2593
2594 //===----------------------------------------------------------------------===//
2595 //                               SwitchInst Class
2596 //===----------------------------------------------------------------------===//
2597
2598 //===---------------------------------------------------------------------------
2599 /// SwitchInst - Multiway switch
2600 ///
2601 class SwitchInst : public TerminatorInst {
2602   void *operator new(size_t, unsigned) = delete;
2603   unsigned ReservedSpace;
2604   // Operand[0]    = Value to switch on
2605   // Operand[1]    = Default basic block destination
2606   // Operand[2n  ] = Value to match
2607   // Operand[2n+1] = BasicBlock to go to on match
2608   SwitchInst(const SwitchInst &SI);
2609   void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
2610   void growOperands();
2611   // allocate space for exactly zero operands
2612   void *operator new(size_t s) {
2613     return User::operator new(s, 0);
2614   }
2615   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2616   /// switch on and a default destination.  The number of additional cases can
2617   /// be specified here to make memory allocation more efficient.  This
2618   /// constructor can also autoinsert before another instruction.
2619   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2620              Instruction *InsertBefore);
2621
2622   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2623   /// switch on and a default destination.  The number of additional cases can
2624   /// be specified here to make memory allocation more efficient.  This
2625   /// constructor also autoinserts at the end of the specified BasicBlock.
2626   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2627              BasicBlock *InsertAtEnd);
2628 protected:
2629   SwitchInst *clone_impl() const override;
2630 public:
2631
2632   // -2
2633   static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
2634
2635   template <class SwitchInstTy, class ConstantIntTy, class BasicBlockTy>
2636   class CaseIteratorT {
2637   protected:
2638
2639     SwitchInstTy *SI;
2640     unsigned Index;
2641
2642   public:
2643
2644     typedef CaseIteratorT<SwitchInstTy, ConstantIntTy, BasicBlockTy> Self;
2645
2646     /// Initializes case iterator for given SwitchInst and for given
2647     /// case number.
2648     CaseIteratorT(SwitchInstTy *SI, unsigned CaseNum) {
2649       this->SI = SI;
2650       Index = CaseNum;
2651     }
2652
2653     /// Initializes case iterator for given SwitchInst and for given
2654     /// TerminatorInst's successor index.
2655     static Self fromSuccessorIndex(SwitchInstTy *SI, unsigned SuccessorIndex) {
2656       assert(SuccessorIndex < SI->getNumSuccessors() &&
2657              "Successor index # out of range!");
2658       return SuccessorIndex != 0 ?
2659              Self(SI, SuccessorIndex - 1) :
2660              Self(SI, DefaultPseudoIndex);
2661     }
2662
2663     /// Resolves case value for current case.
2664     ConstantIntTy *getCaseValue() {
2665       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2666       return reinterpret_cast<ConstantIntTy*>(SI->getOperand(2 + Index*2));
2667     }
2668
2669     /// Resolves successor for current case.
2670     BasicBlockTy *getCaseSuccessor() {
2671       assert((Index < SI->getNumCases() ||
2672               Index == DefaultPseudoIndex) &&
2673              "Index out the number of cases.");
2674       return SI->getSuccessor(getSuccessorIndex());
2675     }
2676
2677     /// Returns number of current case.
2678     unsigned getCaseIndex() const { return Index; }
2679
2680     /// Returns TerminatorInst's successor index for current case successor.
2681     unsigned getSuccessorIndex() const {
2682       assert((Index == DefaultPseudoIndex || Index < SI->getNumCases()) &&
2683              "Index out the number of cases.");
2684       return Index != DefaultPseudoIndex ? Index + 1 : 0;
2685     }
2686
2687     Self operator++() {
2688       // Check index correctness after increment.
2689       // Note: Index == getNumCases() means end().
2690       assert(Index+1 <= SI->getNumCases() && "Index out the number of cases.");
2691       ++Index;
2692       return *this;
2693     }
2694     Self operator++(int) {
2695       Self tmp = *this;
2696       ++(*this);
2697       return tmp;
2698     }
2699     Self operator--() {
2700       // Check index correctness after decrement.
2701       // Note: Index == getNumCases() means end().
2702       // Also allow "-1" iterator here. That will became valid after ++.
2703       assert((Index == 0 || Index-1 <= SI->getNumCases()) &&
2704              "Index out the number of cases.");
2705       --Index;
2706       return *this;
2707     }
2708     Self operator--(int) {
2709       Self tmp = *this;
2710       --(*this);
2711       return tmp;
2712     }
2713     bool operator==(const Self& RHS) const {
2714       assert(RHS.SI == SI && "Incompatible operators.");
2715       return RHS.Index == Index;
2716     }
2717     bool operator!=(const Self& RHS) const {
2718       assert(RHS.SI == SI && "Incompatible operators.");
2719       return RHS.Index != Index;
2720     }
2721     Self &operator*() {
2722       return *this;
2723     }
2724   };
2725
2726   typedef CaseIteratorT<const SwitchInst, const ConstantInt, const BasicBlock>
2727     ConstCaseIt;
2728
2729   class CaseIt : public CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> {
2730
2731     typedef CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> ParentTy;
2732
2733   public:
2734
2735     CaseIt(const ParentTy& Src) : ParentTy(Src) {}
2736     CaseIt(SwitchInst *SI, unsigned CaseNum) : ParentTy(SI, CaseNum) {}
2737
2738     /// Sets the new value for current case.
2739     void setValue(ConstantInt *V) {
2740       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2741       SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
2742     }
2743
2744     /// Sets the new successor for current case.
2745     void setSuccessor(BasicBlock *S) {
2746       SI->setSuccessor(getSuccessorIndex(), S);
2747     }
2748   };
2749
2750   static SwitchInst *Create(Value *Value, BasicBlock *Default,
2751                             unsigned NumCases,
2752                             Instruction *InsertBefore = nullptr) {
2753     return new SwitchInst(Value, Default, NumCases, InsertBefore);
2754   }
2755   static SwitchInst *Create(Value *Value, BasicBlock *Default,
2756                             unsigned NumCases, BasicBlock *InsertAtEnd) {
2757     return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
2758   }
2759
2760   ~SwitchInst();
2761
2762   /// Provide fast operand accessors
2763   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2764
2765   // Accessor Methods for Switch stmt
2766   Value *getCondition() const { return getOperand(0); }
2767   void setCondition(Value *V) { setOperand(0, V); }
2768
2769   BasicBlock *getDefaultDest() const {
2770     return cast<BasicBlock>(getOperand(1));
2771   }
2772
2773   void setDefaultDest(BasicBlock *DefaultCase) {
2774     setOperand(1, reinterpret_cast<Value*>(DefaultCase));
2775   }
2776
2777   /// getNumCases - return the number of 'cases' in this switch instruction,
2778   /// except the default case
2779   unsigned getNumCases() const {
2780     return getNumOperands()/2 - 1;
2781   }
2782
2783   /// Returns a read/write iterator that points to the first
2784   /// case in SwitchInst.
2785   CaseIt case_begin() {
2786     return CaseIt(this, 0);
2787   }
2788   /// Returns a read-only iterator that points to the first
2789   /// case in the SwitchInst.
2790   ConstCaseIt case_begin() const {
2791     return ConstCaseIt(this, 0);
2792   }
2793
2794   /// Returns a read/write iterator that points one past the last
2795   /// in the SwitchInst.
2796   CaseIt case_end() {
2797     return CaseIt(this, getNumCases());
2798   }
2799   /// Returns a read-only iterator that points one past the last
2800   /// in the SwitchInst.
2801   ConstCaseIt case_end() const {
2802     return ConstCaseIt(this, getNumCases());
2803   }
2804
2805   /// cases - iteration adapter for range-for loops.
2806   iterator_range<CaseIt> cases() {
2807     return iterator_range<CaseIt>(case_begin(), case_end());
2808   }
2809
2810   /// cases - iteration adapter for range-for loops.
2811   iterator_range<ConstCaseIt> cases() const {
2812     return iterator_range<ConstCaseIt>(case_begin(), case_end());
2813   }
2814
2815   /// Returns an iterator that points to the default case.
2816   /// Note: this iterator allows to resolve successor only. Attempt
2817   /// to resolve case value causes an assertion.
2818   /// Also note, that increment and decrement also causes an assertion and
2819   /// makes iterator invalid.
2820   CaseIt case_default() {
2821     return CaseIt(this, DefaultPseudoIndex);
2822   }
2823   ConstCaseIt case_default() const {
2824     return ConstCaseIt(this, DefaultPseudoIndex);
2825   }
2826
2827   /// findCaseValue - Search all of the case values for the specified constant.
2828   /// If it is explicitly handled, return the case iterator of it, otherwise
2829   /// return default case iterator to indicate
2830   /// that it is handled by the default handler.
2831   CaseIt findCaseValue(const ConstantInt *C) {
2832     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i)
2833       if (i.getCaseValue() == C)
2834         return i;
2835     return case_default();
2836   }
2837   ConstCaseIt findCaseValue(const ConstantInt *C) const {
2838     for (ConstCaseIt i = case_begin(), e = case_end(); i != e; ++i)
2839       if (i.getCaseValue() == C)
2840         return i;
2841     return case_default();
2842   }
2843
2844   /// findCaseDest - Finds the unique case value for a given successor. Returns
2845   /// null if the successor is not found, not unique, or is the default case.
2846   ConstantInt *findCaseDest(BasicBlock *BB) {
2847     if (BB == getDefaultDest()) return nullptr;
2848
2849     ConstantInt *CI = nullptr;
2850     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i) {
2851       if (i.getCaseSuccessor() == BB) {
2852         if (CI) return nullptr;   // Multiple cases lead to BB.
2853         else CI = i.getCaseValue();
2854       }
2855     }
2856     return CI;
2857   }
2858
2859   /// addCase - Add an entry to the switch instruction...
2860   /// Note:
2861   /// This action invalidates case_end(). Old case_end() iterator will
2862   /// point to the added case.
2863   void addCase(ConstantInt *OnVal, BasicBlock *Dest);
2864
2865   /// removeCase - This method removes the specified case and its successor
2866   /// from the switch instruction. Note that this operation may reorder the
2867   /// remaining cases at index idx and above.
2868   /// Note:
2869   /// This action invalidates iterators for all cases following the one removed,
2870   /// including the case_end() iterator.
2871   void removeCase(CaseIt i);
2872
2873   unsigned getNumSuccessors() const { return getNumOperands()/2; }
2874   BasicBlock *getSuccessor(unsigned idx) const {
2875     assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
2876     return cast<BasicBlock>(getOperand(idx*2+1));
2877   }
2878   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2879     assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
2880     setOperand(idx*2+1, (Value*)NewSucc);
2881   }
2882
2883   // Methods for support type inquiry through isa, cast, and dyn_cast:
2884   static inline bool classof(const Instruction *I) {
2885     return I->getOpcode() == Instruction::Switch;
2886   }
2887   static inline bool classof(const Value *V) {
2888     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2889   }
2890 private:
2891   BasicBlock *getSuccessorV(unsigned idx) const override;
2892   unsigned getNumSuccessorsV() const override;
2893   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2894 };
2895
2896 template <>
2897 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
2898 };
2899
2900 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
2901
2902
2903 //===----------------------------------------------------------------------===//
2904 //                             IndirectBrInst Class
2905 //===----------------------------------------------------------------------===//
2906
2907 //===---------------------------------------------------------------------------
2908 /// IndirectBrInst - Indirect Branch Instruction.
2909 ///
2910 class IndirectBrInst : public TerminatorInst {
2911   void *operator new(size_t, unsigned) = delete;
2912   unsigned ReservedSpace;
2913   // Operand[0]    = Value to switch on
2914   // Operand[1]    = Default basic block destination
2915   // Operand[2n  ] = Value to match
2916   // Operand[2n+1] = BasicBlock to go to on match
2917   IndirectBrInst(const IndirectBrInst &IBI);
2918   void init(Value *Address, unsigned NumDests);
2919   void growOperands();
2920   // allocate space for exactly zero operands
2921   void *operator new(size_t s) {
2922     return User::operator new(s, 0);
2923   }
2924   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
2925   /// Address to jump to.  The number of expected destinations can be specified
2926   /// here to make memory allocation more efficient.  This constructor can also
2927   /// autoinsert before another instruction.
2928   IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
2929
2930   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
2931   /// Address to jump to.  The number of expected destinations can be specified
2932   /// here to make memory allocation more efficient.  This constructor also
2933   /// autoinserts at the end of the specified BasicBlock.
2934   IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
2935 protected:
2936   IndirectBrInst *clone_impl() const override;
2937 public:
2938   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
2939                                 Instruction *InsertBefore = nullptr) {
2940     return new IndirectBrInst(Address, NumDests, InsertBefore);
2941   }
2942   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
2943                                 BasicBlock *InsertAtEnd) {
2944     return new IndirectBrInst(Address, NumDests, InsertAtEnd);
2945   }
2946   ~IndirectBrInst();
2947
2948   /// Provide fast operand accessors.
2949   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2950
2951   // Accessor Methods for IndirectBrInst instruction.
2952   Value *getAddress() { return getOperand(0); }
2953   const Value *getAddress() const { return getOperand(0); }
2954   void setAddress(Value *V) { setOperand(0, V); }
2955
2956
2957   /// getNumDestinations - return the number of possible destinations in this
2958   /// indirectbr instruction.
2959   unsigned getNumDestinations() const { return getNumOperands()-1; }
2960
2961   /// getDestination - Return the specified destination.
2962   BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
2963   const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
2964
2965   /// addDestination - Add a destination.
2966   ///
2967   void addDestination(BasicBlock *Dest);
2968
2969   /// removeDestination - This method removes the specified successor from the
2970   /// indirectbr instruction.
2971   void removeDestination(unsigned i);
2972
2973   unsigned getNumSuccessors() const { return getNumOperands()-1; }
2974   BasicBlock *getSuccessor(unsigned i) const {
2975     return cast<BasicBlock>(getOperand(i+1));
2976   }
2977   void setSuccessor(unsigned i, BasicBlock *NewSucc) {
2978     setOperand(i+1, (Value*)NewSucc);
2979   }
2980
2981   // Methods for support type inquiry through isa, cast, and dyn_cast:
2982   static inline bool classof(const Instruction *I) {
2983     return I->getOpcode() == Instruction::IndirectBr;
2984   }
2985   static inline bool classof(const Value *V) {
2986     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2987   }
2988 private:
2989   BasicBlock *getSuccessorV(unsigned idx) const override;
2990   unsigned getNumSuccessorsV() const override;
2991   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2992 };
2993
2994 template <>
2995 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
2996 };
2997
2998 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
2999
3000
3001 //===----------------------------------------------------------------------===//
3002 //                               InvokeInst Class
3003 //===----------------------------------------------------------------------===//
3004
3005 /// InvokeInst - Invoke instruction.  The SubclassData field is used to hold the
3006 /// calling convention of the call.
3007 ///
3008 class InvokeInst : public TerminatorInst {
3009   AttributeSet AttributeList;
3010   InvokeInst(const InvokeInst &BI);
3011   void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3012             ArrayRef<Value *> Args, const Twine &NameStr);
3013
3014   /// Construct an InvokeInst given a range of arguments.
3015   ///
3016   /// \brief Construct an InvokeInst from a range of arguments
3017   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3018                     ArrayRef<Value *> Args, unsigned Values,
3019                     const Twine &NameStr, Instruction *InsertBefore);
3020
3021   /// Construct an InvokeInst given a range of arguments.
3022   ///
3023   /// \brief Construct an InvokeInst from a range of arguments
3024   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3025                     ArrayRef<Value *> Args, unsigned Values,
3026                     const Twine &NameStr, BasicBlock *InsertAtEnd);
3027 protected:
3028   InvokeInst *clone_impl() const override;
3029 public:
3030   static InvokeInst *Create(Value *Func,
3031                             BasicBlock *IfNormal, BasicBlock *IfException,
3032                             ArrayRef<Value *> Args, const Twine &NameStr = "",
3033                             Instruction *InsertBefore = nullptr) {
3034     unsigned Values = unsigned(Args.size()) + 3;
3035     return new(Values) InvokeInst(Func, IfNormal, IfException, Args,
3036                                   Values, NameStr, InsertBefore);
3037   }
3038   static InvokeInst *Create(Value *Func,
3039                             BasicBlock *IfNormal, BasicBlock *IfException,
3040                             ArrayRef<Value *> Args, const Twine &NameStr,
3041                             BasicBlock *InsertAtEnd) {
3042     unsigned Values = unsigned(Args.size()) + 3;
3043     return new(Values) InvokeInst(Func, IfNormal, IfException, Args,
3044                                   Values, NameStr, InsertAtEnd);
3045   }
3046
3047   /// Provide fast operand accessors
3048   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3049
3050   /// getNumArgOperands - Return the number of invoke arguments.
3051   ///
3052   unsigned getNumArgOperands() const { return getNumOperands() - 3; }
3053
3054   /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3055   ///
3056   Value *getArgOperand(unsigned i) const { return getOperand(i); }
3057   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
3058
3059   /// arg_operands - iteration adapter for range-for loops.
3060   iterator_range<op_iterator> arg_operands() {
3061     return iterator_range<op_iterator>(op_begin(), op_end() - 3);
3062   }
3063
3064   /// arg_operands - iteration adapter for range-for loops.
3065   iterator_range<const_op_iterator> arg_operands() const {
3066     return iterator_range<const_op_iterator>(op_begin(), op_end() - 3);
3067   }
3068
3069   /// \brief Wrappers for getting the \c Use of a invoke argument.
3070   const Use &getArgOperandUse(unsigned i) const { return getOperandUse(i); }
3071   Use &getArgOperandUse(unsigned i) { return getOperandUse(i); }
3072
3073   /// getCallingConv/setCallingConv - Get or set the calling convention of this
3074   /// function call.
3075   CallingConv::ID getCallingConv() const {
3076     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3077   }
3078   void setCallingConv(CallingConv::ID CC) {
3079     setInstructionSubclassData(static_cast<unsigned>(CC));
3080   }
3081
3082   /// getAttributes - Return the parameter attributes for this invoke.
3083   ///
3084   const AttributeSet &getAttributes() const { return AttributeList; }
3085
3086   /// setAttributes - Set the parameter attributes for this invoke.
3087   ///
3088   void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
3089
3090   /// addAttribute - adds the attribute to the list of attributes.
3091   void addAttribute(unsigned i, Attribute::AttrKind attr);
3092
3093   /// removeAttribute - removes the attribute from the list of attributes.
3094   void removeAttribute(unsigned i, Attribute attr);
3095
3096   /// \brief adds the dereferenceable attribute to the list of attributes.
3097   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3098
3099   /// \brief Determine whether this call has the given attribute.
3100   bool hasFnAttr(Attribute::AttrKind A) const {
3101     assert(A != Attribute::NoBuiltin &&
3102            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3103     return hasFnAttrImpl(A);
3104   }
3105
3106   /// \brief Determine whether the call or the callee has the given attributes.
3107   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
3108
3109   /// \brief Extract the alignment for a call or parameter (0=unknown).
3110   unsigned getParamAlignment(unsigned i) const {
3111     return AttributeList.getParamAlignment(i);
3112   }
3113
3114   /// \brief Extract the number of dereferenceable bytes for a call or
3115   /// parameter (0=unknown).
3116   uint64_t getDereferenceableBytes(unsigned i) const {
3117     return AttributeList.getDereferenceableBytes(i);
3118   }
3119
3120   /// \brief Return true if the call should not be treated as a call to a
3121   /// builtin.
3122   bool isNoBuiltin() const {
3123     // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3124     // to check it by hand.
3125     return hasFnAttrImpl(Attribute::NoBuiltin) &&
3126       !hasFnAttrImpl(Attribute::Builtin);
3127   }
3128
3129   /// \brief Return true if the call should not be inlined.
3130   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3131   void setIsNoInline() {
3132     addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
3133   }
3134
3135   /// \brief Determine if the call does not access memory.
3136   bool doesNotAccessMemory() const {
3137     return hasFnAttr(Attribute::ReadNone);
3138   }
3139   void setDoesNotAccessMemory() {
3140     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
3141   }
3142
3143   /// \brief Determine if the call does not access or only reads memory.
3144   bool onlyReadsMemory() const {
3145     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3146   }
3147   void setOnlyReadsMemory() {
3148     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
3149   }
3150
3151   /// \brief Determine if the call cannot return.
3152   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3153   void setDoesNotReturn() {
3154     addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
3155   }
3156
3157   /// \brief Determine if the call cannot unwind.
3158   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3159   void setDoesNotThrow() {
3160     addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
3161   }
3162
3163   /// \brief Determine if the invoke cannot be duplicated.
3164   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3165   void setCannotDuplicate() {
3166     addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
3167   }
3168
3169   /// \brief Determine if the call returns a structure through first
3170   /// pointer argument.
3171   bool hasStructRetAttr() const {
3172     // Be friendly and also check the callee.
3173     return paramHasAttr(1, Attribute::StructRet);
3174   }
3175
3176   /// \brief Determine if any call argument is an aggregate passed by value.
3177   bool hasByValArgument() const {
3178     return AttributeList.hasAttrSomewhere(Attribute::ByVal);
3179   }
3180
3181   /// getCalledFunction - Return the function called, or null if this is an
3182   /// indirect function invocation.
3183   ///
3184   Function *getCalledFunction() const {
3185     return dyn_cast<Function>(Op<-3>());
3186   }
3187
3188   /// getCalledValue - Get a pointer to the function that is invoked by this
3189   /// instruction
3190   const Value *getCalledValue() const { return Op<-3>(); }
3191         Value *getCalledValue()       { return Op<-3>(); }
3192
3193   /// setCalledFunction - Set the function called.
3194   void setCalledFunction(Value* Fn) {
3195     Op<-3>() = Fn;
3196   }
3197
3198   // get*Dest - Return the destination basic blocks...
3199   BasicBlock *getNormalDest() const {
3200     return cast<BasicBlock>(Op<-2>());
3201   }
3202   BasicBlock *getUnwindDest() const {
3203     return cast<BasicBlock>(Op<-1>());
3204   }
3205   void setNormalDest(BasicBlock *B) {
3206     Op<-2>() = reinterpret_cast<Value*>(B);
3207   }
3208   void setUnwindDest(BasicBlock *B) {
3209     Op<-1>() = reinterpret_cast<Value*>(B);
3210   }
3211
3212   /// getLandingPadInst - Get the landingpad instruction from the landing pad
3213   /// block (the unwind destination).
3214   LandingPadInst *getLandingPadInst() const;
3215
3216   BasicBlock *getSuccessor(unsigned i) const {
3217     assert(i < 2 && "Successor # out of range for invoke!");
3218     return i == 0 ? getNormalDest() : getUnwindDest();
3219   }
3220
3221   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3222     assert(idx < 2 && "Successor # out of range for invoke!");
3223     *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
3224   }
3225
3226   unsigned getNumSuccessors() const { return 2; }
3227
3228   // Methods for support type inquiry through isa, cast, and dyn_cast:
3229   static inline bool classof(const Instruction *I) {
3230     return (I->getOpcode() == Instruction::Invoke);
3231   }
3232   static inline bool classof(const Value *V) {
3233     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3234   }
3235
3236 private:
3237   BasicBlock *getSuccessorV(unsigned idx) const override;
3238   unsigned getNumSuccessorsV() const override;
3239   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3240
3241   bool hasFnAttrImpl(Attribute::AttrKind A) const;
3242
3243   // Shadow Instruction::setInstructionSubclassData with a private forwarding
3244   // method so that subclasses cannot accidentally use it.
3245   void setInstructionSubclassData(unsigned short D) {
3246     Instruction::setInstructionSubclassData(D);
3247   }
3248 };
3249
3250 template <>
3251 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
3252 };
3253
3254 InvokeInst::InvokeInst(Value *Func,
3255                        BasicBlock *IfNormal, BasicBlock *IfException,
3256                        ArrayRef<Value *> Args, unsigned Values,
3257                        const Twine &NameStr, Instruction *InsertBefore)
3258   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Func->getType())
3259                                       ->getElementType())->getReturnType(),
3260                    Instruction::Invoke,
3261                    OperandTraits<InvokeInst>::op_end(this) - Values,
3262                    Values, InsertBefore) {
3263   init(Func, IfNormal, IfException, Args, NameStr);
3264 }
3265 InvokeInst::InvokeInst(Value *Func,
3266                        BasicBlock *IfNormal, BasicBlock *IfException,
3267                        ArrayRef<Value *> Args, unsigned Values,
3268                        const Twine &NameStr, BasicBlock *InsertAtEnd)
3269   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Func->getType())
3270                                       ->getElementType())->getReturnType(),
3271                    Instruction::Invoke,
3272                    OperandTraits<InvokeInst>::op_end(this) - Values,
3273                    Values, InsertAtEnd) {
3274   init(Func, IfNormal, IfException, Args, NameStr);
3275 }
3276
3277 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
3278
3279 //===----------------------------------------------------------------------===//
3280 //                              ResumeInst Class
3281 //===----------------------------------------------------------------------===//
3282
3283 //===---------------------------------------------------------------------------
3284 /// ResumeInst - Resume the propagation of an exception.
3285 ///
3286 class ResumeInst : public TerminatorInst {
3287   ResumeInst(const ResumeInst &RI);
3288
3289   explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
3290   ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
3291 protected:
3292   ResumeInst *clone_impl() const override;
3293 public:
3294   static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
3295     return new(1) ResumeInst(Exn, InsertBefore);
3296   }
3297   static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
3298     return new(1) ResumeInst(Exn, InsertAtEnd);
3299   }
3300
3301   /// Provide fast operand accessors
3302   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3303
3304   /// Convenience accessor.
3305   Value *getValue() const { return Op<0>(); }
3306
3307   unsigned getNumSuccessors() const { return 0; }
3308
3309   // Methods for support type inquiry through isa, cast, and dyn_cast:
3310   static inline bool classof(const Instruction *I) {
3311     return I->getOpcode() == Instruction::Resume;
3312   }
3313   static inline bool classof(const Value *V) {
3314     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3315   }
3316 private:
3317   BasicBlock *getSuccessorV(unsigned idx) const override;
3318   unsigned getNumSuccessorsV() const override;
3319   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3320 };
3321
3322 template <>
3323 struct OperandTraits<ResumeInst> :
3324     public FixedNumOperandTraits<ResumeInst, 1> {
3325 };
3326
3327 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
3328
3329 //===----------------------------------------------------------------------===//
3330 //                           UnreachableInst Class
3331 //===----------------------------------------------------------------------===//
3332
3333 //===---------------------------------------------------------------------------
3334 /// UnreachableInst - This function has undefined behavior.  In particular, the
3335 /// presence of this instruction indicates some higher level knowledge that the
3336 /// end of the block cannot be reached.
3337 ///
3338 class UnreachableInst : public TerminatorInst {
3339   void *operator new(size_t, unsigned) = delete;
3340 protected:
3341   UnreachableInst *clone_impl() const override;
3342
3343 public:
3344   // allocate space for exactly zero operands
3345   void *operator new(size_t s) {
3346     return User::operator new(s, 0);
3347   }
3348   explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
3349   explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
3350
3351   unsigned getNumSuccessors() const { return 0; }
3352
3353   // Methods for support type inquiry through isa, cast, and dyn_cast:
3354   static inline bool classof(const Instruction *I) {
3355     return I->getOpcode() == Instruction::Unreachable;
3356   }
3357   static inline bool classof(const Value *V) {
3358     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3359   }
3360 private:
3361   BasicBlock *getSuccessorV(unsigned idx) const override;
3362   unsigned getNumSuccessorsV() const override;
3363   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3364 };
3365
3366 //===----------------------------------------------------------------------===//
3367 //                                 TruncInst Class
3368 //===----------------------------------------------------------------------===//
3369
3370 /// \brief This class represents a truncation of integer types.
3371 class TruncInst : public CastInst {
3372 protected:
3373   /// \brief Clone an identical TruncInst
3374   TruncInst *clone_impl() const override;
3375
3376 public:
3377   /// \brief Constructor with insert-before-instruction semantics
3378   TruncInst(
3379     Value *S,                           ///< The value to be truncated
3380     Type *Ty,                           ///< The (smaller) type to truncate to
3381     const Twine &NameStr = "",          ///< A name for the new instruction
3382     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3383   );
3384
3385   /// \brief Constructor with insert-at-end-of-block semantics
3386   TruncInst(
3387     Value *S,                     ///< The value to be truncated
3388     Type *Ty,                     ///< The (smaller) type to truncate to
3389     const Twine &NameStr,         ///< A name for the new instruction
3390     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3391   );
3392
3393   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3394   static inline bool classof(const Instruction *I) {
3395     return I->getOpcode() == Trunc;
3396   }
3397   static inline bool classof(const Value *V) {
3398     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3399   }
3400 };
3401
3402 //===----------------------------------------------------------------------===//
3403 //                                 ZExtInst Class
3404 //===----------------------------------------------------------------------===//
3405
3406 /// \brief This class represents zero extension of integer types.
3407 class ZExtInst : public CastInst {
3408 protected:
3409   /// \brief Clone an identical ZExtInst
3410   ZExtInst *clone_impl() const override;
3411
3412 public:
3413   /// \brief Constructor with insert-before-instruction semantics
3414   ZExtInst(
3415     Value *S,                           ///< The value to be zero extended
3416     Type *Ty,                           ///< The type to zero extend to
3417     const Twine &NameStr = "",          ///< A name for the new instruction
3418     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3419   );
3420
3421   /// \brief Constructor with insert-at-end semantics.
3422   ZExtInst(
3423     Value *S,                     ///< The value to be zero extended
3424     Type *Ty,                     ///< The type to zero extend to
3425     const Twine &NameStr,         ///< A name for the new instruction
3426     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3427   );
3428
3429   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3430   static inline bool classof(const Instruction *I) {
3431     return I->getOpcode() == ZExt;
3432   }
3433   static inline bool classof(const Value *V) {
3434     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3435   }
3436 };
3437
3438 //===----------------------------------------------------------------------===//
3439 //                                 SExtInst Class
3440 //===----------------------------------------------------------------------===//
3441
3442 /// \brief This class represents a sign extension of integer types.
3443 class SExtInst : public CastInst {
3444 protected:
3445   /// \brief Clone an identical SExtInst
3446   SExtInst *clone_impl() const override;
3447
3448 public:
3449   /// \brief Constructor with insert-before-instruction semantics
3450   SExtInst(
3451     Value *S,                           ///< The value to be sign extended
3452     Type *Ty,                           ///< The type to sign extend to
3453     const Twine &NameStr = "",          ///< A name for the new instruction
3454     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3455   );
3456
3457   /// \brief Constructor with insert-at-end-of-block semantics
3458   SExtInst(
3459     Value *S,                     ///< The value to be sign extended
3460     Type *Ty,                     ///< The type to sign extend to
3461     const Twine &NameStr,         ///< A name for the new instruction
3462     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3463   );
3464
3465   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3466   static inline bool classof(const Instruction *I) {
3467     return I->getOpcode() == SExt;
3468   }
3469   static inline bool classof(const Value *V) {
3470     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3471   }
3472 };
3473
3474 //===----------------------------------------------------------------------===//
3475 //                                 FPTruncInst Class
3476 //===----------------------------------------------------------------------===//
3477
3478 /// \brief This class represents a truncation of floating point types.
3479 class FPTruncInst : public CastInst {
3480 protected:
3481   /// \brief Clone an identical FPTruncInst
3482   FPTruncInst *clone_impl() const override;
3483
3484 public:
3485   /// \brief Constructor with insert-before-instruction semantics
3486   FPTruncInst(
3487     Value *S,                           ///< The value to be truncated
3488     Type *Ty,                           ///< The type to truncate to
3489     const Twine &NameStr = "",          ///< A name for the new instruction
3490     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3491   );
3492
3493   /// \brief Constructor with insert-before-instruction semantics
3494   FPTruncInst(
3495     Value *S,                     ///< The value to be truncated
3496     Type *Ty,                     ///< The type to truncate to
3497     const Twine &NameStr,         ///< A name for the new instruction
3498     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3499   );
3500
3501   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3502   static inline bool classof(const Instruction *I) {
3503     return I->getOpcode() == FPTrunc;
3504   }
3505   static inline bool classof(const Value *V) {
3506     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3507   }
3508 };
3509
3510 //===----------------------------------------------------------------------===//
3511 //                                 FPExtInst Class
3512 //===----------------------------------------------------------------------===//
3513
3514 /// \brief This class represents an extension of floating point types.
3515 class FPExtInst : public CastInst {
3516 protected:
3517   /// \brief Clone an identical FPExtInst
3518   FPExtInst *clone_impl() const override;
3519
3520 public:
3521   /// \brief Constructor with insert-before-instruction semantics
3522   FPExtInst(
3523     Value *S,                           ///< The value to be extended
3524     Type *Ty,                           ///< The type to extend to
3525     const Twine &NameStr = "",          ///< A name for the new instruction
3526     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3527   );
3528
3529   /// \brief Constructor with insert-at-end-of-block semantics
3530   FPExtInst(
3531     Value *S,                     ///< The value to be extended
3532     Type *Ty,                     ///< The type to extend to
3533     const Twine &NameStr,         ///< A name for the new instruction
3534     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3535   );
3536
3537   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3538   static inline bool classof(const Instruction *I) {
3539     return I->getOpcode() == FPExt;
3540   }
3541   static inline bool classof(const Value *V) {
3542     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3543   }
3544 };
3545
3546 //===----------------------------------------------------------------------===//
3547 //                                 UIToFPInst Class
3548 //===----------------------------------------------------------------------===//
3549
3550 /// \brief This class represents a cast unsigned integer to floating point.
3551 class UIToFPInst : public CastInst {
3552 protected:
3553   /// \brief Clone an identical UIToFPInst
3554   UIToFPInst *clone_impl() const override;
3555
3556 public:
3557   /// \brief Constructor with insert-before-instruction semantics
3558   UIToFPInst(
3559     Value *S,                           ///< The value to be converted
3560     Type *Ty,                           ///< The type to convert to
3561     const Twine &NameStr = "",          ///< A name for the new instruction
3562     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3563   );
3564
3565   /// \brief Constructor with insert-at-end-of-block semantics
3566   UIToFPInst(
3567     Value *S,                     ///< The value to be converted
3568     Type *Ty,                     ///< The type to convert to
3569     const Twine &NameStr,         ///< A name for the new instruction
3570     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3571   );
3572
3573   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3574   static inline bool classof(const Instruction *I) {
3575     return I->getOpcode() == UIToFP;
3576   }
3577   static inline bool classof(const Value *V) {
3578     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3579   }
3580 };
3581
3582 //===----------------------------------------------------------------------===//
3583 //                                 SIToFPInst Class
3584 //===----------------------------------------------------------------------===//
3585
3586 /// \brief This class represents a cast from signed integer to floating point.
3587 class SIToFPInst : public CastInst {
3588 protected:
3589   /// \brief Clone an identical SIToFPInst
3590   SIToFPInst *clone_impl() const override;
3591
3592 public:
3593   /// \brief Constructor with insert-before-instruction semantics
3594   SIToFPInst(
3595     Value *S,                           ///< The value to be converted
3596     Type *Ty,                           ///< The type to convert to
3597     const Twine &NameStr = "",          ///< A name for the new instruction
3598     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3599   );
3600
3601   /// \brief Constructor with insert-at-end-of-block semantics
3602   SIToFPInst(
3603     Value *S,                     ///< The value to be converted
3604     Type *Ty,                     ///< The type to convert to
3605     const Twine &NameStr,         ///< A name for the new instruction
3606     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3607   );
3608
3609   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3610   static inline bool classof(const Instruction *I) {
3611     return I->getOpcode() == SIToFP;
3612   }
3613   static inline bool classof(const Value *V) {
3614     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3615   }
3616 };
3617
3618 //===----------------------------------------------------------------------===//
3619 //                                 FPToUIInst Class
3620 //===----------------------------------------------------------------------===//
3621
3622 /// \brief This class represents a cast from floating point to unsigned integer
3623 class FPToUIInst  : public CastInst {
3624 protected:
3625   /// \brief Clone an identical FPToUIInst
3626   FPToUIInst *clone_impl() const override;
3627
3628 public:
3629   /// \brief Constructor with insert-before-instruction semantics
3630   FPToUIInst(
3631     Value *S,                           ///< The value to be converted
3632     Type *Ty,                           ///< The type to convert to
3633     const Twine &NameStr = "",          ///< A name for the new instruction
3634     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3635   );
3636
3637   /// \brief Constructor with insert-at-end-of-block semantics
3638   FPToUIInst(
3639     Value *S,                     ///< The value to be converted
3640     Type *Ty,                     ///< The type to convert to
3641     const Twine &NameStr,         ///< A name for the new instruction
3642     BasicBlock *InsertAtEnd       ///< Where to insert the new instruction
3643   );
3644
3645   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3646   static inline bool classof(const Instruction *I) {
3647     return I->getOpcode() == FPToUI;
3648   }
3649   static inline bool classof(const Value *V) {
3650     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3651   }
3652 };
3653
3654 //===----------------------------------------------------------------------===//
3655 //                                 FPToSIInst Class
3656 //===----------------------------------------------------------------------===//
3657
3658 /// \brief This class represents a cast from floating point to signed integer.
3659 class FPToSIInst  : public CastInst {
3660 protected:
3661   /// \brief Clone an identical FPToSIInst
3662   FPToSIInst *clone_impl() const override;
3663
3664 public:
3665   /// \brief Constructor with insert-before-instruction semantics
3666   FPToSIInst(
3667     Value *S,                           ///< The value to be converted
3668     Type *Ty,                           ///< The type to convert to
3669     const Twine &NameStr = "",          ///< A name for the new instruction
3670     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3671   );
3672
3673   /// \brief Constructor with insert-at-end-of-block semantics
3674   FPToSIInst(
3675     Value *S,                     ///< The value to be converted
3676     Type *Ty,                     ///< The type to convert to
3677     const Twine &NameStr,         ///< A name for the new instruction
3678     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3679   );
3680
3681   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
3682   static inline bool classof(const Instruction *I) {
3683     return I->getOpcode() == FPToSI;
3684   }
3685   static inline bool classof(const Value *V) {
3686     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3687   }
3688 };
3689
3690 //===----------------------------------------------------------------------===//
3691 //                                 IntToPtrInst Class
3692 //===----------------------------------------------------------------------===//
3693
3694 /// \brief This class represents a cast from an integer to a pointer.
3695 class IntToPtrInst : public CastInst {
3696 public:
3697   /// \brief Constructor with insert-before-instruction semantics
3698   IntToPtrInst(
3699     Value *S,                           ///< The value to be converted
3700     Type *Ty,                           ///< The type to convert to
3701     const Twine &NameStr = "",          ///< A name for the new instruction
3702     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3703   );
3704
3705   /// \brief Constructor with insert-at-end-of-block semantics
3706   IntToPtrInst(
3707     Value *S,                     ///< The value to be converted
3708     Type *Ty,                     ///< The type to convert to
3709     const Twine &NameStr,         ///< A name for the new instruction
3710     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3711   );
3712
3713   /// \brief Clone an identical IntToPtrInst
3714   IntToPtrInst *clone_impl() const override;
3715
3716   /// \brief Returns the address space of this instruction's pointer type.
3717   unsigned getAddressSpace() const {
3718     return getType()->getPointerAddressSpace();
3719   }
3720
3721   // Methods for support type inquiry through isa, cast, and dyn_cast:
3722   static inline bool classof(const Instruction *I) {
3723     return I->getOpcode() == IntToPtr;
3724   }
3725   static inline bool classof(const Value *V) {
3726     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3727   }
3728 };
3729
3730 //===----------------------------------------------------------------------===//
3731 //                                 PtrToIntInst Class
3732 //===----------------------------------------------------------------------===//
3733
3734 /// \brief This class represents a cast from a pointer to an integer
3735 class PtrToIntInst : public CastInst {
3736 protected:
3737   /// \brief Clone an identical PtrToIntInst
3738   PtrToIntInst *clone_impl() const override;
3739
3740 public:
3741   /// \brief Constructor with insert-before-instruction semantics
3742   PtrToIntInst(
3743     Value *S,                           ///< The value to be converted
3744     Type *Ty,                           ///< The type to convert to
3745     const Twine &NameStr = "",          ///< A name for the new instruction
3746     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3747   );
3748
3749   /// \brief Constructor with insert-at-end-of-block semantics
3750   PtrToIntInst(
3751     Value *S,                     ///< The value to be converted
3752     Type *Ty,                     ///< The type to convert to
3753     const Twine &NameStr,         ///< A name for the new instruction
3754     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3755   );
3756
3757   /// \brief Gets the pointer operand.
3758   Value *getPointerOperand() { return getOperand(0); }
3759   /// \brief Gets the pointer operand.
3760   const Value *getPointerOperand() const { return getOperand(0); }
3761   /// \brief Gets the operand index of the pointer operand.
3762   static unsigned getPointerOperandIndex() { return 0U; }
3763
3764   /// \brief Returns the address space of the pointer operand.
3765   unsigned getPointerAddressSpace() const {
3766     return getPointerOperand()->getType()->getPointerAddressSpace();
3767   }
3768
3769   // Methods for support type inquiry through isa, cast, and dyn_cast:
3770   static inline bool classof(const Instruction *I) {
3771     return I->getOpcode() == PtrToInt;
3772   }
3773   static inline bool classof(const Value *V) {
3774     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3775   }
3776 };
3777
3778 //===----------------------------------------------------------------------===//
3779 //                             BitCastInst Class
3780 //===----------------------------------------------------------------------===//
3781
3782 /// \brief This class represents a no-op cast from one type to another.
3783 class BitCastInst : public CastInst {
3784 protected:
3785   /// \brief Clone an identical BitCastInst
3786   BitCastInst *clone_impl() const override;
3787
3788 public:
3789   /// \brief Constructor with insert-before-instruction semantics
3790   BitCastInst(
3791     Value *S,                           ///< The value to be casted
3792     Type *Ty,                           ///< The type to casted to
3793     const Twine &NameStr = "",          ///< A name for the new instruction
3794     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3795   );
3796
3797   /// \brief Constructor with insert-at-end-of-block semantics
3798   BitCastInst(
3799     Value *S,                     ///< The value to be casted
3800     Type *Ty,                     ///< The type to casted to
3801     const Twine &NameStr,         ///< A name for the new instruction
3802     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3803   );
3804
3805   // Methods for support type inquiry through isa, cast, and dyn_cast:
3806   static inline bool classof(const Instruction *I) {
3807     return I->getOpcode() == BitCast;
3808   }
3809   static inline bool classof(const Value *V) {
3810     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3811   }
3812 };
3813
3814 //===----------------------------------------------------------------------===//
3815 //                          AddrSpaceCastInst Class
3816 //===----------------------------------------------------------------------===//
3817
3818 /// \brief This class represents a conversion between pointers from
3819 /// one address space to another.
3820 class AddrSpaceCastInst : public CastInst {
3821 protected:
3822   /// \brief Clone an identical AddrSpaceCastInst
3823   AddrSpaceCastInst *clone_impl() const override;
3824
3825 public:
3826   /// \brief Constructor with insert-before-instruction semantics
3827   AddrSpaceCastInst(
3828     Value *S,                           ///< The value to be casted
3829     Type *Ty,                           ///< The type to casted to
3830     const Twine &NameStr = "",          ///< A name for the new instruction
3831     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
3832   );
3833
3834   /// \brief Constructor with insert-at-end-of-block semantics
3835   AddrSpaceCastInst(
3836     Value *S,                     ///< The value to be casted
3837     Type *Ty,                     ///< The type to casted to
3838     const Twine &NameStr,         ///< A name for the new instruction
3839     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3840   );
3841
3842   // Methods for support type inquiry through isa, cast, and dyn_cast:
3843   static inline bool classof(const Instruction *I) {
3844     return I->getOpcode() == AddrSpaceCast;
3845   }
3846   static inline bool classof(const Value *V) {
3847     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3848   }
3849 };
3850
3851 } // End llvm namespace
3852
3853 #endif