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