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