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