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