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