]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/Instructions.h
Merge ^/head r319480 through r319547.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/iterator.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/InstrTypes.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/OperandTraits.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Use.h"
38 #include "llvm/IR/User.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Support/AtomicOrdering.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include <cassert>
44 #include <cstddef>
45 #include <cstdint>
46 #include <iterator>
47
48 namespace llvm {
49
50 class APInt;
51 class ConstantInt;
52 class DataLayout;
53 class LLVMContext;
54
55 enum SynchronizationScope {
56   SingleThread = 0,
57   CrossThread = 1
58 };
59
60 //===----------------------------------------------------------------------===//
61 //                                AllocaInst Class
62 //===----------------------------------------------------------------------===//
63
64 /// an instruction to allocate memory on the stack
65 class AllocaInst : public UnaryInstruction {
66   Type *AllocatedType;
67
68 protected:
69   // Note: Instruction needs to be a friend here to call cloneImpl.
70   friend class Instruction;
71
72   AllocaInst *cloneImpl() const;
73
74 public:
75   explicit AllocaInst(Type *Ty, unsigned AddrSpace,
76                       Value *ArraySize = nullptr,
77                       const Twine &Name = "",
78                       Instruction *InsertBefore = nullptr);
79   AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
80              const Twine &Name, BasicBlock *InsertAtEnd);
81
82   AllocaInst(Type *Ty, unsigned AddrSpace,
83              const Twine &Name, Instruction *InsertBefore = nullptr);
84   AllocaInst(Type *Ty, unsigned AddrSpace,
85              const Twine &Name, BasicBlock *InsertAtEnd);
86
87   AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
88              const Twine &Name = "", Instruction *InsertBefore = nullptr);
89   AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
90              const Twine &Name, BasicBlock *InsertAtEnd);
91
92   /// Return true if there is an allocation size parameter to the allocation
93   /// instruction that is not 1.
94   bool isArrayAllocation() const;
95
96   /// Get the number of elements allocated. For a simple allocation of a single
97   /// element, this will return a constant 1 value.
98   const Value *getArraySize() const { return getOperand(0); }
99   Value *getArraySize() { return getOperand(0); }
100
101   /// Overload to return most specific pointer type.
102   PointerType *getType() const {
103     return cast<PointerType>(Instruction::getType());
104   }
105
106   /// Return the type that is being allocated by the instruction.
107   Type *getAllocatedType() const { return AllocatedType; }
108   /// for use only in special circumstances that need to generically
109   /// transform a whole instruction (eg: IR linking and vectorization).
110   void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
111
112   /// Return the alignment of the memory that is being allocated by the
113   /// instruction.
114   unsigned getAlignment() const {
115     return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
116   }
117   void setAlignment(unsigned Align);
118
119   /// Return true if this alloca is in the entry block of the function and is a
120   /// constant size. If so, the code generator will fold it into the
121   /// prolog/epilog code, so it is basically free.
122   bool isStaticAlloca() const;
123
124   /// Return true if this alloca is used as an inalloca argument to a call. Such
125   /// allocas are never considered static even if they are in the entry block.
126   bool isUsedWithInAlloca() const {
127     return getSubclassDataFromInstruction() & 32;
128   }
129
130   /// Specify whether this alloca is used to represent the arguments to a call.
131   void setUsedWithInAlloca(bool V) {
132     setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
133                                (V ? 32 : 0));
134   }
135
136   /// Return true if this alloca is used as a swifterror argument to a call.
137   bool isSwiftError() const {
138     return getSubclassDataFromInstruction() & 64;
139   }
140
141   /// Specify whether this alloca is used to represent a swifterror.
142   void setSwiftError(bool V) {
143     setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
144                                (V ? 64 : 0));
145   }
146
147   // Methods for support type inquiry through isa, cast, and dyn_cast:
148   static inline bool classof(const Instruction *I) {
149     return (I->getOpcode() == Instruction::Alloca);
150   }
151   static inline bool classof(const Value *V) {
152     return isa<Instruction>(V) && classof(cast<Instruction>(V));
153   }
154
155 private:
156   // Shadow Instruction::setInstructionSubclassData with a private forwarding
157   // method so that subclasses cannot accidentally use it.
158   void setInstructionSubclassData(unsigned short D) {
159     Instruction::setInstructionSubclassData(D);
160   }
161 };
162
163 //===----------------------------------------------------------------------===//
164 //                                LoadInst Class
165 //===----------------------------------------------------------------------===//
166
167 /// An instruction for reading from memory. This uses the SubclassData field in
168 /// Value to store whether or not the load is volatile.
169 class LoadInst : public UnaryInstruction {
170   void AssertOK();
171
172 protected:
173   // Note: Instruction needs to be a friend here to call cloneImpl.
174   friend class Instruction;
175
176   LoadInst *cloneImpl() const;
177
178 public:
179   LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
180   LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
181   LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile = false,
182            Instruction *InsertBefore = nullptr);
183   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
184            Instruction *InsertBefore = nullptr)
185       : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
186                  NameStr, isVolatile, InsertBefore) {}
187   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
188            BasicBlock *InsertAtEnd);
189   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
190            Instruction *InsertBefore = nullptr)
191       : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
192                  NameStr, isVolatile, Align, InsertBefore) {}
193   LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
194            unsigned Align, Instruction *InsertBefore = nullptr);
195   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
196            unsigned Align, BasicBlock *InsertAtEnd);
197   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
198            AtomicOrdering Order, SynchronizationScope SynchScope = CrossThread,
199            Instruction *InsertBefore = nullptr)
200       : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
201                  NameStr, isVolatile, Align, Order, SynchScope, InsertBefore) {}
202   LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
203            unsigned Align, AtomicOrdering Order,
204            SynchronizationScope SynchScope = CrossThread,
205            Instruction *InsertBefore = nullptr);
206   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207            unsigned Align, AtomicOrdering Order,
208            SynchronizationScope SynchScope,
209            BasicBlock *InsertAtEnd);
210   LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
211   LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
212   LoadInst(Type *Ty, Value *Ptr, const char *NameStr = nullptr,
213            bool isVolatile = false, Instruction *InsertBefore = nullptr);
214   explicit LoadInst(Value *Ptr, const char *NameStr = nullptr,
215                     bool isVolatile = false,
216                     Instruction *InsertBefore = nullptr)
217       : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
218                  NameStr, isVolatile, InsertBefore) {}
219   LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
220            BasicBlock *InsertAtEnd);
221
222   /// Return true if this is a load from a volatile memory location.
223   bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
224
225   /// Specify whether this is a volatile load or not.
226   void setVolatile(bool V) {
227     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
228                                (V ? 1 : 0));
229   }
230
231   /// Return the alignment of the access that is being performed.
232   unsigned getAlignment() const {
233     return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
234   }
235
236   void setAlignment(unsigned Align);
237
238   /// Returns the ordering effect of this fence.
239   AtomicOrdering getOrdering() const {
240     return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
241   }
242
243   /// Set the ordering constraint on this load. May not be Release or
244   /// AcquireRelease.
245   void setOrdering(AtomicOrdering Ordering) {
246     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
247                                ((unsigned)Ordering << 7));
248   }
249
250   SynchronizationScope getSynchScope() const {
251     return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
252   }
253
254   /// Specify whether this load is ordered with respect to all
255   /// concurrently executing threads, or only with respect to signal handlers
256   /// executing in the same thread.
257   void setSynchScope(SynchronizationScope xthread) {
258     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
259                                (xthread << 6));
260   }
261
262   void setAtomic(AtomicOrdering Ordering,
263                  SynchronizationScope SynchScope = CrossThread) {
264     setOrdering(Ordering);
265     setSynchScope(SynchScope);
266   }
267
268   bool isSimple() const { return !isAtomic() && !isVolatile(); }
269
270   bool isUnordered() const {
271     return (getOrdering() == AtomicOrdering::NotAtomic ||
272             getOrdering() == AtomicOrdering::Unordered) &&
273            !isVolatile();
274   }
275
276   Value *getPointerOperand() { return getOperand(0); }
277   const Value *getPointerOperand() const { return getOperand(0); }
278   static unsigned getPointerOperandIndex() { return 0U; }
279   Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
280
281   /// Returns the address space of the pointer operand.
282   unsigned getPointerAddressSpace() const {
283     return getPointerOperandType()->getPointerAddressSpace();
284   }
285
286   // Methods for support type inquiry through isa, cast, and dyn_cast:
287   static inline bool classof(const Instruction *I) {
288     return I->getOpcode() == Instruction::Load;
289   }
290   static inline bool classof(const Value *V) {
291     return isa<Instruction>(V) && classof(cast<Instruction>(V));
292   }
293
294 private:
295   // Shadow Instruction::setInstructionSubclassData with a private forwarding
296   // method so that subclasses cannot accidentally use it.
297   void setInstructionSubclassData(unsigned short D) {
298     Instruction::setInstructionSubclassData(D);
299   }
300 };
301
302 //===----------------------------------------------------------------------===//
303 //                                StoreInst Class
304 //===----------------------------------------------------------------------===//
305
306 /// An instruction for storing to memory.
307 class StoreInst : public Instruction {
308   void AssertOK();
309
310 protected:
311   // Note: Instruction needs to be a friend here to call cloneImpl.
312   friend class Instruction;
313
314   StoreInst *cloneImpl() const;
315
316 public:
317   StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
318   StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
319   StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
320             Instruction *InsertBefore = nullptr);
321   StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
322   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
323             unsigned Align, Instruction *InsertBefore = nullptr);
324   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
325             unsigned Align, BasicBlock *InsertAtEnd);
326   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
327             unsigned Align, AtomicOrdering Order,
328             SynchronizationScope SynchScope = CrossThread,
329             Instruction *InsertBefore = nullptr);
330   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
331             unsigned Align, AtomicOrdering Order,
332             SynchronizationScope SynchScope,
333             BasicBlock *InsertAtEnd);
334
335   // allocate space for exactly two operands
336   void *operator new(size_t s) {
337     return User::operator new(s, 2);
338   }
339
340   void *operator new(size_t, unsigned) = delete;
341
342   /// Return true if this is a store to a volatile memory location.
343   bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
344
345   /// Specify whether this is a volatile store or not.
346   void setVolatile(bool V) {
347     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
348                                (V ? 1 : 0));
349   }
350
351   /// Transparently provide more efficient getOperand methods.
352   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
353
354   /// Return the alignment of the access that is being performed
355   unsigned getAlignment() const {
356     return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
357   }
358
359   void setAlignment(unsigned Align);
360
361   /// Returns the ordering effect of this store.
362   AtomicOrdering getOrdering() const {
363     return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
364   }
365
366   /// Set the ordering constraint on this store.  May not be Acquire or
367   /// AcquireRelease.
368   void setOrdering(AtomicOrdering Ordering) {
369     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
370                                ((unsigned)Ordering << 7));
371   }
372
373   SynchronizationScope getSynchScope() const {
374     return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
375   }
376
377   /// Specify whether this store instruction is ordered with respect to all
378   /// concurrently executing threads, or only with respect to signal handlers
379   /// executing in the same thread.
380   void setSynchScope(SynchronizationScope xthread) {
381     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
382                                (xthread << 6));
383   }
384
385   void setAtomic(AtomicOrdering Ordering,
386                  SynchronizationScope SynchScope = CrossThread) {
387     setOrdering(Ordering);
388     setSynchScope(SynchScope);
389   }
390
391   bool isSimple() const { return !isAtomic() && !isVolatile(); }
392
393   bool isUnordered() const {
394     return (getOrdering() == AtomicOrdering::NotAtomic ||
395             getOrdering() == AtomicOrdering::Unordered) &&
396            !isVolatile();
397   }
398
399   Value *getValueOperand() { return getOperand(0); }
400   const Value *getValueOperand() const { return getOperand(0); }
401
402   Value *getPointerOperand() { return getOperand(1); }
403   const Value *getPointerOperand() const { return getOperand(1); }
404   static unsigned getPointerOperandIndex() { return 1U; }
405   Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
406
407   /// Returns the address space of the pointer operand.
408   unsigned getPointerAddressSpace() const {
409     return getPointerOperandType()->getPointerAddressSpace();
410   }
411
412   // Methods for support type inquiry through isa, cast, and dyn_cast:
413   static inline bool classof(const Instruction *I) {
414     return I->getOpcode() == Instruction::Store;
415   }
416   static inline bool classof(const Value *V) {
417     return isa<Instruction>(V) && classof(cast<Instruction>(V));
418   }
419
420 private:
421   // Shadow Instruction::setInstructionSubclassData with a private forwarding
422   // method so that subclasses cannot accidentally use it.
423   void setInstructionSubclassData(unsigned short D) {
424     Instruction::setInstructionSubclassData(D);
425   }
426 };
427
428 template <>
429 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
430 };
431
432 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
433
434 //===----------------------------------------------------------------------===//
435 //                                FenceInst Class
436 //===----------------------------------------------------------------------===//
437
438 /// An instruction for ordering other memory operations.
439 class FenceInst : public Instruction {
440   void Init(AtomicOrdering Ordering, SynchronizationScope SynchScope);
441
442 protected:
443   // Note: Instruction needs to be a friend here to call cloneImpl.
444   friend class Instruction;
445
446   FenceInst *cloneImpl() const;
447
448 public:
449   // Ordering may only be Acquire, Release, AcquireRelease, or
450   // SequentiallyConsistent.
451   FenceInst(LLVMContext &C, AtomicOrdering Ordering,
452             SynchronizationScope SynchScope = CrossThread,
453             Instruction *InsertBefore = nullptr);
454   FenceInst(LLVMContext &C, AtomicOrdering Ordering,
455             SynchronizationScope SynchScope,
456             BasicBlock *InsertAtEnd);
457
458   // allocate space for exactly zero operands
459   void *operator new(size_t s) {
460     return User::operator new(s, 0);
461   }
462
463   void *operator new(size_t, unsigned) = delete;
464
465   /// Returns the ordering effect of this fence.
466   AtomicOrdering getOrdering() const {
467     return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
468   }
469
470   /// Set the ordering constraint on this fence.  May only be Acquire, Release,
471   /// AcquireRelease, or SequentiallyConsistent.
472   void setOrdering(AtomicOrdering Ordering) {
473     setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
474                                ((unsigned)Ordering << 1));
475   }
476
477   SynchronizationScope getSynchScope() const {
478     return SynchronizationScope(getSubclassDataFromInstruction() & 1);
479   }
480
481   /// Specify whether this fence orders other operations with respect to all
482   /// concurrently executing threads, or only with respect to signal handlers
483   /// executing in the same thread.
484   void setSynchScope(SynchronizationScope xthread) {
485     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
486                                xthread);
487   }
488
489   // Methods for support type inquiry through isa, cast, and dyn_cast:
490   static inline bool classof(const Instruction *I) {
491     return I->getOpcode() == Instruction::Fence;
492   }
493   static inline bool classof(const Value *V) {
494     return isa<Instruction>(V) && classof(cast<Instruction>(V));
495   }
496
497 private:
498   // Shadow Instruction::setInstructionSubclassData with a private forwarding
499   // method so that subclasses cannot accidentally use it.
500   void setInstructionSubclassData(unsigned short D) {
501     Instruction::setInstructionSubclassData(D);
502   }
503 };
504
505 //===----------------------------------------------------------------------===//
506 //                                AtomicCmpXchgInst Class
507 //===----------------------------------------------------------------------===//
508
509 /// an instruction that atomically checks whether a
510 /// specified value is in a memory location, and, if it is, stores a new value
511 /// there.  Returns the value that was loaded.
512 ///
513 class AtomicCmpXchgInst : public Instruction {
514   void Init(Value *Ptr, Value *Cmp, Value *NewVal,
515             AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
516             SynchronizationScope SynchScope);
517
518 protected:
519   // Note: Instruction needs to be a friend here to call cloneImpl.
520   friend class Instruction;
521
522   AtomicCmpXchgInst *cloneImpl() const;
523
524 public:
525   AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
526                     AtomicOrdering SuccessOrdering,
527                     AtomicOrdering FailureOrdering,
528                     SynchronizationScope SynchScope,
529                     Instruction *InsertBefore = nullptr);
530   AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
531                     AtomicOrdering SuccessOrdering,
532                     AtomicOrdering FailureOrdering,
533                     SynchronizationScope SynchScope,
534                     BasicBlock *InsertAtEnd);
535
536   // allocate space for exactly three operands
537   void *operator new(size_t s) {
538     return User::operator new(s, 3);
539   }
540
541   void *operator new(size_t, unsigned) = delete;
542
543   /// Return true if this is a cmpxchg from a volatile memory
544   /// location.
545   ///
546   bool isVolatile() const {
547     return getSubclassDataFromInstruction() & 1;
548   }
549
550   /// Specify whether this is a volatile cmpxchg.
551   ///
552   void setVolatile(bool V) {
553      setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
554                                 (unsigned)V);
555   }
556
557   /// Return true if this cmpxchg may spuriously fail.
558   bool isWeak() const {
559     return getSubclassDataFromInstruction() & 0x100;
560   }
561
562   void setWeak(bool IsWeak) {
563     setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
564                                (IsWeak << 8));
565   }
566
567   /// Transparently provide more efficient getOperand methods.
568   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
569
570   /// Set the ordering constraint on this cmpxchg.
571   void setSuccessOrdering(AtomicOrdering Ordering) {
572     assert(Ordering != AtomicOrdering::NotAtomic &&
573            "CmpXchg instructions can only be atomic.");
574     setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
575                                ((unsigned)Ordering << 2));
576   }
577
578   void setFailureOrdering(AtomicOrdering Ordering) {
579     assert(Ordering != AtomicOrdering::NotAtomic &&
580            "CmpXchg instructions can only be atomic.");
581     setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
582                                ((unsigned)Ordering << 5));
583   }
584
585   /// Specify whether this cmpxchg is atomic and orders other operations with
586   /// respect to all concurrently executing threads, or only with respect to
587   /// signal handlers executing in the same thread.
588   void setSynchScope(SynchronizationScope SynchScope) {
589     setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
590                                (SynchScope << 1));
591   }
592
593   /// Returns the ordering constraint on this cmpxchg.
594   AtomicOrdering getSuccessOrdering() const {
595     return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
596   }
597
598   /// Returns the ordering constraint on this cmpxchg.
599   AtomicOrdering getFailureOrdering() const {
600     return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
601   }
602
603   /// Returns whether this cmpxchg is atomic between threads or only within a
604   /// single thread.
605   SynchronizationScope getSynchScope() const {
606     return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
607   }
608
609   Value *getPointerOperand() { return getOperand(0); }
610   const Value *getPointerOperand() const { return getOperand(0); }
611   static unsigned getPointerOperandIndex() { return 0U; }
612
613   Value *getCompareOperand() { return getOperand(1); }
614   const Value *getCompareOperand() const { return getOperand(1); }
615
616   Value *getNewValOperand() { return getOperand(2); }
617   const Value *getNewValOperand() const { return getOperand(2); }
618
619   /// Returns the address space of the pointer operand.
620   unsigned getPointerAddressSpace() const {
621     return getPointerOperand()->getType()->getPointerAddressSpace();
622   }
623
624   /// Returns the strongest permitted ordering on failure, given the
625   /// desired ordering on success.
626   ///
627   /// If the comparison in a cmpxchg operation fails, there is no atomic store
628   /// so release semantics cannot be provided. So this function drops explicit
629   /// Release requests from the AtomicOrdering. A SequentiallyConsistent
630   /// operation would remain SequentiallyConsistent.
631   static AtomicOrdering
632   getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
633     switch (SuccessOrdering) {
634     default:
635       llvm_unreachable("invalid cmpxchg success ordering");
636     case AtomicOrdering::Release:
637     case AtomicOrdering::Monotonic:
638       return AtomicOrdering::Monotonic;
639     case AtomicOrdering::AcquireRelease:
640     case AtomicOrdering::Acquire:
641       return AtomicOrdering::Acquire;
642     case AtomicOrdering::SequentiallyConsistent:
643       return AtomicOrdering::SequentiallyConsistent;
644     }
645   }
646
647   // Methods for support type inquiry through isa, cast, and dyn_cast:
648   static inline bool classof(const Instruction *I) {
649     return I->getOpcode() == Instruction::AtomicCmpXchg;
650   }
651   static inline bool classof(const Value *V) {
652     return isa<Instruction>(V) && classof(cast<Instruction>(V));
653   }
654
655 private:
656   // Shadow Instruction::setInstructionSubclassData with a private forwarding
657   // method so that subclasses cannot accidentally use it.
658   void setInstructionSubclassData(unsigned short D) {
659     Instruction::setInstructionSubclassData(D);
660   }
661 };
662
663 template <>
664 struct OperandTraits<AtomicCmpXchgInst> :
665     public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
666 };
667
668 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
669
670 //===----------------------------------------------------------------------===//
671 //                                AtomicRMWInst Class
672 //===----------------------------------------------------------------------===//
673
674 /// an instruction that atomically reads a memory location,
675 /// combines it with another value, and then stores the result back.  Returns
676 /// the old value.
677 ///
678 class AtomicRMWInst : public Instruction {
679 protected:
680   // Note: Instruction needs to be a friend here to call cloneImpl.
681   friend class Instruction;
682
683   AtomicRMWInst *cloneImpl() const;
684
685 public:
686   /// This enumeration lists the possible modifications atomicrmw can make.  In
687   /// the descriptions, 'p' is the pointer to the instruction's memory location,
688   /// 'old' is the initial value of *p, and 'v' is the other value passed to the
689   /// instruction.  These instructions always return 'old'.
690   enum BinOp {
691     /// *p = v
692     Xchg,
693     /// *p = old + v
694     Add,
695     /// *p = old - v
696     Sub,
697     /// *p = old & v
698     And,
699     /// *p = ~(old & v)
700     Nand,
701     /// *p = old | v
702     Or,
703     /// *p = old ^ v
704     Xor,
705     /// *p = old >signed v ? old : v
706     Max,
707     /// *p = old <signed v ? old : v
708     Min,
709     /// *p = old >unsigned v ? old : v
710     UMax,
711     /// *p = old <unsigned v ? old : v
712     UMin,
713
714     FIRST_BINOP = Xchg,
715     LAST_BINOP = UMin,
716     BAD_BINOP
717   };
718
719   AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
720                 AtomicOrdering Ordering, SynchronizationScope SynchScope,
721                 Instruction *InsertBefore = nullptr);
722   AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
723                 AtomicOrdering Ordering, SynchronizationScope SynchScope,
724                 BasicBlock *InsertAtEnd);
725
726   // allocate space for exactly two operands
727   void *operator new(size_t s) {
728     return User::operator new(s, 2);
729   }
730
731   void *operator new(size_t, unsigned) = delete;
732
733   BinOp getOperation() const {
734     return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
735   }
736
737   void setOperation(BinOp Operation) {
738     unsigned short SubclassData = getSubclassDataFromInstruction();
739     setInstructionSubclassData((SubclassData & 31) |
740                                (Operation << 5));
741   }
742
743   /// Return true if this is a RMW on a volatile memory location.
744   ///
745   bool isVolatile() const {
746     return getSubclassDataFromInstruction() & 1;
747   }
748
749   /// Specify whether this is a volatile RMW or not.
750   ///
751   void setVolatile(bool V) {
752      setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
753                                 (unsigned)V);
754   }
755
756   /// Transparently provide more efficient getOperand methods.
757   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
758
759   /// Set the ordering constraint on this RMW.
760   void setOrdering(AtomicOrdering Ordering) {
761     assert(Ordering != AtomicOrdering::NotAtomic &&
762            "atomicrmw instructions can only be atomic.");
763     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
764                                ((unsigned)Ordering << 2));
765   }
766
767   /// Specify whether this RMW orders other operations with respect to all
768   /// concurrently executing threads, or only with respect to signal handlers
769   /// executing in the same thread.
770   void setSynchScope(SynchronizationScope SynchScope) {
771     setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
772                                (SynchScope << 1));
773   }
774
775   /// Returns the ordering constraint on this RMW.
776   AtomicOrdering getOrdering() const {
777     return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
778   }
779
780   /// Returns whether this RMW is atomic between threads or only within a
781   /// single thread.
782   SynchronizationScope getSynchScope() const {
783     return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
784   }
785
786   Value *getPointerOperand() { return getOperand(0); }
787   const Value *getPointerOperand() const { return getOperand(0); }
788   static unsigned getPointerOperandIndex() { return 0U; }
789
790   Value *getValOperand() { return getOperand(1); }
791   const Value *getValOperand() const { return getOperand(1); }
792
793   /// Returns the address space of the pointer operand.
794   unsigned getPointerAddressSpace() const {
795     return getPointerOperand()->getType()->getPointerAddressSpace();
796   }
797
798   // Methods for support type inquiry through isa, cast, and dyn_cast:
799   static inline bool classof(const Instruction *I) {
800     return I->getOpcode() == Instruction::AtomicRMW;
801   }
802   static inline bool classof(const Value *V) {
803     return isa<Instruction>(V) && classof(cast<Instruction>(V));
804   }
805
806 private:
807   void Init(BinOp Operation, Value *Ptr, Value *Val,
808             AtomicOrdering Ordering, SynchronizationScope SynchScope);
809
810   // Shadow Instruction::setInstructionSubclassData with a private forwarding
811   // method so that subclasses cannot accidentally use it.
812   void setInstructionSubclassData(unsigned short D) {
813     Instruction::setInstructionSubclassData(D);
814   }
815 };
816
817 template <>
818 struct OperandTraits<AtomicRMWInst>
819     : public FixedNumOperandTraits<AtomicRMWInst,2> {
820 };
821
822 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
823
824 //===----------------------------------------------------------------------===//
825 //                             GetElementPtrInst Class
826 //===----------------------------------------------------------------------===//
827
828 // checkGEPType - Simple wrapper function to give a better assertion failure
829 // message on bad indexes for a gep instruction.
830 //
831 inline Type *checkGEPType(Type *Ty) {
832   assert(Ty && "Invalid GetElementPtrInst indices for type!");
833   return Ty;
834 }
835
836 /// an instruction for type-safe pointer arithmetic to
837 /// access elements of arrays and structs
838 ///
839 class GetElementPtrInst : public Instruction {
840   Type *SourceElementType;
841   Type *ResultElementType;
842
843   GetElementPtrInst(const GetElementPtrInst &GEPI);
844
845   /// Constructors - Create a getelementptr instruction with a base pointer an
846   /// list of indices. The first ctor can optionally insert before an existing
847   /// instruction, the second appends the new instruction to the specified
848   /// BasicBlock.
849   inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
850                            ArrayRef<Value *> IdxList, unsigned Values,
851                            const Twine &NameStr, Instruction *InsertBefore);
852   inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
853                            ArrayRef<Value *> IdxList, unsigned Values,
854                            const Twine &NameStr, BasicBlock *InsertAtEnd);
855
856   void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
857
858 protected:
859   // Note: Instruction needs to be a friend here to call cloneImpl.
860   friend class Instruction;
861
862   GetElementPtrInst *cloneImpl() const;
863
864 public:
865   static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
866                                    ArrayRef<Value *> IdxList,
867                                    const Twine &NameStr = "",
868                                    Instruction *InsertBefore = nullptr) {
869     unsigned Values = 1 + unsigned(IdxList.size());
870     if (!PointeeType)
871       PointeeType =
872           cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
873     else
874       assert(
875           PointeeType ==
876           cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
877     return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
878                                           NameStr, InsertBefore);
879   }
880
881   static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
882                                    ArrayRef<Value *> IdxList,
883                                    const Twine &NameStr,
884                                    BasicBlock *InsertAtEnd) {
885     unsigned Values = 1 + unsigned(IdxList.size());
886     if (!PointeeType)
887       PointeeType =
888           cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
889     else
890       assert(
891           PointeeType ==
892           cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
893     return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
894                                           NameStr, InsertAtEnd);
895   }
896
897   /// Create an "inbounds" getelementptr. See the documentation for the
898   /// "inbounds" flag in LangRef.html for details.
899   static GetElementPtrInst *CreateInBounds(Value *Ptr,
900                                            ArrayRef<Value *> IdxList,
901                                            const Twine &NameStr = "",
902                                            Instruction *InsertBefore = nullptr){
903     return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
904   }
905
906   static GetElementPtrInst *
907   CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
908                  const Twine &NameStr = "",
909                  Instruction *InsertBefore = nullptr) {
910     GetElementPtrInst *GEP =
911         Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
912     GEP->setIsInBounds(true);
913     return GEP;
914   }
915
916   static GetElementPtrInst *CreateInBounds(Value *Ptr,
917                                            ArrayRef<Value *> IdxList,
918                                            const Twine &NameStr,
919                                            BasicBlock *InsertAtEnd) {
920     return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
921   }
922
923   static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
924                                            ArrayRef<Value *> IdxList,
925                                            const Twine &NameStr,
926                                            BasicBlock *InsertAtEnd) {
927     GetElementPtrInst *GEP =
928         Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
929     GEP->setIsInBounds(true);
930     return GEP;
931   }
932
933   /// Transparently provide more efficient getOperand methods.
934   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
935
936   Type *getSourceElementType() const { return SourceElementType; }
937
938   void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
939   void setResultElementType(Type *Ty) { ResultElementType = Ty; }
940
941   Type *getResultElementType() const {
942     assert(ResultElementType ==
943            cast<PointerType>(getType()->getScalarType())->getElementType());
944     return ResultElementType;
945   }
946
947   /// Returns the address space of this instruction's pointer type.
948   unsigned getAddressSpace() const {
949     // Note that this is always the same as the pointer operand's address space
950     // and that is cheaper to compute, so cheat here.
951     return getPointerAddressSpace();
952   }
953
954   /// Returns the type of the element that would be loaded with
955   /// a load instruction with the specified parameters.
956   ///
957   /// Null is returned if the indices are invalid for the specified
958   /// pointer type.
959   ///
960   static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
961   static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
962   static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
963
964   inline op_iterator       idx_begin()       { return op_begin()+1; }
965   inline const_op_iterator idx_begin() const { return op_begin()+1; }
966   inline op_iterator       idx_end()         { return op_end(); }
967   inline const_op_iterator idx_end()   const { return op_end(); }
968
969   inline iterator_range<op_iterator> indices() {
970     return make_range(idx_begin(), idx_end());
971   }
972
973   inline iterator_range<const_op_iterator> indices() const {
974     return make_range(idx_begin(), idx_end());
975   }
976
977   Value *getPointerOperand() {
978     return getOperand(0);
979   }
980   const Value *getPointerOperand() const {
981     return getOperand(0);
982   }
983   static unsigned getPointerOperandIndex() {
984     return 0U;    // get index for modifying correct operand.
985   }
986
987   /// Method to return the pointer operand as a
988   /// PointerType.
989   Type *getPointerOperandType() const {
990     return getPointerOperand()->getType();
991   }
992
993   /// Returns the address space of the pointer operand.
994   unsigned getPointerAddressSpace() const {
995     return getPointerOperandType()->getPointerAddressSpace();
996   }
997
998   /// Returns the pointer type returned by the GEP
999   /// instruction, which may be a vector of pointers.
1000   static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1001     return getGEPReturnType(
1002       cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1003       Ptr, IdxList);
1004   }
1005   static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1006                                 ArrayRef<Value *> IdxList) {
1007     Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1008                                    Ptr->getType()->getPointerAddressSpace());
1009     // Vector GEP
1010     if (Ptr->getType()->isVectorTy()) {
1011       unsigned NumElem = Ptr->getType()->getVectorNumElements();
1012       return VectorType::get(PtrTy, NumElem);
1013     }
1014     for (Value *Index : IdxList)
1015       if (Index->getType()->isVectorTy()) {
1016         unsigned NumElem = Index->getType()->getVectorNumElements();
1017         return VectorType::get(PtrTy, NumElem);
1018       }
1019     // Scalar GEP
1020     return PtrTy;
1021   }
1022
1023   unsigned getNumIndices() const {  // Note: always non-negative
1024     return getNumOperands() - 1;
1025   }
1026
1027   bool hasIndices() const {
1028     return getNumOperands() > 1;
1029   }
1030
1031   /// Return true if all of the indices of this GEP are
1032   /// zeros.  If so, the result pointer and the first operand have the same
1033   /// value, just potentially different types.
1034   bool hasAllZeroIndices() const;
1035
1036   /// Return true if all of the indices of this GEP are
1037   /// constant integers.  If so, the result pointer and the first operand have
1038   /// a constant offset between them.
1039   bool hasAllConstantIndices() const;
1040
1041   /// Set or clear the inbounds flag on this GEP instruction.
1042   /// See LangRef.html for the meaning of inbounds on a getelementptr.
1043   void setIsInBounds(bool b = true);
1044
1045   /// Determine whether the GEP has the inbounds flag.
1046   bool isInBounds() const;
1047
1048   /// Accumulate the constant address offset of this GEP if possible.
1049   ///
1050   /// This routine accepts an APInt into which it will accumulate the constant
1051   /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1052   /// all-constant, it returns false and the value of the offset APInt is
1053   /// undefined (it is *not* preserved!). The APInt passed into this routine
1054   /// must be at least as wide as the IntPtr type for the address space of
1055   /// the base GEP pointer.
1056   bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1057
1058   // Methods for support type inquiry through isa, cast, and dyn_cast:
1059   static inline bool classof(const Instruction *I) {
1060     return (I->getOpcode() == Instruction::GetElementPtr);
1061   }
1062   static inline bool classof(const Value *V) {
1063     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1064   }
1065 };
1066
1067 template <>
1068 struct OperandTraits<GetElementPtrInst> :
1069   public VariadicOperandTraits<GetElementPtrInst, 1> {
1070 };
1071
1072 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1073                                      ArrayRef<Value *> IdxList, unsigned Values,
1074                                      const Twine &NameStr,
1075                                      Instruction *InsertBefore)
1076     : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1077                   OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1078                   Values, InsertBefore),
1079       SourceElementType(PointeeType),
1080       ResultElementType(getIndexedType(PointeeType, IdxList)) {
1081   assert(ResultElementType ==
1082          cast<PointerType>(getType()->getScalarType())->getElementType());
1083   init(Ptr, IdxList, NameStr);
1084 }
1085
1086 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1087                                      ArrayRef<Value *> IdxList, unsigned Values,
1088                                      const Twine &NameStr,
1089                                      BasicBlock *InsertAtEnd)
1090     : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1091                   OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1092                   Values, InsertAtEnd),
1093       SourceElementType(PointeeType),
1094       ResultElementType(getIndexedType(PointeeType, IdxList)) {
1095   assert(ResultElementType ==
1096          cast<PointerType>(getType()->getScalarType())->getElementType());
1097   init(Ptr, IdxList, NameStr);
1098 }
1099
1100 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1101
1102 //===----------------------------------------------------------------------===//
1103 //                               ICmpInst Class
1104 //===----------------------------------------------------------------------===//
1105
1106 /// This instruction compares its operands according to the predicate given
1107 /// to the constructor. It only operates on integers or pointers. The operands
1108 /// must be identical types.
1109 /// Represent an integer comparison operator.
1110 class ICmpInst: public CmpInst {
1111   void AssertOK() {
1112     assert(getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1113            getPredicate() <= CmpInst::LAST_ICMP_PREDICATE &&
1114            "Invalid ICmp predicate value");
1115     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1116           "Both operands to ICmp instruction are not of the same type!");
1117     // Check that the operands are the right type
1118     assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1119             getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1120            "Invalid operand types for ICmp instruction");
1121   }
1122
1123 protected:
1124   // Note: Instruction needs to be a friend here to call cloneImpl.
1125   friend class Instruction;
1126
1127   /// Clone an identical ICmpInst
1128   ICmpInst *cloneImpl() const;
1129
1130 public:
1131   /// Constructor with insert-before-instruction semantics.
1132   ICmpInst(
1133     Instruction *InsertBefore,  ///< Where to insert
1134     Predicate pred,  ///< The predicate to use for the comparison
1135     Value *LHS,      ///< The left-hand-side of the expression
1136     Value *RHS,      ///< The right-hand-side of the expression
1137     const Twine &NameStr = ""  ///< Name of the instruction
1138   ) : CmpInst(makeCmpResultType(LHS->getType()),
1139               Instruction::ICmp, pred, LHS, RHS, NameStr,
1140               InsertBefore) {
1141 #ifndef NDEBUG
1142   AssertOK();
1143 #endif
1144   }
1145
1146   /// Constructor with insert-at-end semantics.
1147   ICmpInst(
1148     BasicBlock &InsertAtEnd, ///< Block to insert into.
1149     Predicate pred,  ///< The predicate to use for the comparison
1150     Value *LHS,      ///< The left-hand-side of the expression
1151     Value *RHS,      ///< The right-hand-side of the expression
1152     const Twine &NameStr = ""  ///< Name of the instruction
1153   ) : CmpInst(makeCmpResultType(LHS->getType()),
1154               Instruction::ICmp, pred, LHS, RHS, NameStr,
1155               &InsertAtEnd) {
1156 #ifndef NDEBUG
1157   AssertOK();
1158 #endif
1159   }
1160
1161   /// Constructor with no-insertion semantics
1162   ICmpInst(
1163     Predicate pred, ///< The predicate to use for the comparison
1164     Value *LHS,     ///< The left-hand-side of the expression
1165     Value *RHS,     ///< The right-hand-side of the expression
1166     const Twine &NameStr = "" ///< Name of the instruction
1167   ) : CmpInst(makeCmpResultType(LHS->getType()),
1168               Instruction::ICmp, pred, LHS, RHS, NameStr) {
1169 #ifndef NDEBUG
1170   AssertOK();
1171 #endif
1172   }
1173
1174   /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1175   /// @returns the predicate that would be the result if the operand were
1176   /// regarded as signed.
1177   /// Return the signed version of the predicate
1178   Predicate getSignedPredicate() const {
1179     return getSignedPredicate(getPredicate());
1180   }
1181
1182   /// This is a static version that you can use without an instruction.
1183   /// Return the signed version of the predicate.
1184   static Predicate getSignedPredicate(Predicate pred);
1185
1186   /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1187   /// @returns the predicate that would be the result if the operand were
1188   /// regarded as unsigned.
1189   /// Return the unsigned version of the predicate
1190   Predicate getUnsignedPredicate() const {
1191     return getUnsignedPredicate(getPredicate());
1192   }
1193
1194   /// This is a static version that you can use without an instruction.
1195   /// Return the unsigned version of the predicate.
1196   static Predicate getUnsignedPredicate(Predicate pred);
1197
1198   /// Return true if this predicate is either EQ or NE.  This also
1199   /// tests for commutativity.
1200   static bool isEquality(Predicate P) {
1201     return P == ICMP_EQ || P == ICMP_NE;
1202   }
1203
1204   /// Return true if this predicate is either EQ or NE.  This also
1205   /// tests for commutativity.
1206   bool isEquality() const {
1207     return isEquality(getPredicate());
1208   }
1209
1210   /// @returns true if the predicate of this ICmpInst is commutative
1211   /// Determine if this relation is commutative.
1212   bool isCommutative() const { return isEquality(); }
1213
1214   /// Return true if the predicate is relational (not EQ or NE).
1215   ///
1216   bool isRelational() const {
1217     return !isEquality();
1218   }
1219
1220   /// Return true if the predicate is relational (not EQ or NE).
1221   ///
1222   static bool isRelational(Predicate P) {
1223     return !isEquality(P);
1224   }
1225
1226   /// Exchange the two operands to this instruction in such a way that it does
1227   /// not modify the semantics of the instruction. The predicate value may be
1228   /// changed to retain the same result if the predicate is order dependent
1229   /// (e.g. ult).
1230   /// Swap operands and adjust predicate.
1231   void swapOperands() {
1232     setPredicate(getSwappedPredicate());
1233     Op<0>().swap(Op<1>());
1234   }
1235
1236   // Methods for support type inquiry through isa, cast, and dyn_cast:
1237   static inline bool classof(const Instruction *I) {
1238     return I->getOpcode() == Instruction::ICmp;
1239   }
1240   static inline bool classof(const Value *V) {
1241     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1242   }
1243 };
1244
1245 //===----------------------------------------------------------------------===//
1246 //                               FCmpInst Class
1247 //===----------------------------------------------------------------------===//
1248
1249 /// This instruction compares its operands according to the predicate given
1250 /// to the constructor. It only operates on floating point values or packed
1251 /// vectors of floating point values. The operands must be identical types.
1252 /// Represents a floating point comparison operator.
1253 class FCmpInst: public CmpInst {
1254 protected:
1255   // Note: Instruction needs to be a friend here to call cloneImpl.
1256   friend class Instruction;
1257
1258   /// Clone an identical FCmpInst
1259   FCmpInst *cloneImpl() const;
1260
1261 public:
1262   /// Constructor with insert-before-instruction semantics.
1263   FCmpInst(
1264     Instruction *InsertBefore, ///< Where to insert
1265     Predicate pred,  ///< The predicate to use for the comparison
1266     Value *LHS,      ///< The left-hand-side of the expression
1267     Value *RHS,      ///< The right-hand-side of the expression
1268     const Twine &NameStr = ""  ///< Name of the instruction
1269   ) : CmpInst(makeCmpResultType(LHS->getType()),
1270               Instruction::FCmp, pred, LHS, RHS, NameStr,
1271               InsertBefore) {
1272     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1273            "Invalid FCmp predicate value");
1274     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1275            "Both operands to FCmp instruction are not of the same type!");
1276     // Check that the operands are the right type
1277     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1278            "Invalid operand types for FCmp instruction");
1279   }
1280
1281   /// Constructor with insert-at-end semantics.
1282   FCmpInst(
1283     BasicBlock &InsertAtEnd, ///< Block to insert into.
1284     Predicate pred,  ///< The predicate to use for the comparison
1285     Value *LHS,      ///< The left-hand-side of the expression
1286     Value *RHS,      ///< The right-hand-side of the expression
1287     const Twine &NameStr = ""  ///< Name of the instruction
1288   ) : CmpInst(makeCmpResultType(LHS->getType()),
1289               Instruction::FCmp, pred, LHS, RHS, NameStr,
1290               &InsertAtEnd) {
1291     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1292            "Invalid FCmp predicate value");
1293     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1294            "Both operands to FCmp instruction are not of the same type!");
1295     // Check that the operands are the right type
1296     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1297            "Invalid operand types for FCmp instruction");
1298   }
1299
1300   /// Constructor with no-insertion semantics
1301   FCmpInst(
1302     Predicate pred, ///< The predicate to use for the comparison
1303     Value *LHS,     ///< The left-hand-side of the expression
1304     Value *RHS,     ///< The right-hand-side of the expression
1305     const Twine &NameStr = "" ///< Name of the instruction
1306   ) : CmpInst(makeCmpResultType(LHS->getType()),
1307               Instruction::FCmp, pred, LHS, RHS, NameStr) {
1308     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1309            "Invalid FCmp predicate value");
1310     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1311            "Both operands to FCmp instruction are not of the same type!");
1312     // Check that the operands are the right type
1313     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1314            "Invalid operand types for FCmp instruction");
1315   }
1316
1317   /// @returns true if the predicate of this instruction is EQ or NE.
1318   /// Determine if this is an equality predicate.
1319   static bool isEquality(Predicate Pred) {
1320     return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1321            Pred == FCMP_UNE;
1322   }
1323
1324   /// @returns true if the predicate of this instruction is EQ or NE.
1325   /// Determine if this is an equality predicate.
1326   bool isEquality() const { return isEquality(getPredicate()); }
1327
1328   /// @returns true if the predicate of this instruction is commutative.
1329   /// Determine if this is a commutative predicate.
1330   bool isCommutative() const {
1331     return isEquality() ||
1332            getPredicate() == FCMP_FALSE ||
1333            getPredicate() == FCMP_TRUE ||
1334            getPredicate() == FCMP_ORD ||
1335            getPredicate() == FCMP_UNO;
1336   }
1337
1338   /// @returns true if the predicate is relational (not EQ or NE).
1339   /// Determine if this a relational predicate.
1340   bool isRelational() const { return !isEquality(); }
1341
1342   /// Exchange the two operands to this instruction in such a way that it does
1343   /// not modify the semantics of the instruction. The predicate value may be
1344   /// changed to retain the same result if the predicate is order dependent
1345   /// (e.g. ult).
1346   /// Swap operands and adjust predicate.
1347   void swapOperands() {
1348     setPredicate(getSwappedPredicate());
1349     Op<0>().swap(Op<1>());
1350   }
1351
1352   /// Methods for support type inquiry through isa, cast, and dyn_cast:
1353   static inline bool classof(const Instruction *I) {
1354     return I->getOpcode() == Instruction::FCmp;
1355   }
1356   static inline bool classof(const Value *V) {
1357     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1358   }
1359 };
1360
1361 //===----------------------------------------------------------------------===//
1362 /// This class represents a function call, abstracting a target
1363 /// machine's calling convention.  This class uses low bit of the SubClassData
1364 /// field to indicate whether or not this is a tail call.  The rest of the bits
1365 /// hold the calling convention of the call.
1366 ///
1367 class CallInst : public Instruction,
1368                  public OperandBundleUser<CallInst, User::op_iterator> {
1369   friend class OperandBundleUser<CallInst, User::op_iterator>;
1370
1371   AttributeList Attrs; ///< parameter attributes for call
1372   FunctionType *FTy;
1373
1374   CallInst(const CallInst &CI);
1375
1376   /// Construct a CallInst given a range of arguments.
1377   /// Construct a CallInst from a range of arguments
1378   inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1379                   ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1380                   Instruction *InsertBefore);
1381
1382   inline CallInst(Value *Func, ArrayRef<Value *> Args,
1383                   ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1384                   Instruction *InsertBefore)
1385       : CallInst(cast<FunctionType>(
1386                      cast<PointerType>(Func->getType())->getElementType()),
1387                  Func, Args, Bundles, NameStr, InsertBefore) {}
1388
1389   inline CallInst(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr,
1390                   Instruction *InsertBefore)
1391       : CallInst(Func, Args, None, NameStr, InsertBefore) {}
1392
1393   /// Construct a CallInst given a range of arguments.
1394   /// Construct a CallInst from a range of arguments
1395   inline CallInst(Value *Func, ArrayRef<Value *> Args,
1396                   ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1397                   BasicBlock *InsertAtEnd);
1398
1399   explicit CallInst(Value *F, const Twine &NameStr,
1400                     Instruction *InsertBefore);
1401
1402   CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1403
1404   void init(Value *Func, ArrayRef<Value *> Args,
1405             ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
1406     init(cast<FunctionType>(
1407              cast<PointerType>(Func->getType())->getElementType()),
1408          Func, Args, Bundles, NameStr);
1409   }
1410   void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1411             ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1412   void init(Value *Func, const Twine &NameStr);
1413
1414   bool hasDescriptor() const { return HasDescriptor; }
1415
1416 protected:
1417   // Note: Instruction needs to be a friend here to call cloneImpl.
1418   friend class Instruction;
1419
1420   CallInst *cloneImpl() const;
1421
1422 public:
1423   static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1424                           ArrayRef<OperandBundleDef> Bundles = None,
1425                           const Twine &NameStr = "",
1426                           Instruction *InsertBefore = nullptr) {
1427     return Create(cast<FunctionType>(
1428                       cast<PointerType>(Func->getType())->getElementType()),
1429                   Func, Args, Bundles, NameStr, InsertBefore);
1430   }
1431
1432   static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1433                           const Twine &NameStr,
1434                           Instruction *InsertBefore = nullptr) {
1435     return Create(cast<FunctionType>(
1436                       cast<PointerType>(Func->getType())->getElementType()),
1437                   Func, Args, None, NameStr, InsertBefore);
1438   }
1439
1440   static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1441                           const Twine &NameStr,
1442                           Instruction *InsertBefore = nullptr) {
1443     return new (unsigned(Args.size() + 1))
1444         CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1445   }
1446
1447   static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1448                           ArrayRef<OperandBundleDef> Bundles = None,
1449                           const Twine &NameStr = "",
1450                           Instruction *InsertBefore = nullptr) {
1451     const unsigned TotalOps =
1452         unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1453     const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1454
1455     return new (TotalOps, DescriptorBytes)
1456         CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1457   }
1458
1459   static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1460                           ArrayRef<OperandBundleDef> Bundles,
1461                           const Twine &NameStr, BasicBlock *InsertAtEnd) {
1462     const unsigned TotalOps =
1463         unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1464     const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1465
1466     return new (TotalOps, DescriptorBytes)
1467         CallInst(Func, Args, Bundles, NameStr, InsertAtEnd);
1468   }
1469
1470   static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1471                           const Twine &NameStr, BasicBlock *InsertAtEnd) {
1472     return new (unsigned(Args.size() + 1))
1473         CallInst(Func, Args, None, NameStr, InsertAtEnd);
1474   }
1475
1476   static CallInst *Create(Value *F, const Twine &NameStr = "",
1477                           Instruction *InsertBefore = nullptr) {
1478     return new(1) CallInst(F, NameStr, InsertBefore);
1479   }
1480
1481   static CallInst *Create(Value *F, const Twine &NameStr,
1482                           BasicBlock *InsertAtEnd) {
1483     return new(1) CallInst(F, NameStr, InsertAtEnd);
1484   }
1485
1486   /// Create a clone of \p CI with a different set of operand bundles and
1487   /// insert it before \p InsertPt.
1488   ///
1489   /// The returned call instruction is identical \p CI in every way except that
1490   /// the operand bundles for the new instruction are set to the operand bundles
1491   /// in \p Bundles.
1492   static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1493                           Instruction *InsertPt = nullptr);
1494
1495   /// Generate the IR for a call to malloc:
1496   /// 1. Compute the malloc call's argument as the specified type's size,
1497   ///    possibly multiplied by the array size if the array size is not
1498   ///    constant 1.
1499   /// 2. Call malloc with that argument.
1500   /// 3. Bitcast the result of the malloc call to the specified type.
1501   static Instruction *CreateMalloc(Instruction *InsertBefore,
1502                                    Type *IntPtrTy, Type *AllocTy,
1503                                    Value *AllocSize, Value *ArraySize = nullptr,
1504                                    Function* MallocF = nullptr,
1505                                    const Twine &Name = "");
1506   static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1507                                    Type *IntPtrTy, Type *AllocTy,
1508                                    Value *AllocSize, Value *ArraySize = nullptr,
1509                                    Function* MallocF = nullptr,
1510                                    const Twine &Name = "");
1511   static Instruction *CreateMalloc(Instruction *InsertBefore,
1512                                    Type *IntPtrTy, Type *AllocTy,
1513                                    Value *AllocSize, Value *ArraySize = nullptr,
1514                                    ArrayRef<OperandBundleDef> Bundles = None,
1515                                    Function* MallocF = nullptr,
1516                                    const Twine &Name = "");
1517   static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1518                                    Type *IntPtrTy, Type *AllocTy,
1519                                    Value *AllocSize, Value *ArraySize = nullptr,
1520                                    ArrayRef<OperandBundleDef> Bundles = None,
1521                                    Function* MallocF = nullptr,
1522                                    const Twine &Name = "");
1523   /// Generate the IR for a call to the builtin free function.
1524   static Instruction *CreateFree(Value *Source,
1525                                  Instruction *InsertBefore);
1526   static Instruction *CreateFree(Value *Source,
1527                                  BasicBlock *InsertAtEnd);
1528   static Instruction *CreateFree(Value *Source,
1529                                  ArrayRef<OperandBundleDef> Bundles,
1530                                  Instruction *InsertBefore);
1531   static Instruction *CreateFree(Value *Source,
1532                                  ArrayRef<OperandBundleDef> Bundles,
1533                                  BasicBlock *InsertAtEnd);
1534
1535   FunctionType *getFunctionType() const { return FTy; }
1536
1537   void mutateFunctionType(FunctionType *FTy) {
1538     mutateType(FTy->getReturnType());
1539     this->FTy = FTy;
1540   }
1541
1542   // Note that 'musttail' implies 'tail'.
1543   enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2,
1544                       TCK_NoTail = 3 };
1545   TailCallKind getTailCallKind() const {
1546     return TailCallKind(getSubclassDataFromInstruction() & 3);
1547   }
1548
1549   bool isTailCall() const {
1550     unsigned Kind = getSubclassDataFromInstruction() & 3;
1551     return Kind == TCK_Tail || Kind == TCK_MustTail;
1552   }
1553
1554   bool isMustTailCall() const {
1555     return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1556   }
1557
1558   bool isNoTailCall() const {
1559     return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1560   }
1561
1562   void setTailCall(bool isTC = true) {
1563     setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1564                                unsigned(isTC ? TCK_Tail : TCK_None));
1565   }
1566
1567   void setTailCallKind(TailCallKind TCK) {
1568     setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1569                                unsigned(TCK));
1570   }
1571
1572   /// Provide fast operand accessors
1573   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1574
1575   /// Return the number of call arguments.
1576   ///
1577   unsigned getNumArgOperands() const {
1578     return getNumOperands() - getNumTotalBundleOperands() - 1;
1579   }
1580
1581   /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1582   ///
1583   Value *getArgOperand(unsigned i) const {
1584     assert(i < getNumArgOperands() && "Out of bounds!");
1585     return getOperand(i);
1586   }
1587   void setArgOperand(unsigned i, Value *v) {
1588     assert(i < getNumArgOperands() && "Out of bounds!");
1589     setOperand(i, v);
1590   }
1591
1592   /// Return the iterator pointing to the beginning of the argument list.
1593   op_iterator arg_begin() { return op_begin(); }
1594
1595   /// Return the iterator pointing to the end of the argument list.
1596   op_iterator arg_end() {
1597     // [ call args ], [ operand bundles ], callee
1598     return op_end() - getNumTotalBundleOperands() - 1;
1599   }
1600
1601   /// Iteration adapter for range-for loops.
1602   iterator_range<op_iterator> arg_operands() {
1603     return make_range(arg_begin(), arg_end());
1604   }
1605
1606   /// Return the iterator pointing to the beginning of the argument list.
1607   const_op_iterator arg_begin() const { return op_begin(); }
1608
1609   /// Return the iterator pointing to the end of the argument list.
1610   const_op_iterator arg_end() const {
1611     // [ call args ], [ operand bundles ], callee
1612     return op_end() - getNumTotalBundleOperands() - 1;
1613   }
1614
1615   /// Iteration adapter for range-for loops.
1616   iterator_range<const_op_iterator> arg_operands() const {
1617     return make_range(arg_begin(), arg_end());
1618   }
1619
1620   /// Wrappers for getting the \c Use of a call argument.
1621   const Use &getArgOperandUse(unsigned i) const {
1622     assert(i < getNumArgOperands() && "Out of bounds!");
1623     return getOperandUse(i);
1624   }
1625   Use &getArgOperandUse(unsigned i) {
1626     assert(i < getNumArgOperands() && "Out of bounds!");
1627     return getOperandUse(i);
1628   }
1629
1630   /// If one of the arguments has the 'returned' attribute, return its
1631   /// operand value. Otherwise, return nullptr.
1632   Value *getReturnedArgOperand() const;
1633
1634   /// getCallingConv/setCallingConv - Get or set the calling convention of this
1635   /// function call.
1636   CallingConv::ID getCallingConv() const {
1637     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1638   }
1639   void setCallingConv(CallingConv::ID CC) {
1640     auto ID = static_cast<unsigned>(CC);
1641     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1642     setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1643                                (ID << 2));
1644   }
1645
1646   /// Return the parameter attributes for this call.
1647   ///
1648   AttributeList getAttributes() const { return Attrs; }
1649
1650   /// Set the parameter attributes for this call.
1651   ///
1652   void setAttributes(AttributeList A) { Attrs = A; }
1653
1654   /// adds the attribute to the list of attributes.
1655   void addAttribute(unsigned i, Attribute::AttrKind Kind);
1656
1657   /// adds the attribute to the list of attributes.
1658   void addAttribute(unsigned i, Attribute Attr);
1659
1660   /// Adds the attribute to the indicated argument
1661   void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1662
1663   /// Adds the attribute to the indicated argument
1664   void addParamAttr(unsigned ArgNo, Attribute Attr);
1665
1666   /// removes the attribute from the list of attributes.
1667   void removeAttribute(unsigned i, Attribute::AttrKind Kind);
1668
1669   /// removes the attribute from the list of attributes.
1670   void removeAttribute(unsigned i, StringRef Kind);
1671
1672   /// Removes the attribute from the given argument
1673   void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1674
1675   /// Removes the attribute from the given argument
1676   void removeParamAttr(unsigned ArgNo, StringRef Kind);
1677
1678   /// adds the dereferenceable attribute to the list of attributes.
1679   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1680
1681   /// adds the dereferenceable_or_null attribute to the list of
1682   /// attributes.
1683   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1684
1685   /// Determine whether this call has the given attribute.
1686   bool hasFnAttr(Attribute::AttrKind Kind) const {
1687     assert(Kind != Attribute::NoBuiltin &&
1688            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1689     return hasFnAttrImpl(Kind);
1690   }
1691
1692   /// Determine whether this call has the given attribute.
1693   bool hasFnAttr(StringRef Kind) const {
1694     return hasFnAttrImpl(Kind);
1695   }
1696
1697   /// Determine whether the return value has the given attribute.
1698   bool hasRetAttr(Attribute::AttrKind Kind) const;
1699
1700   /// Determine whether the argument or parameter has the given attribute.
1701   bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1702
1703   /// Get the attribute of a given kind at a position.
1704   Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1705     return getAttributes().getAttribute(i, Kind);
1706   }
1707
1708   /// Get the attribute of a given kind at a position.
1709   Attribute getAttribute(unsigned i, StringRef Kind) const {
1710     return getAttributes().getAttribute(i, Kind);
1711   }
1712
1713   /// Get the attribute of a given kind from a given arg
1714   Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1715     assert(ArgNo < getNumArgOperands() && "Out of bounds");
1716     return getAttributes().getParamAttr(ArgNo, Kind);
1717   }
1718
1719   /// Get the attribute of a given kind from a given arg
1720   Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1721     assert(ArgNo < getNumArgOperands() && "Out of bounds");
1722     return getAttributes().getParamAttr(ArgNo, Kind);
1723   }
1724
1725   /// Return true if the data operand at index \p i has the attribute \p
1726   /// A.
1727   ///
1728   /// Data operands include call arguments and values used in operand bundles,
1729   /// but does not include the callee operand.  This routine dispatches to the
1730   /// underlying AttributeList or the OperandBundleUser as appropriate.
1731   ///
1732   /// The index \p i is interpreted as
1733   ///
1734   ///  \p i == Attribute::ReturnIndex  -> the return value
1735   ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
1736   ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1737   ///     (\p i - 1) in the operand list.
1738   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
1739
1740   /// Extract the alignment of the return value.
1741   unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
1742
1743   /// Extract the alignment for a call or parameter (0=unknown).
1744   unsigned getParamAlignment(unsigned ArgNo) const {
1745     return Attrs.getParamAlignment(ArgNo);
1746   }
1747
1748   /// Extract the number of dereferenceable bytes for a call or
1749   /// parameter (0=unknown).
1750   uint64_t getDereferenceableBytes(unsigned i) const {
1751     return Attrs.getDereferenceableBytes(i);
1752   }
1753
1754   /// Extract the number of dereferenceable_or_null bytes for a call or
1755   /// parameter (0=unknown).
1756   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1757     return Attrs.getDereferenceableOrNullBytes(i);
1758   }
1759
1760   /// @brief Determine if the return value is marked with NoAlias attribute.
1761   bool returnDoesNotAlias() const {
1762     return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1763   }
1764
1765   /// Return true if the call should not be treated as a call to a
1766   /// builtin.
1767   bool isNoBuiltin() const {
1768     return hasFnAttrImpl(Attribute::NoBuiltin) &&
1769       !hasFnAttrImpl(Attribute::Builtin);
1770   }
1771
1772   /// Return true if the call should not be inlined.
1773   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1774   void setIsNoInline() {
1775     addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1776   }
1777
1778   /// Return true if the call can return twice
1779   bool canReturnTwice() const {
1780     return hasFnAttr(Attribute::ReturnsTwice);
1781   }
1782   void setCanReturnTwice() {
1783     addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1784   }
1785
1786   /// Determine if the call does not access memory.
1787   bool doesNotAccessMemory() const {
1788     return hasFnAttr(Attribute::ReadNone);
1789   }
1790   void setDoesNotAccessMemory() {
1791     addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1792   }
1793
1794   /// Determine if the call does not access or only reads memory.
1795   bool onlyReadsMemory() const {
1796     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1797   }
1798   void setOnlyReadsMemory() {
1799     addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1800   }
1801
1802   /// Determine if the call does not access or only writes memory.
1803   bool doesNotReadMemory() const {
1804     return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1805   }
1806   void setDoesNotReadMemory() {
1807     addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1808   }
1809
1810   /// @brief Determine if the call can access memmory only using pointers based
1811   /// on its arguments.
1812   bool onlyAccessesArgMemory() const {
1813     return hasFnAttr(Attribute::ArgMemOnly);
1814   }
1815   void setOnlyAccessesArgMemory() {
1816     addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1817   }
1818
1819   /// Determine if the call cannot return.
1820   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1821   void setDoesNotReturn() {
1822     addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1823   }
1824
1825   /// Determine if the call cannot unwind.
1826   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1827   void setDoesNotThrow() {
1828     addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1829   }
1830
1831   /// Determine if the call cannot be duplicated.
1832   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1833   void setCannotDuplicate() {
1834     addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1835   }
1836
1837   /// Determine if the call is convergent
1838   bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1839   void setConvergent() {
1840     addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1841   }
1842   void setNotConvergent() {
1843     removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1844   }
1845
1846   /// Determine if the call returns a structure through first
1847   /// pointer argument.
1848   bool hasStructRetAttr() const {
1849     if (getNumArgOperands() == 0)
1850       return false;
1851
1852     // Be friendly and also check the callee.
1853     return paramHasAttr(0, Attribute::StructRet);
1854   }
1855
1856   /// Determine if any call argument is an aggregate passed by value.
1857   bool hasByValArgument() const {
1858     return Attrs.hasAttrSomewhere(Attribute::ByVal);
1859   }
1860
1861   /// Return the function called, or null if this is an
1862   /// indirect function invocation.
1863   ///
1864   Function *getCalledFunction() const {
1865     return dyn_cast<Function>(Op<-1>());
1866   }
1867
1868   /// Get a pointer to the function that is invoked by this
1869   /// instruction.
1870   const Value *getCalledValue() const { return Op<-1>(); }
1871         Value *getCalledValue()       { return Op<-1>(); }
1872
1873   /// Set the function called.
1874   void setCalledFunction(Value* Fn) {
1875     setCalledFunction(
1876         cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1877         Fn);
1878   }
1879   void setCalledFunction(FunctionType *FTy, Value *Fn) {
1880     this->FTy = FTy;
1881     assert(FTy == cast<FunctionType>(
1882                       cast<PointerType>(Fn->getType())->getElementType()));
1883     Op<-1>() = Fn;
1884   }
1885
1886   /// Check if this call is an inline asm statement.
1887   bool isInlineAsm() const {
1888     return isa<InlineAsm>(Op<-1>());
1889   }
1890
1891   // Methods for support type inquiry through isa, cast, and dyn_cast:
1892   static inline bool classof(const Instruction *I) {
1893     return I->getOpcode() == Instruction::Call;
1894   }
1895   static inline bool classof(const Value *V) {
1896     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1897   }
1898
1899 private:
1900   template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
1901     if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
1902       return true;
1903
1904     // Operand bundles override attributes on the called function, but don't
1905     // override attributes directly present on the call instruction.
1906     if (isFnAttrDisallowedByOpBundle(Kind))
1907       return false;
1908
1909     if (const Function *F = getCalledFunction())
1910       return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
1911                                              Kind);
1912     return false;
1913   }
1914
1915   // Shadow Instruction::setInstructionSubclassData with a private forwarding
1916   // method so that subclasses cannot accidentally use it.
1917   void setInstructionSubclassData(unsigned short D) {
1918     Instruction::setInstructionSubclassData(D);
1919   }
1920 };
1921
1922 template <>
1923 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1924 };
1925
1926 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1927                    ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1928                    BasicBlock *InsertAtEnd)
1929     : Instruction(
1930           cast<FunctionType>(cast<PointerType>(Func->getType())
1931                                  ->getElementType())->getReturnType(),
1932           Instruction::Call, OperandTraits<CallInst>::op_end(this) -
1933                                  (Args.size() + CountBundleInputs(Bundles) + 1),
1934           unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1935   init(Func, Args, Bundles, NameStr);
1936 }
1937
1938 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1939                    ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1940                    Instruction *InsertBefore)
1941     : Instruction(Ty->getReturnType(), Instruction::Call,
1942                   OperandTraits<CallInst>::op_end(this) -
1943                       (Args.size() + CountBundleInputs(Bundles) + 1),
1944                   unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1945                   InsertBefore) {
1946   init(Ty, Func, Args, Bundles, NameStr);
1947 }
1948
1949 // Note: if you get compile errors about private methods then
1950 //       please update your code to use the high-level operand
1951 //       interfaces. See line 943 above.
1952 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1953
1954 //===----------------------------------------------------------------------===//
1955 //                               SelectInst Class
1956 //===----------------------------------------------------------------------===//
1957
1958 /// This class represents the LLVM 'select' instruction.
1959 ///
1960 class SelectInst : public Instruction {
1961   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1962              Instruction *InsertBefore)
1963     : Instruction(S1->getType(), Instruction::Select,
1964                   &Op<0>(), 3, InsertBefore) {
1965     init(C, S1, S2);
1966     setName(NameStr);
1967   }
1968
1969   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1970              BasicBlock *InsertAtEnd)
1971     : Instruction(S1->getType(), Instruction::Select,
1972                   &Op<0>(), 3, InsertAtEnd) {
1973     init(C, S1, S2);
1974     setName(NameStr);
1975   }
1976
1977   void init(Value *C, Value *S1, Value *S2) {
1978     assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1979     Op<0>() = C;
1980     Op<1>() = S1;
1981     Op<2>() = S2;
1982   }
1983
1984 protected:
1985   // Note: Instruction needs to be a friend here to call cloneImpl.
1986   friend class Instruction;
1987
1988   SelectInst *cloneImpl() const;
1989
1990 public:
1991   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1992                             const Twine &NameStr = "",
1993                             Instruction *InsertBefore = nullptr,
1994                             Instruction *MDFrom = nullptr) {
1995     SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1996     if (MDFrom)
1997       Sel->copyMetadata(*MDFrom);
1998     return Sel;
1999   }
2000
2001   static SelectInst *Create(Value *C, Value *S1, Value *S2,
2002                             const Twine &NameStr,
2003                             BasicBlock *InsertAtEnd) {
2004     return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
2005   }
2006
2007   const Value *getCondition() const { return Op<0>(); }
2008   const Value *getTrueValue() const { return Op<1>(); }
2009   const Value *getFalseValue() const { return Op<2>(); }
2010   Value *getCondition() { return Op<0>(); }
2011   Value *getTrueValue() { return Op<1>(); }
2012   Value *getFalseValue() { return Op<2>(); }
2013
2014   void setCondition(Value *V) { Op<0>() = V; }
2015   void setTrueValue(Value *V) { Op<1>() = V; }
2016   void setFalseValue(Value *V) { Op<2>() = V; }
2017
2018   /// Return a string if the specified operands are invalid
2019   /// for a select operation, otherwise return null.
2020   static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
2021
2022   /// Transparently provide more efficient getOperand methods.
2023   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2024
2025   OtherOps getOpcode() const {
2026     return static_cast<OtherOps>(Instruction::getOpcode());
2027   }
2028
2029   // Methods for support type inquiry through isa, cast, and dyn_cast:
2030   static inline bool classof(const Instruction *I) {
2031     return I->getOpcode() == Instruction::Select;
2032   }
2033   static inline bool classof(const Value *V) {
2034     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2035   }
2036 };
2037
2038 template <>
2039 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
2040 };
2041
2042 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
2043
2044 //===----------------------------------------------------------------------===//
2045 //                                VAArgInst Class
2046 //===----------------------------------------------------------------------===//
2047
2048 /// This class represents the va_arg llvm instruction, which returns
2049 /// an argument of the specified type given a va_list and increments that list
2050 ///
2051 class VAArgInst : public UnaryInstruction {
2052 protected:
2053   // Note: Instruction needs to be a friend here to call cloneImpl.
2054   friend class Instruction;
2055
2056   VAArgInst *cloneImpl() const;
2057
2058 public:
2059   VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
2060              Instruction *InsertBefore = nullptr)
2061     : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
2062     setName(NameStr);
2063   }
2064
2065   VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
2066             BasicBlock *InsertAtEnd)
2067     : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
2068     setName(NameStr);
2069   }
2070
2071   Value *getPointerOperand() { return getOperand(0); }
2072   const Value *getPointerOperand() const { return getOperand(0); }
2073   static unsigned getPointerOperandIndex() { return 0U; }
2074
2075   // Methods for support type inquiry through isa, cast, and dyn_cast:
2076   static inline bool classof(const Instruction *I) {
2077     return I->getOpcode() == VAArg;
2078   }
2079   static inline bool classof(const Value *V) {
2080     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2081   }
2082 };
2083
2084 //===----------------------------------------------------------------------===//
2085 //                                ExtractElementInst Class
2086 //===----------------------------------------------------------------------===//
2087
2088 /// This instruction extracts a single (scalar)
2089 /// element from a VectorType value
2090 ///
2091 class ExtractElementInst : public Instruction {
2092   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
2093                      Instruction *InsertBefore = nullptr);
2094   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
2095                      BasicBlock *InsertAtEnd);
2096
2097 protected:
2098   // Note: Instruction needs to be a friend here to call cloneImpl.
2099   friend class Instruction;
2100
2101   ExtractElementInst *cloneImpl() const;
2102
2103 public:
2104   static ExtractElementInst *Create(Value *Vec, Value *Idx,
2105                                    const Twine &NameStr = "",
2106                                    Instruction *InsertBefore = nullptr) {
2107     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
2108   }
2109
2110   static ExtractElementInst *Create(Value *Vec, Value *Idx,
2111                                    const Twine &NameStr,
2112                                    BasicBlock *InsertAtEnd) {
2113     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
2114   }
2115
2116   /// Return true if an extractelement instruction can be
2117   /// formed with the specified operands.
2118   static bool isValidOperands(const Value *Vec, const Value *Idx);
2119
2120   Value *getVectorOperand() { return Op<0>(); }
2121   Value *getIndexOperand() { return Op<1>(); }
2122   const Value *getVectorOperand() const { return Op<0>(); }
2123   const Value *getIndexOperand() const { return Op<1>(); }
2124
2125   VectorType *getVectorOperandType() const {
2126     return cast<VectorType>(getVectorOperand()->getType());
2127   }
2128
2129   /// Transparently provide more efficient getOperand methods.
2130   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2131
2132   // Methods for support type inquiry through isa, cast, and dyn_cast:
2133   static inline bool classof(const Instruction *I) {
2134     return I->getOpcode() == Instruction::ExtractElement;
2135   }
2136   static inline bool classof(const Value *V) {
2137     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2138   }
2139 };
2140
2141 template <>
2142 struct OperandTraits<ExtractElementInst> :
2143   public FixedNumOperandTraits<ExtractElementInst, 2> {
2144 };
2145
2146 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
2147
2148 //===----------------------------------------------------------------------===//
2149 //                                InsertElementInst Class
2150 //===----------------------------------------------------------------------===//
2151
2152 /// This instruction inserts a single (scalar)
2153 /// element into a VectorType value
2154 ///
2155 class InsertElementInst : public Instruction {
2156   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2157                     const Twine &NameStr = "",
2158                     Instruction *InsertBefore = nullptr);
2159   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2160                     BasicBlock *InsertAtEnd);
2161
2162 protected:
2163   // Note: Instruction needs to be a friend here to call cloneImpl.
2164   friend class Instruction;
2165
2166   InsertElementInst *cloneImpl() const;
2167
2168 public:
2169   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2170                                    const Twine &NameStr = "",
2171                                    Instruction *InsertBefore = nullptr) {
2172     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2173   }
2174
2175   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2176                                    const Twine &NameStr,
2177                                    BasicBlock *InsertAtEnd) {
2178     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2179   }
2180
2181   /// Return true if an insertelement instruction can be
2182   /// formed with the specified operands.
2183   static bool isValidOperands(const Value *Vec, const Value *NewElt,
2184                               const Value *Idx);
2185
2186   /// Overload to return most specific vector type.
2187   ///
2188   VectorType *getType() const {
2189     return cast<VectorType>(Instruction::getType());
2190   }
2191
2192   /// Transparently provide more efficient getOperand methods.
2193   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2194
2195   // Methods for support type inquiry through isa, cast, and dyn_cast:
2196   static inline bool classof(const Instruction *I) {
2197     return I->getOpcode() == Instruction::InsertElement;
2198   }
2199   static inline bool classof(const Value *V) {
2200     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2201   }
2202 };
2203
2204 template <>
2205 struct OperandTraits<InsertElementInst> :
2206   public FixedNumOperandTraits<InsertElementInst, 3> {
2207 };
2208
2209 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2210
2211 //===----------------------------------------------------------------------===//
2212 //                           ShuffleVectorInst Class
2213 //===----------------------------------------------------------------------===//
2214
2215 /// This instruction constructs a fixed permutation of two
2216 /// input vectors.
2217 ///
2218 class ShuffleVectorInst : public Instruction {
2219 protected:
2220   // Note: Instruction needs to be a friend here to call cloneImpl.
2221   friend class Instruction;
2222
2223   ShuffleVectorInst *cloneImpl() const;
2224
2225 public:
2226   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2227                     const Twine &NameStr = "",
2228                     Instruction *InsertBefor = nullptr);
2229   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2230                     const Twine &NameStr, BasicBlock *InsertAtEnd);
2231
2232   // allocate space for exactly three operands
2233   void *operator new(size_t s) {
2234     return User::operator new(s, 3);
2235   }
2236
2237   /// Return true if a shufflevector instruction can be
2238   /// formed with the specified operands.
2239   static bool isValidOperands(const Value *V1, const Value *V2,
2240                               const Value *Mask);
2241
2242   /// Overload to return most specific vector type.
2243   ///
2244   VectorType *getType() const {
2245     return cast<VectorType>(Instruction::getType());
2246   }
2247
2248   /// Transparently provide more efficient getOperand methods.
2249   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2250
2251   Constant *getMask() const {
2252     return cast<Constant>(getOperand(2));
2253   }
2254
2255   /// Return the shuffle mask value for the specified element of the mask.
2256   /// Return -1 if the element is undef.
2257   static int getMaskValue(Constant *Mask, unsigned Elt);
2258
2259   /// Return the shuffle mask value of this instruction for the given element
2260   /// index. Return -1 if the element is undef.
2261   int getMaskValue(unsigned Elt) const {
2262     return getMaskValue(getMask(), Elt);
2263   }
2264
2265   /// Convert the input shuffle mask operand to a vector of integers. Undefined
2266   /// elements of the mask are returned as -1.
2267   static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2268
2269   /// Return the mask for this instruction as a vector of integers. Undefined
2270   /// elements of the mask are returned as -1.
2271   void getShuffleMask(SmallVectorImpl<int> &Result) const {
2272     return getShuffleMask(getMask(), Result);
2273   }
2274
2275   SmallVector<int, 16> getShuffleMask() const {
2276     SmallVector<int, 16> Mask;
2277     getShuffleMask(Mask);
2278     return Mask;
2279   }
2280
2281   /// Change values in a shuffle permute mask assuming the two vector operands
2282   /// of length InVecNumElts have swapped position.
2283   static void commuteShuffleMask(MutableArrayRef<int> Mask,
2284                                  unsigned InVecNumElts) {
2285     for (int &Idx : Mask) {
2286       if (Idx == -1)
2287         continue;
2288       Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2289       assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2290              "shufflevector mask index out of range");
2291     }
2292   }
2293
2294   // Methods for support type inquiry through isa, cast, and dyn_cast:
2295   static inline bool classof(const Instruction *I) {
2296     return I->getOpcode() == Instruction::ShuffleVector;
2297   }
2298   static inline bool classof(const Value *V) {
2299     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2300   }
2301 };
2302
2303 template <>
2304 struct OperandTraits<ShuffleVectorInst> :
2305   public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2306 };
2307
2308 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2309
2310 //===----------------------------------------------------------------------===//
2311 //                                ExtractValueInst Class
2312 //===----------------------------------------------------------------------===//
2313
2314 /// This instruction extracts a struct member or array
2315 /// element value from an aggregate value.
2316 ///
2317 class ExtractValueInst : public UnaryInstruction {
2318   SmallVector<unsigned, 4> Indices;
2319
2320   ExtractValueInst(const ExtractValueInst &EVI);
2321
2322   /// Constructors - Create a extractvalue instruction with a base aggregate
2323   /// value and a list of indices.  The first ctor can optionally insert before
2324   /// an existing instruction, the second appends the new instruction to the
2325   /// specified BasicBlock.
2326   inline ExtractValueInst(Value *Agg,
2327                           ArrayRef<unsigned> Idxs,
2328                           const Twine &NameStr,
2329                           Instruction *InsertBefore);
2330   inline ExtractValueInst(Value *Agg,
2331                           ArrayRef<unsigned> Idxs,
2332                           const Twine &NameStr, BasicBlock *InsertAtEnd);
2333
2334   // allocate space for exactly one operand
2335   void *operator new(size_t s) { return User::operator new(s, 1); }
2336
2337   void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2338
2339 protected:
2340   // Note: Instruction needs to be a friend here to call cloneImpl.
2341   friend class Instruction;
2342
2343   ExtractValueInst *cloneImpl() const;
2344
2345 public:
2346   static ExtractValueInst *Create(Value *Agg,
2347                                   ArrayRef<unsigned> Idxs,
2348                                   const Twine &NameStr = "",
2349                                   Instruction *InsertBefore = nullptr) {
2350     return new
2351       ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2352   }
2353
2354   static ExtractValueInst *Create(Value *Agg,
2355                                   ArrayRef<unsigned> Idxs,
2356                                   const Twine &NameStr,
2357                                   BasicBlock *InsertAtEnd) {
2358     return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2359   }
2360
2361   /// Returns the type of the element that would be extracted
2362   /// with an extractvalue instruction with the specified parameters.
2363   ///
2364   /// Null is returned if the indices are invalid for the specified type.
2365   static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2366
2367   using idx_iterator = const unsigned*;
2368
2369   inline idx_iterator idx_begin() const { return Indices.begin(); }
2370   inline idx_iterator idx_end()   const { return Indices.end(); }
2371   inline iterator_range<idx_iterator> indices() const {
2372     return make_range(idx_begin(), idx_end());
2373   }
2374
2375   Value *getAggregateOperand() {
2376     return getOperand(0);
2377   }
2378   const Value *getAggregateOperand() const {
2379     return getOperand(0);
2380   }
2381   static unsigned getAggregateOperandIndex() {
2382     return 0U;                      // get index for modifying correct operand
2383   }
2384
2385   ArrayRef<unsigned> getIndices() const {
2386     return Indices;
2387   }
2388
2389   unsigned getNumIndices() const {
2390     return (unsigned)Indices.size();
2391   }
2392
2393   bool hasIndices() const {
2394     return true;
2395   }
2396
2397   // Methods for support type inquiry through isa, cast, and dyn_cast:
2398   static inline bool classof(const Instruction *I) {
2399     return I->getOpcode() == Instruction::ExtractValue;
2400   }
2401   static inline bool classof(const Value *V) {
2402     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2403   }
2404 };
2405
2406 ExtractValueInst::ExtractValueInst(Value *Agg,
2407                                    ArrayRef<unsigned> Idxs,
2408                                    const Twine &NameStr,
2409                                    Instruction *InsertBefore)
2410   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2411                      ExtractValue, Agg, InsertBefore) {
2412   init(Idxs, NameStr);
2413 }
2414
2415 ExtractValueInst::ExtractValueInst(Value *Agg,
2416                                    ArrayRef<unsigned> Idxs,
2417                                    const Twine &NameStr,
2418                                    BasicBlock *InsertAtEnd)
2419   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2420                      ExtractValue, Agg, InsertAtEnd) {
2421   init(Idxs, NameStr);
2422 }
2423
2424 //===----------------------------------------------------------------------===//
2425 //                                InsertValueInst Class
2426 //===----------------------------------------------------------------------===//
2427
2428 /// This instruction inserts a struct field of array element
2429 /// value into an aggregate value.
2430 ///
2431 class InsertValueInst : public Instruction {
2432   SmallVector<unsigned, 4> Indices;
2433
2434   InsertValueInst(const InsertValueInst &IVI);
2435
2436   /// Constructors - Create a insertvalue instruction with a base aggregate
2437   /// value, a value to insert, and a list of indices.  The first ctor can
2438   /// optionally insert before an existing instruction, the second appends
2439   /// the new instruction to the specified BasicBlock.
2440   inline InsertValueInst(Value *Agg, Value *Val,
2441                          ArrayRef<unsigned> Idxs,
2442                          const Twine &NameStr,
2443                          Instruction *InsertBefore);
2444   inline InsertValueInst(Value *Agg, Value *Val,
2445                          ArrayRef<unsigned> Idxs,
2446                          const Twine &NameStr, BasicBlock *InsertAtEnd);
2447
2448   /// Constructors - These two constructors are convenience methods because one
2449   /// and two index insertvalue instructions are so common.
2450   InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2451                   const Twine &NameStr = "",
2452                   Instruction *InsertBefore = nullptr);
2453   InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2454                   BasicBlock *InsertAtEnd);
2455
2456   void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2457             const Twine &NameStr);
2458
2459 protected:
2460   // Note: Instruction needs to be a friend here to call cloneImpl.
2461   friend class Instruction;
2462
2463   InsertValueInst *cloneImpl() const;
2464
2465 public:
2466   // allocate space for exactly two operands
2467   void *operator new(size_t s) {
2468     return User::operator new(s, 2);
2469   }
2470
2471   void *operator new(size_t, unsigned) = delete;
2472
2473   static InsertValueInst *Create(Value *Agg, Value *Val,
2474                                  ArrayRef<unsigned> Idxs,
2475                                  const Twine &NameStr = "",
2476                                  Instruction *InsertBefore = nullptr) {
2477     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2478   }
2479
2480   static InsertValueInst *Create(Value *Agg, Value *Val,
2481                                  ArrayRef<unsigned> Idxs,
2482                                  const Twine &NameStr,
2483                                  BasicBlock *InsertAtEnd) {
2484     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2485   }
2486
2487   /// Transparently provide more efficient getOperand methods.
2488   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2489
2490   using idx_iterator = const unsigned*;
2491
2492   inline idx_iterator idx_begin() const { return Indices.begin(); }
2493   inline idx_iterator idx_end()   const { return Indices.end(); }
2494   inline iterator_range<idx_iterator> indices() const {
2495     return make_range(idx_begin(), idx_end());
2496   }
2497
2498   Value *getAggregateOperand() {
2499     return getOperand(0);
2500   }
2501   const Value *getAggregateOperand() const {
2502     return getOperand(0);
2503   }
2504   static unsigned getAggregateOperandIndex() {
2505     return 0U;                      // get index for modifying correct operand
2506   }
2507
2508   Value *getInsertedValueOperand() {
2509     return getOperand(1);
2510   }
2511   const Value *getInsertedValueOperand() const {
2512     return getOperand(1);
2513   }
2514   static unsigned getInsertedValueOperandIndex() {
2515     return 1U;                      // get index for modifying correct operand
2516   }
2517
2518   ArrayRef<unsigned> getIndices() const {
2519     return Indices;
2520   }
2521
2522   unsigned getNumIndices() const {
2523     return (unsigned)Indices.size();
2524   }
2525
2526   bool hasIndices() const {
2527     return true;
2528   }
2529
2530   // Methods for support type inquiry through isa, cast, and dyn_cast:
2531   static inline bool classof(const Instruction *I) {
2532     return I->getOpcode() == Instruction::InsertValue;
2533   }
2534   static inline bool classof(const Value *V) {
2535     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2536   }
2537 };
2538
2539 template <>
2540 struct OperandTraits<InsertValueInst> :
2541   public FixedNumOperandTraits<InsertValueInst, 2> {
2542 };
2543
2544 InsertValueInst::InsertValueInst(Value *Agg,
2545                                  Value *Val,
2546                                  ArrayRef<unsigned> Idxs,
2547                                  const Twine &NameStr,
2548                                  Instruction *InsertBefore)
2549   : Instruction(Agg->getType(), InsertValue,
2550                 OperandTraits<InsertValueInst>::op_begin(this),
2551                 2, InsertBefore) {
2552   init(Agg, Val, Idxs, NameStr);
2553 }
2554
2555 InsertValueInst::InsertValueInst(Value *Agg,
2556                                  Value *Val,
2557                                  ArrayRef<unsigned> Idxs,
2558                                  const Twine &NameStr,
2559                                  BasicBlock *InsertAtEnd)
2560   : Instruction(Agg->getType(), InsertValue,
2561                 OperandTraits<InsertValueInst>::op_begin(this),
2562                 2, InsertAtEnd) {
2563   init(Agg, Val, Idxs, NameStr);
2564 }
2565
2566 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2567
2568 //===----------------------------------------------------------------------===//
2569 //                               PHINode Class
2570 //===----------------------------------------------------------------------===//
2571
2572 // PHINode - The PHINode class is used to represent the magical mystical PHI
2573 // node, that can not exist in nature, but can be synthesized in a computer
2574 // scientist's overactive imagination.
2575 //
2576 class PHINode : public Instruction {
2577   /// The number of operands actually allocated.  NumOperands is
2578   /// the number actually in use.
2579   unsigned ReservedSpace;
2580
2581   PHINode(const PHINode &PN);
2582   // allocate space for exactly zero operands
2583
2584   explicit PHINode(Type *Ty, unsigned NumReservedValues,
2585                    const Twine &NameStr = "",
2586                    Instruction *InsertBefore = nullptr)
2587     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2588       ReservedSpace(NumReservedValues) {
2589     setName(NameStr);
2590     allocHungoffUses(ReservedSpace);
2591   }
2592
2593   PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2594           BasicBlock *InsertAtEnd)
2595     : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2596       ReservedSpace(NumReservedValues) {
2597     setName(NameStr);
2598     allocHungoffUses(ReservedSpace);
2599   }
2600
2601   void *operator new(size_t s) {
2602     return User::operator new(s);
2603   }
2604
2605 protected:
2606   // Note: Instruction needs to be a friend here to call cloneImpl.
2607   friend class Instruction;
2608
2609   PHINode *cloneImpl() const;
2610
2611   // allocHungoffUses - this is more complicated than the generic
2612   // User::allocHungoffUses, because we have to allocate Uses for the incoming
2613   // values and pointers to the incoming blocks, all in one allocation.
2614   void allocHungoffUses(unsigned N) {
2615     User::allocHungoffUses(N, /* IsPhi */ true);
2616   }
2617
2618 public:
2619   void *operator new(size_t, unsigned) = delete;
2620
2621   /// Constructors - NumReservedValues is a hint for the number of incoming
2622   /// edges that this phi node will have (use 0 if you really have no idea).
2623   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2624                          const Twine &NameStr = "",
2625                          Instruction *InsertBefore = nullptr) {
2626     return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2627   }
2628
2629   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2630                          const Twine &NameStr, BasicBlock *InsertAtEnd) {
2631     return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2632   }
2633
2634   /// Provide fast operand accessors
2635   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2636
2637   // Block iterator interface. This provides access to the list of incoming
2638   // basic blocks, which parallels the list of incoming values.
2639
2640   using block_iterator = BasicBlock **;
2641   using const_block_iterator = BasicBlock * const *;
2642
2643   block_iterator block_begin() {
2644     Use::UserRef *ref =
2645       reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2646     return reinterpret_cast<block_iterator>(ref + 1);
2647   }
2648
2649   const_block_iterator block_begin() const {
2650     const Use::UserRef *ref =
2651       reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2652     return reinterpret_cast<const_block_iterator>(ref + 1);
2653   }
2654
2655   block_iterator block_end() {
2656     return block_begin() + getNumOperands();
2657   }
2658
2659   const_block_iterator block_end() const {
2660     return block_begin() + getNumOperands();
2661   }
2662
2663   iterator_range<block_iterator> blocks() {
2664     return make_range(block_begin(), block_end());
2665   }
2666
2667   iterator_range<const_block_iterator> blocks() const {
2668     return make_range(block_begin(), block_end());
2669   }
2670
2671   op_range incoming_values() { return operands(); }
2672
2673   const_op_range incoming_values() const { return operands(); }
2674
2675   /// Return the number of incoming edges
2676   ///
2677   unsigned getNumIncomingValues() const { return getNumOperands(); }
2678
2679   /// Return incoming value number x
2680   ///
2681   Value *getIncomingValue(unsigned i) const {
2682     return getOperand(i);
2683   }
2684   void setIncomingValue(unsigned i, Value *V) {
2685     assert(V && "PHI node got a null value!");
2686     assert(getType() == V->getType() &&
2687            "All operands to PHI node must be the same type as the PHI node!");
2688     setOperand(i, V);
2689   }
2690
2691   static unsigned getOperandNumForIncomingValue(unsigned i) {
2692     return i;
2693   }
2694
2695   static unsigned getIncomingValueNumForOperand(unsigned i) {
2696     return i;
2697   }
2698
2699   /// Return incoming basic block number @p i.
2700   ///
2701   BasicBlock *getIncomingBlock(unsigned i) const {
2702     return block_begin()[i];
2703   }
2704
2705   /// Return incoming basic block corresponding
2706   /// to an operand of the PHI.
2707   ///
2708   BasicBlock *getIncomingBlock(const Use &U) const {
2709     assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2710     return getIncomingBlock(unsigned(&U - op_begin()));
2711   }
2712
2713   /// Return incoming basic block corresponding
2714   /// to value use iterator.
2715   ///
2716   BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2717     return getIncomingBlock(I.getUse());
2718   }
2719
2720   void setIncomingBlock(unsigned i, BasicBlock *BB) {
2721     assert(BB && "PHI node got a null basic block!");
2722     block_begin()[i] = BB;
2723   }
2724
2725   /// Add an incoming value to the end of the PHI list
2726   ///
2727   void addIncoming(Value *V, BasicBlock *BB) {
2728     if (getNumOperands() == ReservedSpace)
2729       growOperands();  // Get more space!
2730     // Initialize some new operands.
2731     setNumHungOffUseOperands(getNumOperands() + 1);
2732     setIncomingValue(getNumOperands() - 1, V);
2733     setIncomingBlock(getNumOperands() - 1, BB);
2734   }
2735
2736   /// Remove an incoming value.  This is useful if a
2737   /// predecessor basic block is deleted.  The value removed is returned.
2738   ///
2739   /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2740   /// is true), the PHI node is destroyed and any uses of it are replaced with
2741   /// dummy values.  The only time there should be zero incoming values to a PHI
2742   /// node is when the block is dead, so this strategy is sound.
2743   ///
2744   Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2745
2746   Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2747     int Idx = getBasicBlockIndex(BB);
2748     assert(Idx >= 0 && "Invalid basic block argument to remove!");
2749     return removeIncomingValue(Idx, DeletePHIIfEmpty);
2750   }
2751
2752   /// Return the first index of the specified basic
2753   /// block in the value list for this PHI.  Returns -1 if no instance.
2754   ///
2755   int getBasicBlockIndex(const BasicBlock *BB) const {
2756     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2757       if (block_begin()[i] == BB)
2758         return i;
2759     return -1;
2760   }
2761
2762   Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2763     int Idx = getBasicBlockIndex(BB);
2764     assert(Idx >= 0 && "Invalid basic block argument!");
2765     return getIncomingValue(Idx);
2766   }
2767
2768   /// If the specified PHI node always merges together the
2769   /// same value, return the value, otherwise return null.
2770   Value *hasConstantValue() const;
2771
2772   /// Whether the specified PHI node always merges
2773   /// together the same value, assuming undefs are equal to a unique
2774   /// non-undef value.
2775   bool hasConstantOrUndefValue() const;
2776
2777   /// Methods for support type inquiry through isa, cast, and dyn_cast:
2778   static inline bool classof(const Instruction *I) {
2779     return I->getOpcode() == Instruction::PHI;
2780   }
2781   static inline bool classof(const Value *V) {
2782     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2783   }
2784
2785 private:
2786   void growOperands();
2787 };
2788
2789 template <>
2790 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2791 };
2792
2793 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2794
2795 //===----------------------------------------------------------------------===//
2796 //                           LandingPadInst Class
2797 //===----------------------------------------------------------------------===//
2798
2799 //===---------------------------------------------------------------------------
2800 /// The landingpad instruction holds all of the information
2801 /// necessary to generate correct exception handling. The landingpad instruction
2802 /// cannot be moved from the top of a landing pad block, which itself is
2803 /// accessible only from the 'unwind' edge of an invoke. This uses the
2804 /// SubclassData field in Value to store whether or not the landingpad is a
2805 /// cleanup.
2806 ///
2807 class LandingPadInst : public Instruction {
2808   /// The number of operands actually allocated.  NumOperands is
2809   /// the number actually in use.
2810   unsigned ReservedSpace;
2811
2812   LandingPadInst(const LandingPadInst &LP);
2813
2814 public:
2815   enum ClauseType { Catch, Filter };
2816
2817 private:
2818   explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2819                           const Twine &NameStr, Instruction *InsertBefore);
2820   explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2821                           const Twine &NameStr, BasicBlock *InsertAtEnd);
2822
2823   // Allocate space for exactly zero operands.
2824   void *operator new(size_t s) {
2825     return User::operator new(s);
2826   }
2827
2828   void growOperands(unsigned Size);
2829   void init(unsigned NumReservedValues, const Twine &NameStr);
2830
2831 protected:
2832   // Note: Instruction needs to be a friend here to call cloneImpl.
2833   friend class Instruction;
2834
2835   LandingPadInst *cloneImpl() const;
2836
2837 public:
2838   void *operator new(size_t, unsigned) = delete;
2839
2840   /// Constructors - NumReservedClauses is a hint for the number of incoming
2841   /// clauses that this landingpad will have (use 0 if you really have no idea).
2842   static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2843                                 const Twine &NameStr = "",
2844                                 Instruction *InsertBefore = nullptr);
2845   static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2846                                 const Twine &NameStr, BasicBlock *InsertAtEnd);
2847
2848   /// Provide fast operand accessors
2849   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2850
2851   /// Return 'true' if this landingpad instruction is a
2852   /// cleanup. I.e., it should be run when unwinding even if its landing pad
2853   /// doesn't catch the exception.
2854   bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2855
2856   /// Indicate that this landingpad instruction is a cleanup.
2857   void setCleanup(bool V) {
2858     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2859                                (V ? 1 : 0));
2860   }
2861
2862   /// Add a catch or filter clause to the landing pad.
2863   void addClause(Constant *ClauseVal);
2864
2865   /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2866   /// determine what type of clause this is.
2867   Constant *getClause(unsigned Idx) const {
2868     return cast<Constant>(getOperandList()[Idx]);
2869   }
2870
2871   /// Return 'true' if the clause and index Idx is a catch clause.
2872   bool isCatch(unsigned Idx) const {
2873     return !isa<ArrayType>(getOperandList()[Idx]->getType());
2874   }
2875
2876   /// Return 'true' if the clause and index Idx is a filter clause.
2877   bool isFilter(unsigned Idx) const {
2878     return isa<ArrayType>(getOperandList()[Idx]->getType());
2879   }
2880
2881   /// Get the number of clauses for this landing pad.
2882   unsigned getNumClauses() const { return getNumOperands(); }
2883
2884   /// Grow the size of the operand list to accommodate the new
2885   /// number of clauses.
2886   void reserveClauses(unsigned Size) { growOperands(Size); }
2887
2888   // Methods for support type inquiry through isa, cast, and dyn_cast:
2889   static inline bool classof(const Instruction *I) {
2890     return I->getOpcode() == Instruction::LandingPad;
2891   }
2892   static inline bool classof(const Value *V) {
2893     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2894   }
2895 };
2896
2897 template <>
2898 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2899 };
2900
2901 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2902
2903 //===----------------------------------------------------------------------===//
2904 //                               ReturnInst Class
2905 //===----------------------------------------------------------------------===//
2906
2907 //===---------------------------------------------------------------------------
2908 /// Return a value (possibly void), from a function.  Execution
2909 /// does not continue in this function any longer.
2910 ///
2911 class ReturnInst : public TerminatorInst {
2912   ReturnInst(const ReturnInst &RI);
2913
2914 private:
2915   // ReturnInst constructors:
2916   // ReturnInst()                  - 'ret void' instruction
2917   // ReturnInst(    null)          - 'ret void' instruction
2918   // ReturnInst(Value* X)          - 'ret X'    instruction
2919   // ReturnInst(    null, Inst *I) - 'ret void' instruction, insert before I
2920   // ReturnInst(Value* X, Inst *I) - 'ret X'    instruction, insert before I
2921   // ReturnInst(    null, BB *B)   - 'ret void' instruction, insert @ end of B
2922   // ReturnInst(Value* X, BB *B)   - 'ret X'    instruction, insert @ end of B
2923   //
2924   // NOTE: If the Value* passed is of type void then the constructor behaves as
2925   // if it was passed NULL.
2926   explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2927                       Instruction *InsertBefore = nullptr);
2928   ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2929   explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2930
2931 protected:
2932   // Note: Instruction needs to be a friend here to call cloneImpl.
2933   friend class Instruction;
2934
2935   ReturnInst *cloneImpl() const;
2936
2937 public:
2938   static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2939                             Instruction *InsertBefore = nullptr) {
2940     return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2941   }
2942
2943   static ReturnInst* Create(LLVMContext &C, Value *retVal,
2944                             BasicBlock *InsertAtEnd) {
2945     return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2946   }
2947
2948   static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2949     return new(0) ReturnInst(C, InsertAtEnd);
2950   }
2951
2952   /// Provide fast operand accessors
2953   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2954
2955   /// Convenience accessor. Returns null if there is no return value.
2956   Value *getReturnValue() const {
2957     return getNumOperands() != 0 ? getOperand(0) : nullptr;
2958   }
2959
2960   unsigned getNumSuccessors() const { return 0; }
2961
2962   // Methods for support type inquiry through isa, cast, and dyn_cast:
2963   static inline bool classof(const Instruction *I) {
2964     return (I->getOpcode() == Instruction::Ret);
2965   }
2966   static inline bool classof(const Value *V) {
2967     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2968   }
2969
2970 private:
2971   friend TerminatorInst;
2972
2973   BasicBlock *getSuccessorV(unsigned idx) const;
2974   unsigned getNumSuccessorsV() const;
2975   void setSuccessorV(unsigned idx, BasicBlock *B);
2976 };
2977
2978 template <>
2979 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2980 };
2981
2982 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2983
2984 //===----------------------------------------------------------------------===//
2985 //                               BranchInst Class
2986 //===----------------------------------------------------------------------===//
2987
2988 //===---------------------------------------------------------------------------
2989 /// Conditional or Unconditional Branch instruction.
2990 ///
2991 class BranchInst : public TerminatorInst {
2992   /// Ops list - Branches are strange.  The operands are ordered:
2993   ///  [Cond, FalseDest,] TrueDest.  This makes some accessors faster because
2994   /// they don't have to check for cond/uncond branchness. These are mostly
2995   /// accessed relative from op_end().
2996   BranchInst(const BranchInst &BI);
2997   // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2998   // BranchInst(BB *B)                           - 'br B'
2999   // BranchInst(BB* T, BB *F, Value *C)          - 'br C, T, F'
3000   // BranchInst(BB* B, Inst *I)                  - 'br B'        insert before I
3001   // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3002   // BranchInst(BB* B, BB *I)                    - 'br B'        insert at end
3003   // BranchInst(BB* T, BB *F, Value *C, BB *I)   - 'br C, T, F', insert at end
3004   explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3005   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3006              Instruction *InsertBefore = nullptr);
3007   BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3008   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3009              BasicBlock *InsertAtEnd);
3010
3011   void AssertOK();
3012
3013 protected:
3014   // Note: Instruction needs to be a friend here to call cloneImpl.
3015   friend class Instruction;
3016
3017   BranchInst *cloneImpl() const;
3018
3019 public:
3020   static BranchInst *Create(BasicBlock *IfTrue,
3021                             Instruction *InsertBefore = nullptr) {
3022     return new(1) BranchInst(IfTrue, InsertBefore);
3023   }
3024
3025   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3026                             Value *Cond, Instruction *InsertBefore = nullptr) {
3027     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3028   }
3029
3030   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3031     return new(1) BranchInst(IfTrue, InsertAtEnd);
3032   }
3033
3034   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3035                             Value *Cond, BasicBlock *InsertAtEnd) {
3036     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3037   }
3038
3039   /// Transparently provide more efficient getOperand methods.
3040   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3041
3042   bool isUnconditional() const { return getNumOperands() == 1; }
3043   bool isConditional()   const { return getNumOperands() == 3; }
3044
3045   Value *getCondition() const {
3046     assert(isConditional() && "Cannot get condition of an uncond branch!");
3047     return Op<-3>();
3048   }
3049
3050   void setCondition(Value *V) {
3051     assert(isConditional() && "Cannot set condition of unconditional branch!");
3052     Op<-3>() = V;
3053   }
3054
3055   unsigned getNumSuccessors() const { return 1+isConditional(); }
3056
3057   BasicBlock *getSuccessor(unsigned i) const {
3058     assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3059     return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3060   }
3061
3062   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3063     assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3064     *(&Op<-1>() - idx) = NewSucc;
3065   }
3066
3067   /// Swap the successors of this branch instruction.
3068   ///
3069   /// Swaps the successors of the branch instruction. This also swaps any
3070   /// branch weight metadata associated with the instruction so that it
3071   /// continues to map correctly to each operand.
3072   void swapSuccessors();
3073
3074   // Methods for support type inquiry through isa, cast, and dyn_cast:
3075   static inline bool classof(const Instruction *I) {
3076     return (I->getOpcode() == Instruction::Br);
3077   }
3078   static inline bool classof(const Value *V) {
3079     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3080   }
3081
3082 private:
3083   friend TerminatorInst;
3084
3085   BasicBlock *getSuccessorV(unsigned idx) const;
3086   unsigned getNumSuccessorsV() const;
3087   void setSuccessorV(unsigned idx, BasicBlock *B);
3088 };
3089
3090 template <>
3091 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3092 };
3093
3094 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3095
3096 //===----------------------------------------------------------------------===//
3097 //                               SwitchInst Class
3098 //===----------------------------------------------------------------------===//
3099
3100 //===---------------------------------------------------------------------------
3101 /// Multiway switch
3102 ///
3103 class SwitchInst : public TerminatorInst {
3104   unsigned ReservedSpace;
3105
3106   // Operand[0]    = Value to switch on
3107   // Operand[1]    = Default basic block destination
3108   // Operand[2n  ] = Value to match
3109   // Operand[2n+1] = BasicBlock to go to on match
3110   SwitchInst(const SwitchInst &SI);
3111
3112   /// Create a new switch instruction, specifying a value to switch on and a
3113   /// default destination. The number of additional cases can be specified here
3114   /// to make memory allocation more efficient. This constructor can also
3115   /// auto-insert before another instruction.
3116   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3117              Instruction *InsertBefore);
3118
3119   /// Create a new switch instruction, specifying a value to switch on and a
3120   /// default destination. The number of additional cases can be specified here
3121   /// to make memory allocation more efficient. This constructor also
3122   /// auto-inserts at the end of the specified BasicBlock.
3123   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3124              BasicBlock *InsertAtEnd);
3125
3126   // allocate space for exactly zero operands
3127   void *operator new(size_t s) {
3128     return User::operator new(s);
3129   }
3130
3131   void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3132   void growOperands();
3133
3134 protected:
3135   // Note: Instruction needs to be a friend here to call cloneImpl.
3136   friend class Instruction;
3137
3138   SwitchInst *cloneImpl() const;
3139
3140 public:
3141   void *operator new(size_t, unsigned) = delete;
3142
3143   // -2
3144   static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3145
3146   template <typename CaseHandleT> class CaseIteratorImpl;
3147
3148   /// A handle to a particular switch case. It exposes a convenient interface
3149   /// to both the case value and the successor block.
3150   ///
3151   /// We define this as a template and instantiate it to form both a const and
3152   /// non-const handle.
3153   template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3154   class CaseHandleImpl {
3155     // Directly befriend both const and non-const iterators.
3156     friend class SwitchInst::CaseIteratorImpl<
3157         CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3158
3159   protected:
3160     // Expose the switch type we're parameterized with to the iterator.
3161     using SwitchInstType = SwitchInstT;
3162
3163     SwitchInstT *SI;
3164     ptrdiff_t Index;
3165
3166     CaseHandleImpl() = default;
3167     CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3168
3169   public:
3170     /// Resolves case value for current case.
3171     ConstantIntT *getCaseValue() const {
3172       assert((unsigned)Index < SI->getNumCases() &&
3173              "Index out the number of cases.");
3174       return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3175     }
3176
3177     /// Resolves successor for current case.
3178     BasicBlockT *getCaseSuccessor() const {
3179       assert(((unsigned)Index < SI->getNumCases() ||
3180               (unsigned)Index == DefaultPseudoIndex) &&
3181              "Index out the number of cases.");
3182       return SI->getSuccessor(getSuccessorIndex());
3183     }
3184
3185     /// Returns number of current case.
3186     unsigned getCaseIndex() const { return Index; }
3187
3188     /// Returns TerminatorInst's successor index for current case successor.
3189     unsigned getSuccessorIndex() const {
3190       assert(((unsigned)Index == DefaultPseudoIndex ||
3191               (unsigned)Index < SI->getNumCases()) &&
3192              "Index out the number of cases.");
3193       return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3194     }
3195
3196     bool operator==(const CaseHandleImpl &RHS) const {
3197       assert(SI == RHS.SI && "Incompatible operators.");
3198       return Index == RHS.Index;
3199     }
3200   };
3201
3202   using ConstCaseHandle =
3203       CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3204
3205   class CaseHandle
3206       : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3207     friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3208
3209   public:
3210     CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3211
3212     /// Sets the new value for current case.
3213     void setValue(ConstantInt *V) {
3214       assert((unsigned)Index < SI->getNumCases() &&
3215              "Index out the number of cases.");
3216       SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3217     }
3218
3219     /// Sets the new successor for current case.
3220     void setSuccessor(BasicBlock *S) {
3221       SI->setSuccessor(getSuccessorIndex(), S);
3222     }
3223   };
3224
3225   template <typename CaseHandleT>
3226   class CaseIteratorImpl
3227       : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3228                                     std::random_access_iterator_tag,
3229                                     CaseHandleT> {
3230     using SwitchInstT = typename CaseHandleT::SwitchInstType;
3231
3232     CaseHandleT Case;
3233
3234   public:
3235     /// Default constructed iterator is in an invalid state until assigned to
3236     /// a case for a particular switch.
3237     CaseIteratorImpl() = default;
3238
3239     /// Initializes case iterator for given SwitchInst and for given
3240     /// case number.
3241     CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3242
3243     /// Initializes case iterator for given SwitchInst and for given
3244     /// TerminatorInst's successor index.
3245     static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3246                                                unsigned SuccessorIndex) {
3247       assert(SuccessorIndex < SI->getNumSuccessors() &&
3248              "Successor index # out of range!");
3249       return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3250                                  : CaseIteratorImpl(SI, DefaultPseudoIndex);
3251     }
3252
3253     /// Support converting to the const variant. This will be a no-op for const
3254     /// variant.
3255     operator CaseIteratorImpl<ConstCaseHandle>() const {
3256       return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3257     }
3258
3259     CaseIteratorImpl &operator+=(ptrdiff_t N) {
3260       // Check index correctness after addition.
3261       // Note: Index == getNumCases() means end().
3262       assert(Case.Index + N >= 0 &&
3263              (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3264              "Case.Index out the number of cases.");
3265       Case.Index += N;
3266       return *this;
3267     }
3268     CaseIteratorImpl &operator-=(ptrdiff_t N) {
3269       // Check index correctness after subtraction.
3270       // Note: Case.Index == getNumCases() means end().
3271       assert(Case.Index - N >= 0 &&
3272              (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3273              "Case.Index out the number of cases.");
3274       Case.Index -= N;
3275       return *this;
3276     }
3277     ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3278       assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3279       return Case.Index - RHS.Case.Index;
3280     }
3281     bool operator==(const CaseIteratorImpl &RHS) const {
3282       return Case == RHS.Case;
3283     }
3284     bool operator<(const CaseIteratorImpl &RHS) const {
3285       assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3286       return Case.Index < RHS.Case.Index;
3287     }
3288     CaseHandleT &operator*() { return Case; }
3289     const CaseHandleT &operator*() const { return Case; }
3290   };
3291
3292   using CaseIt = CaseIteratorImpl<CaseHandle>;
3293   using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3294
3295   static SwitchInst *Create(Value *Value, BasicBlock *Default,
3296                             unsigned NumCases,
3297                             Instruction *InsertBefore = nullptr) {
3298     return new SwitchInst(Value, Default, NumCases, InsertBefore);
3299   }
3300
3301   static SwitchInst *Create(Value *Value, BasicBlock *Default,
3302                             unsigned NumCases, BasicBlock *InsertAtEnd) {
3303     return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3304   }
3305
3306   /// Provide fast operand accessors
3307   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3308
3309   // Accessor Methods for Switch stmt
3310   Value *getCondition() const { return getOperand(0); }
3311   void setCondition(Value *V) { setOperand(0, V); }
3312
3313   BasicBlock *getDefaultDest() const {
3314     return cast<BasicBlock>(getOperand(1));
3315   }
3316
3317   void setDefaultDest(BasicBlock *DefaultCase) {
3318     setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3319   }
3320
3321   /// Return the number of 'cases' in this switch instruction, excluding the
3322   /// default case.
3323   unsigned getNumCases() const {
3324     return getNumOperands()/2 - 1;
3325   }
3326
3327   /// Returns a read/write iterator that points to the first case in the
3328   /// SwitchInst.
3329   CaseIt case_begin() {
3330     return CaseIt(this, 0);
3331   }
3332
3333   /// Returns a read-only iterator that points to the first case in the
3334   /// SwitchInst.
3335   ConstCaseIt case_begin() const {
3336     return ConstCaseIt(this, 0);
3337   }
3338
3339   /// Returns a read/write iterator that points one past the last in the
3340   /// SwitchInst.
3341   CaseIt case_end() {
3342     return CaseIt(this, getNumCases());
3343   }
3344
3345   /// Returns a read-only iterator that points one past the last in the
3346   /// SwitchInst.
3347   ConstCaseIt case_end() const {
3348     return ConstCaseIt(this, getNumCases());
3349   }
3350
3351   /// Iteration adapter for range-for loops.
3352   iterator_range<CaseIt> cases() {
3353     return make_range(case_begin(), case_end());
3354   }
3355
3356   /// Constant iteration adapter for range-for loops.
3357   iterator_range<ConstCaseIt> cases() const {
3358     return make_range(case_begin(), case_end());
3359   }
3360
3361   /// Returns an iterator that points to the default case.
3362   /// Note: this iterator allows to resolve successor only. Attempt
3363   /// to resolve case value causes an assertion.
3364   /// Also note, that increment and decrement also causes an assertion and
3365   /// makes iterator invalid.
3366   CaseIt case_default() {
3367     return CaseIt(this, DefaultPseudoIndex);
3368   }
3369   ConstCaseIt case_default() const {
3370     return ConstCaseIt(this, DefaultPseudoIndex);
3371   }
3372
3373   /// Search all of the case values for the specified constant. If it is
3374   /// explicitly handled, return the case iterator of it, otherwise return
3375   /// default case iterator to indicate that it is handled by the default
3376   /// handler.
3377   CaseIt findCaseValue(const ConstantInt *C) {
3378     CaseIt I = llvm::find_if(
3379         cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3380     if (I != case_end())
3381       return I;
3382
3383     return case_default();
3384   }
3385   ConstCaseIt findCaseValue(const ConstantInt *C) const {
3386     ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3387       return Case.getCaseValue() == C;
3388     });
3389     if (I != case_end())
3390       return I;
3391
3392     return case_default();
3393   }
3394
3395   /// Finds the unique case value for a given successor. Returns null if the
3396   /// successor is not found, not unique, or is the default case.
3397   ConstantInt *findCaseDest(BasicBlock *BB) {
3398     if (BB == getDefaultDest())
3399       return nullptr;
3400
3401     ConstantInt *CI = nullptr;
3402     for (auto Case : cases()) {
3403       if (Case.getCaseSuccessor() != BB)
3404         continue;
3405
3406       if (CI)
3407         return nullptr; // Multiple cases lead to BB.
3408
3409       CI = Case.getCaseValue();
3410     }
3411
3412     return CI;
3413   }
3414
3415   /// Add an entry to the switch instruction.
3416   /// Note:
3417   /// This action invalidates case_end(). Old case_end() iterator will
3418   /// point to the added case.
3419   void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3420
3421   /// This method removes the specified case and its successor from the switch
3422   /// instruction. Note that this operation may reorder the remaining cases at
3423   /// index idx and above.
3424   /// Note:
3425   /// This action invalidates iterators for all cases following the one removed,
3426   /// including the case_end() iterator. It returns an iterator for the next
3427   /// case.
3428   CaseIt removeCase(CaseIt I);
3429
3430   unsigned getNumSuccessors() const { return getNumOperands()/2; }
3431   BasicBlock *getSuccessor(unsigned idx) const {
3432     assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3433     return cast<BasicBlock>(getOperand(idx*2+1));
3434   }
3435   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3436     assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3437     setOperand(idx * 2 + 1, NewSucc);
3438   }
3439
3440   // Methods for support type inquiry through isa, cast, and dyn_cast:
3441   static inline bool classof(const Instruction *I) {
3442     return I->getOpcode() == Instruction::Switch;
3443   }
3444   static inline bool classof(const Value *V) {
3445     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3446   }
3447
3448 private:
3449   friend TerminatorInst;
3450
3451   BasicBlock *getSuccessorV(unsigned idx) const;
3452   unsigned getNumSuccessorsV() const;
3453   void setSuccessorV(unsigned idx, BasicBlock *B);
3454 };
3455
3456 template <>
3457 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3458 };
3459
3460 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3461
3462 //===----------------------------------------------------------------------===//
3463 //                             IndirectBrInst Class
3464 //===----------------------------------------------------------------------===//
3465
3466 //===---------------------------------------------------------------------------
3467 /// Indirect Branch Instruction.
3468 ///
3469 class IndirectBrInst : public TerminatorInst {
3470   unsigned ReservedSpace;
3471
3472   // Operand[0]   = Address to jump to
3473   // Operand[n+1] = n-th destination
3474   IndirectBrInst(const IndirectBrInst &IBI);
3475
3476   /// Create a new indirectbr instruction, specifying an
3477   /// Address to jump to.  The number of expected destinations can be specified
3478   /// here to make memory allocation more efficient.  This constructor can also
3479   /// autoinsert before another instruction.
3480   IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3481
3482   /// Create a new indirectbr instruction, specifying an
3483   /// Address to jump to.  The number of expected destinations can be specified
3484   /// here to make memory allocation more efficient.  This constructor also
3485   /// autoinserts at the end of the specified BasicBlock.
3486   IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3487
3488   // allocate space for exactly zero operands
3489   void *operator new(size_t s) {
3490     return User::operator new(s);
3491   }
3492
3493   void init(Value *Address, unsigned NumDests);
3494   void growOperands();
3495
3496 protected:
3497   // Note: Instruction needs to be a friend here to call cloneImpl.
3498   friend class Instruction;
3499
3500   IndirectBrInst *cloneImpl() const;
3501
3502 public:
3503   void *operator new(size_t, unsigned) = delete;
3504
3505   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3506                                 Instruction *InsertBefore = nullptr) {
3507     return new IndirectBrInst(Address, NumDests, InsertBefore);
3508   }
3509
3510   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3511                                 BasicBlock *InsertAtEnd) {
3512     return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3513   }
3514
3515   /// Provide fast operand accessors.
3516   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3517
3518   // Accessor Methods for IndirectBrInst instruction.
3519   Value *getAddress() { return getOperand(0); }
3520   const Value *getAddress() const { return getOperand(0); }
3521   void setAddress(Value *V) { setOperand(0, V); }
3522
3523   /// return the number of possible destinations in this
3524   /// indirectbr instruction.
3525   unsigned getNumDestinations() const { return getNumOperands()-1; }
3526
3527   /// Return the specified destination.
3528   BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3529   const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3530
3531   /// Add a destination.
3532   ///
3533   void addDestination(BasicBlock *Dest);
3534
3535   /// This method removes the specified successor from the
3536   /// indirectbr instruction.
3537   void removeDestination(unsigned i);
3538
3539   unsigned getNumSuccessors() const { return getNumOperands()-1; }
3540   BasicBlock *getSuccessor(unsigned i) const {
3541     return cast<BasicBlock>(getOperand(i+1));
3542   }
3543   void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3544     setOperand(i + 1, NewSucc);
3545   }
3546
3547   // Methods for support type inquiry through isa, cast, and dyn_cast:
3548   static inline bool classof(const Instruction *I) {
3549     return I->getOpcode() == Instruction::IndirectBr;
3550   }
3551   static inline bool classof(const Value *V) {
3552     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3553   }
3554
3555 private:
3556   friend TerminatorInst;
3557
3558   BasicBlock *getSuccessorV(unsigned idx) const;
3559   unsigned getNumSuccessorsV() const;
3560   void setSuccessorV(unsigned idx, BasicBlock *B);
3561 };
3562
3563 template <>
3564 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3565 };
3566
3567 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3568
3569 //===----------------------------------------------------------------------===//
3570 //                               InvokeInst Class
3571 //===----------------------------------------------------------------------===//
3572
3573 /// Invoke instruction.  The SubclassData field is used to hold the
3574 /// calling convention of the call.
3575 ///
3576 class InvokeInst : public TerminatorInst,
3577                    public OperandBundleUser<InvokeInst, User::op_iterator> {
3578   friend class OperandBundleUser<InvokeInst, User::op_iterator>;
3579
3580   AttributeList Attrs;
3581   FunctionType *FTy;
3582
3583   InvokeInst(const InvokeInst &BI);
3584
3585   /// Construct an InvokeInst given a range of arguments.
3586   ///
3587   /// Construct an InvokeInst from a range of arguments
3588   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3589                     ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3590                     unsigned Values, const Twine &NameStr,
3591                     Instruction *InsertBefore)
3592       : InvokeInst(cast<FunctionType>(
3593                        cast<PointerType>(Func->getType())->getElementType()),
3594                    Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3595                    InsertBefore) {}
3596
3597   inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3598                     BasicBlock *IfException, ArrayRef<Value *> Args,
3599                     ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3600                     const Twine &NameStr, Instruction *InsertBefore);
3601   /// Construct an InvokeInst given a range of arguments.
3602   ///
3603   /// Construct an InvokeInst from a range of arguments
3604   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3605                     ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3606                     unsigned Values, const Twine &NameStr,
3607                     BasicBlock *InsertAtEnd);
3608
3609   bool hasDescriptor() const { return HasDescriptor; }
3610
3611   void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3612             ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3613             const Twine &NameStr) {
3614     init(cast<FunctionType>(
3615              cast<PointerType>(Func->getType())->getElementType()),
3616          Func, IfNormal, IfException, Args, Bundles, NameStr);
3617   }
3618
3619   void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3620             BasicBlock *IfException, ArrayRef<Value *> Args,
3621             ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3622
3623 protected:
3624   // Note: Instruction needs to be a friend here to call cloneImpl.
3625   friend class Instruction;
3626
3627   InvokeInst *cloneImpl() const;
3628
3629 public:
3630   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3631                             BasicBlock *IfException, ArrayRef<Value *> Args,
3632                             const Twine &NameStr,
3633                             Instruction *InsertBefore = nullptr) {
3634     return Create(cast<FunctionType>(
3635                       cast<PointerType>(Func->getType())->getElementType()),
3636                   Func, IfNormal, IfException, Args, None, NameStr,
3637                   InsertBefore);
3638   }
3639
3640   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3641                             BasicBlock *IfException, ArrayRef<Value *> Args,
3642                             ArrayRef<OperandBundleDef> Bundles = None,
3643                             const Twine &NameStr = "",
3644                             Instruction *InsertBefore = nullptr) {
3645     return Create(cast<FunctionType>(
3646                       cast<PointerType>(Func->getType())->getElementType()),
3647                   Func, IfNormal, IfException, Args, Bundles, NameStr,
3648                   InsertBefore);
3649   }
3650
3651   static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3652                             BasicBlock *IfException, ArrayRef<Value *> Args,
3653                             const Twine &NameStr,
3654                             Instruction *InsertBefore = nullptr) {
3655     unsigned Values = unsigned(Args.size()) + 3;
3656     return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3657                                    Values, NameStr, InsertBefore);
3658   }
3659
3660   static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3661                             BasicBlock *IfException, ArrayRef<Value *> Args,
3662                             ArrayRef<OperandBundleDef> Bundles = None,
3663                             const Twine &NameStr = "",
3664                             Instruction *InsertBefore = nullptr) {
3665     unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3666     unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3667
3668     return new (Values, DescriptorBytes)
3669         InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3670                    NameStr, InsertBefore);
3671   }
3672
3673   static InvokeInst *Create(Value *Func,
3674                             BasicBlock *IfNormal, BasicBlock *IfException,
3675                             ArrayRef<Value *> Args, const Twine &NameStr,
3676                             BasicBlock *InsertAtEnd) {
3677     unsigned Values = unsigned(Args.size()) + 3;
3678     return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3679                                    Values, NameStr, InsertAtEnd);
3680   }
3681
3682   static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3683                             BasicBlock *IfException, ArrayRef<Value *> Args,
3684                             ArrayRef<OperandBundleDef> Bundles,
3685                             const Twine &NameStr, BasicBlock *InsertAtEnd) {
3686     unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3687     unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3688
3689     return new (Values, DescriptorBytes)
3690         InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3691                    InsertAtEnd);
3692   }
3693
3694   /// Create a clone of \p II with a different set of operand bundles and
3695   /// insert it before \p InsertPt.
3696   ///
3697   /// The returned invoke instruction is identical to \p II in every way except
3698   /// that the operand bundles for the new instruction are set to the operand
3699   /// bundles in \p Bundles.
3700   static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3701                             Instruction *InsertPt = nullptr);
3702
3703   /// Provide fast operand accessors
3704   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3705
3706   FunctionType *getFunctionType() const { return FTy; }
3707
3708   void mutateFunctionType(FunctionType *FTy) {
3709     mutateType(FTy->getReturnType());
3710     this->FTy = FTy;
3711   }
3712
3713   /// Return the number of invoke arguments.
3714   ///
3715   unsigned getNumArgOperands() const {
3716     return getNumOperands() - getNumTotalBundleOperands() - 3;
3717   }
3718
3719   /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3720   ///
3721   Value *getArgOperand(unsigned i) const {
3722     assert(i < getNumArgOperands() && "Out of bounds!");
3723     return getOperand(i);
3724   }
3725   void setArgOperand(unsigned i, Value *v) {
3726     assert(i < getNumArgOperands() && "Out of bounds!");
3727     setOperand(i, v);
3728   }
3729
3730   /// Return the iterator pointing to the beginning of the argument list.
3731   op_iterator arg_begin() { return op_begin(); }
3732
3733   /// Return the iterator pointing to the end of the argument list.
3734   op_iterator arg_end() {
3735     // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3736     return op_end() - getNumTotalBundleOperands() - 3;
3737   }
3738
3739   /// Iteration adapter for range-for loops.
3740   iterator_range<op_iterator> arg_operands() {
3741     return make_range(arg_begin(), arg_end());
3742   }
3743
3744   /// Return the iterator pointing to the beginning of the argument list.
3745   const_op_iterator arg_begin() const { return op_begin(); }
3746
3747   /// Return the iterator pointing to the end of the argument list.
3748   const_op_iterator arg_end() const {
3749     // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3750     return op_end() - getNumTotalBundleOperands() - 3;
3751   }
3752
3753   /// Iteration adapter for range-for loops.
3754   iterator_range<const_op_iterator> arg_operands() const {
3755     return make_range(arg_begin(), arg_end());
3756   }
3757
3758   /// Wrappers for getting the \c Use of a invoke argument.
3759   const Use &getArgOperandUse(unsigned i) const {
3760     assert(i < getNumArgOperands() && "Out of bounds!");
3761     return getOperandUse(i);
3762   }
3763   Use &getArgOperandUse(unsigned i) {
3764     assert(i < getNumArgOperands() && "Out of bounds!");
3765     return getOperandUse(i);
3766   }
3767
3768   /// If one of the arguments has the 'returned' attribute, return its
3769   /// operand value. Otherwise, return nullptr.
3770   Value *getReturnedArgOperand() const;
3771
3772   /// getCallingConv/setCallingConv - Get or set the calling convention of this
3773   /// function call.
3774   CallingConv::ID getCallingConv() const {
3775     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3776   }
3777   void setCallingConv(CallingConv::ID CC) {
3778     auto ID = static_cast<unsigned>(CC);
3779     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
3780     setInstructionSubclassData(ID);
3781   }
3782
3783   /// Return the parameter attributes for this invoke.
3784   ///
3785   AttributeList getAttributes() const { return Attrs; }
3786
3787   /// Set the parameter attributes for this invoke.
3788   ///
3789   void setAttributes(AttributeList A) { Attrs = A; }
3790
3791   /// adds the attribute to the list of attributes.
3792   void addAttribute(unsigned i, Attribute::AttrKind Kind);
3793
3794   /// adds the attribute to the list of attributes.
3795   void addAttribute(unsigned i, Attribute Attr);
3796
3797   /// Adds the attribute to the indicated argument
3798   void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3799
3800   /// removes the attribute from the list of attributes.
3801   void removeAttribute(unsigned i, Attribute::AttrKind Kind);
3802
3803   /// removes the attribute from the list of attributes.
3804   void removeAttribute(unsigned i, StringRef Kind);
3805
3806   /// Removes the attribute from the given argument
3807   void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3808
3809   /// adds the dereferenceable attribute to the list of attributes.
3810   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3811
3812   /// adds the dereferenceable_or_null attribute to the list of
3813   /// attributes.
3814   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3815
3816   /// Determine whether this call has the given attribute.
3817   bool hasFnAttr(Attribute::AttrKind Kind) const {
3818     assert(Kind != Attribute::NoBuiltin &&
3819            "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3820     return hasFnAttrImpl(Kind);
3821   }
3822
3823   /// Determine whether this call has the given attribute.
3824   bool hasFnAttr(StringRef Kind) const {
3825     return hasFnAttrImpl(Kind);
3826   }
3827
3828   /// Determine whether the return value has the given attribute.
3829   bool hasRetAttr(Attribute::AttrKind Kind) const;
3830
3831   /// Determine whether the argument or parameter has the given attribute.
3832   bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
3833
3834   /// Get the attribute of a given kind at a position.
3835   Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
3836     return getAttributes().getAttribute(i, Kind);
3837   }
3838
3839   /// Get the attribute of a given kind at a position.
3840   Attribute getAttribute(unsigned i, StringRef Kind) const {
3841     return getAttributes().getAttribute(i, Kind);
3842   }
3843
3844   /// Return true if the data operand at index \p i has the attribute \p
3845   /// A.
3846   ///
3847   /// Data operands include invoke arguments and values used in operand bundles,
3848   /// but does not include the invokee operand, or the two successor blocks.
3849   /// This routine dispatches to the underlying AttributeList or the
3850   /// OperandBundleUser as appropriate.
3851   ///
3852   /// The index \p i is interpreted as
3853   ///
3854   ///  \p i == Attribute::ReturnIndex  -> the return value
3855   ///  \p i in [1, arg_size + 1)  -> argument number (\p i - 1)
3856   ///  \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
3857   ///     (\p i - 1) in the operand list.
3858   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
3859
3860   /// Extract the alignment of the return value.
3861   unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
3862
3863   /// Extract the alignment for a call or parameter (0=unknown).
3864   unsigned getParamAlignment(unsigned ArgNo) const {
3865     return Attrs.getParamAlignment(ArgNo);
3866   }
3867
3868   /// Extract the number of dereferenceable bytes for a call or
3869   /// parameter (0=unknown).
3870   uint64_t getDereferenceableBytes(unsigned i) const {
3871     return Attrs.getDereferenceableBytes(i);
3872   }
3873
3874   /// Extract the number of dereferenceable_or_null bytes for a call or
3875   /// parameter (0=unknown).
3876   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
3877     return Attrs.getDereferenceableOrNullBytes(i);
3878   }
3879
3880   /// @brief Determine if the return value is marked with NoAlias attribute.
3881   bool returnDoesNotAlias() const {
3882     return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
3883   }
3884
3885   /// Return true if the call should not be treated as a call to a
3886   /// builtin.
3887   bool isNoBuiltin() const {
3888     // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3889     // to check it by hand.
3890     return hasFnAttrImpl(Attribute::NoBuiltin) &&
3891       !hasFnAttrImpl(Attribute::Builtin);
3892   }
3893
3894   /// Return true if the call should not be inlined.
3895   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3896   void setIsNoInline() {
3897     addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
3898   }
3899
3900   /// Determine if the call does not access memory.
3901   bool doesNotAccessMemory() const {
3902     return hasFnAttr(Attribute::ReadNone);
3903   }
3904   void setDoesNotAccessMemory() {
3905     addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
3906   }
3907
3908   /// Determine if the call does not access or only reads memory.
3909   bool onlyReadsMemory() const {
3910     return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3911   }
3912   void setOnlyReadsMemory() {
3913     addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
3914   }
3915
3916   /// Determine if the call does not access or only writes memory.
3917   bool doesNotReadMemory() const {
3918     return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
3919   }
3920   void setDoesNotReadMemory() {
3921     addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
3922   }
3923
3924   /// @brief Determine if the call access memmory only using it's pointer
3925   /// arguments.
3926   bool onlyAccessesArgMemory() const {
3927     return hasFnAttr(Attribute::ArgMemOnly);
3928   }
3929   void setOnlyAccessesArgMemory() {
3930     addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
3931   }
3932
3933   /// Determine if the call cannot return.
3934   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3935   void setDoesNotReturn() {
3936     addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
3937   }
3938
3939   /// Determine if the call cannot unwind.
3940   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3941   void setDoesNotThrow() {
3942     addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3943   }
3944
3945   /// Determine if the invoke cannot be duplicated.
3946   bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3947   void setCannotDuplicate() {
3948     addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
3949   }
3950
3951   /// Determine if the invoke is convergent
3952   bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
3953   void setConvergent() {
3954     addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3955   }
3956   void setNotConvergent() {
3957     removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3958   }
3959
3960   /// Determine if the call returns a structure through first
3961   /// pointer argument.
3962   bool hasStructRetAttr() const {
3963     if (getNumArgOperands() == 0)
3964       return false;
3965
3966     // Be friendly and also check the callee.
3967     return paramHasAttr(0, Attribute::StructRet);
3968   }
3969
3970   /// Determine if any call argument is an aggregate passed by value.
3971   bool hasByValArgument() const {
3972     return Attrs.hasAttrSomewhere(Attribute::ByVal);
3973   }
3974
3975   /// Return the function called, or null if this is an
3976   /// indirect function invocation.
3977   ///
3978   Function *getCalledFunction() const {
3979     return dyn_cast<Function>(Op<-3>());
3980   }
3981
3982   /// Get a pointer to the function that is invoked by this
3983   /// instruction
3984   const Value *getCalledValue() const { return Op<-3>(); }
3985         Value *getCalledValue()       { return Op<-3>(); }
3986
3987   /// Set the function called.
3988   void setCalledFunction(Value* Fn) {
3989     setCalledFunction(
3990         cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
3991         Fn);
3992   }
3993   void setCalledFunction(FunctionType *FTy, Value *Fn) {
3994     this->FTy = FTy;
3995     assert(FTy == cast<FunctionType>(
3996                       cast<PointerType>(Fn->getType())->getElementType()));
3997     Op<-3>() = Fn;
3998   }
3999
4000   // get*Dest - Return the destination basic blocks...
4001   BasicBlock *getNormalDest() const {
4002     return cast<BasicBlock>(Op<-2>());
4003   }
4004   BasicBlock *getUnwindDest() const {
4005     return cast<BasicBlock>(Op<-1>());
4006   }
4007   void setNormalDest(BasicBlock *B) {
4008     Op<-2>() = reinterpret_cast<Value*>(B);
4009   }
4010   void setUnwindDest(BasicBlock *B) {
4011     Op<-1>() = reinterpret_cast<Value*>(B);
4012   }
4013
4014   /// Get the landingpad instruction from the landing pad
4015   /// block (the unwind destination).
4016   LandingPadInst *getLandingPadInst() const;
4017
4018   BasicBlock *getSuccessor(unsigned i) const {
4019     assert(i < 2 && "Successor # out of range for invoke!");
4020     return i == 0 ? getNormalDest() : getUnwindDest();
4021   }
4022
4023   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4024     assert(idx < 2 && "Successor # out of range for invoke!");
4025     *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
4026   }
4027
4028   unsigned getNumSuccessors() const { return 2; }
4029
4030   // Methods for support type inquiry through isa, cast, and dyn_cast:
4031   static inline bool classof(const Instruction *I) {
4032     return (I->getOpcode() == Instruction::Invoke);
4033   }
4034   static inline bool classof(const Value *V) {
4035     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4036   }
4037
4038 private:
4039   friend TerminatorInst;
4040
4041   BasicBlock *getSuccessorV(unsigned idx) const;
4042   unsigned getNumSuccessorsV() const;
4043   void setSuccessorV(unsigned idx, BasicBlock *B);
4044
4045   template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
4046     if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
4047       return true;
4048
4049     // Operand bundles override attributes on the called function, but don't
4050     // override attributes directly present on the invoke instruction.
4051     if (isFnAttrDisallowedByOpBundle(Kind))
4052       return false;
4053
4054     if (const Function *F = getCalledFunction())
4055       return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
4056                                              Kind);
4057     return false;
4058   }
4059
4060   // Shadow Instruction::setInstructionSubclassData with a private forwarding
4061   // method so that subclasses cannot accidentally use it.
4062   void setInstructionSubclassData(unsigned short D) {
4063     Instruction::setInstructionSubclassData(D);
4064   }
4065 };
4066
4067 template <>
4068 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
4069 };
4070
4071 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4072                        BasicBlock *IfException, ArrayRef<Value *> Args,
4073                        ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4074                        const Twine &NameStr, Instruction *InsertBefore)
4075     : TerminatorInst(Ty->getReturnType(), Instruction::Invoke,
4076                      OperandTraits<InvokeInst>::op_end(this) - Values, Values,
4077                      InsertBefore) {
4078   init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
4079 }
4080
4081 InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
4082                        BasicBlock *IfException, ArrayRef<Value *> Args,
4083                        ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4084                        const Twine &NameStr, BasicBlock *InsertAtEnd)
4085     : TerminatorInst(
4086           cast<FunctionType>(cast<PointerType>(Func->getType())
4087                                  ->getElementType())->getReturnType(),
4088           Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - Values,
4089           Values, InsertAtEnd) {
4090   init(Func, IfNormal, IfException, Args, Bundles, NameStr);
4091 }
4092
4093 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
4094
4095 //===----------------------------------------------------------------------===//
4096 //                              ResumeInst Class
4097 //===----------------------------------------------------------------------===//
4098
4099 //===---------------------------------------------------------------------------
4100 /// Resume the propagation of an exception.
4101 ///
4102 class ResumeInst : public TerminatorInst {
4103   ResumeInst(const ResumeInst &RI);
4104
4105   explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4106   ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4107
4108 protected:
4109   // Note: Instruction needs to be a friend here to call cloneImpl.
4110   friend class Instruction;
4111
4112   ResumeInst *cloneImpl() const;
4113
4114 public:
4115   static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4116     return new(1) ResumeInst(Exn, InsertBefore);
4117   }
4118
4119   static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4120     return new(1) ResumeInst(Exn, InsertAtEnd);
4121   }
4122
4123   /// Provide fast operand accessors
4124   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4125
4126   /// Convenience accessor.
4127   Value *getValue() const { return Op<0>(); }
4128
4129   unsigned getNumSuccessors() const { return 0; }
4130
4131   // Methods for support type inquiry through isa, cast, and dyn_cast:
4132   static inline bool classof(const Instruction *I) {
4133     return I->getOpcode() == Instruction::Resume;
4134   }
4135   static inline bool classof(const Value *V) {
4136     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4137   }
4138
4139 private:
4140   friend TerminatorInst;
4141
4142   BasicBlock *getSuccessorV(unsigned idx) const;
4143   unsigned getNumSuccessorsV() const;
4144   void setSuccessorV(unsigned idx, BasicBlock *B);
4145 };
4146
4147 template <>
4148 struct OperandTraits<ResumeInst> :
4149     public FixedNumOperandTraits<ResumeInst, 1> {
4150 };
4151
4152 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4153
4154 //===----------------------------------------------------------------------===//
4155 //                         CatchSwitchInst Class
4156 //===----------------------------------------------------------------------===//
4157 class CatchSwitchInst : public TerminatorInst {
4158   /// The number of operands actually allocated.  NumOperands is
4159   /// the number actually in use.
4160   unsigned ReservedSpace;
4161
4162   // Operand[0] = Outer scope
4163   // Operand[1] = Unwind block destination
4164   // Operand[n] = BasicBlock to go to on match
4165   CatchSwitchInst(const CatchSwitchInst &CSI);
4166
4167   /// Create a new switch instruction, specifying a
4168   /// default destination.  The number of additional handlers can be specified
4169   /// here to make memory allocation more efficient.
4170   /// This constructor can also autoinsert before another instruction.
4171   CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4172                   unsigned NumHandlers, const Twine &NameStr,
4173                   Instruction *InsertBefore);
4174
4175   /// Create a new switch instruction, specifying a
4176   /// default destination.  The number of additional handlers can be specified
4177   /// here to make memory allocation more efficient.
4178   /// This constructor also autoinserts at the end of the specified BasicBlock.
4179   CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4180                   unsigned NumHandlers, const Twine &NameStr,
4181                   BasicBlock *InsertAtEnd);
4182
4183   // allocate space for exactly zero operands
4184   void *operator new(size_t s) { return User::operator new(s); }
4185
4186   void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4187   void growOperands(unsigned Size);
4188
4189 protected:
4190   // Note: Instruction needs to be a friend here to call cloneImpl.
4191   friend class Instruction;
4192
4193   CatchSwitchInst *cloneImpl() const;
4194
4195 public:
4196   void *operator new(size_t, unsigned) = delete;
4197
4198   static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4199                                  unsigned NumHandlers,
4200                                  const Twine &NameStr = "",
4201                                  Instruction *InsertBefore = nullptr) {
4202     return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4203                                InsertBefore);
4204   }
4205
4206   static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4207                                  unsigned NumHandlers, const Twine &NameStr,
4208                                  BasicBlock *InsertAtEnd) {
4209     return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4210                                InsertAtEnd);
4211   }
4212
4213   /// Provide fast operand accessors
4214   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4215
4216   // Accessor Methods for CatchSwitch stmt
4217   Value *getParentPad() const { return getOperand(0); }
4218   void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4219
4220   // Accessor Methods for CatchSwitch stmt
4221   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4222   bool unwindsToCaller() const { return !hasUnwindDest(); }
4223   BasicBlock *getUnwindDest() const {
4224     if (hasUnwindDest())
4225       return cast<BasicBlock>(getOperand(1));
4226     return nullptr;
4227   }
4228   void setUnwindDest(BasicBlock *UnwindDest) {
4229     assert(UnwindDest);
4230     assert(hasUnwindDest());
4231     setOperand(1, UnwindDest);
4232   }
4233
4234   /// return the number of 'handlers' in this catchswitch
4235   /// instruction, except the default handler
4236   unsigned getNumHandlers() const {
4237     if (hasUnwindDest())
4238       return getNumOperands() - 2;
4239     return getNumOperands() - 1;
4240   }
4241
4242 private:
4243   static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4244   static const BasicBlock *handler_helper(const Value *V) {
4245     return cast<BasicBlock>(V);
4246   }
4247
4248 public:
4249   using DerefFnTy = std::pointer_to_unary_function<Value *, BasicBlock *>;
4250   using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4251   using handler_range = iterator_range<handler_iterator>;
4252   using ConstDerefFnTy =
4253       std::pointer_to_unary_function<const Value *, const BasicBlock *>;
4254   using const_handler_iterator =
4255       mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4256   using const_handler_range = iterator_range<const_handler_iterator>;
4257
4258   /// Returns an iterator that points to the first handler in CatchSwitchInst.
4259   handler_iterator handler_begin() {
4260     op_iterator It = op_begin() + 1;
4261     if (hasUnwindDest())
4262       ++It;
4263     return handler_iterator(It, DerefFnTy(handler_helper));
4264   }
4265
4266   /// Returns an iterator that points to the first handler in the
4267   /// CatchSwitchInst.
4268   const_handler_iterator handler_begin() const {
4269     const_op_iterator It = op_begin() + 1;
4270     if (hasUnwindDest())
4271       ++It;
4272     return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4273   }
4274
4275   /// Returns a read-only iterator that points one past the last
4276   /// handler in the CatchSwitchInst.
4277   handler_iterator handler_end() {
4278     return handler_iterator(op_end(), DerefFnTy(handler_helper));
4279   }
4280
4281   /// Returns an iterator that points one past the last handler in the
4282   /// CatchSwitchInst.
4283   const_handler_iterator handler_end() const {
4284     return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4285   }
4286
4287   /// iteration adapter for range-for loops.
4288   handler_range handlers() {
4289     return make_range(handler_begin(), handler_end());
4290   }
4291
4292   /// iteration adapter for range-for loops.
4293   const_handler_range handlers() const {
4294     return make_range(handler_begin(), handler_end());
4295   }
4296
4297   /// Add an entry to the switch instruction...
4298   /// Note:
4299   /// This action invalidates handler_end(). Old handler_end() iterator will
4300   /// point to the added handler.
4301   void addHandler(BasicBlock *Dest);
4302
4303   void removeHandler(handler_iterator HI);
4304
4305   unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4306   BasicBlock *getSuccessor(unsigned Idx) const {
4307     assert(Idx < getNumSuccessors() &&
4308            "Successor # out of range for catchswitch!");
4309     return cast<BasicBlock>(getOperand(Idx + 1));
4310   }
4311   void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4312     assert(Idx < getNumSuccessors() &&
4313            "Successor # out of range for catchswitch!");
4314     setOperand(Idx + 1, NewSucc);
4315   }
4316
4317   // Methods for support type inquiry through isa, cast, and dyn_cast:
4318   static inline bool classof(const Instruction *I) {
4319     return I->getOpcode() == Instruction::CatchSwitch;
4320   }
4321   static inline bool classof(const Value *V) {
4322     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4323   }
4324
4325 private:
4326   friend TerminatorInst;
4327
4328   BasicBlock *getSuccessorV(unsigned Idx) const;
4329   unsigned getNumSuccessorsV() const;
4330   void setSuccessorV(unsigned Idx, BasicBlock *B);
4331 };
4332
4333 template <>
4334 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4335
4336 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4337
4338 //===----------------------------------------------------------------------===//
4339 //                               CleanupPadInst Class
4340 //===----------------------------------------------------------------------===//
4341 class CleanupPadInst : public FuncletPadInst {
4342 private:
4343   explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4344                           unsigned Values, const Twine &NameStr,
4345                           Instruction *InsertBefore)
4346       : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4347                        NameStr, InsertBefore) {}
4348   explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4349                           unsigned Values, const Twine &NameStr,
4350                           BasicBlock *InsertAtEnd)
4351       : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4352                        NameStr, InsertAtEnd) {}
4353
4354 public:
4355   static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4356                                 const Twine &NameStr = "",
4357                                 Instruction *InsertBefore = nullptr) {
4358     unsigned Values = 1 + Args.size();
4359     return new (Values)
4360         CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4361   }
4362
4363   static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4364                                 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4365     unsigned Values = 1 + Args.size();
4366     return new (Values)
4367         CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4368   }
4369
4370   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4371   static inline bool classof(const Instruction *I) {
4372     return I->getOpcode() == Instruction::CleanupPad;
4373   }
4374   static inline bool classof(const Value *V) {
4375     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4376   }
4377 };
4378
4379 //===----------------------------------------------------------------------===//
4380 //                               CatchPadInst Class
4381 //===----------------------------------------------------------------------===//
4382 class CatchPadInst : public FuncletPadInst {
4383 private:
4384   explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4385                         unsigned Values, const Twine &NameStr,
4386                         Instruction *InsertBefore)
4387       : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4388                        NameStr, InsertBefore) {}
4389   explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4390                         unsigned Values, const Twine &NameStr,
4391                         BasicBlock *InsertAtEnd)
4392       : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4393                        NameStr, InsertAtEnd) {}
4394
4395 public:
4396   static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4397                               const Twine &NameStr = "",
4398                               Instruction *InsertBefore = nullptr) {
4399     unsigned Values = 1 + Args.size();
4400     return new (Values)
4401         CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4402   }
4403
4404   static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4405                               const Twine &NameStr, BasicBlock *InsertAtEnd) {
4406     unsigned Values = 1 + Args.size();
4407     return new (Values)
4408         CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4409   }
4410
4411   /// Convenience accessors
4412   CatchSwitchInst *getCatchSwitch() const {
4413     return cast<CatchSwitchInst>(Op<-1>());
4414   }
4415   void setCatchSwitch(Value *CatchSwitch) {
4416     assert(CatchSwitch);
4417     Op<-1>() = CatchSwitch;
4418   }
4419
4420   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4421   static inline bool classof(const Instruction *I) {
4422     return I->getOpcode() == Instruction::CatchPad;
4423   }
4424   static inline bool classof(const Value *V) {
4425     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4426   }
4427 };
4428
4429 //===----------------------------------------------------------------------===//
4430 //                               CatchReturnInst Class
4431 //===----------------------------------------------------------------------===//
4432
4433 class CatchReturnInst : public TerminatorInst {
4434   CatchReturnInst(const CatchReturnInst &RI);
4435   CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4436   CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4437
4438   void init(Value *CatchPad, BasicBlock *BB);
4439
4440 protected:
4441   // Note: Instruction needs to be a friend here to call cloneImpl.
4442   friend class Instruction;
4443
4444   CatchReturnInst *cloneImpl() const;
4445
4446 public:
4447   static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4448                                  Instruction *InsertBefore = nullptr) {
4449     assert(CatchPad);
4450     assert(BB);
4451     return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4452   }
4453
4454   static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4455                                  BasicBlock *InsertAtEnd) {
4456     assert(CatchPad);
4457     assert(BB);
4458     return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4459   }
4460
4461   /// Provide fast operand accessors
4462   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4463
4464   /// Convenience accessors.
4465   CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4466   void setCatchPad(CatchPadInst *CatchPad) {
4467     assert(CatchPad);
4468     Op<0>() = CatchPad;
4469   }
4470
4471   BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4472   void setSuccessor(BasicBlock *NewSucc) {
4473     assert(NewSucc);
4474     Op<1>() = NewSucc;
4475   }
4476   unsigned getNumSuccessors() const { return 1; }
4477
4478   /// Get the parentPad of this catchret's catchpad's catchswitch.
4479   /// The successor block is implicitly a member of this funclet.
4480   Value *getCatchSwitchParentPad() const {
4481     return getCatchPad()->getCatchSwitch()->getParentPad();
4482   }
4483
4484   // Methods for support type inquiry through isa, cast, and dyn_cast:
4485   static inline bool classof(const Instruction *I) {
4486     return (I->getOpcode() == Instruction::CatchRet);
4487   }
4488   static inline bool classof(const Value *V) {
4489     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4490   }
4491
4492 private:
4493   friend TerminatorInst;
4494
4495   BasicBlock *getSuccessorV(unsigned Idx) const;
4496   unsigned getNumSuccessorsV() const;
4497   void setSuccessorV(unsigned Idx, BasicBlock *B);
4498 };
4499
4500 template <>
4501 struct OperandTraits<CatchReturnInst>
4502     : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4503
4504 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4505
4506 //===----------------------------------------------------------------------===//
4507 //                               CleanupReturnInst Class
4508 //===----------------------------------------------------------------------===//
4509
4510 class CleanupReturnInst : public TerminatorInst {
4511 private:
4512   CleanupReturnInst(const CleanupReturnInst &RI);
4513   CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4514                     Instruction *InsertBefore = nullptr);
4515   CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4516                     BasicBlock *InsertAtEnd);
4517
4518   void init(Value *CleanupPad, BasicBlock *UnwindBB);
4519
4520 protected:
4521   // Note: Instruction needs to be a friend here to call cloneImpl.
4522   friend class Instruction;
4523
4524   CleanupReturnInst *cloneImpl() const;
4525
4526 public:
4527   static CleanupReturnInst *Create(Value *CleanupPad,
4528                                    BasicBlock *UnwindBB = nullptr,
4529                                    Instruction *InsertBefore = nullptr) {
4530     assert(CleanupPad);
4531     unsigned Values = 1;
4532     if (UnwindBB)
4533       ++Values;
4534     return new (Values)
4535         CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4536   }
4537
4538   static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4539                                    BasicBlock *InsertAtEnd) {
4540     assert(CleanupPad);
4541     unsigned Values = 1;
4542     if (UnwindBB)
4543       ++Values;
4544     return new (Values)
4545         CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4546   }
4547
4548   /// Provide fast operand accessors
4549   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4550
4551   bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4552   bool unwindsToCaller() const { return !hasUnwindDest(); }
4553
4554   /// Convenience accessor.
4555   CleanupPadInst *getCleanupPad() const {
4556     return cast<CleanupPadInst>(Op<0>());
4557   }
4558   void setCleanupPad(CleanupPadInst *CleanupPad) {
4559     assert(CleanupPad);
4560     Op<0>() = CleanupPad;
4561   }
4562
4563   unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4564
4565   BasicBlock *getUnwindDest() const {
4566     return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4567   }
4568   void setUnwindDest(BasicBlock *NewDest) {
4569     assert(NewDest);
4570     assert(hasUnwindDest());
4571     Op<1>() = NewDest;
4572   }
4573
4574   // Methods for support type inquiry through isa, cast, and dyn_cast:
4575   static inline bool classof(const Instruction *I) {
4576     return (I->getOpcode() == Instruction::CleanupRet);
4577   }
4578   static inline bool classof(const Value *V) {
4579     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4580   }
4581
4582 private:
4583   friend TerminatorInst;
4584
4585   BasicBlock *getSuccessorV(unsigned Idx) const;
4586   unsigned getNumSuccessorsV() const;
4587   void setSuccessorV(unsigned Idx, BasicBlock *B);
4588
4589   // Shadow Instruction::setInstructionSubclassData with a private forwarding
4590   // method so that subclasses cannot accidentally use it.
4591   void setInstructionSubclassData(unsigned short D) {
4592     Instruction::setInstructionSubclassData(D);
4593   }
4594 };
4595
4596 template <>
4597 struct OperandTraits<CleanupReturnInst>
4598     : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4599
4600 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4601
4602 //===----------------------------------------------------------------------===//
4603 //                           UnreachableInst Class
4604 //===----------------------------------------------------------------------===//
4605
4606 //===---------------------------------------------------------------------------
4607 /// This function has undefined behavior.  In particular, the
4608 /// presence of this instruction indicates some higher level knowledge that the
4609 /// end of the block cannot be reached.
4610 ///
4611 class UnreachableInst : public TerminatorInst {
4612 protected:
4613   // Note: Instruction needs to be a friend here to call cloneImpl.
4614   friend class Instruction;
4615
4616   UnreachableInst *cloneImpl() const;
4617
4618 public:
4619   explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4620   explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4621
4622   // allocate space for exactly zero operands
4623   void *operator new(size_t s) {
4624     return User::operator new(s, 0);
4625   }
4626
4627   void *operator new(size_t, unsigned) = delete;
4628
4629   unsigned getNumSuccessors() const { return 0; }
4630
4631   // Methods for support type inquiry through isa, cast, and dyn_cast:
4632   static inline bool classof(const Instruction *I) {
4633     return I->getOpcode() == Instruction::Unreachable;
4634   }
4635   static inline bool classof(const Value *V) {
4636     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4637   }
4638
4639 private:
4640   friend TerminatorInst;
4641
4642   BasicBlock *getSuccessorV(unsigned idx) const;
4643   unsigned getNumSuccessorsV() const;
4644   void setSuccessorV(unsigned idx, BasicBlock *B);
4645 };
4646
4647 //===----------------------------------------------------------------------===//
4648 //                                 TruncInst Class
4649 //===----------------------------------------------------------------------===//
4650
4651 /// This class represents a truncation of integer types.
4652 class TruncInst : public CastInst {
4653 protected:
4654   // Note: Instruction needs to be a friend here to call cloneImpl.
4655   friend class Instruction;
4656
4657   /// Clone an identical TruncInst
4658   TruncInst *cloneImpl() const;
4659
4660 public:
4661   /// Constructor with insert-before-instruction semantics
4662   TruncInst(
4663     Value *S,                           ///< The value to be truncated
4664     Type *Ty,                           ///< The (smaller) type to truncate to
4665     const Twine &NameStr = "",          ///< A name for the new instruction
4666     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4667   );
4668
4669   /// Constructor with insert-at-end-of-block semantics
4670   TruncInst(
4671     Value *S,                     ///< The value to be truncated
4672     Type *Ty,                     ///< The (smaller) type to truncate to
4673     const Twine &NameStr,         ///< A name for the new instruction
4674     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4675   );
4676
4677   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4678   static inline bool classof(const Instruction *I) {
4679     return I->getOpcode() == Trunc;
4680   }
4681   static inline bool classof(const Value *V) {
4682     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4683   }
4684 };
4685
4686 //===----------------------------------------------------------------------===//
4687 //                                 ZExtInst Class
4688 //===----------------------------------------------------------------------===//
4689
4690 /// This class represents zero extension of integer types.
4691 class ZExtInst : public CastInst {
4692 protected:
4693   // Note: Instruction needs to be a friend here to call cloneImpl.
4694   friend class Instruction;
4695
4696   /// Clone an identical ZExtInst
4697   ZExtInst *cloneImpl() const;
4698
4699 public:
4700   /// Constructor with insert-before-instruction semantics
4701   ZExtInst(
4702     Value *S,                           ///< The value to be zero extended
4703     Type *Ty,                           ///< The type to zero extend to
4704     const Twine &NameStr = "",          ///< A name for the new instruction
4705     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4706   );
4707
4708   /// Constructor with insert-at-end semantics.
4709   ZExtInst(
4710     Value *S,                     ///< The value to be zero extended
4711     Type *Ty,                     ///< The type to zero extend to
4712     const Twine &NameStr,         ///< A name for the new instruction
4713     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4714   );
4715
4716   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4717   static inline bool classof(const Instruction *I) {
4718     return I->getOpcode() == ZExt;
4719   }
4720   static inline bool classof(const Value *V) {
4721     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4722   }
4723 };
4724
4725 //===----------------------------------------------------------------------===//
4726 //                                 SExtInst Class
4727 //===----------------------------------------------------------------------===//
4728
4729 /// This class represents a sign extension of integer types.
4730 class SExtInst : public CastInst {
4731 protected:
4732   // Note: Instruction needs to be a friend here to call cloneImpl.
4733   friend class Instruction;
4734
4735   /// Clone an identical SExtInst
4736   SExtInst *cloneImpl() const;
4737
4738 public:
4739   /// Constructor with insert-before-instruction semantics
4740   SExtInst(
4741     Value *S,                           ///< The value to be sign extended
4742     Type *Ty,                           ///< The type to sign extend to
4743     const Twine &NameStr = "",          ///< A name for the new instruction
4744     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4745   );
4746
4747   /// Constructor with insert-at-end-of-block semantics
4748   SExtInst(
4749     Value *S,                     ///< The value to be sign extended
4750     Type *Ty,                     ///< The type to sign extend to
4751     const Twine &NameStr,         ///< A name for the new instruction
4752     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4753   );
4754
4755   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4756   static inline bool classof(const Instruction *I) {
4757     return I->getOpcode() == SExt;
4758   }
4759   static inline bool classof(const Value *V) {
4760     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4761   }
4762 };
4763
4764 //===----------------------------------------------------------------------===//
4765 //                                 FPTruncInst Class
4766 //===----------------------------------------------------------------------===//
4767
4768 /// This class represents a truncation of floating point types.
4769 class FPTruncInst : public CastInst {
4770 protected:
4771   // Note: Instruction needs to be a friend here to call cloneImpl.
4772   friend class Instruction;
4773
4774   /// Clone an identical FPTruncInst
4775   FPTruncInst *cloneImpl() const;
4776
4777 public:
4778   /// Constructor with insert-before-instruction semantics
4779   FPTruncInst(
4780     Value *S,                           ///< The value to be truncated
4781     Type *Ty,                           ///< The type to truncate to
4782     const Twine &NameStr = "",          ///< A name for the new instruction
4783     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4784   );
4785
4786   /// Constructor with insert-before-instruction semantics
4787   FPTruncInst(
4788     Value *S,                     ///< The value to be truncated
4789     Type *Ty,                     ///< The type to truncate to
4790     const Twine &NameStr,         ///< A name for the new instruction
4791     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4792   );
4793
4794   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4795   static inline bool classof(const Instruction *I) {
4796     return I->getOpcode() == FPTrunc;
4797   }
4798   static inline bool classof(const Value *V) {
4799     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4800   }
4801 };
4802
4803 //===----------------------------------------------------------------------===//
4804 //                                 FPExtInst Class
4805 //===----------------------------------------------------------------------===//
4806
4807 /// This class represents an extension of floating point types.
4808 class FPExtInst : public CastInst {
4809 protected:
4810   // Note: Instruction needs to be a friend here to call cloneImpl.
4811   friend class Instruction;
4812
4813   /// Clone an identical FPExtInst
4814   FPExtInst *cloneImpl() const;
4815
4816 public:
4817   /// Constructor with insert-before-instruction semantics
4818   FPExtInst(
4819     Value *S,                           ///< The value to be extended
4820     Type *Ty,                           ///< The type to extend to
4821     const Twine &NameStr = "",          ///< A name for the new instruction
4822     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4823   );
4824
4825   /// Constructor with insert-at-end-of-block semantics
4826   FPExtInst(
4827     Value *S,                     ///< The value to be extended
4828     Type *Ty,                     ///< The type to extend to
4829     const Twine &NameStr,         ///< A name for the new instruction
4830     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4831   );
4832
4833   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4834   static inline bool classof(const Instruction *I) {
4835     return I->getOpcode() == FPExt;
4836   }
4837   static inline bool classof(const Value *V) {
4838     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4839   }
4840 };
4841
4842 //===----------------------------------------------------------------------===//
4843 //                                 UIToFPInst Class
4844 //===----------------------------------------------------------------------===//
4845
4846 /// This class represents a cast unsigned integer to floating point.
4847 class UIToFPInst : public CastInst {
4848 protected:
4849   // Note: Instruction needs to be a friend here to call cloneImpl.
4850   friend class Instruction;
4851
4852   /// Clone an identical UIToFPInst
4853   UIToFPInst *cloneImpl() const;
4854
4855 public:
4856   /// Constructor with insert-before-instruction semantics
4857   UIToFPInst(
4858     Value *S,                           ///< The value to be converted
4859     Type *Ty,                           ///< The type to convert to
4860     const Twine &NameStr = "",          ///< A name for the new instruction
4861     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4862   );
4863
4864   /// Constructor with insert-at-end-of-block semantics
4865   UIToFPInst(
4866     Value *S,                     ///< The value to be converted
4867     Type *Ty,                     ///< The type to convert to
4868     const Twine &NameStr,         ///< A name for the new instruction
4869     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4870   );
4871
4872   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4873   static inline bool classof(const Instruction *I) {
4874     return I->getOpcode() == UIToFP;
4875   }
4876   static inline bool classof(const Value *V) {
4877     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4878   }
4879 };
4880
4881 //===----------------------------------------------------------------------===//
4882 //                                 SIToFPInst Class
4883 //===----------------------------------------------------------------------===//
4884
4885 /// This class represents a cast from signed integer to floating point.
4886 class SIToFPInst : public CastInst {
4887 protected:
4888   // Note: Instruction needs to be a friend here to call cloneImpl.
4889   friend class Instruction;
4890
4891   /// Clone an identical SIToFPInst
4892   SIToFPInst *cloneImpl() const;
4893
4894 public:
4895   /// Constructor with insert-before-instruction semantics
4896   SIToFPInst(
4897     Value *S,                           ///< The value to be converted
4898     Type *Ty,                           ///< The type to convert to
4899     const Twine &NameStr = "",          ///< A name for the new instruction
4900     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4901   );
4902
4903   /// Constructor with insert-at-end-of-block semantics
4904   SIToFPInst(
4905     Value *S,                     ///< The value to be converted
4906     Type *Ty,                     ///< The type to convert to
4907     const Twine &NameStr,         ///< A name for the new instruction
4908     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4909   );
4910
4911   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4912   static inline bool classof(const Instruction *I) {
4913     return I->getOpcode() == SIToFP;
4914   }
4915   static inline bool classof(const Value *V) {
4916     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4917   }
4918 };
4919
4920 //===----------------------------------------------------------------------===//
4921 //                                 FPToUIInst Class
4922 //===----------------------------------------------------------------------===//
4923
4924 /// This class represents a cast from floating point to unsigned integer
4925 class FPToUIInst  : public CastInst {
4926 protected:
4927   // Note: Instruction needs to be a friend here to call cloneImpl.
4928   friend class Instruction;
4929
4930   /// Clone an identical FPToUIInst
4931   FPToUIInst *cloneImpl() const;
4932
4933 public:
4934   /// Constructor with insert-before-instruction semantics
4935   FPToUIInst(
4936     Value *S,                           ///< The value to be converted
4937     Type *Ty,                           ///< The type to convert to
4938     const Twine &NameStr = "",          ///< A name for the new instruction
4939     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4940   );
4941
4942   /// Constructor with insert-at-end-of-block semantics
4943   FPToUIInst(
4944     Value *S,                     ///< The value to be converted
4945     Type *Ty,                     ///< The type to convert to
4946     const Twine &NameStr,         ///< A name for the new instruction
4947     BasicBlock *InsertAtEnd       ///< Where to insert the new instruction
4948   );
4949
4950   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4951   static inline bool classof(const Instruction *I) {
4952     return I->getOpcode() == FPToUI;
4953   }
4954   static inline bool classof(const Value *V) {
4955     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4956   }
4957 };
4958
4959 //===----------------------------------------------------------------------===//
4960 //                                 FPToSIInst Class
4961 //===----------------------------------------------------------------------===//
4962
4963 /// This class represents a cast from floating point to signed integer.
4964 class FPToSIInst  : public CastInst {
4965 protected:
4966   // Note: Instruction needs to be a friend here to call cloneImpl.
4967   friend class Instruction;
4968
4969   /// Clone an identical FPToSIInst
4970   FPToSIInst *cloneImpl() const;
4971
4972 public:
4973   /// Constructor with insert-before-instruction semantics
4974   FPToSIInst(
4975     Value *S,                           ///< The value to be converted
4976     Type *Ty,                           ///< The type to convert to
4977     const Twine &NameStr = "",          ///< A name for the new instruction
4978     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4979   );
4980
4981   /// Constructor with insert-at-end-of-block semantics
4982   FPToSIInst(
4983     Value *S,                     ///< The value to be converted
4984     Type *Ty,                     ///< The type to convert to
4985     const Twine &NameStr,         ///< A name for the new instruction
4986     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
4987   );
4988
4989   /// Methods for support type inquiry through isa, cast, and dyn_cast:
4990   static inline bool classof(const Instruction *I) {
4991     return I->getOpcode() == FPToSI;
4992   }
4993   static inline bool classof(const Value *V) {
4994     return isa<Instruction>(V) && classof(cast<Instruction>(V));
4995   }
4996 };
4997
4998 //===----------------------------------------------------------------------===//
4999 //                                 IntToPtrInst Class
5000 //===----------------------------------------------------------------------===//
5001
5002 /// This class represents a cast from an integer to a pointer.
5003 class IntToPtrInst : public CastInst {
5004 public:
5005   // Note: Instruction needs to be a friend here to call cloneImpl.
5006   friend class Instruction;
5007
5008   /// Constructor with insert-before-instruction semantics
5009   IntToPtrInst(
5010     Value *S,                           ///< The value to be converted
5011     Type *Ty,                           ///< The type to convert to
5012     const Twine &NameStr = "",          ///< A name for the new instruction
5013     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5014   );
5015
5016   /// Constructor with insert-at-end-of-block semantics
5017   IntToPtrInst(
5018     Value *S,                     ///< The value to be converted
5019     Type *Ty,                     ///< The type to convert to
5020     const Twine &NameStr,         ///< A name for the new instruction
5021     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
5022   );
5023
5024   /// Clone an identical IntToPtrInst.
5025   IntToPtrInst *cloneImpl() const;
5026
5027   /// Returns the address space of this instruction's pointer type.
5028   unsigned getAddressSpace() const {
5029     return getType()->getPointerAddressSpace();
5030   }
5031
5032   // Methods for support type inquiry through isa, cast, and dyn_cast:
5033   static inline bool classof(const Instruction *I) {
5034     return I->getOpcode() == IntToPtr;
5035   }
5036   static inline bool classof(const Value *V) {
5037     return isa<Instruction>(V) && classof(cast<Instruction>(V));
5038   }
5039 };
5040
5041 //===----------------------------------------------------------------------===//
5042 //                                 PtrToIntInst Class
5043 //===----------------------------------------------------------------------===//
5044
5045 /// This class represents a cast from a pointer to an integer.
5046 class PtrToIntInst : public CastInst {
5047 protected:
5048   // Note: Instruction needs to be a friend here to call cloneImpl.
5049   friend class Instruction;
5050
5051   /// Clone an identical PtrToIntInst.
5052   PtrToIntInst *cloneImpl() const;
5053
5054 public:
5055   /// Constructor with insert-before-instruction semantics
5056   PtrToIntInst(
5057     Value *S,                           ///< The value to be converted
5058     Type *Ty,                           ///< The type to convert to
5059     const Twine &NameStr = "",          ///< A name for the new instruction
5060     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5061   );
5062
5063   /// Constructor with insert-at-end-of-block semantics
5064   PtrToIntInst(
5065     Value *S,                     ///< The value to be converted
5066     Type *Ty,                     ///< The type to convert to
5067     const Twine &NameStr,         ///< A name for the new instruction
5068     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
5069   );
5070
5071   /// Gets the pointer operand.
5072   Value *getPointerOperand() { return getOperand(0); }
5073   /// Gets the pointer operand.
5074   const Value *getPointerOperand() const { return getOperand(0); }
5075   /// Gets the operand index of the pointer operand.
5076   static unsigned getPointerOperandIndex() { return 0U; }
5077
5078   /// Returns the address space of the pointer operand.
5079   unsigned getPointerAddressSpace() const {
5080     return getPointerOperand()->getType()->getPointerAddressSpace();
5081   }
5082
5083   // Methods for support type inquiry through isa, cast, and dyn_cast:
5084   static inline bool classof(const Instruction *I) {
5085     return I->getOpcode() == PtrToInt;
5086   }
5087   static inline bool classof(const Value *V) {
5088     return isa<Instruction>(V) && classof(cast<Instruction>(V));
5089   }
5090 };
5091
5092 //===----------------------------------------------------------------------===//
5093 //                             BitCastInst Class
5094 //===----------------------------------------------------------------------===//
5095
5096 /// This class represents a no-op cast from one type to another.
5097 class BitCastInst : public CastInst {
5098 protected:
5099   // Note: Instruction needs to be a friend here to call cloneImpl.
5100   friend class Instruction;
5101
5102   /// Clone an identical BitCastInst.
5103   BitCastInst *cloneImpl() const;
5104
5105 public:
5106   /// Constructor with insert-before-instruction semantics
5107   BitCastInst(
5108     Value *S,                           ///< The value to be casted
5109     Type *Ty,                           ///< The type to casted to
5110     const Twine &NameStr = "",          ///< A name for the new instruction
5111     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5112   );
5113
5114   /// Constructor with insert-at-end-of-block semantics
5115   BitCastInst(
5116     Value *S,                     ///< The value to be casted
5117     Type *Ty,                     ///< The type to casted to
5118     const Twine &NameStr,         ///< A name for the new instruction
5119     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
5120   );
5121
5122   // Methods for support type inquiry through isa, cast, and dyn_cast:
5123   static inline bool classof(const Instruction *I) {
5124     return I->getOpcode() == BitCast;
5125   }
5126   static inline bool classof(const Value *V) {
5127     return isa<Instruction>(V) && classof(cast<Instruction>(V));
5128   }
5129 };
5130
5131 //===----------------------------------------------------------------------===//
5132 //                          AddrSpaceCastInst Class
5133 //===----------------------------------------------------------------------===//
5134
5135 /// This class represents a conversion between pointers from one address space
5136 /// to another.
5137 class AddrSpaceCastInst : public CastInst {
5138 protected:
5139   // Note: Instruction needs to be a friend here to call cloneImpl.
5140   friend class Instruction;
5141
5142   /// Clone an identical AddrSpaceCastInst.
5143   AddrSpaceCastInst *cloneImpl() const;
5144
5145 public:
5146   /// Constructor with insert-before-instruction semantics
5147   AddrSpaceCastInst(
5148     Value *S,                           ///< The value to be casted
5149     Type *Ty,                           ///< The type to casted to
5150     const Twine &NameStr = "",          ///< A name for the new instruction
5151     Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5152   );
5153
5154   /// Constructor with insert-at-end-of-block semantics
5155   AddrSpaceCastInst(
5156     Value *S,                     ///< The value to be casted
5157     Type *Ty,                     ///< The type to casted to
5158     const Twine &NameStr,         ///< A name for the new instruction
5159     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
5160   );
5161
5162   // Methods for support type inquiry through isa, cast, and dyn_cast:
5163   static inline bool classof(const Instruction *I) {
5164     return I->getOpcode() == AddrSpaceCast;
5165   }
5166   static inline bool classof(const Value *V) {
5167     return isa<Instruction>(V) && classof(cast<Instruction>(V));
5168   }
5169
5170   /// Gets the pointer operand.
5171   Value *getPointerOperand() {
5172     return getOperand(0);
5173   }
5174
5175   /// Gets the pointer operand.
5176   const Value *getPointerOperand() const {
5177     return getOperand(0);
5178   }
5179
5180   /// Gets the operand index of the pointer operand.
5181   static unsigned getPointerOperandIndex() {
5182     return 0U;
5183   }
5184
5185   /// Returns the address space of the pointer operand.
5186   unsigned getSrcAddressSpace() const {
5187     return getPointerOperand()->getType()->getPointerAddressSpace();
5188   }
5189
5190   /// Returns the address space of the result.
5191   unsigned getDestAddressSpace() const {
5192     return getType()->getPointerAddressSpace();
5193   }
5194 };
5195
5196 } // end namespace llvm
5197
5198 #endif // LLVM_IR_INSTRUCTIONS_H