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