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