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