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