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