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