Add arg_begin() and arg_end() to CallInst and InvokeInst; NFCI
[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   /// \brief Return the iterator pointing to the beginning of the argument list.
1547   op_iterator arg_begin() { return op_begin(); }
1548
1549   /// \brief Return the iterator pointing to the end of the argument list.
1550   op_iterator arg_end() {
1551     // [ call args ], [ operand bundles ], callee
1552     return op_end() - getNumTotalBundleOperands() - 1;
1553   };
1554
1555   /// \brief Iteration adapter for range-for loops.
1556   iterator_range<op_iterator> arg_operands() {
1557     return make_range(arg_begin(), arg_end());
1558   }
1559
1560   /// \brief Return the iterator pointing to the beginning of the argument list.
1561   const_op_iterator arg_begin() const { return op_begin(); }
1562
1563   /// \brief Return the iterator pointing to the end of the argument list.
1564   const_op_iterator arg_end() const {
1565     // [ call args ], [ operand bundles ], callee
1566     return op_end() - getNumTotalBundleOperands() - 1;
1567   };
1568
1569   /// \brief Iteration adapter for range-for loops.
1570   iterator_range<const_op_iterator> arg_operands() const {
1571     return make_range(arg_begin(), arg_end());
1572   }
1573
1574   /// \brief Wrappers for getting the \c Use of a call argument.
1575   const Use &getArgOperandUse(unsigned i) const {
1576     assert(i < getNumArgOperands() && "Out of bounds!");
1577     return getOperandUse(i);
1578   }
1579   Use &getArgOperandUse(unsigned i) {
1580     assert(i < getNumArgOperands() && "Out of bounds!");
1581     return getOperandUse(i);
1582   }
1583
1584   /// getCallingConv/setCallingConv - Get or set the calling convention of this
1585   /// function call.
1586   CallingConv::ID getCallingConv() const {
1587     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1588   }
1589   void setCallingConv(CallingConv::ID CC) {
1590     auto ID = static_cast<unsigned>(CC);
1591     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1592     setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1593                                (ID << 2));
1594   }
1595
1596   /// getAttributes - Return the parameter attributes for this call.
1597   ///
1598   const AttributeSet &getAttributes() const { return AttributeList; }
1599
1600   /// setAttributes - Set the parameter attributes for this call.
1601   ///
1602   void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
1603
1604   /// addAttribute - adds the attribute to the list of attributes.
1605   void addAttribute(unsigned i, Attribute::AttrKind attr);
1606
1607   /// addAttribute - adds the attribute to the list of attributes.
1608   void addAttribute(unsigned i, StringRef Kind, StringRef Value);
1609
1610   /// removeAttribute - removes the attribute from the list of attributes.
1611   void removeAttribute(unsigned i, Attribute attr);
1612
1613   /// \brief adds the dereferenceable attribute to the list of attributes.
1614   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1615
1616   /// \brief adds the dereferenceable_or_null attribute to the list of
1617   /// attributes.
1618   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1619
1620   /// \brief Determine whether this call has the given attribute.
1621   bool hasFnAttr(Attribute::AttrKind A) const {
1622     assert(A != Attribute::NoBuiltin &&
1623            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1624     return hasFnAttrImpl(A);
1625   }
1626
1627   /// \brief Determine whether this call has the given attribute.
1628   bool hasFnAttr(StringRef A) const {
1629     return hasFnAttrImpl(A);
1630   }
1631
1632   /// \brief Determine whether the call or the callee has the given attributes.
1633   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
1634
1635   /// \brief Return true if the data operand at index \p i has the attribute \p
1636   /// A.
1637   ///
1638   /// Data operands include call arguments and values used in operand bundles,
1639   /// but does not include the callee operand.  This routine dispatches to the
1640   /// underlying AttributeList or the OperandBundleUser as appropriate.
1641   ///
1642   /// The index \p i is interpreted as
1643   ///
1644   ///  \p i == Attribute::ReturnIndex  -> the return value
1645   ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
1646   ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1647   ///     (\p i - 1) in the operand list.
1648   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind A) const;
1649
1650   /// \brief Extract the alignment for a call or parameter (0=unknown).
1651   unsigned getParamAlignment(unsigned i) const {
1652     return AttributeList.getParamAlignment(i);
1653   }
1654
1655   /// \brief Extract the number of dereferenceable bytes for a call or
1656   /// parameter (0=unknown).
1657   uint64_t getDereferenceableBytes(unsigned i) const {
1658     return AttributeList.getDereferenceableBytes(i);
1659   }
1660
1661   /// \brief Extract the number of dereferenceable_or_null bytes for a call or
1662   /// parameter (0=unknown).
1663   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1664     return AttributeList.getDereferenceableOrNullBytes(i);
1665   }
1666
1667   /// @brief Determine if the parameter or return value is marked with NoAlias
1668   /// attribute.
1669   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
1670   bool doesNotAlias(unsigned n) const {
1671     return AttributeList.hasAttribute(n, Attribute::NoAlias);
1672   }
1673
1674   /// \brief Return true if the call should not be treated as a call to a
1675   /// builtin.
1676   bool isNoBuiltin() const {
1677     return hasFnAttrImpl(Attribute::NoBuiltin) &&
1678       !hasFnAttrImpl(Attribute::Builtin);
1679   }
1680
1681   /// \brief Return true if the call should not be inlined.
1682   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1683   void setIsNoInline() {
1684     addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
1685   }
1686
1687   /// \brief Return true if the call can return twice
1688   bool canReturnTwice() const {
1689     return hasFnAttr(Attribute::ReturnsTwice);
1690   }
1691   void setCanReturnTwice() {
1692     addAttribute(AttributeSet::FunctionIndex, Attribute::ReturnsTwice);
1693   }
1694
1695   /// \brief Determine if the call does not access memory.
1696   bool doesNotAccessMemory() const {
1697     return hasFnAttr(Attribute::ReadNone);
1698   }
1699   void setDoesNotAccessMemory() {
1700     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
1701   }
1702
1703   /// \brief Determine if the call does not access or only reads memory.
1704   bool onlyReadsMemory() const {
1705     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1706   }
1707   void setOnlyReadsMemory() {
1708     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
1709   }
1710
1711   /// @brief Determine if the call can access memmory only using pointers based
1712   /// on its arguments.
1713   bool onlyAccessesArgMemory() const {
1714     return hasFnAttr(Attribute::ArgMemOnly);
1715   }
1716   void setOnlyAccessesArgMemory() {
1717     addAttribute(AttributeSet::FunctionIndex, Attribute::ArgMemOnly);
1718   }
1719
1720   /// \brief Determine if the call cannot return.
1721   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1722   void setDoesNotReturn() {
1723     addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
1724   }
1725
1726   /// \brief Determine if the call cannot unwind.
1727   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1728   void setDoesNotThrow() {
1729     addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
1730   }
1731
1732   /// \brief Determine if the call cannot be duplicated.
1733   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1734   void setCannotDuplicate() {
1735     addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
1736   }
1737
1738   /// \brief Determine if the call is convergent
1739   bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1740   void setConvergent() {
1741     addAttribute(AttributeSet::FunctionIndex, Attribute::Convergent);
1742   }
1743
1744   /// \brief Determine if the call returns a structure through first
1745   /// pointer argument.
1746   bool hasStructRetAttr() const {
1747     if (getNumArgOperands() == 0)
1748       return false;
1749
1750     // Be friendly and also check the callee.
1751     return paramHasAttr(1, Attribute::StructRet);
1752   }
1753
1754   /// \brief Determine if any call argument is an aggregate passed by value.
1755   bool hasByValArgument() const {
1756     return AttributeList.hasAttrSomewhere(Attribute::ByVal);
1757   }
1758
1759   /// getCalledFunction - Return the function called, or null if this is an
1760   /// indirect function invocation.
1761   ///
1762   Function *getCalledFunction() const {
1763     return dyn_cast<Function>(Op<-1>());
1764   }
1765
1766   /// getCalledValue - Get a pointer to the function that is invoked by this
1767   /// instruction.
1768   const Value *getCalledValue() const { return Op<-1>(); }
1769         Value *getCalledValue()       { return Op<-1>(); }
1770
1771   /// setCalledFunction - Set the function called.
1772   void setCalledFunction(Value* Fn) {
1773     setCalledFunction(
1774         cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1775         Fn);
1776   }
1777   void setCalledFunction(FunctionType *FTy, Value *Fn) {
1778     this->FTy = FTy;
1779     assert(FTy == cast<FunctionType>(
1780                       cast<PointerType>(Fn->getType())->getElementType()));
1781     Op<-1>() = Fn;
1782   }
1783
1784   /// isInlineAsm - Check if this call is an inline asm statement.
1785   bool isInlineAsm() const {
1786     return isa<InlineAsm>(Op<-1>());
1787   }
1788
1789   // Methods for support type inquiry through isa, cast, and dyn_cast:
1790   static inline bool classof(const Instruction *I) {
1791     return I->getOpcode() == Instruction::Call;
1792   }
1793   static inline bool classof(const Value *V) {
1794     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1795   }
1796
1797 private:
1798   template <typename AttrKind> bool hasFnAttrImpl(AttrKind A) const {
1799     if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
1800       return true;
1801
1802     // Operand bundles override attributes on the called function, but don't
1803     // override attributes directly present on the call instruction.
1804     if (isFnAttrDisallowedByOpBundle(A))
1805       return false;
1806
1807     if (const Function *F = getCalledFunction())
1808       return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
1809     return false;
1810   }
1811
1812   // Shadow Instruction::setInstructionSubclassData with a private forwarding
1813   // method so that subclasses cannot accidentally use it.
1814   void setInstructionSubclassData(unsigned short D) {
1815     Instruction::setInstructionSubclassData(D);
1816   }
1817 };
1818
1819 template <>
1820 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1821 };
1822
1823 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1824                    ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1825                    BasicBlock *InsertAtEnd)
1826     : Instruction(
1827           cast<FunctionType>(cast<PointerType>(Func->getType())
1828                                  ->getElementType())->getReturnType(),
1829           Instruction::Call, OperandTraits<CallInst>::op_end(this) -
1830                                  (Args.size() + CountBundleInputs(Bundles) + 1),
1831           unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1832   init(Func, Args, Bundles, NameStr);
1833 }
1834
1835 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1836                    ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1837                    Instruction *InsertBefore)
1838     : Instruction(Ty->getReturnType(), Instruction::Call,
1839                   OperandTraits<CallInst>::op_end(this) -
1840                       (Args.size() + CountBundleInputs(Bundles) + 1),
1841                   unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1842                   InsertBefore) {
1843   init(Ty, Func, Args, Bundles, NameStr);
1844 }
1845
1846 // Note: if you get compile errors about private methods then
1847 //       please update your code to use the high-level operand
1848 //       interfaces. See line 943 above.
1849 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1850
1851 //===----------------------------------------------------------------------===//
1852 //                               SelectInst Class
1853 //===----------------------------------------------------------------------===//
1854
1855 /// SelectInst - This class represents the LLVM 'select' instruction.
1856 ///
1857 class SelectInst : public Instruction {
1858   void init(Value *C, Value *S1, Value *S2) {
1859     assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1860     Op<0>() = C;
1861     Op<1>() = S1;
1862     Op<2>() = S2;
1863   }
1864
1865   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1866              Instruction *InsertBefore)
1867     : Instruction(S1->getType(), Instruction::Select,
1868                   &Op<0>(), 3, InsertBefore) {
1869     init(C, S1, S2);
1870     setName(NameStr);
1871   }
1872   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1873              BasicBlock *InsertAtEnd)
1874     : Instruction(S1->getType(), Instruction::Select,
1875                   &Op<0>(), 3, InsertAtEnd) {
1876     init(C, S1, S2);
1877     setName(NameStr);
1878   }
1879
1880 protected:
1881   // Note: Instruction needs to be a friend here to call cloneImpl.
1882   friend class Instruction;
1883   SelectInst *cloneImpl() const;
1884
1885 public:
1886   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1887                             const Twine &NameStr = "",
1888                             Instruction *InsertBefore = nullptr) {
1889     return new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1890   }
1891   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1892                             const Twine &NameStr,
1893                             BasicBlock *InsertAtEnd) {
1894     return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1895   }
1896
1897   const Value *getCondition() const { return Op<0>(); }
1898   const Value *getTrueValue() const { return Op<1>(); }
1899   const Value *getFalseValue() const { return Op<2>(); }
1900   Value *getCondition() { return Op<0>(); }
1901   Value *getTrueValue() { return Op<1>(); }
1902   Value *getFalseValue() { return Op<2>(); }
1903
1904   /// areInvalidOperands - Return a string if the specified operands are invalid
1905   /// for a select operation, otherwise return null.
1906   static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1907
1908   /// Transparently provide more efficient getOperand methods.
1909   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1910
1911   OtherOps getOpcode() const {
1912     return static_cast<OtherOps>(Instruction::getOpcode());
1913   }
1914
1915   // Methods for support type inquiry through isa, cast, and dyn_cast:
1916   static inline bool classof(const Instruction *I) {
1917     return I->getOpcode() == Instruction::Select;
1918   }
1919   static inline bool classof(const Value *V) {
1920     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1921   }
1922 };
1923
1924 template <>
1925 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1926 };
1927
1928 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1929
1930 //===----------------------------------------------------------------------===//
1931 //                                VAArgInst Class
1932 //===----------------------------------------------------------------------===//
1933
1934 /// VAArgInst - This class represents the va_arg llvm instruction, which returns
1935 /// an argument of the specified type given a va_list and increments that list
1936 ///
1937 class VAArgInst : public UnaryInstruction {
1938 protected:
1939   // Note: Instruction needs to be a friend here to call cloneImpl.
1940   friend class Instruction;
1941   VAArgInst *cloneImpl() const;
1942
1943 public:
1944   VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1945              Instruction *InsertBefore = nullptr)
1946     : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1947     setName(NameStr);
1948   }
1949   VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1950             BasicBlock *InsertAtEnd)
1951     : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1952     setName(NameStr);
1953   }
1954
1955   Value *getPointerOperand() { return getOperand(0); }
1956   const Value *getPointerOperand() const { return getOperand(0); }
1957   static unsigned getPointerOperandIndex() { return 0U; }
1958
1959   // Methods for support type inquiry through isa, cast, and dyn_cast:
1960   static inline bool classof(const Instruction *I) {
1961     return I->getOpcode() == VAArg;
1962   }
1963   static inline bool classof(const Value *V) {
1964     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1965   }
1966 };
1967
1968 //===----------------------------------------------------------------------===//
1969 //                                ExtractElementInst Class
1970 //===----------------------------------------------------------------------===//
1971
1972 /// ExtractElementInst - This instruction extracts a single (scalar)
1973 /// element from a VectorType value
1974 ///
1975 class ExtractElementInst : public Instruction {
1976   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1977                      Instruction *InsertBefore = nullptr);
1978   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1979                      BasicBlock *InsertAtEnd);
1980
1981 protected:
1982   // Note: Instruction needs to be a friend here to call cloneImpl.
1983   friend class Instruction;
1984   ExtractElementInst *cloneImpl() const;
1985
1986 public:
1987   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1988                                    const Twine &NameStr = "",
1989                                    Instruction *InsertBefore = nullptr) {
1990     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1991   }
1992   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1993                                    const Twine &NameStr,
1994                                    BasicBlock *InsertAtEnd) {
1995     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1996   }
1997
1998   /// isValidOperands - Return true if an extractelement instruction can be
1999   /// formed with the specified operands.
2000   static bool isValidOperands(const Value *Vec, const Value *Idx);
2001
2002   Value *getVectorOperand() { return Op<0>(); }
2003   Value *getIndexOperand() { return Op<1>(); }
2004   const Value *getVectorOperand() const { return Op<0>(); }
2005   const Value *getIndexOperand() const { return Op<1>(); }
2006
2007   VectorType *getVectorOperandType() const {
2008     return cast<VectorType>(getVectorOperand()->getType());
2009   }
2010
2011   /// Transparently provide more efficient getOperand methods.
2012   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2013
2014   // Methods for support type inquiry through isa, cast, and dyn_cast:
2015   static inline bool classof(const Instruction *I) {
2016     return I->getOpcode() == Instruction::ExtractElement;
2017   }
2018   static inline bool classof(const Value *V) {
2019     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2020   }
2021 };
2022
2023 template <>
2024 struct OperandTraits<ExtractElementInst> :
2025   public FixedNumOperandTraits<ExtractElementInst, 2> {
2026 };
2027
2028 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
2029
2030 //===----------------------------------------------------------------------===//
2031 //                                InsertElementInst Class
2032 //===----------------------------------------------------------------------===//
2033
2034 /// InsertElementInst - This instruction inserts a single (scalar)
2035 /// element into a VectorType value
2036 ///
2037 class InsertElementInst : public Instruction {
2038   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2039                     const Twine &NameStr = "",
2040                     Instruction *InsertBefore = nullptr);
2041   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2042                     BasicBlock *InsertAtEnd);
2043
2044 protected:
2045   // Note: Instruction needs to be a friend here to call cloneImpl.
2046   friend class Instruction;
2047   InsertElementInst *cloneImpl() const;
2048
2049 public:
2050   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2051                                    const Twine &NameStr = "",
2052                                    Instruction *InsertBefore = nullptr) {
2053     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2054   }
2055   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2056                                    const Twine &NameStr,
2057                                    BasicBlock *InsertAtEnd) {
2058     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2059   }
2060
2061   /// isValidOperands - Return true if an insertelement instruction can be
2062   /// formed with the specified operands.
2063   static bool isValidOperands(const Value *Vec, const Value *NewElt,
2064                               const Value *Idx);
2065
2066   /// getType - Overload to return most specific vector type.
2067   ///
2068   VectorType *getType() const {
2069     return cast<VectorType>(Instruction::getType());
2070   }
2071
2072   /// Transparently provide more efficient getOperand methods.
2073   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2074
2075   // Methods for support type inquiry through isa, cast, and dyn_cast:
2076   static inline bool classof(const Instruction *I) {
2077     return I->getOpcode() == Instruction::InsertElement;
2078   }
2079   static inline bool classof(const Value *V) {
2080     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2081   }
2082 };
2083
2084 template <>
2085 struct OperandTraits<InsertElementInst> :
2086   public FixedNumOperandTraits<InsertElementInst, 3> {
2087 };
2088
2089 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2090
2091 //===----------------------------------------------------------------------===//
2092 //                           ShuffleVectorInst Class
2093 //===----------------------------------------------------------------------===//
2094
2095 /// ShuffleVectorInst - This instruction constructs a fixed permutation of two
2096 /// input vectors.
2097 ///
2098 class ShuffleVectorInst : public Instruction {
2099 protected:
2100   // Note: Instruction needs to be a friend here to call cloneImpl.
2101   friend class Instruction;
2102   ShuffleVectorInst *cloneImpl() const;
2103
2104 public:
2105   // allocate space for exactly three operands
2106   void *operator new(size_t s) {
2107     return User::operator new(s, 3);
2108   }
2109   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2110                     const Twine &NameStr = "",
2111                     Instruction *InsertBefor = nullptr);
2112   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2113                     const Twine &NameStr, BasicBlock *InsertAtEnd);
2114
2115   /// isValidOperands - Return true if a shufflevector instruction can be
2116   /// formed with the specified operands.
2117   static bool isValidOperands(const Value *V1, const Value *V2,
2118                               const Value *Mask);
2119
2120   /// getType - Overload to return most specific vector type.
2121   ///
2122   VectorType *getType() const {
2123     return cast<VectorType>(Instruction::getType());
2124   }
2125
2126   /// Transparently provide more efficient getOperand methods.
2127   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2128
2129   Constant *getMask() const {
2130     return cast<Constant>(getOperand(2));
2131   }
2132
2133   /// getMaskValue - Return the index from the shuffle mask for the specified
2134   /// output result.  This is either -1 if the element is undef or a number less
2135   /// than 2*numelements.
2136   static int getMaskValue(Constant *Mask, unsigned i);
2137
2138   int getMaskValue(unsigned i) const {
2139     return getMaskValue(getMask(), i);
2140   }
2141
2142   /// getShuffleMask - Return the full mask for this instruction, where each
2143   /// element is the element number and undef's are returned as -1.
2144   static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2145
2146   void getShuffleMask(SmallVectorImpl<int> &Result) const {
2147     return getShuffleMask(getMask(), Result);
2148   }
2149
2150   SmallVector<int, 16> getShuffleMask() const {
2151     SmallVector<int, 16> Mask;
2152     getShuffleMask(Mask);
2153     return Mask;
2154   }
2155
2156   // Methods for support type inquiry through isa, cast, and dyn_cast:
2157   static inline bool classof(const Instruction *I) {
2158     return I->getOpcode() == Instruction::ShuffleVector;
2159   }
2160   static inline bool classof(const Value *V) {
2161     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2162   }
2163 };
2164
2165 template <>
2166 struct OperandTraits<ShuffleVectorInst> :
2167   public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2168 };
2169
2170 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2171
2172 //===----------------------------------------------------------------------===//
2173 //                                ExtractValueInst Class
2174 //===----------------------------------------------------------------------===//
2175
2176 /// ExtractValueInst - This instruction extracts a struct member or array
2177 /// element value from an aggregate value.
2178 ///
2179 class ExtractValueInst : public UnaryInstruction {
2180   SmallVector<unsigned, 4> Indices;
2181
2182   ExtractValueInst(const ExtractValueInst &EVI);
2183   void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2184
2185   /// Constructors - Create a extractvalue instruction with a base aggregate
2186   /// value and a list of indices.  The first ctor can optionally insert before
2187   /// an existing instruction, the second appends the new instruction to the
2188   /// specified BasicBlock.
2189   inline ExtractValueInst(Value *Agg,
2190                           ArrayRef<unsigned> Idxs,
2191                           const Twine &NameStr,
2192                           Instruction *InsertBefore);
2193   inline ExtractValueInst(Value *Agg,
2194                           ArrayRef<unsigned> Idxs,
2195                           const Twine &NameStr, BasicBlock *InsertAtEnd);
2196
2197   // allocate space for exactly one operand
2198   void *operator new(size_t s) { return User::operator new(s, 1); }
2199
2200 protected:
2201   // Note: Instruction needs to be a friend here to call cloneImpl.
2202   friend class Instruction;
2203   ExtractValueInst *cloneImpl() const;
2204
2205 public:
2206   static ExtractValueInst *Create(Value *Agg,
2207                                   ArrayRef<unsigned> Idxs,
2208                                   const Twine &NameStr = "",
2209                                   Instruction *InsertBefore = nullptr) {
2210     return new
2211       ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2212   }
2213   static ExtractValueInst *Create(Value *Agg,
2214                                   ArrayRef<unsigned> Idxs,
2215                                   const Twine &NameStr,
2216                                   BasicBlock *InsertAtEnd) {
2217     return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2218   }
2219
2220   /// getIndexedType - Returns the type of the element that would be extracted
2221   /// with an extractvalue instruction with the specified parameters.
2222   ///
2223   /// Null is returned if the indices are invalid for the specified type.
2224   static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2225
2226   typedef const unsigned* idx_iterator;
2227   inline idx_iterator idx_begin() const { return Indices.begin(); }
2228   inline idx_iterator idx_end()   const { return Indices.end(); }
2229   inline iterator_range<idx_iterator> indices() const {
2230     return make_range(idx_begin(), idx_end());
2231   }
2232
2233   Value *getAggregateOperand() {
2234     return getOperand(0);
2235   }
2236   const Value *getAggregateOperand() const {
2237     return getOperand(0);
2238   }
2239   static unsigned getAggregateOperandIndex() {
2240     return 0U;                      // get index for modifying correct operand
2241   }
2242
2243   ArrayRef<unsigned> getIndices() const {
2244     return Indices;
2245   }
2246
2247   unsigned getNumIndices() const {
2248     return (unsigned)Indices.size();
2249   }
2250
2251   bool hasIndices() const {
2252     return true;
2253   }
2254
2255   // Methods for support type inquiry through isa, cast, and dyn_cast:
2256   static inline bool classof(const Instruction *I) {
2257     return I->getOpcode() == Instruction::ExtractValue;
2258   }
2259   static inline bool classof(const Value *V) {
2260     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2261   }
2262 };
2263
2264 ExtractValueInst::ExtractValueInst(Value *Agg,
2265                                    ArrayRef<unsigned> Idxs,
2266                                    const Twine &NameStr,
2267                                    Instruction *InsertBefore)
2268   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2269                      ExtractValue, Agg, InsertBefore) {
2270   init(Idxs, NameStr);
2271 }
2272 ExtractValueInst::ExtractValueInst(Value *Agg,
2273                                    ArrayRef<unsigned> Idxs,
2274                                    const Twine &NameStr,
2275                                    BasicBlock *InsertAtEnd)
2276   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2277                      ExtractValue, Agg, InsertAtEnd) {
2278   init(Idxs, NameStr);
2279 }
2280
2281 //===----------------------------------------------------------------------===//
2282 //                                InsertValueInst Class
2283 //===----------------------------------------------------------------------===//
2284
2285 /// InsertValueInst - This instruction inserts a struct field of array element
2286 /// value into an aggregate value.
2287 ///
2288 class InsertValueInst : public Instruction {
2289   SmallVector<unsigned, 4> Indices;
2290
2291   void *operator new(size_t, unsigned) = delete;
2292   InsertValueInst(const InsertValueInst &IVI);
2293   void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2294             const Twine &NameStr);
2295
2296   /// Constructors - Create a insertvalue instruction with a base aggregate
2297   /// value, a value to insert, and a list of indices.  The first ctor can
2298   /// optionally insert before an existing instruction, the second appends
2299   /// the new instruction to the specified BasicBlock.
2300   inline InsertValueInst(Value *Agg, Value *Val,
2301                          ArrayRef<unsigned> Idxs,
2302                          const Twine &NameStr,
2303                          Instruction *InsertBefore);
2304   inline InsertValueInst(Value *Agg, Value *Val,
2305                          ArrayRef<unsigned> Idxs,
2306                          const Twine &NameStr, BasicBlock *InsertAtEnd);
2307
2308   /// Constructors - These two constructors are convenience methods because one
2309   /// and two index insertvalue instructions are so common.
2310   InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2311                   const Twine &NameStr = "",
2312                   Instruction *InsertBefore = nullptr);
2313   InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2314                   BasicBlock *InsertAtEnd);
2315
2316 protected:
2317   // Note: Instruction needs to be a friend here to call cloneImpl.
2318   friend class Instruction;
2319   InsertValueInst *cloneImpl() const;
2320
2321 public:
2322   // allocate space for exactly two operands
2323   void *operator new(size_t s) {
2324     return User::operator new(s, 2);
2325   }
2326
2327   static InsertValueInst *Create(Value *Agg, Value *Val,
2328                                  ArrayRef<unsigned> Idxs,
2329                                  const Twine &NameStr = "",
2330                                  Instruction *InsertBefore = nullptr) {
2331     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2332   }
2333   static InsertValueInst *Create(Value *Agg, Value *Val,
2334                                  ArrayRef<unsigned> Idxs,
2335                                  const Twine &NameStr,
2336                                  BasicBlock *InsertAtEnd) {
2337     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2338   }
2339
2340   /// Transparently provide more efficient getOperand methods.
2341   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2342
2343   typedef const unsigned* idx_iterator;
2344   inline idx_iterator idx_begin() const { return Indices.begin(); }
2345   inline idx_iterator idx_end()   const { return Indices.end(); }
2346   inline iterator_range<idx_iterator> indices() const {
2347     return make_range(idx_begin(), idx_end());
2348   }
2349
2350   Value *getAggregateOperand() {
2351     return getOperand(0);
2352   }
2353   const Value *getAggregateOperand() const {
2354     return getOperand(0);
2355   }
2356   static unsigned getAggregateOperandIndex() {
2357     return 0U;                      // get index for modifying correct operand
2358   }
2359
2360   Value *getInsertedValueOperand() {
2361     return getOperand(1);
2362   }
2363   const Value *getInsertedValueOperand() const {
2364     return getOperand(1);
2365   }
2366   static unsigned getInsertedValueOperandIndex() {
2367     return 1U;                      // get index for modifying correct operand
2368   }
2369
2370   ArrayRef<unsigned> getIndices() const {
2371     return Indices;
2372   }
2373
2374   unsigned getNumIndices() const {
2375     return (unsigned)Indices.size();
2376   }
2377
2378   bool hasIndices() const {
2379     return true;
2380   }
2381
2382   // Methods for support type inquiry through isa, cast, and dyn_cast:
2383   static inline bool classof(const Instruction *I) {
2384     return I->getOpcode() == Instruction::InsertValue;
2385   }
2386   static inline bool classof(const Value *V) {
2387     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2388   }
2389 };
2390
2391 template <>
2392 struct OperandTraits<InsertValueInst> :
2393   public FixedNumOperandTraits<InsertValueInst, 2> {
2394 };
2395
2396 InsertValueInst::InsertValueInst(Value *Agg,
2397                                  Value *Val,
2398                                  ArrayRef<unsigned> Idxs,
2399                                  const Twine &NameStr,
2400                                  Instruction *InsertBefore)
2401   : Instruction(Agg->getType(), InsertValue,
2402                 OperandTraits<InsertValueInst>::op_begin(this),
2403                 2, InsertBefore) {
2404   init(Agg, Val, Idxs, NameStr);
2405 }
2406 InsertValueInst::InsertValueInst(Value *Agg,
2407                                  Value *Val,
2408                                  ArrayRef<unsigned> Idxs,
2409                                  const Twine &NameStr,
2410                                  BasicBlock *InsertAtEnd)
2411   : Instruction(Agg->getType(), InsertValue,
2412                 OperandTraits<InsertValueInst>::op_begin(this),
2413                 2, InsertAtEnd) {
2414   init(Agg, Val, Idxs, NameStr);
2415 }
2416
2417 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2418
2419 //===----------------------------------------------------------------------===//
2420 //                               PHINode Class
2421 //===----------------------------------------------------------------------===//
2422
2423 // PHINode - The PHINode class is used to represent the magical mystical PHI
2424 // node, that can not exist in nature, but can be synthesized in a computer
2425 // scientist's overactive imagination.
2426 //
2427 class PHINode : public Instruction {
2428   void *operator new(size_t, unsigned) = delete;
2429   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2430   /// the number actually in use.
2431   unsigned ReservedSpace;
2432   PHINode(const PHINode &PN);
2433   // allocate space for exactly zero operands
2434   void *operator new(size_t s) {
2435     return User::operator new(s);
2436   }
2437   explicit PHINode(Type *Ty, unsigned NumReservedValues,
2438                    const Twine &NameStr = "",
2439                    Instruction *InsertBefore = nullptr)
2440     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2441       ReservedSpace(NumReservedValues) {
2442     setName(NameStr);
2443     allocHungoffUses(ReservedSpace);
2444   }
2445
2446   PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2447           BasicBlock *InsertAtEnd)
2448     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2449       ReservedSpace(NumReservedValues) {
2450     setName(NameStr);
2451     allocHungoffUses(ReservedSpace);
2452   }
2453
2454 protected:
2455   // allocHungoffUses - this is more complicated than the generic
2456   // User::allocHungoffUses, because we have to allocate Uses for the incoming
2457   // values and pointers to the incoming blocks, all in one allocation.
2458   void allocHungoffUses(unsigned N) {
2459     User::allocHungoffUses(N, /* IsPhi */ true);
2460   }
2461
2462   // Note: Instruction needs to be a friend here to call cloneImpl.
2463   friend class Instruction;
2464   PHINode *cloneImpl() const;
2465
2466 public:
2467   /// Constructors - NumReservedValues is a hint for the number of incoming
2468   /// edges that this phi node will have (use 0 if you really have no idea).
2469   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2470                          const Twine &NameStr = "",
2471                          Instruction *InsertBefore = nullptr) {
2472     return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2473   }
2474   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2475                          const Twine &NameStr, BasicBlock *InsertAtEnd) {
2476     return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2477   }
2478
2479   /// Provide fast operand accessors
2480   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2481
2482   // Block iterator interface. This provides access to the list of incoming
2483   // basic blocks, which parallels the list of incoming values.
2484
2485   typedef BasicBlock **block_iterator;
2486   typedef BasicBlock * const *const_block_iterator;
2487
2488   block_iterator block_begin() {
2489     Use::UserRef *ref =
2490       reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2491     return reinterpret_cast<block_iterator>(ref + 1);
2492   }
2493
2494   const_block_iterator block_begin() const {
2495     const Use::UserRef *ref =
2496       reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2497     return reinterpret_cast<const_block_iterator>(ref + 1);
2498   }
2499
2500   block_iterator block_end() {
2501     return block_begin() + getNumOperands();
2502   }
2503
2504   const_block_iterator block_end() const {
2505     return block_begin() + getNumOperands();
2506   }
2507
2508   op_range incoming_values() { return operands(); }
2509
2510   const_op_range incoming_values() const { return operands(); }
2511
2512   /// getNumIncomingValues - Return the number of incoming edges
2513   ///
2514   unsigned getNumIncomingValues() const { return getNumOperands(); }
2515
2516   /// getIncomingValue - Return incoming value number x
2517   ///
2518   Value *getIncomingValue(unsigned i) const {
2519     return getOperand(i);
2520   }
2521   void setIncomingValue(unsigned i, Value *V) {
2522     assert(V && "PHI node got a null value!");
2523     assert(getType() == V->getType() &&
2524            "All operands to PHI node must be the same type as the PHI node!");
2525     setOperand(i, V);
2526   }
2527   static unsigned getOperandNumForIncomingValue(unsigned i) {
2528     return i;
2529   }
2530   static unsigned getIncomingValueNumForOperand(unsigned i) {
2531     return i;
2532   }
2533
2534   /// getIncomingBlock - Return incoming basic block number @p i.
2535   ///
2536   BasicBlock *getIncomingBlock(unsigned i) const {
2537     return block_begin()[i];
2538   }
2539
2540   /// getIncomingBlock - Return incoming basic block corresponding
2541   /// to an operand of the PHI.
2542   ///
2543   BasicBlock *getIncomingBlock(const Use &U) const {
2544     assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2545     return getIncomingBlock(unsigned(&U - op_begin()));
2546   }
2547
2548   /// getIncomingBlock - Return incoming basic block corresponding
2549   /// to value use iterator.
2550   ///
2551   BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2552     return getIncomingBlock(I.getUse());
2553   }
2554
2555   void setIncomingBlock(unsigned i, BasicBlock *BB) {
2556     assert(BB && "PHI node got a null basic block!");
2557     block_begin()[i] = BB;
2558   }
2559
2560   /// addIncoming - Add an incoming value to the end of the PHI list
2561   ///
2562   void addIncoming(Value *V, BasicBlock *BB) {
2563     if (getNumOperands() == ReservedSpace)
2564       growOperands();  // Get more space!
2565     // Initialize some new operands.
2566     setNumHungOffUseOperands(getNumOperands() + 1);
2567     setIncomingValue(getNumOperands() - 1, V);
2568     setIncomingBlock(getNumOperands() - 1, BB);
2569   }
2570
2571   /// removeIncomingValue - Remove an incoming value.  This is useful if a
2572   /// predecessor basic block is deleted.  The value removed is returned.
2573   ///
2574   /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2575   /// is true), the PHI node is destroyed and any uses of it are replaced with
2576   /// dummy values.  The only time there should be zero incoming values to a PHI
2577   /// node is when the block is dead, so this strategy is sound.
2578   ///
2579   Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2580
2581   Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2582     int Idx = getBasicBlockIndex(BB);
2583     assert(Idx >= 0 && "Invalid basic block argument to remove!");
2584     return removeIncomingValue(Idx, DeletePHIIfEmpty);
2585   }
2586
2587   /// getBasicBlockIndex - Return the first index of the specified basic
2588   /// block in the value list for this PHI.  Returns -1 if no instance.
2589   ///
2590   int getBasicBlockIndex(const BasicBlock *BB) const {
2591     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2592       if (block_begin()[i] == BB)
2593         return i;
2594     return -1;
2595   }
2596
2597   Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2598     int Idx = getBasicBlockIndex(BB);
2599     assert(Idx >= 0 && "Invalid basic block argument!");
2600     return getIncomingValue(Idx);
2601   }
2602
2603   /// hasConstantValue - If the specified PHI node always merges together the
2604   /// same value, return the value, otherwise return null.
2605   Value *hasConstantValue() const;
2606
2607   /// Methods for support type inquiry through isa, cast, and dyn_cast:
2608   static inline bool classof(const Instruction *I) {
2609     return I->getOpcode() == Instruction::PHI;
2610   }
2611   static inline bool classof(const Value *V) {
2612     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2613   }
2614
2615 private:
2616   void growOperands();
2617 };
2618
2619 template <>
2620 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2621 };
2622
2623 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2624
2625 //===----------------------------------------------------------------------===//
2626 //                           LandingPadInst Class
2627 //===----------------------------------------------------------------------===//
2628
2629 //===---------------------------------------------------------------------------
2630 /// LandingPadInst - The landingpad instruction holds all of the information
2631 /// necessary to generate correct exception handling. The landingpad instruction
2632 /// cannot be moved from the top of a landing pad block, which itself is
2633 /// accessible only from the 'unwind' edge of an invoke. This uses the
2634 /// SubclassData field in Value to store whether or not the landingpad is a
2635 /// cleanup.
2636 ///
2637 class LandingPadInst : public Instruction {
2638   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2639   /// the number actually in use.
2640   unsigned ReservedSpace;
2641   LandingPadInst(const LandingPadInst &LP);
2642
2643 public:
2644   enum ClauseType { Catch, Filter };
2645
2646 private:
2647   void *operator new(size_t, unsigned) = delete;
2648   // Allocate space for exactly zero operands.
2649   void *operator new(size_t s) {
2650     return User::operator new(s);
2651   }
2652   void growOperands(unsigned Size);
2653   void init(unsigned NumReservedValues, const Twine &NameStr);
2654
2655   explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2656                           const Twine &NameStr, Instruction *InsertBefore);
2657   explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2658                           const Twine &NameStr, BasicBlock *InsertAtEnd);
2659
2660 protected:
2661   // Note: Instruction needs to be a friend here to call cloneImpl.
2662   friend class Instruction;
2663   LandingPadInst *cloneImpl() const;
2664
2665 public:
2666   /// Constructors - NumReservedClauses is a hint for the number of incoming
2667   /// clauses that this landingpad will have (use 0 if you really have no idea).
2668   static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2669                                 const Twine &NameStr = "",
2670                                 Instruction *InsertBefore = nullptr);
2671   static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2672                                 const Twine &NameStr, BasicBlock *InsertAtEnd);
2673
2674   /// Provide fast operand accessors
2675   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2676
2677   /// isCleanup - Return 'true' if this landingpad instruction is a
2678   /// cleanup. I.e., it should be run when unwinding even if its landing pad
2679   /// doesn't catch the exception.
2680   bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2681
2682   /// setCleanup - Indicate that this landingpad instruction is a cleanup.
2683   void setCleanup(bool V) {
2684     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2685                                (V ? 1 : 0));
2686   }
2687
2688   /// Add a catch or filter clause to the landing pad.
2689   void addClause(Constant *ClauseVal);
2690
2691   /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2692   /// determine what type of clause this is.
2693   Constant *getClause(unsigned Idx) const {
2694     return cast<Constant>(getOperandList()[Idx]);
2695   }
2696
2697   /// isCatch - Return 'true' if the clause and index Idx is a catch clause.
2698   bool isCatch(unsigned Idx) const {
2699     return !isa<ArrayType>(getOperandList()[Idx]->getType());
2700   }
2701
2702   /// isFilter - Return 'true' if the clause and index Idx is a filter clause.
2703   bool isFilter(unsigned Idx) const {
2704     return isa<ArrayType>(getOperandList()[Idx]->getType());
2705   }
2706
2707   /// getNumClauses - Get the number of clauses for this landing pad.
2708   unsigned getNumClauses() const { return getNumOperands(); }
2709
2710   /// reserveClauses - Grow the size of the operand list to accommodate the new
2711   /// number of clauses.
2712   void reserveClauses(unsigned Size) { growOperands(Size); }
2713
2714   // Methods for support type inquiry through isa, cast, and dyn_cast:
2715   static inline bool classof(const Instruction *I) {
2716     return I->getOpcode() == Instruction::LandingPad;
2717   }
2718   static inline bool classof(const Value *V) {
2719     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2720   }
2721 };
2722
2723 template <>
2724 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2725 };
2726
2727 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2728
2729 //===----------------------------------------------------------------------===//
2730 //                               ReturnInst Class
2731 //===----------------------------------------------------------------------===//
2732
2733 //===---------------------------------------------------------------------------
2734 /// ReturnInst - Return a value (possibly void), from a function.  Execution
2735 /// does not continue in this function any longer.
2736 ///
2737 class ReturnInst : public TerminatorInst {
2738   ReturnInst(const ReturnInst &RI);
2739
2740 private:
2741   // ReturnInst constructors:
2742   // ReturnInst()                  - 'ret void' instruction
2743   // ReturnInst(    null)          - 'ret void' instruction
2744   // ReturnInst(Value* X)          - 'ret X'    instruction
2745   // ReturnInst(    null, Inst *I) - 'ret void' instruction, insert before I
2746   // ReturnInst(Value* X, Inst *I) - 'ret X'    instruction, insert before I
2747   // ReturnInst(    null, BB *B)   - 'ret void' instruction, insert @ end of B
2748   // ReturnInst(Value* X, BB *B)   - 'ret X'    instruction, insert @ end of B
2749   //
2750   // NOTE: If the Value* passed is of type void then the constructor behaves as
2751   // if it was passed NULL.
2752   explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2753                       Instruction *InsertBefore = nullptr);
2754   ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2755   explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2756
2757 protected:
2758   // Note: Instruction needs to be a friend here to call cloneImpl.
2759   friend class Instruction;
2760   ReturnInst *cloneImpl() const;
2761
2762 public:
2763   static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2764                             Instruction *InsertBefore = nullptr) {
2765     return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2766   }
2767   static ReturnInst* Create(LLVMContext &C, Value *retVal,
2768                             BasicBlock *InsertAtEnd) {
2769     return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2770   }
2771   static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2772     return new(0) ReturnInst(C, InsertAtEnd);
2773   }
2774   ~ReturnInst() override;
2775
2776   /// Provide fast operand accessors
2777   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2778
2779   /// Convenience accessor. Returns null if there is no return value.
2780   Value *getReturnValue() const {
2781     return getNumOperands() != 0 ? getOperand(0) : nullptr;
2782   }
2783
2784   unsigned getNumSuccessors() const { return 0; }
2785
2786   // Methods for support type inquiry through isa, cast, and dyn_cast:
2787   static inline bool classof(const Instruction *I) {
2788     return (I->getOpcode() == Instruction::Ret);
2789   }
2790   static inline bool classof(const Value *V) {
2791     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2792   }
2793
2794 private:
2795   BasicBlock *getSuccessorV(unsigned idx) const override;
2796   unsigned getNumSuccessorsV() const override;
2797   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2798 };
2799
2800 template <>
2801 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2802 };
2803
2804 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2805
2806 //===----------------------------------------------------------------------===//
2807 //                               BranchInst Class
2808 //===----------------------------------------------------------------------===//
2809
2810 //===---------------------------------------------------------------------------
2811 /// BranchInst - Conditional or Unconditional Branch instruction.
2812 ///
2813 class BranchInst : public TerminatorInst {
2814   /// Ops list - Branches are strange.  The operands are ordered:
2815   ///  [Cond, FalseDest,] TrueDest.  This makes some accessors faster because
2816   /// they don't have to check for cond/uncond branchness. These are mostly
2817   /// accessed relative from op_end().
2818   BranchInst(const BranchInst &BI);
2819   void AssertOK();
2820   // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2821   // BranchInst(BB *B)                           - 'br B'
2822   // BranchInst(BB* T, BB *F, Value *C)          - 'br C, T, F'
2823   // BranchInst(BB* B, Inst *I)                  - 'br B'        insert before I
2824   // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2825   // BranchInst(BB* B, BB *I)                    - 'br B'        insert at end
2826   // BranchInst(BB* T, BB *F, Value *C, BB *I)   - 'br C, T, F', insert at end
2827   explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2828   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2829              Instruction *InsertBefore = nullptr);
2830   BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2831   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2832              BasicBlock *InsertAtEnd);
2833
2834 protected:
2835   // Note: Instruction needs to be a friend here to call cloneImpl.
2836   friend class Instruction;
2837   BranchInst *cloneImpl() const;
2838
2839 public:
2840   static BranchInst *Create(BasicBlock *IfTrue,
2841                             Instruction *InsertBefore = nullptr) {
2842     return new(1) BranchInst(IfTrue, InsertBefore);
2843   }
2844   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2845                             Value *Cond, Instruction *InsertBefore = nullptr) {
2846     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
2847   }
2848   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
2849     return new(1) BranchInst(IfTrue, InsertAtEnd);
2850   }
2851   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2852                             Value *Cond, BasicBlock *InsertAtEnd) {
2853     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
2854   }
2855
2856   /// Transparently provide more efficient getOperand methods.
2857   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2858
2859   bool isUnconditional() const { return getNumOperands() == 1; }
2860   bool isConditional()   const { return getNumOperands() == 3; }
2861
2862   Value *getCondition() const {
2863     assert(isConditional() && "Cannot get condition of an uncond branch!");
2864     return Op<-3>();
2865   }
2866
2867   void setCondition(Value *V) {
2868     assert(isConditional() && "Cannot set condition of unconditional branch!");
2869     Op<-3>() = V;
2870   }
2871
2872   unsigned getNumSuccessors() const { return 1+isConditional(); }
2873
2874   BasicBlock *getSuccessor(unsigned i) const {
2875     assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
2876     return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
2877   }
2878
2879   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2880     assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
2881     *(&Op<-1>() - idx) = NewSucc;
2882   }
2883
2884   /// \brief Swap the successors of this branch instruction.
2885   ///
2886   /// Swaps the successors of the branch instruction. This also swaps any
2887   /// branch weight metadata associated with the instruction so that it
2888   /// continues to map correctly to each operand.
2889   void swapSuccessors();
2890
2891   // Methods for support type inquiry through isa, cast, and dyn_cast:
2892   static inline bool classof(const Instruction *I) {
2893     return (I->getOpcode() == Instruction::Br);
2894   }
2895   static inline bool classof(const Value *V) {
2896     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2897   }
2898
2899 private:
2900   BasicBlock *getSuccessorV(unsigned idx) const override;
2901   unsigned getNumSuccessorsV() const override;
2902   void setSuccessorV(unsigned idx, BasicBlock *B) override;
2903 };
2904
2905 template <>
2906 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
2907 };
2908
2909 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
2910
2911 //===----------------------------------------------------------------------===//
2912 //                               SwitchInst Class
2913 //===----------------------------------------------------------------------===//
2914
2915 //===---------------------------------------------------------------------------
2916 /// SwitchInst - Multiway switch
2917 ///
2918 class SwitchInst : public TerminatorInst {
2919   void *operator new(size_t, unsigned) = delete;
2920   unsigned ReservedSpace;
2921   // Operand[0]    = Value to switch on
2922   // Operand[1]    = Default basic block destination
2923   // Operand[2n  ] = Value to match
2924   // Operand[2n+1] = BasicBlock to go to on match
2925   SwitchInst(const SwitchInst &SI);
2926   void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
2927   void growOperands();
2928   // allocate space for exactly zero operands
2929   void *operator new(size_t s) {
2930     return User::operator new(s);
2931   }
2932   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2933   /// switch on and a default destination.  The number of additional cases can
2934   /// be specified here to make memory allocation more efficient.  This
2935   /// constructor can also autoinsert before another instruction.
2936   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2937              Instruction *InsertBefore);
2938
2939   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2940   /// switch on and a default destination.  The number of additional cases can
2941   /// be specified here to make memory allocation more efficient.  This
2942   /// constructor also autoinserts at the end of the specified BasicBlock.
2943   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2944              BasicBlock *InsertAtEnd);
2945
2946 protected:
2947   // Note: Instruction needs to be a friend here to call cloneImpl.
2948   friend class Instruction;
2949   SwitchInst *cloneImpl() const;
2950
2951 public:
2952   // -2
2953   static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
2954
2955   template <class SwitchInstTy, class ConstantIntTy, class BasicBlockTy>
2956   class CaseIteratorT {
2957   protected:
2958     SwitchInstTy *SI;
2959     unsigned Index;
2960
2961   public:
2962     typedef CaseIteratorT<SwitchInstTy, ConstantIntTy, BasicBlockTy> Self;
2963
2964     /// Initializes case iterator for given SwitchInst and for given
2965     /// case number.
2966     CaseIteratorT(SwitchInstTy *SI, unsigned CaseNum) {
2967       this->SI = SI;
2968       Index = CaseNum;
2969     }
2970
2971     /// Initializes case iterator for given SwitchInst and for given
2972     /// TerminatorInst's successor index.
2973     static Self fromSuccessorIndex(SwitchInstTy *SI, unsigned SuccessorIndex) {
2974       assert(SuccessorIndex < SI->getNumSuccessors() &&
2975              "Successor index # out of range!");
2976       return SuccessorIndex != 0 ?
2977              Self(SI, SuccessorIndex - 1) :
2978              Self(SI, DefaultPseudoIndex);
2979     }
2980
2981     /// Resolves case value for current case.
2982     ConstantIntTy *getCaseValue() {
2983       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2984       return reinterpret_cast<ConstantIntTy*>(SI->getOperand(2 + Index*2));
2985     }
2986
2987     /// Resolves successor for current case.
2988     BasicBlockTy *getCaseSuccessor() {
2989       assert((Index < SI->getNumCases() ||
2990               Index == DefaultPseudoIndex) &&
2991              "Index out the number of cases.");
2992       return SI->getSuccessor(getSuccessorIndex());
2993     }
2994
2995     /// Returns number of current case.
2996     unsigned getCaseIndex() const { return Index; }
2997
2998     /// Returns TerminatorInst's successor index for current case successor.
2999     unsigned getSuccessorIndex() const {
3000       assert((Index == DefaultPseudoIndex || Index < SI->getNumCases()) &&
3001              "Index out the number of cases.");
3002       return Index != DefaultPseudoIndex ? Index + 1 : 0;
3003     }
3004
3005     Self operator++() {
3006       // Check index correctness after increment.
3007       // Note: Index == getNumCases() means end().
3008       assert(Index+1 <= SI->getNumCases() && "Index out the number of cases.");
3009       ++Index;
3010       return *this;
3011     }
3012     Self operator++(int) {
3013       Self tmp = *this;
3014       ++(*this);
3015       return tmp;
3016     }
3017     Self operator--() {
3018       // Check index correctness after decrement.
3019       // Note: Index == getNumCases() means end().
3020       // Also allow "-1" iterator here. That will became valid after ++.
3021       assert((Index == 0 || Index-1 <= SI->getNumCases()) &&
3022              "Index out the number of cases.");
3023       --Index;
3024       return *this;
3025     }
3026     Self operator--(int) {
3027       Self tmp = *this;
3028       --(*this);
3029       return tmp;
3030     }
3031     bool operator==(const Self& RHS) const {
3032       assert(RHS.SI == SI && "Incompatible operators.");
3033       return RHS.Index == Index;
3034     }
3035     bool operator!=(const Self& RHS) const {
3036       assert(RHS.SI == SI && "Incompatible operators.");
3037       return RHS.Index != Index;
3038     }
3039     Self &operator*() {
3040       return *this;
3041     }
3042   };
3043
3044   typedef CaseIteratorT<const SwitchInst, const ConstantInt, const BasicBlock>
3045     ConstCaseIt;
3046
3047   class CaseIt : public CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> {
3048
3049     typedef CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> ParentTy;
3050
3051   public:
3052     CaseIt(const ParentTy &Src) : ParentTy(Src) {}
3053     CaseIt(SwitchInst *SI, unsigned CaseNum) : ParentTy(SI, CaseNum) {}
3054
3055     /// Sets the new value for current case.
3056     void setValue(ConstantInt *V) {
3057       assert(Index < SI->getNumCases() && "Index out the number of cases.");
3058       SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3059     }
3060
3061     /// Sets the new successor for current case.
3062     void setSuccessor(BasicBlock *S) {
3063       SI->setSuccessor(getSuccessorIndex(), S);
3064     }
3065   };
3066
3067   static SwitchInst *Create(Value *Value, BasicBlock *Default,
3068                             unsigned NumCases,
3069                             Instruction *InsertBefore = nullptr) {
3070     return new SwitchInst(Value, Default, NumCases, InsertBefore);
3071   }
3072   static SwitchInst *Create(Value *Value, BasicBlock *Default,
3073                             unsigned NumCases, BasicBlock *InsertAtEnd) {
3074     return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3075   }
3076
3077   /// Provide fast operand accessors
3078   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3079
3080   // Accessor Methods for Switch stmt
3081   Value *getCondition() const { return getOperand(0); }
3082   void setCondition(Value *V) { setOperand(0, V); }
3083
3084   BasicBlock *getDefaultDest() const {
3085     return cast<BasicBlock>(getOperand(1));
3086   }
3087
3088   void setDefaultDest(BasicBlock *DefaultCase) {
3089     setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3090   }
3091
3092   /// getNumCases - return the number of 'cases' in this switch instruction,
3093   /// except the default case
3094   unsigned getNumCases() const {
3095     return getNumOperands()/2 - 1;
3096   }
3097
3098   /// Returns a read/write iterator that points to the first
3099   /// case in SwitchInst.
3100   CaseIt case_begin() {
3101     return CaseIt(this, 0);
3102   }
3103   /// Returns a read-only iterator that points to the first
3104   /// case in the SwitchInst.
3105   ConstCaseIt case_begin() const {
3106     return ConstCaseIt(this, 0);
3107   }
3108
3109   /// Returns a read/write iterator that points one past the last
3110   /// in the SwitchInst.
3111   CaseIt case_end() {
3112     return CaseIt(this, getNumCases());
3113   }
3114   /// Returns a read-only iterator that points one past the last
3115   /// in the SwitchInst.
3116   ConstCaseIt case_end() const {
3117     return ConstCaseIt(this, getNumCases());
3118   }
3119
3120   /// cases - iteration adapter for range-for loops.
3121   iterator_range<CaseIt> cases() {
3122     return make_range(case_begin(), case_end());
3123   }
3124
3125   /// cases - iteration adapter for range-for loops.
3126   iterator_range<ConstCaseIt> cases() const {
3127     return make_range(case_begin(), case_end());
3128   }
3129
3130   /// Returns an iterator that points to the default case.
3131   /// Note: this iterator allows to resolve successor only. Attempt
3132   /// to resolve case value causes an assertion.
3133   /// Also note, that increment and decrement also causes an assertion and
3134   /// makes iterator invalid.
3135   CaseIt case_default() {
3136     return CaseIt(this, DefaultPseudoIndex);
3137   }
3138   ConstCaseIt case_default() const {
3139     return ConstCaseIt(this, DefaultPseudoIndex);
3140   }
3141
3142   /// findCaseValue - Search all of the case values for the specified constant.
3143   /// If it is explicitly handled, return the case iterator of it, otherwise
3144   /// return default case iterator to indicate
3145   /// that it is handled by the default handler.
3146   CaseIt findCaseValue(const ConstantInt *C) {
3147     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i)
3148       if (i.getCaseValue() == C)
3149         return i;
3150     return case_default();
3151   }
3152   ConstCaseIt findCaseValue(const ConstantInt *C) const {
3153     for (ConstCaseIt i = case_begin(), e = case_end(); i != e; ++i)
3154       if (i.getCaseValue() == C)
3155         return i;
3156     return case_default();
3157   }
3158
3159   /// findCaseDest - Finds the unique case value for a given successor. Returns
3160   /// null if the successor is not found, not unique, or is the default case.
3161   ConstantInt *findCaseDest(BasicBlock *BB) {
3162     if (BB == getDefaultDest()) return nullptr;
3163
3164     ConstantInt *CI = nullptr;
3165     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i) {
3166       if (i.getCaseSuccessor() == BB) {
3167         if (CI) return nullptr;   // Multiple cases lead to BB.
3168         else CI = i.getCaseValue();
3169       }
3170     }
3171     return CI;
3172   }
3173
3174   /// addCase - Add an entry to the switch instruction...
3175   /// Note:
3176   /// This action invalidates case_end(). Old case_end() iterator will
3177   /// point to the added case.
3178   void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3179
3180   /// removeCase - This method removes the specified case and its successor
3181   /// from the switch instruction. Note that this operation may reorder the
3182   /// remaining cases at index idx and above.
3183   /// Note:
3184   /// This action invalidates iterators for all cases following the one removed,
3185   /// including the case_end() iterator.
3186   void removeCase(CaseIt i);
3187
3188   unsigned getNumSuccessors() const { return getNumOperands()/2; }
3189   BasicBlock *getSuccessor(unsigned idx) const {
3190     assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3191     return cast<BasicBlock>(getOperand(idx*2+1));
3192   }
3193   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3194     assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3195     setOperand(idx * 2 + 1, NewSucc);
3196   }
3197
3198   // Methods for support type inquiry through isa, cast, and dyn_cast:
3199   static inline bool classof(const Instruction *I) {
3200     return I->getOpcode() == Instruction::Switch;
3201   }
3202   static inline bool classof(const Value *V) {
3203     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3204   }
3205
3206 private:
3207   BasicBlock *getSuccessorV(unsigned idx) const override;
3208   unsigned getNumSuccessorsV() const override;
3209   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3210 };
3211
3212 template <>
3213 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3214 };
3215
3216 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3217
3218 //===----------------------------------------------------------------------===//
3219 //                             IndirectBrInst Class
3220 //===----------------------------------------------------------------------===//
3221
3222 //===---------------------------------------------------------------------------
3223 /// IndirectBrInst - Indirect Branch Instruction.
3224 ///
3225 class IndirectBrInst : public TerminatorInst {
3226   void *operator new(size_t, unsigned) = delete;
3227   unsigned ReservedSpace;
3228   // Operand[0]    = Value to switch on
3229   // Operand[1]    = Default basic block destination
3230   // Operand[2n  ] = Value to match
3231   // Operand[2n+1] = BasicBlock to go to on match
3232   IndirectBrInst(const IndirectBrInst &IBI);
3233   void init(Value *Address, unsigned NumDests);
3234   void growOperands();
3235   // allocate space for exactly zero operands
3236   void *operator new(size_t s) {
3237     return User::operator new(s);
3238   }
3239   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
3240   /// Address to jump to.  The number of expected destinations can be specified
3241   /// here to make memory allocation more efficient.  This constructor can also
3242   /// autoinsert before another instruction.
3243   IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3244
3245   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
3246   /// Address to jump to.  The number of expected destinations can be specified
3247   /// here to make memory allocation more efficient.  This constructor also
3248   /// autoinserts at the end of the specified BasicBlock.
3249   IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3250
3251 protected:
3252   // Note: Instruction needs to be a friend here to call cloneImpl.
3253   friend class Instruction;
3254   IndirectBrInst *cloneImpl() const;
3255
3256 public:
3257   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3258                                 Instruction *InsertBefore = nullptr) {
3259     return new IndirectBrInst(Address, NumDests, InsertBefore);
3260   }
3261   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3262                                 BasicBlock *InsertAtEnd) {
3263     return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3264   }
3265
3266   /// Provide fast operand accessors.
3267   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3268
3269   // Accessor Methods for IndirectBrInst instruction.
3270   Value *getAddress() { return getOperand(0); }
3271   const Value *getAddress() const { return getOperand(0); }
3272   void setAddress(Value *V) { setOperand(0, V); }
3273
3274   /// getNumDestinations - return the number of possible destinations in this
3275   /// indirectbr instruction.
3276   unsigned getNumDestinations() const { return getNumOperands()-1; }
3277
3278   /// getDestination - Return the specified destination.
3279   BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3280   const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3281
3282   /// addDestination - Add a destination.
3283   ///
3284   void addDestination(BasicBlock *Dest);
3285
3286   /// removeDestination - This method removes the specified successor from the
3287   /// indirectbr instruction.
3288   void removeDestination(unsigned i);
3289
3290   unsigned getNumSuccessors() const { return getNumOperands()-1; }
3291   BasicBlock *getSuccessor(unsigned i) const {
3292     return cast<BasicBlock>(getOperand(i+1));
3293   }
3294   void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3295     setOperand(i + 1, NewSucc);
3296   }
3297
3298   // Methods for support type inquiry through isa, cast, and dyn_cast:
3299   static inline bool classof(const Instruction *I) {
3300     return I->getOpcode() == Instruction::IndirectBr;
3301   }
3302   static inline bool classof(const Value *V) {
3303     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3304   }
3305
3306 private:
3307   BasicBlock *getSuccessorV(unsigned idx) const override;
3308   unsigned getNumSuccessorsV() const override;
3309   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3310 };
3311
3312 template <>
3313 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3314 };
3315
3316 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3317
3318 //===----------------------------------------------------------------------===//
3319 //                               InvokeInst Class
3320 //===----------------------------------------------------------------------===//
3321
3322 /// InvokeInst - Invoke instruction.  The SubclassData field is used to hold the
3323 /// calling convention of the call.
3324 ///
3325 class InvokeInst : public TerminatorInst,
3326                    public OperandBundleUser<InvokeInst, User::op_iterator> {
3327   AttributeSet AttributeList;
3328   FunctionType *FTy;
3329   InvokeInst(const InvokeInst &BI);
3330   void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3331             ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3332             const Twine &NameStr) {
3333     init(cast<FunctionType>(
3334              cast<PointerType>(Func->getType())->getElementType()),
3335          Func, IfNormal, IfException, Args, Bundles, NameStr);
3336   }
3337   void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3338             BasicBlock *IfException, ArrayRef<Value *> Args,
3339             ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3340
3341   /// Construct an InvokeInst given a range of arguments.
3342   ///
3343   /// \brief Construct an InvokeInst from a range of arguments
3344   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3345                     ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3346                     unsigned Values, const Twine &NameStr,
3347                     Instruction *InsertBefore)
3348       : InvokeInst(cast<FunctionType>(
3349                        cast<PointerType>(Func->getType())->getElementType()),
3350                    Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3351                    InsertBefore) {}
3352
3353   inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3354                     BasicBlock *IfException, ArrayRef<Value *> Args,
3355                     ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3356                     const Twine &NameStr, Instruction *InsertBefore);
3357   /// Construct an InvokeInst given a range of arguments.
3358   ///
3359   /// \brief Construct an InvokeInst from a range of arguments
3360   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3361                     ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3362                     unsigned Values, const Twine &NameStr,
3363                     BasicBlock *InsertAtEnd);
3364
3365   friend class OperandBundleUser<InvokeInst, User::op_iterator>;
3366   bool hasDescriptor() const { return HasDescriptor; }
3367
3368 protected:
3369   // Note: Instruction needs to be a friend here to call cloneImpl.
3370   friend class Instruction;
3371   InvokeInst *cloneImpl() const;
3372
3373 public:
3374   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3375                             BasicBlock *IfException, ArrayRef<Value *> Args,
3376                             const Twine &NameStr,
3377                             Instruction *InsertBefore = nullptr) {
3378     return Create(cast<FunctionType>(
3379                       cast<PointerType>(Func->getType())->getElementType()),
3380                   Func, IfNormal, IfException, Args, None, NameStr,
3381                   InsertBefore);
3382   }
3383   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3384                             BasicBlock *IfException, ArrayRef<Value *> Args,
3385                             ArrayRef<OperandBundleDef> Bundles = None,
3386                             const Twine &NameStr = "",
3387                             Instruction *InsertBefore = nullptr) {
3388     return Create(cast<FunctionType>(
3389                       cast<PointerType>(Func->getType())->getElementType()),
3390                   Func, IfNormal, IfException, Args, Bundles, NameStr,
3391                   InsertBefore);
3392   }
3393   static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3394                             BasicBlock *IfException, ArrayRef<Value *> Args,
3395                             const Twine &NameStr,
3396                             Instruction *InsertBefore = nullptr) {
3397     unsigned Values = unsigned(Args.size()) + 3;
3398     return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3399                                    Values, NameStr, InsertBefore);
3400   }
3401   static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3402                             BasicBlock *IfException, ArrayRef<Value *> Args,
3403                             ArrayRef<OperandBundleDef> Bundles = None,
3404                             const Twine &NameStr = "",
3405                             Instruction *InsertBefore = nullptr) {
3406     unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3407     unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3408
3409     return new (Values, DescriptorBytes)
3410         InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3411                    NameStr, InsertBefore);
3412   }
3413   static InvokeInst *Create(Value *Func,
3414                             BasicBlock *IfNormal, BasicBlock *IfException,
3415                             ArrayRef<Value *> Args, const Twine &NameStr,
3416                             BasicBlock *InsertAtEnd) {
3417     unsigned Values = unsigned(Args.size()) + 3;
3418     return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3419                                    Values, NameStr, InsertAtEnd);
3420   }
3421   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3422                             BasicBlock *IfException, ArrayRef<Value *> Args,
3423                             ArrayRef<OperandBundleDef> Bundles,
3424                             const Twine &NameStr, BasicBlock *InsertAtEnd) {
3425     unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3426     unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3427
3428     return new (Values, DescriptorBytes)
3429         InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3430                    InsertAtEnd);
3431   }
3432
3433   /// \brief Create a clone of \p II with a different set of operand bundles and
3434   /// insert it before \p InsertPt.
3435   ///
3436   /// The returned invoke instruction is identical to \p II in every way except
3437   /// that the operand bundles for the new instruction are set to the operand
3438   /// bundles in \p Bundles.
3439   static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3440                             Instruction *InsertPt = nullptr);
3441
3442   /// Provide fast operand accessors
3443   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3444
3445   FunctionType *getFunctionType() const { return FTy; }
3446
3447   void mutateFunctionType(FunctionType *FTy) {
3448     mutateType(FTy->getReturnType());
3449     this->FTy = FTy;
3450   }
3451
3452   /// getNumArgOperands - Return the number of invoke arguments.
3453   ///
3454   unsigned getNumArgOperands() const {
3455     return getNumOperands() - getNumTotalBundleOperands() - 3;
3456   }
3457
3458   /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3459   ///
3460   Value *getArgOperand(unsigned i) const {
3461     assert(i < getNumArgOperands() && "Out of bounds!");
3462     return getOperand(i);
3463   }
3464   void setArgOperand(unsigned i, Value *v) {
3465     assert(i < getNumArgOperands() && "Out of bounds!");
3466     setOperand(i, v);
3467   }
3468
3469   /// \brief Return the iterator pointing to the beginning of the argument list.
3470   op_iterator arg_begin() { return op_begin(); }
3471
3472   /// \brief Return the iterator pointing to the end of the argument list.
3473   op_iterator arg_end() {
3474     // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3475     return op_end() - getNumTotalBundleOperands() - 3;
3476   };
3477
3478   /// \brief Iteration adapter for range-for loops.
3479   iterator_range<op_iterator> arg_operands() {
3480     return make_range(arg_begin(), arg_end());
3481   }
3482
3483   /// \brief Return the iterator pointing to the beginning of the argument list.
3484   const_op_iterator arg_begin() const { return op_begin(); }
3485
3486   /// \brief Return the iterator pointing to the end of the argument list.
3487   const_op_iterator arg_end() const {
3488     // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3489     return op_end() - getNumTotalBundleOperands() - 3;
3490   };
3491
3492   /// \brief Iteration adapter for range-for loops.
3493   iterator_range<const_op_iterator> arg_operands() const {
3494     return make_range(arg_begin(), arg_end());
3495   }
3496
3497   /// \brief Wrappers for getting the \c Use of a invoke argument.
3498   const Use &getArgOperandUse(unsigned i) const {
3499     assert(i < getNumArgOperands() && "Out of bounds!");
3500     return getOperandUse(i);
3501   }
3502   Use &getArgOperandUse(unsigned i) {
3503     assert(i < getNumArgOperands() && "Out of bounds!");
3504     return getOperandUse(i);
3505   }
3506
3507   /// getCallingConv/setCallingConv - Get or set the calling convention of this
3508   /// function call.
3509   CallingConv::ID getCallingConv() const {
3510     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3511   }
3512   void setCallingConv(CallingConv::ID CC) {
3513     auto ID = static_cast<unsigned>(CC);
3514     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
3515     setInstructionSubclassData(ID);
3516   }
3517
3518   /// getAttributes - Return the parameter attributes for this invoke.
3519   ///
3520   const AttributeSet &getAttributes() const { return AttributeList; }
3521
3522   /// setAttributes - Set the parameter attributes for this invoke.
3523   ///
3524   void setAttributes(const AttributeSet &Attrs) { AttributeList = Attrs; }
3525
3526   /// addAttribute - adds the attribute to the list of attributes.
3527   void addAttribute(unsigned i, Attribute::AttrKind attr);
3528
3529   /// removeAttribute - removes the attribute from the list of attributes.
3530   void removeAttribute(unsigned i, Attribute attr);
3531
3532   /// \brief adds the dereferenceable attribute to the list of attributes.
3533   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3534
3535   /// \brief adds the dereferenceable_or_null attribute to the list of
3536   /// attributes.
3537   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3538
3539   /// \brief Determine whether this call has the given attribute.
3540   bool hasFnAttr(Attribute::AttrKind A) const {
3541     assert(A != Attribute::NoBuiltin &&
3542            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3543     return hasFnAttrImpl(A);
3544   }
3545
3546   /// \brief Determine whether the call or the callee has the given attributes.
3547   bool paramHasAttr(unsigned i, Attribute::AttrKind A) const;
3548
3549   /// \brief Return true if the data operand at index \p i has the attribute \p
3550   /// A.
3551   ///
3552   /// Data operands include invoke arguments and values used in operand bundles,
3553   /// but does not include the invokee operand, or the two successor blocks.
3554   /// This routine dispatches to the underlying AttributeList or the
3555   /// OperandBundleUser as appropriate.
3556   ///
3557   /// The index \p i is interpreted as
3558   ///
3559   ///  \p i == Attribute::ReturnIndex  -> the return value
3560   ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
3561   ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
3562   ///     (\p i - 1) in the operand list.
3563   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind A) const;
3564
3565   /// \brief Extract the alignment for a call or parameter (0=unknown).
3566   unsigned getParamAlignment(unsigned i) const {
3567     return AttributeList.getParamAlignment(i);
3568   }
3569
3570   /// \brief Extract the number of dereferenceable bytes for a call or
3571   /// parameter (0=unknown).
3572   uint64_t getDereferenceableBytes(unsigned i) const {
3573     return AttributeList.getDereferenceableBytes(i);
3574   }
3575
3576   /// \brief Extract the number of dereferenceable_or_null bytes for a call or
3577   /// parameter (0=unknown).
3578   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
3579     return AttributeList.getDereferenceableOrNullBytes(i);
3580   }
3581
3582   /// @brief Determine if the parameter or return value is marked with NoAlias
3583   /// attribute.
3584   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
3585   bool doesNotAlias(unsigned n) const {
3586     return AttributeList.hasAttribute(n, Attribute::NoAlias);
3587   }
3588
3589   /// \brief Return true if the call should not be treated as a call to a
3590   /// builtin.
3591   bool isNoBuiltin() const {
3592     // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3593     // to check it by hand.
3594     return hasFnAttrImpl(Attribute::NoBuiltin) &&
3595       !hasFnAttrImpl(Attribute::Builtin);
3596   }
3597
3598   /// \brief Return true if the call should not be inlined.
3599   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3600   void setIsNoInline() {
3601     addAttribute(AttributeSet::FunctionIndex, Attribute::NoInline);
3602   }
3603
3604   /// \brief Determine if the call does not access memory.
3605   bool doesNotAccessMemory() const {
3606     return hasFnAttr(Attribute::ReadNone);
3607   }
3608   void setDoesNotAccessMemory() {
3609     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
3610   }
3611
3612   /// \brief Determine if the call does not access or only reads memory.
3613   bool onlyReadsMemory() const {
3614     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3615   }
3616   void setOnlyReadsMemory() {
3617     addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
3618   }
3619
3620   /// @brief Determine if the call access memmory only using it's pointer
3621   /// arguments.
3622   bool onlyAccessesArgMemory() const {
3623     return hasFnAttr(Attribute::ArgMemOnly);
3624   }
3625   void setOnlyAccessesArgMemory() {
3626     addAttribute(AttributeSet::FunctionIndex, Attribute::ArgMemOnly);
3627   }
3628
3629   /// \brief Determine if the call cannot return.
3630   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3631   void setDoesNotReturn() {
3632     addAttribute(AttributeSet::FunctionIndex, Attribute::NoReturn);
3633   }
3634
3635   /// \brief Determine if the call cannot unwind.
3636   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3637   void setDoesNotThrow() {
3638     addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
3639   }
3640
3641   /// \brief Determine if the invoke cannot be duplicated.
3642   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3643   void setCannotDuplicate() {
3644     addAttribute(AttributeSet::FunctionIndex, Attribute::NoDuplicate);
3645   }
3646
3647   /// \brief Determine if the call returns a structure through first
3648   /// pointer argument.
3649   bool hasStructRetAttr() const {
3650     if (getNumArgOperands() == 0)
3651       return false;
3652
3653     // Be friendly and also check the callee.
3654     return paramHasAttr(1, Attribute::StructRet);
3655   }
3656
3657   /// \brief Determine if any call argument is an aggregate passed by value.
3658   bool hasByValArgument() const {
3659     return AttributeList.hasAttrSomewhere(Attribute::ByVal);
3660   }
3661
3662   /// getCalledFunction - Return the function called, or null if this is an
3663   /// indirect function invocation.
3664   ///
3665   Function *getCalledFunction() const {
3666     return dyn_cast<Function>(Op<-3>());
3667   }
3668
3669   /// getCalledValue - Get a pointer to the function that is invoked by this
3670   /// instruction
3671   const Value *getCalledValue() const { return Op<-3>(); }
3672         Value *getCalledValue()       { return Op<-3>(); }
3673
3674   /// setCalledFunction - Set the function called.
3675   void setCalledFunction(Value* Fn) {
3676     setCalledFunction(
3677         cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
3678         Fn);
3679   }
3680   void setCalledFunction(FunctionType *FTy, Value *Fn) {
3681     this->FTy = FTy;
3682     assert(FTy == cast<FunctionType>(
3683                       cast<PointerType>(Fn->getType())->getElementType()));
3684     Op<-3>() = Fn;
3685   }
3686
3687   // get*Dest - Return the destination basic blocks...
3688   BasicBlock *getNormalDest() const {
3689     return cast<BasicBlock>(Op<-2>());
3690   }
3691   BasicBlock *getUnwindDest() const {
3692     return cast<BasicBlock>(Op<-1>());
3693   }
3694   void setNormalDest(BasicBlock *B) {
3695     Op<-2>() = reinterpret_cast<Value*>(B);
3696   }
3697   void setUnwindDest(BasicBlock *B) {
3698     Op<-1>() = reinterpret_cast<Value*>(B);
3699   }
3700
3701   /// getLandingPadInst - Get the landingpad instruction from the landing pad
3702   /// block (the unwind destination).
3703   LandingPadInst *getLandingPadInst() const;
3704
3705   BasicBlock *getSuccessor(unsigned i) const {
3706     assert(i < 2 && "Successor # out of range for invoke!");
3707     return i == 0 ? getNormalDest() : getUnwindDest();
3708   }
3709
3710   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3711     assert(idx < 2 && "Successor # out of range for invoke!");
3712     *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
3713   }
3714
3715   unsigned getNumSuccessors() const { return 2; }
3716
3717   // Methods for support type inquiry through isa, cast, and dyn_cast:
3718   static inline bool classof(const Instruction *I) {
3719     return (I->getOpcode() == Instruction::Invoke);
3720   }
3721   static inline bool classof(const Value *V) {
3722     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3723   }
3724
3725 private:
3726   BasicBlock *getSuccessorV(unsigned idx) const override;
3727   unsigned getNumSuccessorsV() const override;
3728   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3729
3730   bool hasFnAttrImpl(Attribute::AttrKind A) const;
3731
3732   // Shadow Instruction::setInstructionSubclassData with a private forwarding
3733   // method so that subclasses cannot accidentally use it.
3734   void setInstructionSubclassData(unsigned short D) {
3735     Instruction::setInstructionSubclassData(D);
3736   }
3737 };
3738
3739 template <>
3740 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
3741 };
3742
3743 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3744                        BasicBlock *IfException, ArrayRef<Value *> Args,
3745                        ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3746                        const Twine &NameStr, Instruction *InsertBefore)
3747     : TerminatorInst(Ty->getReturnType(), Instruction::Invoke,
3748                      OperandTraits<InvokeInst>::op_end(this) - Values, Values,
3749                      InsertBefore) {
3750   init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3751 }
3752 InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
3753                        BasicBlock *IfException, ArrayRef<Value *> Args,
3754                        ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3755                        const Twine &NameStr, BasicBlock *InsertAtEnd)
3756     : TerminatorInst(
3757           cast<FunctionType>(cast<PointerType>(Func->getType())
3758                                  ->getElementType())->getReturnType(),
3759           Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - Values,
3760           Values, InsertAtEnd) {
3761   init(Func, IfNormal, IfException, Args, Bundles, NameStr);
3762 }
3763
3764 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
3765
3766 //===----------------------------------------------------------------------===//
3767 //                              ResumeInst Class
3768 //===----------------------------------------------------------------------===//
3769
3770 //===---------------------------------------------------------------------------
3771 /// ResumeInst - Resume the propagation of an exception.
3772 ///
3773 class ResumeInst : public TerminatorInst {
3774   ResumeInst(const ResumeInst &RI);
3775
3776   explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
3777   ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
3778
3779 protected:
3780   // Note: Instruction needs to be a friend here to call cloneImpl.
3781   friend class Instruction;
3782   ResumeInst *cloneImpl() const;
3783
3784 public:
3785   static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
3786     return new(1) ResumeInst(Exn, InsertBefore);
3787   }
3788   static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
3789     return new(1) ResumeInst(Exn, InsertAtEnd);
3790   }
3791
3792   /// Provide fast operand accessors
3793   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3794
3795   /// Convenience accessor.
3796   Value *getValue() const { return Op<0>(); }
3797
3798   unsigned getNumSuccessors() const { return 0; }
3799
3800   // Methods for support type inquiry through isa, cast, and dyn_cast:
3801   static inline bool classof(const Instruction *I) {
3802     return I->getOpcode() == Instruction::Resume;
3803   }
3804   static inline bool classof(const Value *V) {
3805     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3806   }
3807
3808 private:
3809   BasicBlock *getSuccessorV(unsigned idx) const override;
3810   unsigned getNumSuccessorsV() const override;
3811   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3812 };
3813
3814 template <>
3815 struct OperandTraits<ResumeInst> :
3816     public FixedNumOperandTraits<ResumeInst, 1> {
3817 };
3818
3819 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
3820
3821 //===----------------------------------------------------------------------===//
3822 //                               CatchEndPadInst Class
3823 //===----------------------------------------------------------------------===//
3824
3825 class CatchEndPadInst : public TerminatorInst {
3826 private:
3827   CatchEndPadInst(const CatchEndPadInst &RI);
3828
3829   void init(BasicBlock *UnwindBB);
3830   CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB, unsigned Values,
3831                   Instruction *InsertBefore = nullptr);
3832   CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB, unsigned Values,
3833                   BasicBlock *InsertAtEnd);
3834
3835 protected:
3836   // Note: Instruction needs to be a friend here to call cloneImpl.
3837   friend class Instruction;
3838   CatchEndPadInst *cloneImpl() const;
3839
3840 public:
3841   static CatchEndPadInst *Create(LLVMContext &C, BasicBlock *UnwindBB = nullptr,
3842                                  Instruction *InsertBefore = nullptr) {
3843     unsigned Values = UnwindBB ? 1 : 0;
3844     return new (Values) CatchEndPadInst(C, UnwindBB, Values, InsertBefore);
3845   }
3846   static CatchEndPadInst *Create(LLVMContext &C, BasicBlock *UnwindBB,
3847                                  BasicBlock *InsertAtEnd) {
3848     unsigned Values = UnwindBB ? 1 : 0;
3849     return new (Values) CatchEndPadInst(C, UnwindBB, Values, InsertAtEnd);
3850   }
3851
3852   /// Provide fast operand accessors
3853   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3854
3855   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
3856   bool unwindsToCaller() const { return !hasUnwindDest(); }
3857
3858   /// Convenience accessor. Returns null if there is no return value.
3859   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
3860
3861   BasicBlock *getUnwindDest() const {
3862     return hasUnwindDest() ? cast<BasicBlock>(Op<-1>()) : nullptr;
3863   }
3864   void setUnwindDest(BasicBlock *NewDest) {
3865     assert(NewDest);
3866     Op<-1>() = NewDest;
3867   }
3868
3869   // Methods for support type inquiry through isa, cast, and dyn_cast:
3870   static inline bool classof(const Instruction *I) {
3871     return (I->getOpcode() == Instruction::CatchEndPad);
3872   }
3873   static inline bool classof(const Value *V) {
3874     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3875   }
3876
3877 private:
3878   BasicBlock *getSuccessorV(unsigned Idx) const override;
3879   unsigned getNumSuccessorsV() const override;
3880   void setSuccessorV(unsigned Idx, BasicBlock *B) override;
3881
3882   // Shadow Instruction::setInstructionSubclassData with a private forwarding
3883   // method so that subclasses cannot accidentally use it.
3884   void setInstructionSubclassData(unsigned short D) {
3885     Instruction::setInstructionSubclassData(D);
3886   }
3887 };
3888
3889 template <>
3890 struct OperandTraits<CatchEndPadInst>
3891     : public VariadicOperandTraits<CatchEndPadInst> {};
3892
3893 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchEndPadInst, Value)
3894
3895 //===----------------------------------------------------------------------===//
3896 //                           CatchPadInst Class
3897 //===----------------------------------------------------------------------===//
3898
3899 class CatchPadInst : public TerminatorInst {
3900 private:
3901   void init(BasicBlock *IfNormal, BasicBlock *IfException,
3902             ArrayRef<Value *> Args, const Twine &NameStr);
3903
3904   CatchPadInst(const CatchPadInst &CPI);
3905
3906   explicit CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
3907                         ArrayRef<Value *> Args, unsigned Values,
3908                         const Twine &NameStr, Instruction *InsertBefore);
3909   explicit CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
3910                         ArrayRef<Value *> Args, unsigned Values,
3911                         const Twine &NameStr, BasicBlock *InsertAtEnd);
3912
3913 protected:
3914   // Note: Instruction needs to be a friend here to call cloneImpl.
3915   friend class Instruction;
3916   CatchPadInst *cloneImpl() const;
3917
3918 public:
3919   static CatchPadInst *Create(BasicBlock *IfNormal, BasicBlock *IfException,
3920                               ArrayRef<Value *> Args, const Twine &NameStr = "",
3921                               Instruction *InsertBefore = nullptr) {
3922     unsigned Values = unsigned(Args.size()) + 2;
3923     return new (Values) CatchPadInst(IfNormal, IfException, Args, Values,
3924                                      NameStr, InsertBefore);
3925   }
3926   static CatchPadInst *Create(BasicBlock *IfNormal, BasicBlock *IfException,
3927                               ArrayRef<Value *> Args, const Twine &NameStr,
3928                               BasicBlock *InsertAtEnd) {
3929     unsigned Values = unsigned(Args.size()) + 2;
3930     return new (Values)
3931         CatchPadInst(IfNormal, IfException, Args, Values, NameStr, InsertAtEnd);
3932   }
3933
3934   /// Provide fast operand accessors
3935   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3936
3937   /// getNumArgOperands - Return the number of catchpad arguments.
3938   ///
3939   unsigned getNumArgOperands() const { return getNumOperands() - 2; }
3940
3941   /// getArgOperand/setArgOperand - Return/set the i-th catchpad argument.
3942   ///
3943   Value *getArgOperand(unsigned i) const { return getOperand(i); }
3944   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
3945
3946   /// arg_operands - iteration adapter for range-for loops.
3947   iterator_range<op_iterator> arg_operands() {
3948     return make_range(op_begin(), op_end() - 2);
3949   }
3950
3951   /// arg_operands - iteration adapter for range-for loops.
3952   iterator_range<const_op_iterator> arg_operands() const {
3953     return make_range(op_begin(), op_end() - 2);
3954   }
3955
3956   /// \brief Wrappers for getting the \c Use of a catchpad argument.
3957   const Use &getArgOperandUse(unsigned i) const { return getOperandUse(i); }
3958   Use &getArgOperandUse(unsigned i) { return getOperandUse(i); }
3959
3960   // get*Dest - Return the destination basic blocks...
3961   BasicBlock *getNormalDest() const { return cast<BasicBlock>(Op<-2>()); }
3962   BasicBlock *getUnwindDest() const { return cast<BasicBlock>(Op<-1>()); }
3963   void setNormalDest(BasicBlock *B) { Op<-2>() = B; }
3964   void setUnwindDest(BasicBlock *B) { Op<-1>() = B; }
3965
3966   BasicBlock *getSuccessor(unsigned i) const {
3967     assert(i < 2 && "Successor # out of range for catchpad!");
3968     return i == 0 ? getNormalDest() : getUnwindDest();
3969   }
3970
3971   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3972     assert(idx < 2 && "Successor # out of range for catchpad!");
3973     *(&Op<-2>() + idx) = NewSucc;
3974   }
3975
3976   unsigned getNumSuccessors() const { return 2; }
3977
3978   // Methods for support type inquiry through isa, cast, and dyn_cast:
3979   static inline bool classof(const Instruction *I) {
3980     return I->getOpcode() == Instruction::CatchPad;
3981   }
3982   static inline bool classof(const Value *V) {
3983     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3984   }
3985
3986 private:
3987   BasicBlock *getSuccessorV(unsigned idx) const override;
3988   unsigned getNumSuccessorsV() const override;
3989   void setSuccessorV(unsigned idx, BasicBlock *B) override;
3990 };
3991
3992 template <>
3993 struct OperandTraits<CatchPadInst>
3994     : public VariadicOperandTraits<CatchPadInst, /*MINARITY=*/2> {};
3995
3996 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchPadInst, Value)
3997
3998 //===----------------------------------------------------------------------===//
3999 //                           TerminatePadInst Class
4000 //===----------------------------------------------------------------------===//
4001
4002 class TerminatePadInst : public TerminatorInst {
4003 private:
4004   void init(BasicBlock *BB, ArrayRef<Value *> Args);
4005
4006   TerminatePadInst(const TerminatePadInst &TPI);
4007
4008   explicit TerminatePadInst(LLVMContext &C, BasicBlock *BB,
4009                             ArrayRef<Value *> Args, unsigned Values,
4010                             Instruction *InsertBefore);
4011   explicit TerminatePadInst(LLVMContext &C, BasicBlock *BB,
4012                             ArrayRef<Value *> Args, unsigned Values,
4013                             BasicBlock *InsertAtEnd);
4014
4015 protected:
4016   // Note: Instruction needs to be a friend here to call cloneImpl.
4017   friend class Instruction;
4018   TerminatePadInst *cloneImpl() const;
4019
4020 public:
4021   static TerminatePadInst *Create(LLVMContext &C, BasicBlock *BB = nullptr,
4022                                   ArrayRef<Value *> Args = None,
4023                                   Instruction *InsertBefore = nullptr) {
4024     unsigned Values = unsigned(Args.size());
4025     if (BB)
4026       ++Values;
4027     return new (Values) TerminatePadInst(C, BB, Args, Values, InsertBefore);
4028   }
4029   static TerminatePadInst *Create(LLVMContext &C, BasicBlock *BB,
4030                                   ArrayRef<Value *> Args,
4031                                   BasicBlock *InsertAtEnd) {
4032     unsigned Values = unsigned(Args.size());
4033     if (BB)
4034       ++Values;
4035     return new (Values) TerminatePadInst(C, BB, Args, Values, InsertAtEnd);
4036   }
4037
4038   /// Provide fast operand accessors
4039   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4040
4041   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4042   bool unwindsToCaller() const { return !hasUnwindDest(); }
4043
4044   /// getNumArgOperands - Return the number of terminatepad arguments.
4045   ///
4046   unsigned getNumArgOperands() const {
4047     unsigned NumOperands = getNumOperands();
4048     if (hasUnwindDest())
4049       return NumOperands - 1;
4050     return NumOperands;
4051   }
4052
4053   /// getArgOperand/setArgOperand - Return/set the i-th terminatepad argument.
4054   ///
4055   Value *getArgOperand(unsigned i) const { return getOperand(i); }
4056   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
4057
4058   const_op_iterator arg_end() const {
4059     if (hasUnwindDest())
4060       return op_end() - 1;
4061     return op_end();
4062   }
4063
4064   op_iterator arg_end() {
4065     if (hasUnwindDest())
4066       return op_end() - 1;
4067     return op_end();
4068   }
4069
4070   /// arg_operands - iteration adapter for range-for loops.
4071   iterator_range<op_iterator> arg_operands() {
4072     return make_range(op_begin(), arg_end());
4073   }
4074
4075   /// arg_operands - iteration adapter for range-for loops.
4076   iterator_range<const_op_iterator> arg_operands() const {
4077     return make_range(op_begin(), arg_end());
4078   }
4079
4080   /// \brief Wrappers for getting the \c Use of a terminatepad argument.
4081   const Use &getArgOperandUse(unsigned i) const { return getOperandUse(i); }
4082   Use &getArgOperandUse(unsigned i) { return getOperandUse(i); }
4083
4084   // get*Dest - Return the destination basic blocks...
4085   BasicBlock *getUnwindDest() const {
4086     if (!hasUnwindDest())
4087       return nullptr;
4088     return cast<BasicBlock>(Op<-1>());
4089   }
4090   void setUnwindDest(BasicBlock *B) {
4091     assert(B && hasUnwindDest());
4092     Op<-1>() = B;
4093   }
4094
4095   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4096
4097   // Methods for support type inquiry through isa, cast, and dyn_cast:
4098   static inline bool classof(const Instruction *I) {
4099     return I->getOpcode() == Instruction::TerminatePad;
4100   }
4101   static inline bool classof(const Value *V) {
4102     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4103   }
4104
4105 private:
4106   BasicBlock *getSuccessorV(unsigned idx) const override;
4107   unsigned getNumSuccessorsV() const override;
4108   void setSuccessorV(unsigned idx, BasicBlock *B) override;
4109
4110   // Shadow Instruction::setInstructionSubclassData with a private forwarding
4111   // method so that subclasses cannot accidentally use it.
4112   void setInstructionSubclassData(unsigned short D) {
4113     Instruction::setInstructionSubclassData(D);
4114   }
4115 };
4116
4117 template <>
4118 struct OperandTraits<TerminatePadInst>
4119     : public VariadicOperandTraits<TerminatePadInst, /*MINARITY=*/1> {};
4120
4121 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(TerminatePadInst, Value)
4122
4123 //===----------------------------------------------------------------------===//
4124 //                           CleanupPadInst Class
4125 //===----------------------------------------------------------------------===//
4126
4127 class CleanupPadInst : public Instruction {
4128 private:
4129   void init(ArrayRef<Value *> Args, const Twine &NameStr);
4130
4131   CleanupPadInst(const CleanupPadInst &CPI);
4132
4133   explicit CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
4134                           const Twine &NameStr, Instruction *InsertBefore);
4135   explicit CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
4136                           const Twine &NameStr, BasicBlock *InsertAtEnd);
4137
4138 protected:
4139   // Note: Instruction needs to be a friend here to call cloneImpl.
4140   friend class Instruction;
4141   CleanupPadInst *cloneImpl() const;
4142
4143 public:
4144   static CleanupPadInst *Create(LLVMContext &C, ArrayRef<Value *> Args,
4145                                 const Twine &NameStr = "",
4146                                 Instruction *InsertBefore = nullptr) {
4147     return new (Args.size()) CleanupPadInst(C, Args, NameStr, InsertBefore);
4148   }
4149   static CleanupPadInst *Create(LLVMContext &C, ArrayRef<Value *> Args,
4150                                 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4151     return new (Args.size()) CleanupPadInst(C, Args, NameStr, InsertAtEnd);
4152   }
4153
4154   /// Provide fast operand accessors
4155   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4156
4157   // Methods for support type inquiry through isa, cast, and dyn_cast:
4158   static inline bool classof(const Instruction *I) {
4159     return I->getOpcode() == Instruction::CleanupPad;
4160   }
4161   static inline bool classof(const Value *V) {
4162     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4163   }
4164 };
4165
4166 template <>
4167 struct OperandTraits<CleanupPadInst>
4168     : public VariadicOperandTraits<CleanupPadInst, /*MINARITY=*/0> {};
4169
4170 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupPadInst, Value)
4171
4172 //===----------------------------------------------------------------------===//
4173 //                               CatchReturnInst Class
4174 //===----------------------------------------------------------------------===//
4175
4176 class CatchReturnInst : public TerminatorInst {
4177   CatchReturnInst(const CatchReturnInst &RI);
4178
4179   void init(CatchPadInst *CatchPad, BasicBlock *BB);
4180   CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
4181                   Instruction *InsertBefore);
4182   CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
4183                   BasicBlock *InsertAtEnd);
4184
4185 protected:
4186   // Note: Instruction needs to be a friend here to call cloneImpl.
4187   friend class Instruction;
4188   CatchReturnInst *cloneImpl() const;
4189
4190 public:
4191   static CatchReturnInst *Create(CatchPadInst *CatchPad, BasicBlock *BB,
4192                                  Instruction *InsertBefore = nullptr) {
4193     assert(CatchPad);
4194     assert(BB);
4195     return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4196   }
4197   static CatchReturnInst *Create(CatchPadInst *CatchPad, BasicBlock *BB,
4198                                  BasicBlock *InsertAtEnd) {
4199     assert(CatchPad);
4200     assert(BB);
4201     return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4202   }
4203
4204   /// Provide fast operand accessors
4205   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4206
4207   /// Convenience accessors.
4208   CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4209   void setCatchPad(CatchPadInst *CatchPad) {
4210     assert(CatchPad);
4211     Op<0>() = CatchPad;
4212   }
4213
4214   BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4215   void setSuccessor(BasicBlock *NewSucc) {
4216     assert(NewSucc);
4217     Op<1>() = NewSucc;
4218   }
4219   unsigned getNumSuccessors() const { return 1; }
4220
4221   // Methods for support type inquiry through isa, cast, and dyn_cast:
4222   static inline bool classof(const Instruction *I) {
4223     return (I->getOpcode() == Instruction::CatchRet);
4224   }
4225   static inline bool classof(const Value *V) {
4226     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4227   }
4228
4229 private:
4230   BasicBlock *getSuccessorV(unsigned Idx) const override;
4231   unsigned getNumSuccessorsV() const override;
4232   void setSuccessorV(unsigned Idx, BasicBlock *B) override;
4233 };
4234
4235 template <>
4236 struct OperandTraits<CatchReturnInst>
4237     : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4238
4239 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4240
4241 //===----------------------------------------------------------------------===//
4242 //                               CleanupEndPadInst Class
4243 //===----------------------------------------------------------------------===//
4244
4245 class CleanupEndPadInst : public TerminatorInst {
4246 private:
4247   CleanupEndPadInst(const CleanupEndPadInst &CEPI);
4248
4249   void init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB);
4250   CleanupEndPadInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB,
4251                     unsigned Values, Instruction *InsertBefore = nullptr);
4252   CleanupEndPadInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB,
4253                     unsigned Values, BasicBlock *InsertAtEnd);
4254
4255 protected:
4256   // Note: Instruction needs to be a friend here to call cloneImpl.
4257   friend class Instruction;
4258   CleanupEndPadInst *cloneImpl() const;
4259
4260 public:
4261   static CleanupEndPadInst *Create(CleanupPadInst *CleanupPad,
4262                                    BasicBlock *UnwindBB = nullptr,
4263                                    Instruction *InsertBefore = nullptr) {
4264     unsigned Values = UnwindBB ? 2 : 1;
4265     return new (Values)
4266         CleanupEndPadInst(CleanupPad, UnwindBB, Values, InsertBefore);
4267   }
4268   static CleanupEndPadInst *Create(CleanupPadInst *CleanupPad,
4269                                    BasicBlock *UnwindBB,
4270                                    BasicBlock *InsertAtEnd) {
4271     unsigned Values = UnwindBB ? 2 : 1;
4272     return new (Values)
4273         CleanupEndPadInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4274   }
4275
4276   /// Provide fast operand accessors
4277   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4278
4279   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4280   bool unwindsToCaller() const { return !hasUnwindDest(); }
4281
4282   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4283
4284   /// Convenience accessors
4285   CleanupPadInst *getCleanupPad() const {
4286     return cast<CleanupPadInst>(Op<-1>());
4287   }
4288   void setCleanupPad(CleanupPadInst *CleanupPad) {
4289     assert(CleanupPad);
4290     Op<-1>() = CleanupPad;
4291   }
4292
4293   BasicBlock *getUnwindDest() const {
4294     return hasUnwindDest() ? cast<BasicBlock>(Op<-2>()) : nullptr;
4295   }
4296   void setUnwindDest(BasicBlock *NewDest) {
4297     assert(hasUnwindDest());
4298     assert(NewDest);
4299     Op<-2>() = NewDest;
4300   }
4301
4302   // Methods for support type inquiry through isa, cast, and dyn_cast:
4303   static inline bool classof(const Instruction *I) {
4304     return (I->getOpcode() == Instruction::CleanupEndPad);
4305   }
4306   static inline bool classof(const Value *V) {
4307     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4308   }
4309
4310 private:
4311   BasicBlock *getSuccessorV(unsigned Idx) const override;
4312   unsigned getNumSuccessorsV() const override;
4313   void setSuccessorV(unsigned Idx, BasicBlock *B) override;
4314
4315   // Shadow Instruction::setInstructionSubclassData with a private forwarding
4316   // method so that subclasses cannot accidentally use it.
4317   void setInstructionSubclassData(unsigned short D) {
4318     Instruction::setInstructionSubclassData(D);
4319   }
4320 };
4321
4322 template <>
4323 struct OperandTraits<CleanupEndPadInst>
4324     : public VariadicOperandTraits<CleanupEndPadInst, /*MINARITY=*/1> {};
4325
4326 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupEndPadInst, Value)
4327
4328 //===----------------------------------------------------------------------===//
4329 //                               CleanupReturnInst Class
4330 //===----------------------------------------------------------------------===//
4331
4332 class CleanupReturnInst : public TerminatorInst {
4333 private:
4334   CleanupReturnInst(const CleanupReturnInst &RI);
4335
4336   void init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB);
4337   CleanupReturnInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB,
4338                     unsigned Values, Instruction *InsertBefore = nullptr);
4339   CleanupReturnInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB,
4340                     unsigned Values, BasicBlock *InsertAtEnd);
4341
4342 protected:
4343   // Note: Instruction needs to be a friend here to call cloneImpl.
4344   friend class Instruction;
4345   CleanupReturnInst *cloneImpl() const;
4346
4347 public:
4348   static CleanupReturnInst *Create(CleanupPadInst *CleanupPad,
4349                                    BasicBlock *UnwindBB = nullptr,
4350                                    Instruction *InsertBefore = nullptr) {
4351     assert(CleanupPad);
4352     unsigned Values = 1;
4353     if (UnwindBB)
4354       ++Values;
4355     return new (Values)
4356         CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4357   }
4358   static CleanupReturnInst *Create(CleanupPadInst *CleanupPad,
4359                                    BasicBlock *UnwindBB,
4360                                    BasicBlock *InsertAtEnd) {
4361     assert(CleanupPad);
4362     unsigned Values = 1;
4363     if (UnwindBB)
4364       ++Values;
4365     return new (Values)
4366         CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4367   }
4368
4369   /// Provide fast operand accessors
4370   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4371
4372   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4373   bool unwindsToCaller() const { return !hasUnwindDest(); }
4374
4375   /// Convenience accessor.
4376   CleanupPadInst *getCleanupPad() const {
4377     return cast<CleanupPadInst>(Op<-1>());
4378   }
4379   void setCleanupPad(CleanupPadInst *CleanupPad) {
4380     assert(CleanupPad);
4381     Op<-1>() = CleanupPad;
4382   }
4383
4384   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4385
4386   BasicBlock *getUnwindDest() const {
4387     return hasUnwindDest() ? cast<BasicBlock>(Op<-2>()) : nullptr;
4388   }
4389   void setUnwindDest(BasicBlock *NewDest) {
4390     assert(NewDest);
4391     assert(hasUnwindDest());
4392     Op<-2>() = NewDest;
4393   }
4394
4395   // Methods for support type inquiry through isa, cast, and dyn_cast:
4396   static inline bool classof(const Instruction *I) {
4397     return (I->getOpcode() == Instruction::CleanupRet);
4398   }
4399   static inline bool classof(const Value *V) {
4400     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4401   }
4402
4403 private:
4404   BasicBlock *getSuccessorV(unsigned Idx) const override;
4405   unsigned getNumSuccessorsV() const override;
4406   void setSuccessorV(unsigned Idx, BasicBlock *B) override;
4407
4408   // Shadow Instruction::setInstructionSubclassData with a private forwarding
4409   // method so that subclasses cannot accidentally use it.
4410   void setInstructionSubclassData(unsigned short D) {
4411     Instruction::setInstructionSubclassData(D);
4412   }
4413 };
4414
4415 template <>
4416 struct OperandTraits<CleanupReturnInst>
4417     : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4418
4419 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4420
4421 //===----------------------------------------------------------------------===//
4422 //                           UnreachableInst Class
4423 //===----------------------------------------------------------------------===//
4424
4425 //===---------------------------------------------------------------------------
4426 /// UnreachableInst - This function has undefined behavior.  In particular, the
4427 /// presence of this instruction indicates some higher level knowledge that the
4428 /// end of the block cannot be reached.
4429 ///
4430 class UnreachableInst : public TerminatorInst {
4431   void *operator new(size_t, unsigned) = delete;
4432
4433 protected:
4434   // Note: Instruction needs to be a friend here to call cloneImpl.
4435   friend class Instruction;
4436   UnreachableInst *cloneImpl() const;
4437
4438 public:
4439   // allocate space for exactly zero operands
4440   void *operator new(size_t s) {
4441     return User::operator new(s, 0);
4442   }
4443   explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4444   explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4445
4446   unsigned getNumSuccessors() const { return 0; }
4447
4448   // Methods for support type inquiry through isa, cast, and dyn_cast:
4449   static inline bool classof(const Instruction *I) {
4450     return I->getOpcode() == Instruction::Unreachable;
4451   }
4452   static inline bool classof(const Value *V) {
4453     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4454   }
4455
4456 private:
4457   BasicBlock *getSuccessorV(unsigned idx) const override;
4458   unsigned getNumSuccessorsV() const override;
4459   void setSuccessorV(unsigned idx, BasicBlock *B) override;
4460 };
4461
4462 //===----------------------------------------------------------------------===//
4463 //                                 TruncInst Class
4464 //===----------------------------------------------------------------------===//
4465
4466 /// \brief This class represents a truncation of integer types.
4467 class TruncInst : public CastInst {
4468 protected:
4469   // Note: Instruction needs to be a friend here to call cloneImpl.
4470   friend class Instruction;
4471   /// \brief Clone an identical TruncInst
4472   TruncInst *cloneImpl() const;
4473
4474 public:
4475   /// \brief Constructor with insert-before-instruction semantics
4476   TruncInst(
4477     Value *S,                           ///< The value to be truncated
4478     Type *Ty,                           ///< The (smaller) type to truncate to
4479     const Twine &NameStr = "",          ///< A name for the new instruction
4480     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4481   );
4482
4483   /// \brief Constructor with insert-at-end-of-block semantics
4484   TruncInst(
4485     Value *S,                     ///< The value to be truncated
4486     Type *Ty,                     ///< The (smaller) type to truncate to
4487     const Twine &NameStr,         ///< A name for the new instruction
4488     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4489   );
4490
4491   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4492   static inline bool classof(const Instruction *I) {
4493     return I->getOpcode() == Trunc;
4494   }
4495   static inline bool classof(const Value *V) {
4496     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4497   }
4498 };
4499
4500 //===----------------------------------------------------------------------===//
4501 //                                 ZExtInst Class
4502 //===----------------------------------------------------------------------===//
4503
4504 /// \brief This class represents zero extension of integer types.
4505 class ZExtInst : public CastInst {
4506 protected:
4507   // Note: Instruction needs to be a friend here to call cloneImpl.
4508   friend class Instruction;
4509   /// \brief Clone an identical ZExtInst
4510   ZExtInst *cloneImpl() const;
4511
4512 public:
4513   /// \brief Constructor with insert-before-instruction semantics
4514   ZExtInst(
4515     Value *S,                           ///< The value to be zero extended
4516     Type *Ty,                           ///< The type to zero extend to
4517     const Twine &NameStr = "",          ///< A name for the new instruction
4518     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4519   );
4520
4521   /// \brief Constructor with insert-at-end semantics.
4522   ZExtInst(
4523     Value *S,                     ///< The value to be zero extended
4524     Type *Ty,                     ///< The type to zero extend to
4525     const Twine &NameStr,         ///< A name for the new instruction
4526     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4527   );
4528
4529   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4530   static inline bool classof(const Instruction *I) {
4531     return I->getOpcode() == ZExt;
4532   }
4533   static inline bool classof(const Value *V) {
4534     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4535   }
4536 };
4537
4538 //===----------------------------------------------------------------------===//
4539 //                                 SExtInst Class
4540 //===----------------------------------------------------------------------===//
4541
4542 /// \brief This class represents a sign extension of integer types.
4543 class SExtInst : public CastInst {
4544 protected:
4545   // Note: Instruction needs to be a friend here to call cloneImpl.
4546   friend class Instruction;
4547   /// \brief Clone an identical SExtInst
4548   SExtInst *cloneImpl() const;
4549
4550 public:
4551   /// \brief Constructor with insert-before-instruction semantics
4552   SExtInst(
4553     Value *S,                           ///< The value to be sign extended
4554     Type *Ty,                           ///< The type to sign extend to
4555     const Twine &NameStr = "",          ///< A name for the new instruction
4556     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4557   );
4558
4559   /// \brief Constructor with insert-at-end-of-block semantics
4560   SExtInst(
4561     Value *S,                     ///< The value to be sign extended
4562     Type *Ty,                     ///< The type to sign extend to
4563     const Twine &NameStr,         ///< A name for the new instruction
4564     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4565   );
4566
4567   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4568   static inline bool classof(const Instruction *I) {
4569     return I->getOpcode() == SExt;
4570   }
4571   static inline bool classof(const Value *V) {
4572     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4573   }
4574 };
4575
4576 //===----------------------------------------------------------------------===//
4577 //                                 FPTruncInst Class
4578 //===----------------------------------------------------------------------===//
4579
4580 /// \brief This class represents a truncation of floating point types.
4581 class FPTruncInst : public CastInst {
4582 protected:
4583   // Note: Instruction needs to be a friend here to call cloneImpl.
4584   friend class Instruction;
4585   /// \brief Clone an identical FPTruncInst
4586   FPTruncInst *cloneImpl() const;
4587
4588 public:
4589   /// \brief Constructor with insert-before-instruction semantics
4590   FPTruncInst(
4591     Value *S,                           ///< The value to be truncated
4592     Type *Ty,                           ///< The type to truncate to
4593     const Twine &NameStr = "",          ///< A name for the new instruction
4594     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4595   );
4596
4597   /// \brief Constructor with insert-before-instruction semantics
4598   FPTruncInst(
4599     Value *S,                     ///< The value to be truncated
4600     Type *Ty,                     ///< The type to truncate to
4601     const Twine &NameStr,         ///< A name for the new instruction
4602     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4603   );
4604
4605   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4606   static inline bool classof(const Instruction *I) {
4607     return I->getOpcode() == FPTrunc;
4608   }
4609   static inline bool classof(const Value *V) {
4610     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4611   }
4612 };
4613
4614 //===----------------------------------------------------------------------===//
4615 //                                 FPExtInst Class
4616 //===----------------------------------------------------------------------===//
4617
4618 /// \brief This class represents an extension of floating point types.
4619 class FPExtInst : public CastInst {
4620 protected:
4621   // Note: Instruction needs to be a friend here to call cloneImpl.
4622   friend class Instruction;
4623   /// \brief Clone an identical FPExtInst
4624   FPExtInst *cloneImpl() const;
4625
4626 public:
4627   /// \brief Constructor with insert-before-instruction semantics
4628   FPExtInst(
4629     Value *S,                           ///< The value to be extended
4630     Type *Ty,                           ///< The type to extend to
4631     const Twine &NameStr = "",          ///< A name for the new instruction
4632     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4633   );
4634
4635   /// \brief Constructor with insert-at-end-of-block semantics
4636   FPExtInst(
4637     Value *S,                     ///< The value to be extended
4638     Type *Ty,                     ///< The type to extend to
4639     const Twine &NameStr,         ///< A name for the new instruction
4640     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4641   );
4642
4643   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4644   static inline bool classof(const Instruction *I) {
4645     return I->getOpcode() == FPExt;
4646   }
4647   static inline bool classof(const Value *V) {
4648     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4649   }
4650 };
4651
4652 //===----------------------------------------------------------------------===//
4653 //                                 UIToFPInst Class
4654 //===----------------------------------------------------------------------===//
4655
4656 /// \brief This class represents a cast unsigned integer to floating point.
4657 class UIToFPInst : public CastInst {
4658 protected:
4659   // Note: Instruction needs to be a friend here to call cloneImpl.
4660   friend class Instruction;
4661   /// \brief Clone an identical UIToFPInst
4662   UIToFPInst *cloneImpl() const;
4663
4664 public:
4665   /// \brief Constructor with insert-before-instruction semantics
4666   UIToFPInst(
4667     Value *S,                           ///< The value to be converted
4668     Type *Ty,                           ///< The type to convert to
4669     const Twine &NameStr = "",          ///< A name for the new instruction
4670     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4671   );
4672
4673   /// \brief Constructor with insert-at-end-of-block semantics
4674   UIToFPInst(
4675     Value *S,                     ///< The value to be converted
4676     Type *Ty,                     ///< The type to convert to
4677     const Twine &NameStr,         ///< A name for the new instruction
4678     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4679   );
4680
4681   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4682   static inline bool classof(const Instruction *I) {
4683     return I->getOpcode() == UIToFP;
4684   }
4685   static inline bool classof(const Value *V) {
4686     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4687   }
4688 };
4689
4690 //===----------------------------------------------------------------------===//
4691 //                                 SIToFPInst Class
4692 //===----------------------------------------------------------------------===//
4693
4694 /// \brief This class represents a cast from signed integer to floating point.
4695 class SIToFPInst : public CastInst {
4696 protected:
4697   // Note: Instruction needs to be a friend here to call cloneImpl.
4698   friend class Instruction;
4699   /// \brief Clone an identical SIToFPInst
4700   SIToFPInst *cloneImpl() const;
4701
4702 public:
4703   /// \brief Constructor with insert-before-instruction semantics
4704   SIToFPInst(
4705     Value *S,                           ///< The value to be converted
4706     Type *Ty,                           ///< The type to convert to
4707     const Twine &NameStr = "",          ///< A name for the new instruction
4708     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4709   );
4710
4711   /// \brief Constructor with insert-at-end-of-block semantics
4712   SIToFPInst(
4713     Value *S,                     ///< The value to be converted
4714     Type *Ty,                     ///< The type to convert to
4715     const Twine &NameStr,         ///< A name for the new instruction
4716     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4717   );
4718
4719   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4720   static inline bool classof(const Instruction *I) {
4721     return I->getOpcode() == SIToFP;
4722   }
4723   static inline bool classof(const Value *V) {
4724     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4725   }
4726 };
4727
4728 //===----------------------------------------------------------------------===//
4729 //                                 FPToUIInst Class
4730 //===----------------------------------------------------------------------===//
4731
4732 /// \brief This class represents a cast from floating point to unsigned integer
4733 class FPToUIInst  : public CastInst {
4734 protected:
4735   // Note: Instruction needs to be a friend here to call cloneImpl.
4736   friend class Instruction;
4737   /// \brief Clone an identical FPToUIInst
4738   FPToUIInst *cloneImpl() const;
4739
4740 public:
4741   /// \brief Constructor with insert-before-instruction semantics
4742   FPToUIInst(
4743     Value *S,                           ///< The value to be converted
4744     Type *Ty,                           ///< The type to convert to
4745     const Twine &NameStr = "",          ///< A name for the new instruction
4746     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4747   );
4748
4749   /// \brief Constructor with insert-at-end-of-block semantics
4750   FPToUIInst(
4751     Value *S,                     ///< The value to be converted
4752     Type *Ty,                     ///< The type to convert to
4753     const Twine &NameStr,         ///< A name for the new instruction
4754     BasicBlock *InsertAtEnd       ///< Where to insert the new instruction
4755   );
4756
4757   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4758   static inline bool classof(const Instruction *I) {
4759     return I->getOpcode() == FPToUI;
4760   }
4761   static inline bool classof(const Value *V) {
4762     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4763   }
4764 };
4765
4766 //===----------------------------------------------------------------------===//
4767 //                                 FPToSIInst Class
4768 //===----------------------------------------------------------------------===//
4769
4770 /// \brief This class represents a cast from floating point to signed integer.
4771 class FPToSIInst  : public CastInst {
4772 protected:
4773   // Note: Instruction needs to be a friend here to call cloneImpl.
4774   friend class Instruction;
4775   /// \brief Clone an identical FPToSIInst
4776   FPToSIInst *cloneImpl() const;
4777
4778 public:
4779   /// \brief Constructor with insert-before-instruction semantics
4780   FPToSIInst(
4781     Value *S,                           ///< The value to be converted
4782     Type *Ty,                           ///< The type to convert to
4783     const Twine &NameStr = "",          ///< A name for the new instruction
4784     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4785   );
4786
4787   /// \brief Constructor with insert-at-end-of-block semantics
4788   FPToSIInst(
4789     Value *S,                     ///< The value to be converted
4790     Type *Ty,                     ///< The type to convert to
4791     const Twine &NameStr,         ///< A name for the new instruction
4792     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4793   );
4794
4795   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
4796   static inline bool classof(const Instruction *I) {
4797     return I->getOpcode() == FPToSI;
4798   }
4799   static inline bool classof(const Value *V) {
4800     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4801   }
4802 };
4803
4804 //===----------------------------------------------------------------------===//
4805 //                                 IntToPtrInst Class
4806 //===----------------------------------------------------------------------===//
4807
4808 /// \brief This class represents a cast from an integer to a pointer.
4809 class IntToPtrInst : public CastInst {
4810 public:
4811   /// \brief Constructor with insert-before-instruction semantics
4812   IntToPtrInst(
4813     Value *S,                           ///< The value to be converted
4814     Type *Ty,                           ///< The type to convert to
4815     const Twine &NameStr = "",          ///< A name for the new instruction
4816     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4817   );
4818
4819   /// \brief Constructor with insert-at-end-of-block semantics
4820   IntToPtrInst(
4821     Value *S,                     ///< The value to be converted
4822     Type *Ty,                     ///< The type to convert to
4823     const Twine &NameStr,         ///< A name for the new instruction
4824     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4825   );
4826
4827   // Note: Instruction needs to be a friend here to call cloneImpl.
4828   friend class Instruction;
4829   /// \brief Clone an identical IntToPtrInst
4830   IntToPtrInst *cloneImpl() const;
4831
4832   /// \brief Returns the address space of this instruction's pointer type.
4833   unsigned getAddressSpace() const {
4834     return getType()->getPointerAddressSpace();
4835   }
4836
4837   // Methods for support type inquiry through isa, cast, and dyn_cast:
4838   static inline bool classof(const Instruction *I) {
4839     return I->getOpcode() == IntToPtr;
4840   }
4841   static inline bool classof(const Value *V) {
4842     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4843   }
4844 };
4845
4846 //===----------------------------------------------------------------------===//
4847 //                                 PtrToIntInst Class
4848 //===----------------------------------------------------------------------===//
4849
4850 /// \brief This class represents a cast from a pointer to an integer
4851 class PtrToIntInst : public CastInst {
4852 protected:
4853   // Note: Instruction needs to be a friend here to call cloneImpl.
4854   friend class Instruction;
4855   /// \brief Clone an identical PtrToIntInst
4856   PtrToIntInst *cloneImpl() const;
4857
4858 public:
4859   /// \brief Constructor with insert-before-instruction semantics
4860   PtrToIntInst(
4861     Value *S,                           ///< The value to be converted
4862     Type *Ty,                           ///< The type to convert to
4863     const Twine &NameStr = "",          ///< A name for the new instruction
4864     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4865   );
4866
4867   /// \brief Constructor with insert-at-end-of-block semantics
4868   PtrToIntInst(
4869     Value *S,                     ///< The value to be converted
4870     Type *Ty,                     ///< The type to convert to
4871     const Twine &NameStr,         ///< A name for the new instruction
4872     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4873   );
4874
4875   /// \brief Gets the pointer operand.
4876   Value *getPointerOperand() { return getOperand(0); }
4877   /// \brief Gets the pointer operand.
4878   const Value *getPointerOperand() const { return getOperand(0); }
4879   /// \brief Gets the operand index of the pointer operand.
4880   static unsigned getPointerOperandIndex() { return 0U; }
4881
4882   /// \brief Returns the address space of the pointer operand.
4883   unsigned getPointerAddressSpace() const {
4884     return getPointerOperand()->getType()->getPointerAddressSpace();
4885   }
4886
4887   // Methods for support type inquiry through isa, cast, and dyn_cast:
4888   static inline bool classof(const Instruction *I) {
4889     return I->getOpcode() == PtrToInt;
4890   }
4891   static inline bool classof(const Value *V) {
4892     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4893   }
4894 };
4895
4896 //===----------------------------------------------------------------------===//
4897 //                             BitCastInst Class
4898 //===----------------------------------------------------------------------===//
4899
4900 /// \brief This class represents a no-op cast from one type to another.
4901 class BitCastInst : public CastInst {
4902 protected:
4903   // Note: Instruction needs to be a friend here to call cloneImpl.
4904   friend class Instruction;
4905   /// \brief Clone an identical BitCastInst
4906   BitCastInst *cloneImpl() const;
4907
4908 public:
4909   /// \brief Constructor with insert-before-instruction semantics
4910   BitCastInst(
4911     Value *S,                           ///< The value to be casted
4912     Type *Ty,                           ///< The type to casted to
4913     const Twine &NameStr = "",          ///< A name for the new instruction
4914     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4915   );
4916
4917   /// \brief Constructor with insert-at-end-of-block semantics
4918   BitCastInst(
4919     Value *S,                     ///< The value to be casted
4920     Type *Ty,                     ///< The type to casted to
4921     const Twine &NameStr,         ///< A name for the new instruction
4922     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4923   );
4924
4925   // Methods for support type inquiry through isa, cast, and dyn_cast:
4926   static inline bool classof(const Instruction *I) {
4927     return I->getOpcode() == BitCast;
4928   }
4929   static inline bool classof(const Value *V) {
4930     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4931   }
4932 };
4933
4934 //===----------------------------------------------------------------------===//
4935 //                          AddrSpaceCastInst Class
4936 //===----------------------------------------------------------------------===//
4937
4938 /// \brief This class represents a conversion between pointers from
4939 /// one address space to another.
4940 class AddrSpaceCastInst : public CastInst {
4941 protected:
4942   // Note: Instruction needs to be a friend here to call cloneImpl.
4943   friend class Instruction;
4944   /// \brief Clone an identical AddrSpaceCastInst
4945   AddrSpaceCastInst *cloneImpl() const;
4946
4947 public:
4948   /// \brief Constructor with insert-before-instruction semantics
4949   AddrSpaceCastInst(
4950     Value *S,                           ///< The value to be casted
4951     Type *Ty,                           ///< The type to casted to
4952     const Twine &NameStr = "",          ///< A name for the new instruction
4953     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4954   );
4955
4956   /// \brief Constructor with insert-at-end-of-block semantics
4957   AddrSpaceCastInst(
4958     Value *S,                     ///< The value to be casted
4959     Type *Ty,                     ///< The type to casted to
4960     const Twine &NameStr,         ///< A name for the new instruction
4961     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4962   );
4963
4964   // Methods for support type inquiry through isa, cast, and dyn_cast:
4965   static inline bool classof(const Instruction *I) {
4966     return I->getOpcode() == AddrSpaceCast;
4967   }
4968   static inline bool classof(const Value *V) {
4969     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4970   }
4971 };
4972
4973 } // End llvm namespace
4974
4975 #endif