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