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