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