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 
738  static StringRef getOperationName(BinOp Op);
739 
741  unsigned short SubclassData = getSubclassDataFromInstruction();
742  setInstructionSubclassData((SubclassData & 31) |
743  (Operation << 5));
744  }
745 
746  /// Return true if this is a RMW on a volatile memory location.
747  ///
748  bool isVolatile() const {
749  return getSubclassDataFromInstruction() & 1;
750  }
751 
752  /// Specify whether this is a volatile RMW or not.
753  ///
754  void setVolatile(bool V) {
755  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
756  (unsigned)V);
757  }
758 
759  /// Transparently provide more efficient getOperand methods.
761 
762  /// Returns the ordering constraint of this rmw instruction.
764  return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
765  }
766 
767  /// Sets the ordering constraint of this rmw instruction.
768  void setOrdering(AtomicOrdering Ordering) {
769  assert(Ordering != AtomicOrdering::NotAtomic &&
770  "atomicrmw instructions can only be atomic.");
771  setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
772  ((unsigned)Ordering << 2));
773  }
774 
775  /// Returns the synchronization scope ID of this rmw instruction.
777  return SSID;
778  }
779 
780  /// Sets the synchronization scope ID of this rmw instruction.
782  this->SSID = SSID;
783  }
784 
786  const Value *getPointerOperand() const { return getOperand(0); }
787  static unsigned getPointerOperandIndex() { return 0U; }
788 
789  Value *getValOperand() { return getOperand(1); }
790  const Value *getValOperand() const { return getOperand(1); }
791 
792  /// Returns the address space of the pointer operand.
793  unsigned getPointerAddressSpace() const {
795  }
796 
797  // Methods for support type inquiry through isa, cast, and dyn_cast:
798  static bool classof(const Instruction *I) {
799  return I->getOpcode() == Instruction::AtomicRMW;
800  }
801  static bool classof(const Value *V) {
802  return isa<Instruction>(V) && classof(cast<Instruction>(V));
803  }
804 
805 private:
806  void Init(BinOp Operation, Value *Ptr, Value *Val,
807  AtomicOrdering Ordering, SyncScope::ID SSID);
808 
809  // Shadow Instruction::setInstructionSubclassData with a private forwarding
810  // method so that subclasses cannot accidentally use it.
811  void setInstructionSubclassData(unsigned short D) {
813  }
814 
815  /// The synchronization scope ID of this rmw instruction. Not quite enough
816  /// room in SubClassData for everything, so synchronization scope ID gets its
817  /// own field.
818  SyncScope::ID SSID;
819 };
820 
821 template <>
823  : public FixedNumOperandTraits<AtomicRMWInst,2> {
824 };
825 
827 
828 //===----------------------------------------------------------------------===//
829 // GetElementPtrInst Class
830 //===----------------------------------------------------------------------===//
831 
832 // checkGEPType - Simple wrapper function to give a better assertion failure
833 // message on bad indexes for a gep instruction.
834 //
836  assert(Ty && "Invalid GetElementPtrInst indices for type!");
837  return Ty;
838 }
839 
840 /// an instruction for type-safe pointer arithmetic to
841 /// access elements of arrays and structs
842 ///
844  Type *SourceElementType;
845  Type *ResultElementType;
846 
848 
849  /// Constructors - Create a getelementptr instruction with a base pointer an
850  /// list of indices. The first ctor can optionally insert before an existing
851  /// instruction, the second appends the new instruction to the specified
852  /// BasicBlock.
853  inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
854  ArrayRef<Value *> IdxList, unsigned Values,
855  const Twine &NameStr, Instruction *InsertBefore);
856  inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
857  ArrayRef<Value *> IdxList, unsigned Values,
858  const Twine &NameStr, BasicBlock *InsertAtEnd);
859 
860  void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
861 
862 protected:
863  // Note: Instruction needs to be a friend here to call cloneImpl.
864  friend class Instruction;
865 
866  GetElementPtrInst *cloneImpl() const;
867 
868 public:
869  static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
870  ArrayRef<Value *> IdxList,
871  const Twine &NameStr = "",
872  Instruction *InsertBefore = nullptr) {
873  unsigned Values = 1 + unsigned(IdxList.size());
874  if (!PointeeType)
875  PointeeType =
876  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
877  else
878  assert(
879  PointeeType ==
880  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
881  return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
882  NameStr, InsertBefore);
883  }
884 
885  static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
886  ArrayRef<Value *> IdxList,
887  const Twine &NameStr,
888  BasicBlock *InsertAtEnd) {
889  unsigned Values = 1 + unsigned(IdxList.size());
890  if (!PointeeType)
891  PointeeType =
892  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
893  else
894  assert(
895  PointeeType ==
896  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
897  return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
898  NameStr, InsertAtEnd);
899  }
900 
901  /// Create an "inbounds" getelementptr. See the documentation for the
902  /// "inbounds" flag in LangRef.html for details.
904  ArrayRef<Value *> IdxList,
905  const Twine &NameStr = "",
906  Instruction *InsertBefore = nullptr){
907  return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
908  }
909 
910  static GetElementPtrInst *
911  CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
912  const Twine &NameStr = "",
913  Instruction *InsertBefore = nullptr) {
915  Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
916  GEP->setIsInBounds(true);
917  return GEP;
918  }
919 
921  ArrayRef<Value *> IdxList,
922  const Twine &NameStr,
923  BasicBlock *InsertAtEnd) {
924  return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
925  }
926 
927  static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
928  ArrayRef<Value *> IdxList,
929  const Twine &NameStr,
930  BasicBlock *InsertAtEnd) {
932  Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
933  GEP->setIsInBounds(true);
934  return GEP;
935  }
936 
937  /// Transparently provide more efficient getOperand methods.
939 
940  Type *getSourceElementType() const { return SourceElementType; }
941 
942  void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
943  void setResultElementType(Type *Ty) { ResultElementType = Ty; }
944 
946  assert(ResultElementType ==
947  cast<PointerType>(getType()->getScalarType())->getElementType());
948  return ResultElementType;
949  }
950 
951  /// Returns the address space of this instruction's pointer type.
952  unsigned getAddressSpace() const {
953  // Note that this is always the same as the pointer operand's address space
954  // and that is cheaper to compute, so cheat here.
955  return getPointerAddressSpace();
956  }
957 
958  /// Returns the type of the element that would be loaded with
959  /// a load instruction with the specified parameters.
960  ///
961  /// Null is returned if the indices are invalid for the specified
962  /// pointer type.
963  ///
964  static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
965  static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
966  static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
967 
968  inline op_iterator idx_begin() { return op_begin()+1; }
969  inline const_op_iterator idx_begin() const { return op_begin()+1; }
970  inline op_iterator idx_end() { return op_end(); }
971  inline const_op_iterator idx_end() const { return op_end(); }
972 
974  return make_range(idx_begin(), idx_end());
975  }
976 
978  return make_range(idx_begin(), idx_end());
979  }
980 
982  return getOperand(0);
983  }
984  const Value *getPointerOperand() const {
985  return getOperand(0);
986  }
987  static unsigned getPointerOperandIndex() {
988  return 0U; // get index for modifying correct operand.
989  }
990 
991  /// Method to return the pointer operand as a
992  /// PointerType.
994  return getPointerOperand()->getType();
995  }
996 
997  /// Returns the address space of the pointer operand.
998  unsigned getPointerAddressSpace() const {
999  return getPointerOperandType()->getPointerAddressSpace();
1000  }
1001 
1002  /// Returns the pointer type returned by the GEP
1003  /// instruction, which may be a vector of pointers.
1005  return getGEPReturnType(
1006  cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1007  Ptr, IdxList);
1008  }
1009  static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1010  ArrayRef<Value *> IdxList) {
1011  Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1012  Ptr->getType()->getPointerAddressSpace());
1013  // Vector GEP
1014  if (Ptr->getType()->isVectorTy()) {
1015  unsigned NumElem = Ptr->getType()->getVectorNumElements();
1016  return VectorType::get(PtrTy, NumElem);
1017  }
1018  for (Value *Index : IdxList)
1019  if (Index->getType()->isVectorTy()) {
1020  unsigned NumElem = Index->getType()->getVectorNumElements();
1021  return VectorType::get(PtrTy, NumElem);
1022  }
1023  // Scalar GEP
1024  return PtrTy;
1025  }
1026 
1027  unsigned getNumIndices() const { // Note: always non-negative
1028  return getNumOperands() - 1;
1029  }
1030 
1031  bool hasIndices() const {
1032  return getNumOperands() > 1;
1033  }
1034 
1035  /// Return true if all of the indices of this GEP are
1036  /// zeros. If so, the result pointer and the first operand have the same
1037  /// value, just potentially different types.
1038  bool hasAllZeroIndices() const;
1039 
1040  /// Return true if all of the indices of this GEP are
1041  /// constant integers. If so, the result pointer and the first operand have
1042  /// a constant offset between them.
1043  bool hasAllConstantIndices() const;
1044 
1045  /// Set or clear the inbounds flag on this GEP instruction.
1046  /// See LangRef.html for the meaning of inbounds on a getelementptr.
1047  void setIsInBounds(bool b = true);
1048 
1049  /// Determine whether the GEP has the inbounds flag.
1050  bool isInBounds() const;
1051 
1052  /// Accumulate the constant address offset of this GEP if possible.
1053  ///
1054  /// This routine accepts an APInt into which it will accumulate the constant
1055  /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1056  /// all-constant, it returns false and the value of the offset APInt is
1057  /// undefined (it is *not* preserved!). The APInt passed into this routine
1058  /// must be at least as wide as the IntPtr type for the address space of
1059  /// the base GEP pointer.
1060  bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1061 
1062  // Methods for support type inquiry through isa, cast, and dyn_cast:
1063  static bool classof(const Instruction *I) {
1064  return (I->getOpcode() == Instruction::GetElementPtr);
1065  }
1066  static bool classof(const Value *V) {
1067  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1068  }
1069 };
1070 
1071 template <>
1073  public VariadicOperandTraits<GetElementPtrInst, 1> {
1074 };
1075 
1076 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1077  ArrayRef<Value *> IdxList, unsigned Values,
1078  const Twine &NameStr,
1079  Instruction *InsertBefore)
1080  : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1082  Values, InsertBefore),
1083  SourceElementType(PointeeType),
1084  ResultElementType(getIndexedType(PointeeType, IdxList)) {
1085  assert(ResultElementType ==
1086  cast<PointerType>(getType()->getScalarType())->getElementType());
1087  init(Ptr, IdxList, NameStr);
1088 }
1089 
1090 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1091  ArrayRef<Value *> IdxList, unsigned Values,
1092  const Twine &NameStr,
1093  BasicBlock *InsertAtEnd)
1094  : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1096  Values, InsertAtEnd),
1097  SourceElementType(PointeeType),
1098  ResultElementType(getIndexedType(PointeeType, IdxList)) {
1099  assert(ResultElementType ==
1100  cast<PointerType>(getType()->getScalarType())->getElementType());
1101  init(Ptr, IdxList, NameStr);
1102 }
1103 
1104 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1105 
1106 //===----------------------------------------------------------------------===//
1107 // UnaryOperator Class
1108 //===----------------------------------------------------------------------===//
1109 
1110 /// a unary instruction
1112  void AssertOK();
1113 
1114 protected:
1115  UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
1116  const Twine &Name, Instruction *InsertBefore);
1117  UnaryOperator(UnaryOps iType, Value *S, Type *Ty,
1118  const Twine &Name, BasicBlock *InsertAtEnd);
1119 
1120  // Note: Instruction needs to be a friend here to call cloneImpl.
1121  friend class Instruction;
1122 
1123  UnaryOperator *cloneImpl() const;
1124 
1125 public:
1126 
1127  /// Construct a unary instruction, given the opcode and an operand.
1128  /// Optionally (if InstBefore is specified) insert the instruction
1129  /// into a BasicBlock right before the specified instruction. The specified
1130  /// Instruction is allowed to be a dereferenced end iterator.
1131  ///
1132  static UnaryOperator *Create(UnaryOps Op, Value *S,
1133  const Twine &Name = Twine(),
1134  Instruction *InsertBefore = nullptr);
1135 
1136  /// Construct a unary instruction, given the opcode and an operand.
1137  /// Also automatically insert this instruction to the end of the
1138  /// BasicBlock specified.
1139  ///
1140  static UnaryOperator *Create(UnaryOps Op, Value *S,
1141  const Twine &Name,
1142  BasicBlock *InsertAtEnd);
1143 
1144  /// These methods just forward to Create, and are useful when you
1145  /// statically know what type of instruction you're going to create. These
1146  /// helpers just save some typing.
1147 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1148  static UnaryInstruction *Create##OPC(Value *V, \
1149  const Twine &Name = "") {\
1150  return Create(Instruction::OPC, V, Name);\
1151  }
1152 #include "llvm/IR/Instruction.def"
1153 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1154  static UnaryInstruction *Create##OPC(Value *V, \
1155  const Twine &Name, BasicBlock *BB) {\
1156  return Create(Instruction::OPC, V, Name, BB);\
1157  }
1158 #include "llvm/IR/Instruction.def"
1159 #define HANDLE_UNARY_INST(N, OPC, CLASS) \
1160  static UnaryInstruction *Create##OPC(Value *V, \
1161  const Twine &Name, Instruction *I) {\
1162  return Create(Instruction::OPC, V, Name, I);\
1163  }
1164 #include "llvm/IR/Instruction.def"
1165 
1167  return static_cast<UnaryOps>(Instruction::getOpcode());
1168  }
1169 };
1170 
1171 //===----------------------------------------------------------------------===//
1172 // ICmpInst Class
1173 //===----------------------------------------------------------------------===//
1174 
1175 /// This instruction compares its operands according to the predicate given
1176 /// to the constructor. It only operates on integers or pointers. The operands
1177 /// must be identical types.
1178 /// Represent an integer comparison operator.
1179 class ICmpInst: public CmpInst {
1180  void AssertOK() {
1181  assert(isIntPredicate() &&
1182  "Invalid ICmp predicate value");
1183  assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1184  "Both operands to ICmp instruction are not of the same type!");
1185  // Check that the operands are the right type
1186  assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1187  getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1188  "Invalid operand types for ICmp instruction");
1189  }
1190 
1191 protected:
1192  // Note: Instruction needs to be a friend here to call cloneImpl.
1193  friend class Instruction;
1194 
1195  /// Clone an identical ICmpInst
1196  ICmpInst *cloneImpl() const;
1197 
1198 public:
1199  /// Constructor with insert-before-instruction semantics.
1201  Instruction *InsertBefore, ///< Where to insert
1202  Predicate pred, ///< The predicate to use for the comparison
1203  Value *LHS, ///< The left-hand-side of the expression
1204  Value *RHS, ///< The right-hand-side of the expression
1205  const Twine &NameStr = "" ///< Name of the instruction
1206  ) : CmpInst(makeCmpResultType(LHS->getType()),
1207  Instruction::ICmp, pred, LHS, RHS, NameStr,
1208  InsertBefore) {
1209 #ifndef NDEBUG
1210  AssertOK();
1211 #endif
1212  }
1213 
1214  /// Constructor with insert-at-end semantics.
1216  BasicBlock &InsertAtEnd, ///< Block to insert into.
1217  Predicate pred, ///< The predicate to use for the comparison
1218  Value *LHS, ///< The left-hand-side of the expression
1219  Value *RHS, ///< The right-hand-side of the expression
1220  const Twine &NameStr = "" ///< Name of the instruction
1221  ) : CmpInst(makeCmpResultType(LHS->getType()),
1222  Instruction::ICmp, pred, LHS, RHS, NameStr,
1223  &InsertAtEnd) {
1224 #ifndef NDEBUG
1225  AssertOK();
1226 #endif
1227  }
1228 
1229  /// Constructor with no-insertion semantics
1231  Predicate pred, ///< The predicate to use for the comparison
1232  Value *LHS, ///< The left-hand-side of the expression
1233  Value *RHS, ///< The right-hand-side of the expression
1234  const Twine &NameStr = "" ///< Name of the instruction
1235  ) : CmpInst(makeCmpResultType(LHS->getType()),
1236  Instruction::ICmp, pred, LHS, RHS, NameStr) {
1237 #ifndef NDEBUG
1238  AssertOK();
1239 #endif
1240  }
1241 
1242  /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1243  /// @returns the predicate that would be the result if the operand were
1244  /// regarded as signed.
1245  /// Return the signed version of the predicate
1247  return getSignedPredicate(getPredicate());
1248  }
1249 
1250  /// This is a static version that you can use without an instruction.
1251  /// Return the signed version of the predicate.
1252  static Predicate getSignedPredicate(Predicate pred);
1253 
1254  /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1255  /// @returns the predicate that would be the result if the operand were
1256  /// regarded as unsigned.
1257  /// Return the unsigned version of the predicate
1259  return getUnsignedPredicate(getPredicate());
1260  }
1261 
1262  /// This is a static version that you can use without an instruction.
1263  /// Return the unsigned version of the predicate.
1264  static Predicate getUnsignedPredicate(Predicate pred);
1265 
1266  /// Return true if this predicate is either EQ or NE. This also
1267  /// tests for commutativity.
1268  static bool isEquality(Predicate P) {
1269  return P == ICMP_EQ || P == ICMP_NE;
1270  }
1271 
1272  /// Return true if this predicate is either EQ or NE. This also
1273  /// tests for commutativity.
1274  bool isEquality() const {
1275  return isEquality(getPredicate());
1276  }
1277 
1278  /// @returns true if the predicate of this ICmpInst is commutative
1279  /// Determine if this relation is commutative.
1280  bool isCommutative() const { return isEquality(); }
1281 
1282  /// Return true if the predicate is relational (not EQ or NE).
1283  ///
1284  bool isRelational() const {
1285  return !isEquality();
1286  }
1287 
1288  /// Return true if the predicate is relational (not EQ or NE).
1289  ///
1290  static bool isRelational(Predicate P) {
1291  return !isEquality(P);
1292  }
1293 
1294  /// Exchange the two operands to this instruction in such a way that it does
1295  /// not modify the semantics of the instruction. The predicate value may be
1296  /// changed to retain the same result if the predicate is order dependent
1297  /// (e.g. ult).
1298  /// Swap operands and adjust predicate.
1299  void swapOperands() {
1300  setPredicate(getSwappedPredicate());
1301  Op<0>().swap(Op<1>());
1302  }
1303 
1304  // Methods for support type inquiry through isa, cast, and dyn_cast:
1305  static bool classof(const Instruction *I) {
1306  return I->getOpcode() == Instruction::ICmp;
1307  }
1308  static bool classof(const Value *V) {
1309  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1310  }
1311 };
1312 
1313 //===----------------------------------------------------------------------===//
1314 // FCmpInst Class
1315 //===----------------------------------------------------------------------===//
1316 
1317 /// This instruction compares its operands according to the predicate given
1318 /// to the constructor. It only operates on floating point values or packed
1319 /// vectors of floating point values. The operands must be identical types.
1320 /// Represents a floating point comparison operator.
1321 class FCmpInst: public CmpInst {
1322  void AssertOK() {
1323  assert(isFPPredicate() && "Invalid FCmp predicate value");
1324  assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1325  "Both operands to FCmp instruction are not of the same type!");
1326  // Check that the operands are the right type
1327  assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1328  "Invalid operand types for FCmp instruction");
1329  }
1330 
1331 protected:
1332  // Note: Instruction needs to be a friend here to call cloneImpl.
1333  friend class Instruction;
1334 
1335  /// Clone an identical FCmpInst
1336  FCmpInst *cloneImpl() const;
1337 
1338 public:
1339  /// Constructor with insert-before-instruction semantics.
1341  Instruction *InsertBefore, ///< Where to insert
1342  Predicate pred, ///< The predicate to use for the comparison
1343  Value *LHS, ///< The left-hand-side of the expression
1344  Value *RHS, ///< The right-hand-side of the expression
1345  const Twine &NameStr = "" ///< Name of the instruction
1346  ) : CmpInst(makeCmpResultType(LHS->getType()),
1347  Instruction::FCmp, pred, LHS, RHS, NameStr,
1348  InsertBefore) {
1349  AssertOK();
1350  }
1351 
1352  /// Constructor with insert-at-end semantics.
1354  BasicBlock &InsertAtEnd, ///< Block to insert into.
1355  Predicate pred, ///< The predicate to use for the comparison
1356  Value *LHS, ///< The left-hand-side of the expression
1357  Value *RHS, ///< The right-hand-side of the expression
1358  const Twine &NameStr = "" ///< Name of the instruction
1359  ) : CmpInst(makeCmpResultType(LHS->getType()),
1360  Instruction::FCmp, pred, LHS, RHS, NameStr,
1361  &InsertAtEnd) {
1362  AssertOK();
1363  }
1364 
1365  /// Constructor with no-insertion semantics
1367  Predicate Pred, ///< The predicate to use for the comparison
1368  Value *LHS, ///< The left-hand-side of the expression
1369  Value *RHS, ///< The right-hand-side of the expression
1370  const Twine &NameStr = "", ///< Name of the instruction
1371  Instruction *FlagsSource = nullptr
1372  ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1373  RHS, NameStr, nullptr, FlagsSource) {
1374  AssertOK();
1375  }
1376 
1377  /// @returns true if the predicate of this instruction is EQ or NE.
1378  /// Determine if this is an equality predicate.
1379  static bool isEquality(Predicate Pred) {
1380  return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1381  Pred == FCMP_UNE;
1382  }
1383 
1384  /// @returns true if the predicate of this instruction is EQ or NE.
1385  /// Determine if this is an equality predicate.
1386  bool isEquality() const { return isEquality(getPredicate()); }
1387 
1388  /// @returns true if the predicate of this instruction is commutative.
1389  /// Determine if this is a commutative predicate.
1390  bool isCommutative() const {
1391  return isEquality() ||
1392  getPredicate() == FCMP_FALSE ||
1393  getPredicate() == FCMP_TRUE ||
1394  getPredicate() == FCMP_ORD ||
1395  getPredicate() == FCMP_UNO;
1396  }
1397 
1398  /// @returns true if the predicate is relational (not EQ or NE).
1399  /// Determine if this a relational predicate.
1400  bool isRelational() const { return !isEquality(); }
1401 
1402  /// Exchange the two operands to this instruction in such a way that it does
1403  /// not modify the semantics of the instruction. The predicate value may be
1404  /// changed to retain the same result if the predicate is order dependent
1405  /// (e.g. ult).
1406  /// Swap operands and adjust predicate.
1407  void swapOperands() {
1408  setPredicate(getSwappedPredicate());
1409  Op<0>().swap(Op<1>());
1410  }
1411 
1412  /// Methods for support type inquiry through isa, cast, and dyn_cast:
1413  static bool classof(const Instruction *I) {
1414  return I->getOpcode() == Instruction::FCmp;
1415  }
1416  static bool classof(const Value *V) {
1417  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1418  }
1419 };
1420 
1421 class CallInst;
1422 class InvokeInst;
1423 
1424 template <class T> struct CallBaseParent { using type = Instruction; };
1425 
1426 //===----------------------------------------------------------------------===//
1427 /// Base class for all callable instructions (InvokeInst and CallInst)
1428 /// Holds everything related to calling a function, abstracting from the base
1429 /// type @p BaseInstTy and the concrete instruction @p InstTy
1430 ///
1431 template <class InstTy>
1432 class CallBase : public CallBaseParent<InstTy>::type,
1433  public OperandBundleUser<InstTy, User::op_iterator> {
1434 protected:
1435  AttributeList Attrs; ///< parameter attributes for callable
1438 
1439  template <class... ArgsTy>
1440  CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
1441  : BaseInstTy(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {}
1442  bool hasDescriptor() const { return Value::HasDescriptor; }
1443 
1444  using BaseInstTy::BaseInstTy;
1445 
1446  using OperandBundleUser<InstTy,
1447  User::op_iterator>::isFnAttrDisallowedByOpBundle;
1452 
1453 public:
1456  using OperandBundleUser<InstTy,
1457  User::op_iterator>::getBundleOperandsStartIndex;
1458 
1459  static bool classof(const Instruction *I) {
1461  "CallBase is not meant to be used as part of the classof hierarchy");
1462  }
1463 
1464 public:
1465  /// Return the parameter attributes for this call.
1466  ///
1467  AttributeList getAttributes() const { return Attrs; }
1468 
1469  /// Set the parameter attributes for this call.
1470  ///
1471  void setAttributes(AttributeList A) { Attrs = A; }
1472 
1473  FunctionType *getFunctionType() const { return FTy; }
1474 
1477  this->FTy = FTy;
1478  }
1479 
1480  /// Return the number of call arguments.
1481  ///
1482  unsigned getNumArgOperands() const {
1483  return getNumOperands() - getNumTotalBundleOperands() - InstTy::ArgOffset;
1484  }
1485 
1486  /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1487  ///
1488  Value *getArgOperand(unsigned i) const {
1489  assert(i < getNumArgOperands() && "Out of bounds!");
1490  return getOperand(i);
1491  }
1492  void setArgOperand(unsigned i, Value *v) {
1493  assert(i < getNumArgOperands() && "Out of bounds!");
1494  setOperand(i, v);
1495  }
1496 
1497  /// Return the iterator pointing to the beginning of the argument list.
1499 
1500  /// Return the iterator pointing to the end of the argument list.
1502  // [ call args ], [ operand bundles ], callee
1503  return op_end() - getNumTotalBundleOperands() - InstTy::ArgOffset;
1504  }
1505 
1506  /// Iteration adapter for range-for loops.
1508  return make_range(arg_begin(), arg_end());
1509  }
1510 
1511  /// Return the iterator pointing to the beginning of the argument list.
1513 
1514  /// Return the iterator pointing to the end of the argument list.
1516  // [ call args ], [ operand bundles ], callee
1517  return op_end() - getNumTotalBundleOperands() - InstTy::ArgOffset;
1518  }
1519 
1520  /// Iteration adapter for range-for loops.
1522  return make_range(arg_begin(), arg_end());
1523  }
1524 
1525  /// Wrappers for getting the \c Use of a call argument.
1526  const Use &getArgOperandUse(unsigned i) const {
1527  assert(i < getNumArgOperands() && "Out of bounds!");
1528  return User::getOperandUse(i);
1529  }
1530  Use &getArgOperandUse(unsigned i) {
1531  assert(i < getNumArgOperands() && "Out of bounds!");
1532  return User::getOperandUse(i);
1533  }
1534 
1535  /// If one of the arguments has the 'returned' attribute, return its
1536  /// operand value. Otherwise, return nullptr.
1538  unsigned Index;
1539 
1540  if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index)
1541  return getArgOperand(Index - AttributeList::FirstArgIndex);
1542  if (const Function *F = getCalledFunction())
1543  if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) &&
1544  Index)
1545  return getArgOperand(Index - AttributeList::FirstArgIndex);
1546 
1547  return nullptr;
1548  }
1549 
1551  return OperandTraits<CallBase>::op_begin(this);
1552  }
1553 
1555  return OperandTraits<CallBase>::op_begin(const_cast<CallBase *>(this));
1556  }
1557 
1559 
1561  return OperandTraits<CallBase>::op_end(const_cast<CallBase *>(this));
1562  }
1563 
1564  Value *getOperand(unsigned i_nocapture) const {
1565  assert(i_nocapture < OperandTraits<CallBase>::operands(this) &&
1566  "getOperand() out of range!");
1567  return cast_or_null<Value>(OperandTraits<CallBase>::op_begin(
1568  const_cast<CallBase *>(this))[i_nocapture]
1569  .get());
1570  }
1571 
1572  void setOperand(unsigned i_nocapture, Value *Val_nocapture) {
1573  assert(i_nocapture < OperandTraits<CallBase>::operands(this) &&
1574  "setOperand() out of range!");
1575  OperandTraits<CallBase>::op_begin(this)[i_nocapture] = Val_nocapture;
1576  }
1577 
1578  unsigned getNumOperands() const {
1579  return OperandTraits<CallBase>::operands(this);
1580  }
1581  template <int Idx_nocapture> Use &Op() {
1582  return User::OpFrom<Idx_nocapture>(this);
1583  }
1584  template <int Idx_nocapture> const Use &Op() const {
1585  return User::OpFrom<Idx_nocapture>(this);
1586  }
1587 
1588  /// Return the function called, or null if this is an
1589  /// indirect function invocation.
1590  ///
1592  return dyn_cast_or_null<Function>(Op<-InstTy::ArgOffset>());
1593  }
1594 
1595  /// Determine whether this call has the given attribute.
1597  assert(Kind != Attribute::NoBuiltin &&
1598  "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin");
1599  return hasFnAttrImpl(Kind);
1600  }
1601 
1602  /// Determine whether this call has the given attribute.
1603  bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); }
1604 
1605  /// getCallingConv/setCallingConv - Get or set the calling convention of this
1606  /// function call.
1608  return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1609  }
1611  auto ID = static_cast<unsigned>(CC);
1612  assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1613  setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1614  (ID << 2));
1615  }
1616 
1617 
1618  /// adds the attribute to the list of attributes.
1620  AttributeList PAL = getAttributes();
1621  PAL = PAL.addAttribute(getContext(), i, Kind);
1622  setAttributes(PAL);
1623  }
1624 
1625  /// adds the attribute to the list of attributes.
1626  void addAttribute(unsigned i, Attribute Attr) {
1627  AttributeList PAL = getAttributes();
1628  PAL = PAL.addAttribute(getContext(), i, Attr);
1629  setAttributes(PAL);
1630  }
1631 
1632  /// Adds the attribute to the indicated argument
1633  void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1634  assert(ArgNo < getNumArgOperands() && "Out of bounds");
1635  AttributeList PAL = getAttributes();
1636  PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
1637  setAttributes(PAL);
1638  }
1639 
1640  /// Adds the attribute to the indicated argument
1641  void addParamAttr(unsigned ArgNo, Attribute Attr) {
1642  assert(ArgNo < getNumArgOperands() && "Out of bounds");
1643  AttributeList PAL = getAttributes();
1644  PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
1645  setAttributes(PAL);
1646  }
1647 
1648  /// removes the attribute from the list of attributes.
1650  AttributeList PAL = getAttributes();
1651  PAL = PAL.removeAttribute(getContext(), i, Kind);
1652  setAttributes(PAL);
1653  }
1654 
1655  /// removes the attribute from the list of attributes.
1656  void removeAttribute(unsigned i, StringRef Kind) {
1657  AttributeList PAL = getAttributes();
1658  PAL = PAL.removeAttribute(getContext(), i, Kind);
1659  setAttributes(PAL);
1660  }
1661 
1662  /// Removes the attribute from the given argument
1663  void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1664  assert(ArgNo < getNumArgOperands() && "Out of bounds");
1665  AttributeList PAL = getAttributes();
1666  PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1667  setAttributes(PAL);
1668  }
1669 
1670  /// Removes the attribute from the given argument
1671  void removeParamAttr(unsigned ArgNo, StringRef Kind) {
1672  assert(ArgNo < getNumArgOperands() && "Out of bounds");
1673  AttributeList PAL = getAttributes();
1674  PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
1675  setAttributes(PAL);
1676  }
1677 
1678  /// adds the dereferenceable attribute to the list of attributes.
1679  void addDereferenceableAttr(unsigned i, uint64_t Bytes) {
1680  AttributeList PAL = getAttributes();
1681  PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
1682  setAttributes(PAL);
1683  }
1684 
1685  /// adds the dereferenceable_or_null attribute to the list of
1686  /// attributes.
1687  void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
1688  AttributeList PAL = getAttributes();
1689  PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
1690  setAttributes(PAL);
1691  }
1692 
1693  /// Determine whether the return value has the given attribute.
1695  if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind))
1696  return true;
1697 
1698  // Look at the callee, if available.
1699  if (const Function *F = getCalledFunction())
1700  return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind);
1701  return false;
1702  }
1703 
1704  /// Determine whether the argument or parameter has the given attribute.
1705  bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1706  assert(ArgNo < getNumArgOperands() && "Param index out of bounds!");
1707 
1708  if (Attrs.hasParamAttribute(ArgNo, Kind))
1709  return true;
1710  if (const Function *F = getCalledFunction())
1711  return F->getAttributes().hasParamAttribute(ArgNo, Kind);
1712  return false;
1713  }
1714 
1715  /// Get the attribute of a given kind at a position.
1717  return getAttributes().getAttribute(i, Kind);
1718  }
1719 
1720  /// Get the attribute of a given kind at a position.
1721  Attribute getAttribute(unsigned i, StringRef Kind) const {
1722  return getAttributes().getAttribute(i, Kind);
1723  }
1724 
1725  /// Get the attribute of a given kind from a given arg
1727  assert(ArgNo < getNumArgOperands() && "Out of bounds");
1728  return getAttributes().getParamAttr(ArgNo, Kind);
1729  }
1730 
1731  /// Get the attribute of a given kind from a given arg
1732  Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1733  assert(ArgNo < getNumArgOperands() && "Out of bounds");
1734  return getAttributes().getParamAttr(ArgNo, Kind);
1735  }
1736  /// Return true if the data operand at index \p i has the attribute \p
1737  /// A.
1738  ///
1739  /// Data operands include call arguments and values used in operand bundles,
1740  /// but does not include the callee operand. This routine dispatches to the
1741  /// underlying AttributeList or the OperandBundleUser as appropriate.
1742  ///
1743  /// The index \p i is interpreted as
1744  ///
1745  /// \p i == Attribute::ReturnIndex -> the return value
1746  /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
1747  /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1748  /// (\p i - 1) in the operand list.
1750  // There are getNumOperands() - (InstTy::ArgOffset - 1) data operands.
1751  // The last operand is the callee.
1752  assert(i < (getNumOperands() - InstTy::ArgOffset + 1) &&
1753  "Data operand index out of bounds!");
1754 
1755  // The attribute A can either be directly specified, if the operand in
1756  // question is a call argument; or be indirectly implied by the kind of its
1757  // containing operand bundle, if the operand is a bundle operand.
1758 
1759  if (i == AttributeList::ReturnIndex)
1760  return hasRetAttr(Kind);
1761 
1762  // FIXME: Avoid these i - 1 calculations and update the API to use
1763  // zero-based indices.
1764  if (i < (getNumArgOperands() + 1))
1765  return paramHasAttr(i - 1, Kind);
1766 
1767  assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
1768  "Must be either a call argument or an operand bundle!");
1769  return bundleOperandHasAttr(i - 1, Kind);
1770  }
1771 
1772  /// Extract the alignment of the return value.
1773  unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
1774 
1775  /// Extract the alignment for a call or parameter (0=unknown).
1776  unsigned getParamAlignment(unsigned ArgNo) const {
1777  return Attrs.getParamAlignment(ArgNo);
1778  }
1779 
1780  /// Extract the number of dereferenceable bytes for a call or
1781  /// parameter (0=unknown).
1782  uint64_t getDereferenceableBytes(unsigned i) const {
1783  return Attrs.getDereferenceableBytes(i);
1784  }
1785 
1786  /// Extract the number of dereferenceable_or_null bytes for a call or
1787  /// parameter (0=unknown).
1788  uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1789  return Attrs.getDereferenceableOrNullBytes(i);
1790  }
1791 
1792  /// Determine if the return value is marked with NoAlias attribute.
1793  bool returnDoesNotAlias() const {
1795  }
1796 
1797  /// Return true if the call should not be treated as a call to a
1798  /// builtin.
1799  bool isNoBuiltin() const {
1800  return hasFnAttrImpl(Attribute::NoBuiltin) &&
1801  !hasFnAttrImpl(Attribute::Builtin);
1802  }
1803 
1804  /// Determine if the call requires strict floating point semantics.
1805  bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1806 
1807  /// Return true if the call should not be inlined.
1808  bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1809  void setIsNoInline() {
1810  addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1811  }
1812  /// Determine if the call does not access memory.
1813  bool doesNotAccessMemory() const {
1814  return hasFnAttr(Attribute::ReadNone);
1815  }
1817  addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1818  }
1819 
1820  /// Determine if the call does not access or only reads memory.
1821  bool onlyReadsMemory() const {
1822  return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1823  }
1825  addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1826  }
1827 
1828  /// Determine if the call does not access or only writes memory.
1829  bool doesNotReadMemory() const {
1830  return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1831  }
1833  addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1834  }
1835 
1836  /// Determine if the call can access memmory only using pointers based
1837  /// on its arguments.
1838  bool onlyAccessesArgMemory() const {
1839  return hasFnAttr(Attribute::ArgMemOnly);
1840  }
1842  addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1843  }
1844 
1845  /// Determine if the function may only access memory that is
1846  /// inaccessible from the IR.
1848  return hasFnAttr(Attribute::InaccessibleMemOnly);
1849  }
1851  addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
1852  }
1853 
1854  /// Determine if the function may only access memory that is
1855  /// either inaccessible from the IR or pointed to by its arguments.
1857  return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
1858  }
1860  addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOrArgMemOnly);
1861  }
1862  /// Determine if the call cannot return.
1863  bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1865  addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1866  }
1867 
1868  /// Determine if the call should not perform indirect branch tracking.
1869  bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
1870 
1871  /// Determine if the call cannot unwind.
1872  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1874  addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1875  }
1876 
1877  /// Determine if the invoke cannot be duplicated.
1878  bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1880  addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1881  }
1882 
1883  /// Determine if the invoke is convergent
1884  bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1885  void setConvergent() {
1887  }
1890  }
1891 
1892  /// Determine if the call returns a structure through first
1893  /// pointer argument.
1894  bool hasStructRetAttr() const {
1895  if (getNumArgOperands() == 0)
1896  return false;
1897 
1898  // Be friendly and also check the callee.
1899  return paramHasAttr(0, Attribute::StructRet);
1900  }
1901 
1902  /// Determine if any call argument is an aggregate passed by value.
1903  bool hasByValArgument() const {
1904  return Attrs.hasAttrSomewhere(Attribute::ByVal);
1905  }
1906  /// Get a pointer to the function that is invoked by this
1907  /// instruction.
1908  const Value *getCalledValue() const { return Op<-InstTy::ArgOffset>(); }
1909  Value *getCalledValue() { return Op<-InstTy::ArgOffset>(); }
1910 
1911  /// Set the function called.
1913  setCalledFunction(
1914  cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1915  Fn);
1916  }
1918  this->FTy = FTy;
1919  assert(FTy == cast<FunctionType>(
1920  cast<PointerType>(Fn->getType())->getElementType()));
1921  Op<-InstTy::ArgOffset>() = Fn;
1922  }
1923 
1924 protected:
1925  template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
1926  if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
1927  return true;
1928 
1929  // Operand bundles override attributes on the called function, but don't
1930  // override attributes directly present on the call instruction.
1931  if (isFnAttrDisallowedByOpBundle(Kind))
1932  return false;
1933 
1934  if (const Function *F = getCalledFunction())
1935  return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
1936  Kind);
1937  return false;
1938  }
1939 };
1940 
1941 //===----------------------------------------------------------------------===//
1942 /// This class represents a function call, abstracting a target
1943 /// machine's calling convention. This class uses low bit of the SubClassData
1944 /// field to indicate whether or not this is a tail call. The rest of the bits
1945 /// hold the calling convention of the call.
1946 ///
1947 class CallInst : public CallBase<CallInst> {
1949 
1950  CallInst(const CallInst &CI);
1951 
1952  /// Construct a CallInst given a range of arguments.
1953  /// Construct a CallInst from a range of arguments
1954  inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1955  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1956  Instruction *InsertBefore);
1957 
1958  inline CallInst(Value *Func, ArrayRef<Value *> Args,
1959  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1960  Instruction *InsertBefore)
1961  : CallInst(cast<FunctionType>(
1962  cast<PointerType>(Func->getType())->getElementType()),
1963  Func, Args, Bundles, NameStr, InsertBefore) {}
1964 
1965  inline CallInst(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr,
1966  Instruction *InsertBefore)
1967  : CallInst(Func, Args, None, NameStr, InsertBefore) {}
1968 
1969  /// Construct a CallInst given a range of arguments.
1970  /// Construct a CallInst from a range of arguments
1971  inline CallInst(Value *Func, ArrayRef<Value *> Args,
1972  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1973  BasicBlock *InsertAtEnd);
1974 
1975  explicit CallInst(Value *F, const Twine &NameStr, Instruction *InsertBefore);
1976 
1977  CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1978 
1979  void init(Value *Func, ArrayRef<Value *> Args,
1980  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
1981  init(cast<FunctionType>(
1982  cast<PointerType>(Func->getType())->getElementType()),
1983  Func, Args, Bundles, NameStr);
1984  }
1985  void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1986  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1987  void init(Value *Func, const Twine &NameStr);
1988 
1989 protected:
1990  // Note: Instruction needs to be a friend here to call cloneImpl.
1991  friend class Instruction;
1992 
1993  CallInst *cloneImpl() const;
1994 
1995 public:
1996  static constexpr int ArgOffset = 1;
1997 
1998  static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1999  ArrayRef<OperandBundleDef> Bundles = None,
2000  const Twine &NameStr = "",
2001  Instruction *InsertBefore = nullptr) {
2002  return Create(cast<FunctionType>(
2003  cast<PointerType>(Func->getType())->getElementType()),
2004  Func, Args, Bundles, NameStr, InsertBefore);
2005  }
2006 
2007  static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
2008  const Twine &NameStr,
2009  Instruction *InsertBefore = nullptr) {
2010  return Create(cast<FunctionType>(
2011  cast<PointerType>(Func->getType())->getElementType()),
2012  Func, Args, None, NameStr, InsertBefore);
2013  }
2014 
2015  static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
2016  const Twine &NameStr,
2017  Instruction *InsertBefore = nullptr) {
2018  return new (unsigned(Args.size() + 1))
2019  CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
2020  }
2021 
2022  static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
2023  ArrayRef<OperandBundleDef> Bundles = None,
2024  const Twine &NameStr = "",
2025  Instruction *InsertBefore = nullptr) {
2026  const unsigned TotalOps =
2027  unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
2028  const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
2029 
2030  return new (TotalOps, DescriptorBytes)
2031  CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
2032  }
2033 
2034  static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
2036  const Twine &NameStr, BasicBlock *InsertAtEnd) {
2037  const unsigned TotalOps =
2038  unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
2039  const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
2040 
2041  return new (TotalOps, DescriptorBytes)
2042  CallInst(Func, Args, Bundles, NameStr, InsertAtEnd);
2043  }
2044 
2045  static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
2046  const Twine &NameStr, BasicBlock *InsertAtEnd) {
2047  return new (unsigned(Args.size() + 1))
2048  CallInst(Func, Args, None, NameStr, InsertAtEnd);
2049  }
2050 
2051  static CallInst *Create(Value *F, const Twine &NameStr = "",
2052  Instruction *InsertBefore = nullptr) {
2053  return new (1) CallInst(F, NameStr, InsertBefore);
2054  }
2055 
2056  static CallInst *Create(Value *F, const Twine &NameStr,
2057  BasicBlock *InsertAtEnd) {
2058  return new (1) CallInst(F, NameStr, InsertAtEnd);
2059  }
2060 
2061  /// Create a clone of \p CI with a different set of operand bundles and
2062  /// insert it before \p InsertPt.
2063  ///
2064  /// The returned call instruction is identical \p CI in every way except that
2065  /// the operand bundles for the new instruction are set to the operand bundles
2066  /// in \p Bundles.
2067  static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
2068  Instruction *InsertPt = nullptr);
2069 
2070  /// Generate the IR for a call to malloc:
2071  /// 1. Compute the malloc call's argument as the specified type's size,
2072  /// possibly multiplied by the array size if the array size is not
2073  /// constant 1.
2074  /// 2. Call malloc with that argument.
2075  /// 3. Bitcast the result of the malloc call to the specified type.
2076  static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
2077  Type *AllocTy, Value *AllocSize,
2078  Value *ArraySize = nullptr,
2079  Function *MallocF = nullptr,
2080  const Twine &Name = "");
2081  static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
2082  Type *AllocTy, Value *AllocSize,
2083  Value *ArraySize = nullptr,
2084  Function *MallocF = nullptr,
2085  const Twine &Name = "");
2086  static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
2087  Type *AllocTy, Value *AllocSize,
2088  Value *ArraySize = nullptr,
2089  ArrayRef<OperandBundleDef> Bundles = None,
2090  Function *MallocF = nullptr,
2091  const Twine &Name = "");
2092  static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
2093  Type *AllocTy, Value *AllocSize,
2094  Value *ArraySize = nullptr,
2095  ArrayRef<OperandBundleDef> Bundles = None,
2096  Function *MallocF = nullptr,
2097  const Twine &Name = "");
2098  /// Generate the IR for a call to the builtin free function.
2099  static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
2100  static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
2101  static Instruction *CreateFree(Value *Source,
2103  Instruction *InsertBefore);
2104  static Instruction *CreateFree(Value *Source,
2106  BasicBlock *InsertAtEnd);
2107 
2108  // Note that 'musttail' implies 'tail'.
2110  TCK_None = 0,
2111  TCK_Tail = 1,
2112  TCK_MustTail = 2,
2113  TCK_NoTail = 3
2114  };
2117  }
2118 
2119  bool isTailCall() const {
2120  unsigned Kind = getSubclassDataFromInstruction() & 3;
2121  return Kind == TCK_Tail || Kind == TCK_MustTail;
2122  }
2123 
2124  bool isMustTailCall() const {
2125  return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
2126  }
2127 
2128  bool isNoTailCall() const {
2129  return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
2130  }
2131 
2132  void setTailCall(bool isTC = true) {
2133  setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
2134  unsigned(isTC ? TCK_Tail : TCK_None));
2135  }
2136 
2138  setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
2139  unsigned(TCK));
2140  }
2141 
2142  /// Return true if the call can return twice
2143  bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
2145  addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
2146  }
2147 
2148  /// Check if this call is an inline asm statement.
2149  bool isInlineAsm() const { return isa<InlineAsm>(Op<-1>()); }
2150 
2151  // Methods for support type inquiry through isa, cast, and dyn_cast:
2152  static bool classof(const Instruction *I) {
2153  return I->getOpcode() == Instruction::Call;
2154  }
2155  static bool classof(const Value *V) {
2156  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2157  }
2158 
2159 private:
2160  // Shadow Instruction::setInstructionSubclassData with a private forwarding
2161  // method so that subclasses cannot accidentally use it.
2162  void setInstructionSubclassData(unsigned short D) {
2164  }
2165 };
2166 
2167 template <>
2169  : public VariadicOperandTraits<CallBase<CallInst>, 1> {};
2170 
2171 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
2172  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
2173  BasicBlock *InsertAtEnd)
2175  cast<FunctionType>(
2176  cast<PointerType>(Func->getType())->getElementType())
2177  ->getReturnType(),
2180  (Args.size() + CountBundleInputs(Bundles) + 1),
2181  unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
2182  init(Func, Args, Bundles, NameStr);
2183 }
2184 
2185 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
2186  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
2187  Instruction *InsertBefore)
2190  (Args.size() + CountBundleInputs(Bundles) + 1),
2191  unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
2192  InsertBefore) {
2193  init(Ty, Func, Args, Bundles, NameStr);
2194 }
2195 
2196 //===----------------------------------------------------------------------===//
2197 // SelectInst Class
2198 //===----------------------------------------------------------------------===//
2199 
2200 /// This class represents the LLVM 'select' instruction.
2201 ///
2202 class SelectInst : public Instruction {
2203  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
2204  Instruction *InsertBefore)
2206  &Op<0>(), 3, InsertBefore) {
2207  init(C, S1, S2);
2208  setName(NameStr);
2209  }
2210 
2211  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
2212  BasicBlock *InsertAtEnd)
2214  &Op<0>(), 3, InsertAtEnd) {
2215  init(C, S1, S2);
2216  setName(NameStr);
2217  }
2218 
2219  void init(Value *C, Value *S1, Value *S2) {
2220  assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
2221  Op<0>() = C;
2222  Op<1>() = S1;
2223  Op<2>() = S2;
2224  }
2225 
2226 protected:
2227  // Note: Instruction needs to be a friend here to call cloneImpl.
2228  friend class Instruction;
2229 
2230  SelectInst *cloneImpl() const;
2231 
2232 public:
2233  static SelectInst *Create(Value *C, Value *S1, Value *S2,
2234  const Twine &NameStr = "",
2235  Instruction *InsertBefore = nullptr,
2236  Instruction *MDFrom = nullptr) {
2237  SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
2238  if (MDFrom)
2239  Sel->copyMetadata(*MDFrom);
2240  return Sel;
2241  }
2242 
2243  static SelectInst *Create(Value *C, Value *S1, Value *S2,
2244  const Twine &NameStr,
2245  BasicBlock *InsertAtEnd) {
2246  return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
2247  }
2248 
2249  const Value *getCondition() const { return Op<0>(); }
2250  const Value *getTrueValue() const { return Op<1>(); }
2251  const Value *getFalseValue() const { return Op<2>(); }
2252  Value *getCondition() { return Op<0>(); }
2253  Value *getTrueValue() { return Op<1>(); }
2254  Value *getFalseValue() { return Op<2>(); }
2255 
2256  void setCondition(Value *V) { Op<0>() = V; }
2257  void setTrueValue(Value *V) { Op<1>() = V; }
2258  void setFalseValue(Value *V) { Op<2>() = V; }
2259 
2260  /// Return a string if the specified operands are invalid
2261  /// for a select operation, otherwise return null.
2262  static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
2263 
2264  /// Transparently provide more efficient getOperand methods.
2266 
2268  return static_cast<OtherOps>(Instruction::getOpcode());
2269  }
2270 
2271  // Methods for support type inquiry through isa, cast, and dyn_cast:
2272  static bool classof(const Instruction *I) {
2273  return I->getOpcode() == Instruction::Select;
2274  }
2275  static bool classof(const Value *V) {
2276  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2277  }
2278 };
2279 
2280 template <>
2281 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
2282 };
2283 
2285 
2286 //===----------------------------------------------------------------------===//
2287 // VAArgInst Class
2288 //===----------------------------------------------------------------------===//
2289 
2290 /// This class represents the va_arg llvm instruction, which returns
2291 /// an argument of the specified type given a va_list and increments that list
2292 ///
2293 class VAArgInst : public UnaryInstruction {
2294 protected:
2295  // Note: Instruction needs to be a friend here to call cloneImpl.
2296  friend class Instruction;
2297 
2298  VAArgInst *cloneImpl() const;
2299 
2300 public:
2301  VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
2302  Instruction *InsertBefore = nullptr)
2303  : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
2304  setName(NameStr);
2305  }
2306 
2307  VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
2308  BasicBlock *InsertAtEnd)
2309  : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
2310  setName(NameStr);
2311  }
2312 
2314  const Value *getPointerOperand() const { return getOperand(0); }
2315  static unsigned getPointerOperandIndex() { return 0U; }
2316 
2317  // Methods for support type inquiry through isa, cast, and dyn_cast:
2318  static bool classof(const Instruction *I) {
2319  return I->getOpcode() == VAArg;
2320  }
2321  static bool classof(const Value *V) {
2322  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2323  }
2324 };
2325 
2326 //===----------------------------------------------------------------------===//
2327 // ExtractElementInst Class
2328 //===----------------------------------------------------------------------===//
2329 
2330 /// This instruction extracts a single (scalar)
2331 /// element from a VectorType value
2332 ///
2334  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
2335  Instruction *InsertBefore = nullptr);
2336  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
2337  BasicBlock *InsertAtEnd);
2338 
2339 protected:
2340  // Note: Instruction needs to be a friend here to call cloneImpl.
2341  friend class Instruction;
2342 
2343  ExtractElementInst *cloneImpl() const;
2344 
2345 public:
2346  static ExtractElementInst *Create(Value *Vec, Value *Idx,
2347  const Twine &NameStr = "",
2348  Instruction *InsertBefore = nullptr) {
2349  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
2350  }
2351 
2352  static ExtractElementInst *Create(Value *Vec, Value *Idx,
2353  const Twine &NameStr,
2354  BasicBlock *InsertAtEnd) {
2355  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
2356  }
2357 
2358  /// Return true if an extractelement instruction can be
2359  /// formed with the specified operands.
2360  static bool isValidOperands(const Value *Vec, const Value *Idx);
2361 
2362  Value *getVectorOperand() { return Op<0>(); }
2363  Value *getIndexOperand() { return Op<1>(); }
2364  const Value *getVectorOperand() const { return Op<0>(); }
2365  const Value *getIndexOperand() const { return Op<1>(); }
2366 
2368  return cast<VectorType>(getVectorOperand()->getType());
2369  }
2370 
2371  /// Transparently provide more efficient getOperand methods.
2373 
2374  // Methods for support type inquiry through isa, cast, and dyn_cast:
2375  static bool classof(const Instruction *I) {
2376  return I->getOpcode() == Instruction::ExtractElement;
2377  }
2378  static bool classof(const Value *V) {
2379  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2380  }
2381 };
2382 
2383 template <>
2385  public FixedNumOperandTraits<ExtractElementInst, 2> {
2386 };
2387 
2388 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
2389 
2390 //===----------------------------------------------------------------------===//
2391 // InsertElementInst Class
2392 //===----------------------------------------------------------------------===//
2393 
2394 /// This instruction inserts a single (scalar)
2395 /// element into a VectorType value
2396 ///
2398  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2399  const Twine &NameStr = "",
2400  Instruction *InsertBefore = nullptr);
2401  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2402  BasicBlock *InsertAtEnd);
2403 
2404 protected:
2405  // Note: Instruction needs to be a friend here to call cloneImpl.
2406  friend class Instruction;
2407 
2408  InsertElementInst *cloneImpl() const;
2409 
2410 public:
2411  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2412  const Twine &NameStr = "",
2413  Instruction *InsertBefore = nullptr) {
2414  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2415  }
2416 
2417  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2418  const Twine &NameStr,
2419  BasicBlock *InsertAtEnd) {
2420  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2421  }
2422 
2423  /// Return true if an insertelement instruction can be
2424  /// formed with the specified operands.
2425  static bool isValidOperands(const Value *Vec, const Value *NewElt,
2426  const Value *Idx);
2427 
2428  /// Overload to return most specific vector type.
2429  ///
2430  VectorType *getType() const {
2431  return cast<VectorType>(Instruction::getType());
2432  }
2433 
2434  /// Transparently provide more efficient getOperand methods.
2436 
2437  // Methods for support type inquiry through isa, cast, and dyn_cast:
2438  static bool classof(const Instruction *I) {
2439  return I->getOpcode() == Instruction::InsertElement;
2440  }
2441  static bool classof(const Value *V) {
2442  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2443  }
2444 };
2445 
2446 template <>
2448  public FixedNumOperandTraits<InsertElementInst, 3> {
2449 };
2450 
2451 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2452 
2453 //===----------------------------------------------------------------------===//
2454 // ShuffleVectorInst Class
2455 //===----------------------------------------------------------------------===//
2456 
2457 /// This instruction constructs a fixed permutation of two
2458 /// input vectors.
2459 ///
2461 protected:
2462  // Note: Instruction needs to be a friend here to call cloneImpl.
2463  friend class Instruction;
2464 
2465  ShuffleVectorInst *cloneImpl() const;
2466 
2467 public:
2469  const Twine &NameStr = "",
2470  Instruction *InsertBefor = nullptr);
2472  const Twine &NameStr, BasicBlock *InsertAtEnd);
2473 
2474  // allocate space for exactly three operands
2475  void *operator new(size_t s) {
2476  return User::operator new(s, 3);
2477  }
2478 
2479  /// Return true if a shufflevector instruction can be
2480  /// formed with the specified operands.
2481  static bool isValidOperands(const Value *V1, const Value *V2,
2482  const Value *Mask);
2483 
2484  /// Overload to return most specific vector type.
2485  ///
2486  VectorType *getType() const {
2487  return cast<VectorType>(Instruction::getType());
2488  }
2489 
2490  /// Transparently provide more efficient getOperand methods.
2492 
2493  Constant *getMask() const {
2494  return cast<Constant>(getOperand(2));
2495  }
2496 
2497  /// Return the shuffle mask value for the specified element of the mask.
2498  /// Return -1 if the element is undef.
2499  static int getMaskValue(const Constant *Mask, unsigned Elt);
2500 
2501  /// Return the shuffle mask value of this instruction for the given element
2502  /// index. Return -1 if the element is undef.
2503  int getMaskValue(unsigned Elt) const {
2504  return getMaskValue(getMask(), Elt);
2505  }
2506 
2507  /// Convert the input shuffle mask operand to a vector of integers. Undefined
2508  /// elements of the mask are returned as -1.
2509  static void getShuffleMask(const Constant *Mask,
2510  SmallVectorImpl<int> &Result);
2511 
2512  /// Return the mask for this instruction as a vector of integers. Undefined
2513  /// elements of the mask are returned as -1.
2514  void getShuffleMask(SmallVectorImpl<int> &Result) const {
2515  return getShuffleMask(getMask(), Result);
2516  }
2517 
2520  getShuffleMask(Mask);
2521  return Mask;
2522  }
2523 
2524  /// Return true if this shuffle returns a vector with a different number of
2525  /// elements than its source vectors.
2526  /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2527  /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2528  bool changesLength() const {
2529  unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2530  unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2531  return NumSourceElts != NumMaskElts;
2532  }
2533 
2534  /// Return true if this shuffle returns a vector with a greater number of
2535  /// elements than its source vectors.
2536  /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2537  bool increasesLength() const {
2538  unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2539  unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2540  return NumSourceElts < NumMaskElts;
2541  }
2542 
2543  /// Return true if this shuffle mask chooses elements from exactly one source
2544  /// vector.
2545  /// Example: <7,5,undef,7>
2546  /// This assumes that vector operands are the same length as the mask.
2547  static bool isSingleSourceMask(ArrayRef<int> Mask);
2548  static bool isSingleSourceMask(const Constant *Mask) {
2549  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2550  SmallVector<int, 16> MaskAsInts;
2551  getShuffleMask(Mask, MaskAsInts);
2552  return isSingleSourceMask(MaskAsInts);
2553  }
2554 
2555  /// Return true if this shuffle chooses elements from exactly one source
2556  /// vector without changing the length of that vector.
2557  /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2558  /// TODO: Optionally allow length-changing shuffles.
2559  bool isSingleSource() const {
2560  return !changesLength() && isSingleSourceMask(getMask());
2561  }
2562 
2563  /// Return true if this shuffle mask chooses elements from exactly one source
2564  /// vector without lane crossings. A shuffle using this mask is not
2565  /// necessarily a no-op because it may change the number of elements from its
2566  /// input vectors or it may provide demanded bits knowledge via undef lanes.
2567  /// Example: <undef,undef,2,3>
2568  static bool isIdentityMask(ArrayRef<int> Mask);
2569  static bool isIdentityMask(const Constant *Mask) {
2570  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2571  SmallVector<int, 16> MaskAsInts;
2572  getShuffleMask(Mask, MaskAsInts);
2573  return isIdentityMask(MaskAsInts);
2574  }
2575 
2576  /// Return true if this shuffle chooses elements from exactly one source
2577  /// vector without lane crossings and does not change the number of elements
2578  /// from its input vectors.
2579  /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2580  bool isIdentity() const {
2581  return !changesLength() && isIdentityMask(getShuffleMask());
2582  }
2583 
2584  /// Return true if this shuffle lengthens exactly one source vector with
2585  /// undefs in the high elements.
2586  bool isIdentityWithPadding() const;
2587 
2588  /// Return true if this shuffle extracts the first N elements of exactly one
2589  /// source vector.
2590  bool isIdentityWithExtract() const;
2591 
2592  /// Return true if this shuffle concatenates its 2 source vectors. This
2593  /// returns false if either input is undefined. In that case, the shuffle is
2594  /// is better classified as an identity with padding operation.
2595  bool isConcat() const;
2596 
2597  /// Return true if this shuffle mask chooses elements from its source vectors
2598  /// without lane crossings. A shuffle using this mask would be
2599  /// equivalent to a vector select with a constant condition operand.
2600  /// Example: <4,1,6,undef>
2601  /// This returns false if the mask does not choose from both input vectors.
2602  /// In that case, the shuffle is better classified as an identity shuffle.
2603  /// This assumes that vector operands are the same length as the mask
2604  /// (a length-changing shuffle can never be equivalent to a vector select).
2605  static bool isSelectMask(ArrayRef<int> Mask);
2606  static bool isSelectMask(const Constant *Mask) {
2607  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2608  SmallVector<int, 16> MaskAsInts;
2609  getShuffleMask(Mask, MaskAsInts);
2610  return isSelectMask(MaskAsInts);
2611  }
2612 
2613  /// Return true if this shuffle chooses elements from its source vectors
2614  /// without lane crossings and all operands have the same number of elements.
2615  /// In other words, this shuffle is equivalent to a vector select with a
2616  /// constant condition operand.
2617  /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2618  /// This returns false if the mask does not choose from both input vectors.
2619  /// In that case, the shuffle is better classified as an identity shuffle.
2620  /// TODO: Optionally allow length-changing shuffles.
2621  bool isSelect() const {
2622  return !changesLength() && isSelectMask(getMask());
2623  }
2624 
2625  /// Return true if this shuffle mask swaps the order of elements from exactly
2626  /// one source vector.
2627  /// Example: <7,6,undef,4>
2628  /// This assumes that vector operands are the same length as the mask.
2629  static bool isReverseMask(ArrayRef<int> Mask);
2630  static bool isReverseMask(const Constant *Mask) {
2631  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2632  SmallVector<int, 16> MaskAsInts;
2633  getShuffleMask(Mask, MaskAsInts);
2634  return isReverseMask(MaskAsInts);
2635  }
2636 
2637  /// Return true if this shuffle swaps the order of elements from exactly
2638  /// one source vector.
2639  /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2640  /// TODO: Optionally allow length-changing shuffles.
2641  bool isReverse() const {
2642  return !changesLength() && isReverseMask(getMask());
2643  }
2644 
2645  /// Return true if this shuffle mask chooses all elements with the same value
2646  /// as the first element of exactly one source vector.
2647  /// Example: <4,undef,undef,4>
2648  /// This assumes that vector operands are the same length as the mask.
2649  static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2650  static bool isZeroEltSplatMask(const Constant *Mask) {
2651  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2652  SmallVector<int, 16> MaskAsInts;
2653  getShuffleMask(Mask, MaskAsInts);
2654  return isZeroEltSplatMask(MaskAsInts);
2655  }
2656 
2657  /// Return true if all elements of this shuffle are the same value as the
2658  /// first element of exactly one source vector without changing the length
2659  /// of that vector.
2660  /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2661  /// TODO: Optionally allow length-changing shuffles.
2662  /// TODO: Optionally allow splats from other elements.
2663  bool isZeroEltSplat() const {
2664  return !changesLength() && isZeroEltSplatMask(getMask());
2665  }
2666 
2667  /// Return true if this shuffle mask is a transpose mask.
2668  /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2669  /// even- or odd-numbered vector elements from two n-dimensional source
2670  /// vectors and write each result into consecutive elements of an
2671  /// n-dimensional destination vector. Two shuffles are necessary to complete
2672  /// the transpose, one for the even elements and another for the odd elements.
2673  /// This description closely follows how the TRN1 and TRN2 AArch64
2674  /// instructions operate.
2675  ///
2676  /// For example, a simple 2x2 matrix can be transposed with:
2677  ///
2678  /// ; Original matrix
2679  /// m0 = < a, b >
2680  /// m1 = < c, d >
2681  ///
2682  /// ; Transposed matrix
2683  /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2684  /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2685  ///
2686  /// For matrices having greater than n columns, the resulting nx2 transposed
2687  /// matrix is stored in two result vectors such that one vector contains
2688  /// interleaved elements from all the even-numbered rows and the other vector
2689  /// contains interleaved elements from all the odd-numbered rows. For example,
2690  /// a 2x4 matrix can be transposed with:
2691  ///
2692  /// ; Original matrix
2693  /// m0 = < a, b, c, d >
2694  /// m1 = < e, f, g, h >
2695  ///
2696  /// ; Transposed matrix
2697  /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2698  /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2699  static bool isTransposeMask(ArrayRef<int> Mask);
2700  static bool isTransposeMask(const Constant *Mask) {
2701  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2702  SmallVector<int, 16> MaskAsInts;
2703  getShuffleMask(Mask, MaskAsInts);
2704  return isTransposeMask(MaskAsInts);
2705  }
2706 
2707  /// Return true if this shuffle transposes the elements of its inputs without
2708  /// changing the length of the vectors. This operation may also be known as a
2709  /// merge or interleave. See the description for isTransposeMask() for the
2710  /// exact specification.
2711  /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2712  bool isTranspose() const {
2713  return !changesLength() && isTransposeMask(getMask());
2714  }
2715 
2716  /// Return true if this shuffle mask is an extract subvector mask.
2717  /// A valid extract subvector mask returns a smaller vector from a single
2718  /// source operand. The base extraction index is returned as well.
2719  static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2720  int &Index);
2721  static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2722  int &Index) {
2723  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2724  SmallVector<int, 16> MaskAsInts;
2725  getShuffleMask(Mask, MaskAsInts);
2726  return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2727  }
2728 
2729  /// Return true if this shuffle mask is an extract subvector mask.
2730  bool isExtractSubvectorMask(int &Index) const {
2731  int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2732  return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2733  }
2734 
2735  /// Change values in a shuffle permute mask assuming the two vector operands
2736  /// of length InVecNumElts have swapped position.
2738  unsigned InVecNumElts) {
2739  for (int &Idx : Mask) {
2740  if (Idx == -1)
2741  continue;
2742  Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2743  assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2744  "shufflevector mask index out of range");
2745  }
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::ShuffleVector;
2751  }
2752  static bool classof(const Value *V) {
2753  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2754  }
2755 };
2756 
2757 template <>
2759  public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2760 };
2761 
2762 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2763 
2764 //===----------------------------------------------------------------------===//
2765 // ExtractValueInst Class
2766 //===----------------------------------------------------------------------===//
2767 
2768 /// This instruction extracts a struct member or array
2769 /// element value from an aggregate value.
2770 ///
2772  SmallVector<unsigned, 4> Indices;
2773 
2774  ExtractValueInst(const ExtractValueInst &EVI);
2775 
2776  /// Constructors - Create a extractvalue instruction with a base aggregate
2777  /// value and a list of indices. The first ctor can optionally insert before
2778  /// an existing instruction, the second appends the new instruction to the
2779  /// specified BasicBlock.
2780  inline ExtractValueInst(Value *Agg,
2781  ArrayRef<unsigned> Idxs,
2782  const Twine &NameStr,
2783  Instruction *InsertBefore);
2784  inline ExtractValueInst(Value *Agg,
2785  ArrayRef<unsigned> Idxs,
2786  const Twine &NameStr, BasicBlock *InsertAtEnd);
2787 
2788  void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2789 
2790 protected:
2791  // Note: Instruction needs to be a friend here to call cloneImpl.
2792  friend class Instruction;
2793 
2794  ExtractValueInst *cloneImpl() const;
2795 
2796 public:
2798  ArrayRef<unsigned> Idxs,
2799  const Twine &NameStr = "",
2800  Instruction *InsertBefore = nullptr) {
2801  return new
2802  ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2803  }
2804 
2806  ArrayRef<unsigned> Idxs,
2807  const Twine &NameStr,
2808  BasicBlock *InsertAtEnd) {
2809  return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2810  }
2811 
2812  /// Returns the type of the element that would be extracted
2813  /// with an extractvalue instruction with the specified parameters.
2814  ///
2815  /// Null is returned if the indices are invalid for the specified type.
2816  static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2817 
2818  using idx_iterator = const unsigned*;
2819 
2820  inline idx_iterator idx_begin() const { return Indices.begin(); }
2821  inline idx_iterator idx_end() const { return Indices.end(); }
2823  return make_range(idx_begin(), idx_end());
2824  }
2825 
2827  return getOperand(0);
2828  }
2829  const Value *getAggregateOperand() const {
2830  return getOperand(0);
2831  }
2832  static unsigned getAggregateOperandIndex() {
2833  return 0U; // get index for modifying correct operand
2834  }
2835 
2837  return Indices;
2838  }
2839 
2840  unsigned getNumIndices() const {
2841  return (unsigned)Indices.size();
2842  }
2843 
2844  bool hasIndices() const {
2845  return true;
2846  }
2847 
2848  // Methods for support type inquiry through isa, cast, and dyn_cast:
2849  static bool classof(const Instruction *I) {
2850  return I->getOpcode() == Instruction::ExtractValue;
2851  }
2852  static bool classof(const Value *V) {
2853  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2854  }
2855 };
2856 
2857 ExtractValueInst::ExtractValueInst(Value *Agg,
2858  ArrayRef<unsigned> Idxs,
2859  const Twine &NameStr,
2860  Instruction *InsertBefore)
2861  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2862  ExtractValue, Agg, InsertBefore) {
2863  init(Idxs, NameStr);
2864 }
2865 
2866 ExtractValueInst::ExtractValueInst(Value *Agg,
2867  ArrayRef<unsigned> Idxs,
2868  const Twine &NameStr,
2869  BasicBlock *InsertAtEnd)
2870  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2871  ExtractValue, Agg, InsertAtEnd) {
2872  init(Idxs, NameStr);
2873 }
2874 
2875 //===----------------------------------------------------------------------===//
2876 // InsertValueInst Class
2877 //===----------------------------------------------------------------------===//
2878 
2879 /// This instruction inserts a struct field of array element
2880 /// value into an aggregate value.
2881 ///
2883  SmallVector<unsigned, 4> Indices;
2884 
2885  InsertValueInst(const InsertValueInst &IVI);
2886 
2887  /// Constructors - Create a insertvalue instruction with a base aggregate
2888  /// value, a value to insert, and a list of indices. The first ctor can
2889  /// optionally insert before an existing instruction, the second appends
2890  /// the new instruction to the specified BasicBlock.
2891  inline InsertValueInst(Value *Agg, Value *Val,
2892  ArrayRef<unsigned> Idxs,
2893  const Twine &NameStr,
2894  Instruction *InsertBefore);
2895  inline InsertValueInst(Value *Agg, Value *Val,
2896  ArrayRef<unsigned> Idxs,
2897  const Twine &NameStr, BasicBlock *InsertAtEnd);
2898 
2899  /// Constructors - These two constructors are convenience methods because one
2900  /// and two index insertvalue instructions are so common.
2901  InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2902  const Twine &NameStr = "",
2903  Instruction *InsertBefore = nullptr);
2904  InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2905  BasicBlock *InsertAtEnd);
2906 
2907  void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2908  const Twine &NameStr);
2909 
2910 protected:
2911  // Note: Instruction needs to be a friend here to call cloneImpl.
2912  friend class Instruction;
2913 
2914  InsertValueInst *cloneImpl() const;
2915 
2916 public:
2917  // allocate space for exactly two operands
2918  void *operator new(size_t s) {
2919  return User::operator new(s, 2);
2920  }
2921 
2922  static InsertValueInst *Create(Value *Agg, Value *Val,
2923  ArrayRef<unsigned> Idxs,
2924  const Twine &NameStr = "",
2925  Instruction *InsertBefore = nullptr) {
2926  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2927  }
2928 
2929  static InsertValueInst *Create(Value *Agg, Value *Val,
2930  ArrayRef<unsigned> Idxs,
2931  const Twine &NameStr,
2932  BasicBlock *InsertAtEnd) {
2933  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2934  }
2935 
2936  /// Transparently provide more efficient getOperand methods.
2938 
2939  using idx_iterator = const unsigned*;
2940 
2941  inline idx_iterator idx_begin() const { return Indices.begin(); }
2942  inline idx_iterator idx_end() const { return Indices.end(); }
2944  return make_range(idx_begin(), idx_end());
2945  }
2946 
2948  return getOperand(0);
2949  }
2950  const Value *getAggregateOperand() const {
2951  return getOperand(0);
2952  }
2953  static unsigned getAggregateOperandIndex() {
2954  return 0U; // get index for modifying correct operand
2955  }
2956 
2958  return getOperand(1);
2959  }
2961  return getOperand(1);
2962  }
2963  static unsigned getInsertedValueOperandIndex() {
2964  return 1U; // get index for modifying correct operand
2965  }
2966 
2968  return Indices;
2969  }
2970 
2971  unsigned getNumIndices() const {
2972  return (unsigned)Indices.size();
2973  }
2974 
2975  bool hasIndices() const {
2976  return true;
2977  }
2978 
2979  // Methods for support type inquiry through isa, cast, and dyn_cast:
2980  static bool classof(const Instruction *I) {
2981  return I->getOpcode() == Instruction::InsertValue;
2982  }
2983  static bool classof(const Value *V) {
2984  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2985  }
2986 };
2987 
2988 template <>
2990  public FixedNumOperandTraits<InsertValueInst, 2> {
2991 };
2992 
2993 InsertValueInst::InsertValueInst(Value *Agg,
2994  Value *Val,
2995  ArrayRef<unsigned> Idxs,
2996  const Twine &NameStr,
2997  Instruction *InsertBefore)
2998  : Instruction(Agg->getType(), InsertValue,
3000  2, InsertBefore) {
3001  init(Agg, Val, Idxs, NameStr);
3002 }
3003 
3004 InsertValueInst::InsertValueInst(Value *Agg,
3005  Value *Val,
3006  ArrayRef<unsigned> Idxs,
3007  const Twine &NameStr,
3008  BasicBlock *InsertAtEnd)
3009  : Instruction(Agg->getType(), InsertValue,
3011  2, InsertAtEnd) {
3012  init(Agg, Val, Idxs, NameStr);
3013 }
3014 
3016 
3017 //===----------------------------------------------------------------------===//
3018 // PHINode Class
3019 //===----------------------------------------------------------------------===//
3020 
3021 // PHINode - The PHINode class is used to represent the magical mystical PHI
3022 // node, that can not exist in nature, but can be synthesized in a computer
3023 // scientist's overactive imagination.
3024 //
3025 class PHINode : public Instruction {
3026  /// The number of operands actually allocated. NumOperands is
3027  /// the number actually in use.
3028  unsigned ReservedSpace;
3029 
3030  PHINode(const PHINode &PN);
3031 
3032  explicit PHINode(Type *Ty, unsigned NumReservedValues,
3033  const Twine &NameStr = "",
3034  Instruction *InsertBefore = nullptr)
3035  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
3036  ReservedSpace(NumReservedValues) {
3037  setName(NameStr);
3038  allocHungoffUses(ReservedSpace);
3039  }
3040 
3041  PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
3042  BasicBlock *InsertAtEnd)
3043  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
3044  ReservedSpace(NumReservedValues) {
3045  setName(NameStr);
3046  allocHungoffUses(ReservedSpace);
3047  }
3048 
3049 protected:
3050  // Note: Instruction needs to be a friend here to call cloneImpl.
3051  friend class Instruction;
3052 
3053  PHINode *cloneImpl() const;
3054 
3055  // allocHungoffUses - this is more complicated than the generic
3056  // User::allocHungoffUses, because we have to allocate Uses for the incoming
3057  // values and pointers to the incoming blocks, all in one allocation.
3058  void allocHungoffUses(unsigned N) {
3059  User::allocHungoffUses(N, /* IsPhi */ true);
3060  }
3061 
3062 public:
3063  /// Constructors - NumReservedValues is a hint for the number of incoming
3064  /// edges that this phi node will have (use 0 if you really have no idea).
3065  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
3066  const Twine &NameStr = "",
3067  Instruction *InsertBefore = nullptr) {
3068  return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
3069  }
3070 
3071  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
3072  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3073  return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
3074  }
3075 
3076  /// Provide fast operand accessors
3078 
3079  // Block iterator interface. This provides access to the list of incoming
3080  // basic blocks, which parallels the list of incoming values.
3081 
3084 
3086  Use::UserRef *ref =
3087  reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
3088  return reinterpret_cast<block_iterator>(ref + 1);
3089  }
3090 
3092  const Use::UserRef *ref =
3093  reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
3094  return reinterpret_cast<const_block_iterator>(ref + 1);
3095  }
3096 
3098  return block_begin() + getNumOperands();
3099  }
3100 
3102  return block_begin() + getNumOperands();
3103  }
3104 
3106  return make_range(block_begin(), block_end());
3107  }
3108 
3110  return make_range(block_begin(), block_end());
3111  }
3112 
3114 
3116 
3117  /// Return the number of incoming edges
3118  ///
3119  unsigned getNumIncomingValues() const { return getNumOperands(); }
3120 
3121  /// Return incoming value number x
3122  ///
3123  Value *getIncomingValue(unsigned i) const {
3124  return getOperand(i);
3125  }
3126  void setIncomingValue(unsigned i, Value *V) {
3127  assert(V && "PHI node got a null value!");
3128  assert(getType() == V->getType() &&
3129  "All operands to PHI node must be the same type as the PHI node!");
3130  setOperand(i, V);
3131  }
3132 
3133  static unsigned getOperandNumForIncomingValue(unsigned i) {
3134  return i;
3135  }
3136 
3137  static unsigned getIncomingValueNumForOperand(unsigned i) {
3138  return i;
3139  }
3140 
3141  /// Return incoming basic block number @p i.
3142  ///
3143  BasicBlock *getIncomingBlock(unsigned i) const {
3144  return block_begin()[i];
3145  }
3146 
3147  /// Return incoming basic block corresponding
3148  /// to an operand of the PHI.
3149  ///
3150  BasicBlock *getIncomingBlock(const Use &U) const {
3151  assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
3152  return getIncomingBlock(unsigned(&U - op_begin()));
3153  }
3154 
3155  /// Return incoming basic block corresponding
3156  /// to value use iterator.
3157  ///
3159  return getIncomingBlock(I.getUse());
3160  }
3161 
3162  void setIncomingBlock(unsigned i, BasicBlock *BB) {
3163  assert(BB && "PHI node got a null basic block!");
3164  block_begin()[i] = BB;
3165  }
3166 
3167  /// Add an incoming value to the end of the PHI list
3168  ///
3169  void addIncoming(Value *V, BasicBlock *BB) {
3170  if (getNumOperands() == ReservedSpace)
3171  growOperands(); // Get more space!
3172  // Initialize some new operands.
3174  setIncomingValue(getNumOperands() - 1, V);
3175  setIncomingBlock(getNumOperands() - 1, BB);
3176  }
3177 
3178  /// Remove an incoming value. This is useful if a
3179  /// predecessor basic block is deleted. The value removed is returned.
3180  ///
3181  /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
3182  /// is true), the PHI node is destroyed and any uses of it are replaced with
3183  /// dummy values. The only time there should be zero incoming values to a PHI
3184  /// node is when the block is dead, so this strategy is sound.
3185  ///
3186  Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
3187 
3188  Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
3189  int Idx = getBasicBlockIndex(BB);
3190  assert(Idx >= 0 && "Invalid basic block argument to remove!");
3191  return removeIncomingValue(Idx, DeletePHIIfEmpty);
3192  }
3193 
3194  /// Return the first index of the specified basic
3195  /// block in the value list for this PHI. Returns -1 if no instance.
3196  ///
3197  int getBasicBlockIndex(const BasicBlock *BB) const {
3198  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3199  if (block_begin()[i] == BB)
3200  return i;
3201  return -1;
3202  }
3203 
3205  int Idx = getBasicBlockIndex(BB);
3206  assert(Idx >= 0 && "Invalid basic block argument!");
3207  return getIncomingValue(Idx);
3208  }
3209 
3210  /// If the specified PHI node always merges together the
3211  /// same value, return the value, otherwise return null.
3212  Value *hasConstantValue() const;
3213 
3214  /// Whether the specified PHI node always merges
3215  /// together the same value, assuming undefs are equal to a unique
3216  /// non-undef value.
3217  bool hasConstantOrUndefValue() const;
3218 
3219  /// Methods for support type inquiry through isa, cast, and dyn_cast:
3220  static bool classof(const Instruction *I) {
3221  return I->getOpcode() == Instruction::PHI;
3222  }
3223  static bool classof(const Value *V) {
3224  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3225  }
3226 
3227 private:
3228  void growOperands();
3229 };
3230 
3231 template <>
3233 };
3234 
3236 
3237 //===----------------------------------------------------------------------===//
3238 // LandingPadInst Class
3239 //===----------------------------------------------------------------------===//
3240 
3241 //===---------------------------------------------------------------------------
3242 /// The landingpad instruction holds all of the information
3243 /// necessary to generate correct exception handling. The landingpad instruction
3244 /// cannot be moved from the top of a landing pad block, which itself is
3245 /// accessible only from the 'unwind' edge of an invoke. This uses the
3246 /// SubclassData field in Value to store whether or not the landingpad is a
3247 /// cleanup.
3248 ///
3249 class LandingPadInst : public Instruction {
3250  /// The number of operands actually allocated. NumOperands is
3251  /// the number actually in use.
3252  unsigned ReservedSpace;
3253 
3254  LandingPadInst(const LandingPadInst &LP);
3255 
3256 public:
3258 
3259 private:
3260  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
3261  const Twine &NameStr, Instruction *InsertBefore);
3262  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
3263  const Twine &NameStr, BasicBlock *InsertAtEnd);
3264 
3265  // Allocate space for exactly zero operands.
3266  void *operator new(size_t s) {
3267  return User::operator new(s);
3268  }
3269 
3270  void growOperands(unsigned Size);
3271  void init(unsigned NumReservedValues, const Twine &NameStr);
3272 
3273 protected:
3274  // Note: Instruction needs to be a friend here to call cloneImpl.
3275  friend class Instruction;
3276 
3277  LandingPadInst *cloneImpl() const;
3278 
3279 public:
3280  /// Constructors - NumReservedClauses is a hint for the number of incoming
3281  /// clauses that this landingpad will have (use 0 if you really have no idea).
3282  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
3283  const Twine &NameStr = "",
3284  Instruction *InsertBefore = nullptr);
3285  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
3286  const Twine &NameStr, BasicBlock *InsertAtEnd);
3287 
3288  /// Provide fast operand accessors
3290 
3291  /// Return 'true' if this landingpad instruction is a
3292  /// cleanup. I.e., it should be run when unwinding even if its landing pad
3293  /// doesn't catch the exception.
3294  bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
3295 
3296  /// Indicate that this landingpad instruction is a cleanup.
3297  void setCleanup(bool V) {
3298  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
3299  (V ? 1 : 0));
3300  }
3301 
3302  /// Add a catch or filter clause to the landing pad.
3303  void addClause(Constant *ClauseVal);
3304 
3305  /// Get the value of the clause at index Idx. Use isCatch/isFilter to
3306  /// determine what type of clause this is.
3307  Constant *getClause(unsigned Idx) const {
3308  return cast<Constant>(getOperandList()[Idx]);
3309  }
3310 
3311  /// Return 'true' if the clause and index Idx is a catch clause.
3312  bool isCatch(unsigned Idx) const {
3313  return !isa<ArrayType>(getOperandList()[Idx]->getType());
3314  }
3315 
3316  /// Return 'true' if the clause and index Idx is a filter clause.
3317  bool isFilter(unsigned Idx) const {
3318  return isa<ArrayType>(getOperandList()[Idx]->getType());
3319  }
3320 
3321  /// Get the number of clauses for this landing pad.
3322  unsigned getNumClauses() const { return getNumOperands(); }
3323 
3324  /// Grow the size of the operand list to accommodate the new
3325  /// number of clauses.
3326  void reserveClauses(unsigned Size) { growOperands(Size); }
3327 
3328  // Methods for support type inquiry through isa, cast, and dyn_cast:
3329  static bool classof(const Instruction *I) {
3330  return I->getOpcode() == Instruction::LandingPad;
3331  }
3332  static bool classof(const Value *V) {
3333  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3334  }
3335 };
3336 
3337 template <>
3339 };
3340 
3342 
3343 //===----------------------------------------------------------------------===//
3344 // ReturnInst Class
3345 //===----------------------------------------------------------------------===//
3346 
3347 //===---------------------------------------------------------------------------
3348 /// Return a value (possibly void), from a function. Execution
3349 /// does not continue in this function any longer.
3350 ///
3351 class ReturnInst : public Instruction {
3352  ReturnInst(const ReturnInst &RI);
3353 
3354 private:
3355  // ReturnInst constructors:
3356  // ReturnInst() - 'ret void' instruction
3357  // ReturnInst( null) - 'ret void' instruction
3358  // ReturnInst(Value* X) - 'ret X' instruction
3359  // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
3360  // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
3361  // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
3362  // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
3363  //
3364  // NOTE: If the Value* passed is of type void then the constructor behaves as
3365  // if it was passed NULL.
3366  explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
3367  Instruction *InsertBefore = nullptr);
3368  ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
3369  explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
3370 
3371 protected:
3372  // Note: Instruction needs to be a friend here to call cloneImpl.
3373  friend class Instruction;
3374 
3375  ReturnInst *cloneImpl() const;
3376 
3377 public:
3378  static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
3379  Instruction *InsertBefore = nullptr) {
3380  return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
3381  }
3382 
3383  static ReturnInst* Create(LLVMContext &C, Value *retVal,
3384  BasicBlock *InsertAtEnd) {
3385  return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
3386  }
3387 
3388  static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
3389  return new(0) ReturnInst(C, InsertAtEnd);
3390  }
3391 
3392  /// Provide fast operand accessors
3394 
3395  /// Convenience accessor. Returns null if there is no return value.
3397  return getNumOperands() != 0 ? getOperand(0) : nullptr;
3398  }
3399 
3400  unsigned getNumSuccessors() const { return 0; }
3401 
3402  // Methods for support type inquiry through isa, cast, and dyn_cast:
3403  static bool classof(const Instruction *I) {
3404  return (I->getOpcode() == Instruction::Ret);
3405  }
3406  static bool classof(const Value *V) {
3407  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3408  }
3409 
3410 private:
3411  BasicBlock *getSuccessor(unsigned idx) const {
3412  llvm_unreachable("ReturnInst has no successors!");
3413  }
3414 
3415  void setSuccessor(unsigned idx, BasicBlock *B) {
3416  llvm_unreachable("ReturnInst has no successors!");
3417  }
3418 };
3419 
3420 template <>
3421 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
3422 };
3423 
3425 
3426 //===----------------------------------------------------------------------===//
3427 // BranchInst Class
3428 //===----------------------------------------------------------------------===//
3429 
3430 //===---------------------------------------------------------------------------
3431 /// Conditional or Unconditional Branch instruction.
3432 ///
3433 class BranchInst : public Instruction {
3434  /// Ops list - Branches are strange. The operands are ordered:
3435  /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
3436  /// they don't have to check for cond/uncond branchness. These are mostly
3437  /// accessed relative from op_end().
3438  BranchInst(const BranchInst &BI);
3439  // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
3440  // BranchInst(BB *B) - 'br B'
3441  // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
3442  // BranchInst(BB* B, Inst *I) - 'br B' insert before I
3443  // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3444  // BranchInst(BB* B, BB *I) - 'br B' insert at end
3445  // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
3446  explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3447  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3448  Instruction *InsertBefore = nullptr);
3449  BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3450  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3451  BasicBlock *InsertAtEnd);
3452 
3453  void AssertOK();
3454 
3455 protected:
3456  // Note: Instruction needs to be a friend here to call cloneImpl.
3457  friend class Instruction;
3458 
3459  BranchInst *cloneImpl() const;
3460 
3461 public:
3462  /// Iterator type that casts an operand to a basic block.
3463  ///
3464  /// This only makes sense because the successors are stored as adjacent
3465  /// operands for branch instructions.
3467  : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3468  std::random_access_iterator_tag, BasicBlock *,
3469  ptrdiff_t, BasicBlock *, BasicBlock *> {
3470  explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3471 
3472  BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3473  BasicBlock *operator->() const { return operator*(); }
3474  };
3475 
3476  /// The const version of `succ_op_iterator`.
3478  : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3479  std::random_access_iterator_tag,
3480  const BasicBlock *, ptrdiff_t, const BasicBlock *,
3481  const BasicBlock *> {
3483  : iterator_adaptor_base(I) {}
3484 
3485  const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3486  const BasicBlock *operator->() const { return operator*(); }
3487  };
3488 
3489  static BranchInst *Create(BasicBlock *IfTrue,
3490  Instruction *InsertBefore = nullptr) {
3491  return new(1) BranchInst(IfTrue, InsertBefore);
3492  }
3493 
3494  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3495  Value *Cond, Instruction *InsertBefore = nullptr) {
3496  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3497  }
3498 
3499  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3500  return new(1) BranchInst(IfTrue, InsertAtEnd);
3501  }
3502 
3503  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3504  Value *Cond, BasicBlock *InsertAtEnd) {
3505  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3506  }
3507 
3508  /// Transparently provide more efficient getOperand methods.
3510 
3511  bool isUnconditional() const { return getNumOperands() == 1; }
3512  bool isConditional() const { return getNumOperands() == 3; }
3513 
3514  Value *getCondition() const {
3515  assert(isConditional() && "Cannot get condition of an uncond branch!");
3516  return Op<-3>();
3517  }
3518 
3519  void setCondition(Value *V) {
3520  assert(isConditional() && "Cannot set condition of unconditional branch!");
3521  Op<-3>() = V;
3522  }
3523 
3524  unsigned getNumSuccessors() const { return 1+isConditional(); }
3525 
3526  BasicBlock *getSuccessor(unsigned i) const {
3527  assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3528  return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3529  }
3530 
3531  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3532  assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3533  *(&Op<-1>() - idx) = NewSucc;
3534  }
3535 
3536  /// Swap the successors of this branch instruction.
3537  ///
3538  /// Swaps the successors of the branch instruction. This also swaps any
3539  /// branch weight metadata associated with the instruction so that it
3540  /// continues to map correctly to each operand.
3541  void swapSuccessors();
3542 
3544  return make_range(
3545  succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3547  }
3548 
3551  std::next(value_op_begin(), isConditional() ? 1 : 0)),
3553  }
3554 
3555  // Methods for support type inquiry through isa, cast, and dyn_cast:
3556  static bool classof(const Instruction *I) {
3557  return (I->getOpcode() == Instruction::Br);
3558  }
3559  static bool classof(const Value *V) {
3560  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3561  }
3562 };
3563 
3564 template <>
3565 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3566 };
3567 
3569 
3570 //===----------------------------------------------------------------------===//
3571 // SwitchInst Class
3572 //===----------------------------------------------------------------------===//
3573 
3574 //===---------------------------------------------------------------------------
3575 /// Multiway switch
3576 ///
3577 class SwitchInst : public Instruction {
3578  unsigned ReservedSpace;
3579 
3580  // Operand[0] = Value to switch on
3581  // Operand[1] = Default basic block destination
3582  // Operand[2n ] = Value to match
3583  // Operand[2n+1] = BasicBlock to go to on match
3584  SwitchInst(const SwitchInst &SI);
3585 
3586  /// Create a new switch instruction, specifying a value to switch on and a
3587  /// default destination. The number of additional cases can be specified here
3588  /// to make memory allocation more efficient. This constructor can also
3589  /// auto-insert before another instruction.
3590  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3591  Instruction *InsertBefore);
3592 
3593  /// Create a new switch instruction, specifying a value to switch on and a
3594  /// default destination. The number of additional cases can be specified here
3595  /// to make memory allocation more efficient. This constructor also
3596  /// auto-inserts at the end of the specified BasicBlock.
3597  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3598  BasicBlock *InsertAtEnd);
3599 
3600  // allocate space for exactly zero operands
3601  void *operator new(size_t s) {
3602  return User::operator new(s);
3603  }
3604 
3605  void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3606  void growOperands();
3607 
3608 protected:
3609  // Note: Instruction needs to be a friend here to call cloneImpl.
3610  friend class Instruction;
3611 
3612  SwitchInst *cloneImpl() const;
3613 
3614 public:
3615  // -2
3616  static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3617 
3618  template <typename CaseHandleT> class CaseIteratorImpl;
3619 
3620  /// A handle to a particular switch case. It exposes a convenient interface
3621  /// to both the case value and the successor block.
3622  ///
3623  /// We define this as a template and instantiate it to form both a const and
3624  /// non-const handle.
3625  template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3627  // Directly befriend both const and non-const iterators.
3628  friend class SwitchInst::CaseIteratorImpl<
3629  CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3630 
3631  protected:
3632  // Expose the switch type we're parameterized with to the iterator.
3633  using SwitchInstType = SwitchInstT;
3634 
3635  SwitchInstT *SI;
3637 
3638  CaseHandleImpl() = default;
3639  CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3640 
3641  public:
3642  /// Resolves case value for current case.
3643  ConstantIntT *getCaseValue() const {
3644  assert((unsigned)Index < SI->getNumCases() &&
3645  "Index out the number of cases.");
3646  return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3647  }
3648 
3649  /// Resolves successor for current case.
3650  BasicBlockT *getCaseSuccessor() const {
3651  assert(((unsigned)Index < SI->getNumCases() ||
3652  (unsigned)Index == DefaultPseudoIndex) &&
3653  "Index out the number of cases.");
3654  return SI->getSuccessor(getSuccessorIndex());
3655  }
3656 
3657  /// Returns number of current case.
3658  unsigned getCaseIndex() const { return Index; }
3659 
3660  /// Returns successor index for current case successor.
3661  unsigned getSuccessorIndex() const {
3662  assert(((unsigned)Index == DefaultPseudoIndex ||
3663  (unsigned)Index < SI->getNumCases()) &&
3664  "Index out the number of cases.");
3665  return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3666  }
3667 
3668  bool operator==(const CaseHandleImpl &RHS) const {
3669  assert(SI == RHS.SI && "Incompatible operators.");
3670  return Index == RHS.Index;
3671  }
3672  };
3673 
3674  using ConstCaseHandle =
3676 
3678  : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3680 
3681  public:
3683 
3684  /// Sets the new value for current case.
3686  assert((unsigned)Index < SI->getNumCases() &&
3687  "Index out the number of cases.");
3688  SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3689  }
3690 
3691  /// Sets the new successor for current case.
3693  SI->setSuccessor(getSuccessorIndex(), S);
3694  }
3695  };
3696 
3697  template <typename CaseHandleT>
3698  class CaseIteratorImpl
3699  : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3700  std::random_access_iterator_tag,
3701  CaseHandleT> {
3702  using SwitchInstT = typename CaseHandleT::SwitchInstType;
3703 
3704  CaseHandleT Case;
3705 
3706  public:
3707  /// Default constructed iterator is in an invalid state until assigned to
3708  /// a case for a particular switch.
3709  CaseIteratorImpl() = default;
3710 
3711  /// Initializes case iterator for given SwitchInst and for given
3712  /// case number.
3713  CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3714 
3715  /// Initializes case iterator for given SwitchInst and for given
3716  /// successor index.
3717  static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3718  unsigned SuccessorIndex) {
3719  assert(SuccessorIndex < SI->getNumSuccessors() &&
3720  "Successor index # out of range!");
3721  return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3722  : CaseIteratorImpl(SI, DefaultPseudoIndex);
3723  }
3724 
3725  /// Support converting to the const variant. This will be a no-op for const
3726  /// variant.
3728  return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3729  }
3730 
3732  // Check index correctness after addition.
3733  // Note: Index == getNumCases() means end().
3734  assert(Case.Index + N >= 0 &&
3735  (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3736  "Case.Index out the number of cases.");
3737  Case.Index += N;
3738  return *this;
3739  }
3741  // Check index correctness after subtraction.
3742  // Note: Case.Index == getNumCases() means end().
3743  assert(Case.Index - N >= 0 &&
3744  (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3745  "Case.Index out the number of cases.");
3746  Case.Index -= N;
3747  return *this;
3748  }
3750  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3751  return Case.Index - RHS.Case.Index;
3752  }
3753  bool operator==(const CaseIteratorImpl &RHS) const {
3754  return Case == RHS.Case;
3755  }
3756  bool operator<(const CaseIteratorImpl &RHS) const {
3757  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3758  return Case.Index < RHS.Case.Index;
3759  }
3760  CaseHandleT &operator*() { return Case; }
3761  const CaseHandleT &operator*() const { return Case; }
3762  };
3763 
3766 
3767  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3768  unsigned NumCases,
3769  Instruction *InsertBefore = nullptr) {
3770  return new SwitchInst(Value, Default, NumCases, InsertBefore);
3771  }
3772 
3773  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3774  unsigned NumCases, BasicBlock *InsertAtEnd) {
3775  return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3776  }
3777 
3778  /// Provide fast operand accessors
3780 
3781  // Accessor Methods for Switch stmt
3782  Value *getCondition() const { return getOperand(0); }
3783  void setCondition(Value *V) { setOperand(0, V); }
3784 
3786  return cast<BasicBlock>(getOperand(1));
3787  }
3788 
3789  void setDefaultDest(BasicBlock *DefaultCase) {
3790  setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3791  }
3792 
3793  /// Return the number of 'cases' in this switch instruction, excluding the
3794  /// default case.
3795  unsigned getNumCases() const {
3796  return getNumOperands()/2 - 1;
3797  }
3798 
3799  /// Returns a read/write iterator that points to the first case in the
3800  /// SwitchInst.
3802  return CaseIt(this, 0);
3803  }
3804 
3805  /// Returns a read-only iterator that points to the first case in the
3806  /// SwitchInst.
3808  return ConstCaseIt(this, 0);
3809  }
3810 
3811  /// Returns a read/write iterator that points one past the last in the
3812  /// SwitchInst.
3814  return CaseIt(this, getNumCases());
3815  }
3816 
3817  /// Returns a read-only iterator that points one past the last in the
3818  /// SwitchInst.
3820  return ConstCaseIt(this, getNumCases());
3821  }
3822 
3823  /// Iteration adapter for range-for loops.
3825  return make_range(case_begin(), case_end());
3826  }
3827 
3828  /// Constant iteration adapter for range-for loops.
3830  return make_range(case_begin(), case_end());
3831  }
3832 
3833  /// Returns an iterator that points to the default case.
3834  /// Note: this iterator allows to resolve successor only. Attempt
3835  /// to resolve case value causes an assertion.
3836  /// Also note, that increment and decrement also causes an assertion and
3837  /// makes iterator invalid.
3839  return CaseIt(this, DefaultPseudoIndex);
3840  }
3842  return ConstCaseIt(this, DefaultPseudoIndex);
3843  }
3844 
3845  /// Search all of the case values for the specified constant. If it is
3846  /// explicitly handled, return the case iterator of it, otherwise return
3847  /// default case iterator to indicate that it is handled by the default
3848  /// handler.
3851  cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3852  if (I != case_end())
3853  return I;
3854 
3855  return case_default();
3856  }
3858  ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3859  return Case.getCaseValue() == C;
3860  });
3861  if (I != case_end())
3862  return I;
3863 
3864  return case_default();
3865  }
3866 
3867  /// Finds the unique case value for a given successor. Returns null if the
3868  /// successor is not found, not unique, or is the default case.
3870  if (BB == getDefaultDest())
3871  return nullptr;
3872 
3873  ConstantInt *CI = nullptr;
3874  for (auto Case : cases()) {
3875  if (Case.getCaseSuccessor() != BB)
3876  continue;
3877 
3878  if (CI)
3879  return nullptr; // Multiple cases lead to BB.
3880 
3881  CI = Case.getCaseValue();
3882  }
3883 
3884  return CI;
3885  }
3886 
3887  /// Add an entry to the switch instruction.
3888  /// Note:
3889  /// This action invalidates case_end(). Old case_end() iterator will
3890  /// point to the added case.
3891  void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3892 
3893  /// This method removes the specified case and its successor from the switch
3894  /// instruction. Note that this operation may reorder the remaining cases at
3895  /// index idx and above.
3896  /// Note:
3897  /// This action invalidates iterators for all cases following the one removed,
3898  /// including the case_end() iterator. It returns an iterator for the next
3899  /// case.
3900  CaseIt removeCase(CaseIt I);
3901 
3902  unsigned getNumSuccessors() const { return getNumOperands()/2; }
3903  BasicBlock *getSuccessor(unsigned idx) const {
3904  assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3905  return cast<BasicBlock>(getOperand(idx*2+1));
3906  }
3907  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3908  assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3909  setOperand(idx * 2 + 1, NewSucc);
3910  }
3911 
3912  // Methods for support type inquiry through isa, cast, and dyn_cast:
3913  static bool classof(const Instruction *I) {
3914  return I->getOpcode() == Instruction::Switch;
3915  }
3916  static bool classof(const Value *V) {
3917  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3918  }
3919 };
3920 
3921 template <>
3923 };
3924 
3925 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3926 
3927 //===----------------------------------------------------------------------===//
3928 // IndirectBrInst Class
3929 //===----------------------------------------------------------------------===//
3930 
3931 //===---------------------------------------------------------------------------
3932 /// Indirect Branch Instruction.
3933 ///
3934 class IndirectBrInst : public Instruction {
3935  unsigned ReservedSpace;
3936 
3937  // Operand[0] = Address to jump to
3938  // Operand[n+1] = n-th destination
3939  IndirectBrInst(const IndirectBrInst &IBI);
3940 
3941  /// Create a new indirectbr instruction, specifying an
3942  /// Address to jump to. The number of expected destinations can be specified
3943  /// here to make memory allocation more efficient. This constructor can also
3944  /// autoinsert before another instruction.
3945  IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3946 
3947  /// Create a new indirectbr instruction, specifying an
3948  /// Address to jump to. The number of expected destinations can be specified
3949  /// here to make memory allocation more efficient. This constructor also
3950  /// autoinserts at the end of the specified BasicBlock.
3951  IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3952 
3953  // allocate space for exactly zero operands
3954  void *operator new(size_t s) {
3955  return User::operator new(s);
3956  }
3957 
3958  void init(Value *Address, unsigned NumDests);
3959  void growOperands();
3960 
3961 protected:
3962  // Note: Instruction needs to be a friend here to call cloneImpl.
3963  friend class Instruction;
3964 
3965  IndirectBrInst *cloneImpl() const;
3966 
3967 public:
3968  /// Iterator type that casts an operand to a basic block.
3969  ///
3970  /// This only makes sense because the successors are stored as adjacent
3971  /// operands for indirectbr instructions.
3973  : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3974  std::random_access_iterator_tag, BasicBlock *,
3975  ptrdiff_t, BasicBlock *, BasicBlock *> {
3977 
3978  BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3979  BasicBlock *operator->() const { return operator*(); }
3980  };
3981 
3982  /// The const version of `succ_op_iterator`.
3984  : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3985  std::random_access_iterator_tag,
3986  const BasicBlock *, ptrdiff_t, const BasicBlock *,
3987  const BasicBlock *> {
3989  : iterator_adaptor_base(I) {}
3990 
3991  const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3992  const BasicBlock *operator->() const { return operator*(); }
3993  };
3994 
3995  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3996  Instruction *InsertBefore = nullptr) {
3997  return new IndirectBrInst(Address, NumDests, InsertBefore);
3998  }
3999 
4000  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
4001  BasicBlock *InsertAtEnd) {
4002  return new IndirectBrInst(Address, NumDests, InsertAtEnd);
4003  }
4004 
4005  /// Provide fast operand accessors.
4007 
4008  // Accessor Methods for IndirectBrInst instruction.
4009  Value *getAddress() { return getOperand(0); }
4010  const Value *getAddress() const { return getOperand(0); }
4011  void setAddress(Value *V) { setOperand(0, V); }
4012 
4013  /// return the number of possible destinations in this
4014  /// indirectbr instruction.
4015  unsigned getNumDestinations() const { return getNumOperands()-1; }
4016 
4017  /// Return the specified destination.
4018  BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
4019  const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
4020 
4021  /// Add a destination.
4022  ///
4023  void addDestination(BasicBlock *Dest);
4024 
4025  /// This method removes the specified successor from the
4026  /// indirectbr instruction.
4027  void removeDestination(unsigned i);
4028 
4029  unsigned getNumSuccessors() const { return getNumOperands()-1; }
4030  BasicBlock *getSuccessor(unsigned i) const {
4031  return cast<BasicBlock>(getOperand(i+1));
4032  }
4033  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4034  setOperand(i + 1, NewSucc);
4035  }
4036 
4038  return make_range(succ_op_iterator(std::next(value_op_begin())),
4040  }
4041 
4043  return make_range(const_succ_op_iterator(std::next(value_op_begin())),
4045  }
4046 
4047  // Methods for support type inquiry through isa, cast, and dyn_cast:
4048  static bool classof(const Instruction *I) {
4049  return I->getOpcode() == Instruction::IndirectBr;
4050  }
4051  static bool classof(const Value *V) {
4052  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4053  }
4054 };
4055 
4056 template <>
4058 };
4059 
4060 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
4061 
4062 //===----------------------------------------------------------------------===//
4063 // InvokeInst Class
4064 //===----------------------------------------------------------------------===//
4065 
4066 /// Invoke instruction. The SubclassData field is used to hold the
4067 /// calling convention of the call.
4068 ///
4069 class InvokeInst : public CallBase<InvokeInst> {
4071 
4072  InvokeInst(const InvokeInst &BI);
4073 
4074  /// Construct an InvokeInst given a range of arguments.
4075  ///
4076  /// Construct an InvokeInst from a range of arguments
4077  inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
4078  ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
4079  unsigned Values, const Twine &NameStr,
4080  Instruction *InsertBefore)
4081  : InvokeInst(cast<FunctionType>(
4082  cast<PointerType>(Func->getType())->getElementType()),
4083  Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
4084  InsertBefore) {}
4085 
4086  inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4087  BasicBlock *IfException, ArrayRef<Value *> Args,
4088  ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4089  const Twine &NameStr, Instruction *InsertBefore);
4090  /// Construct an InvokeInst given a range of arguments.
4091  ///
4092  /// Construct an InvokeInst from a range of arguments
4093  inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
4095  unsigned Values, const Twine &NameStr,
4096  BasicBlock *InsertAtEnd);
4097 
4098 
4099  void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
4101  const Twine &NameStr) {
4102  init(cast<FunctionType>(
4103  cast<PointerType>(Func->getType())->getElementType()),
4104  Func, IfNormal, IfException, Args, Bundles, NameStr);
4105  }
4106 
4107  void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
4108  BasicBlock *IfException, ArrayRef<Value *> Args,
4109  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
4110 
4111 protected:
4112  // Note: Instruction needs to be a friend here to call cloneImpl.
4113  friend class Instruction;
4114 
4115  InvokeInst *cloneImpl() const;
4116 
4117 public:
4118  static constexpr int ArgOffset = 3;
4119  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
4120  BasicBlock *IfException, ArrayRef<Value *> Args,
4121  const Twine &NameStr,
4122  Instruction *InsertBefore = nullptr) {
4123  return Create(cast<FunctionType>(
4124  cast<PointerType>(Func->getType())->getElementType()),
4125  Func, IfNormal, IfException, Args, None, NameStr,
4126  InsertBefore);
4127  }
4128 
4129  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
4130  BasicBlock *IfException, ArrayRef<Value *> Args,
4131  ArrayRef<OperandBundleDef> Bundles = None,
4132  const Twine &NameStr = "",
4133  Instruction *InsertBefore = nullptr) {
4134  return Create(cast<FunctionType>(
4135  cast<PointerType>(Func->getType())->getElementType()),
4136  Func, IfNormal, IfException, Args, Bundles, NameStr,
4137  InsertBefore);
4138  }
4139 
4140  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4141  BasicBlock *IfException, ArrayRef<Value *> Args,
4142  const Twine &NameStr,
4143  Instruction *InsertBefore = nullptr) {
4144  unsigned Values = unsigned(Args.size()) + 3;
4145  return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
4146  Values, NameStr, InsertBefore);
4147  }
4148 
4149  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4150  BasicBlock *IfException, ArrayRef<Value *> Args,
4151  ArrayRef<OperandBundleDef> Bundles = None,
4152  const Twine &NameStr = "",
4153  Instruction *InsertBefore = nullptr) {
4154  unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
4155  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4156 
4157  return new (Values, DescriptorBytes)
4158  InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
4159  NameStr, InsertBefore);
4160  }
4161 
4162  static InvokeInst *Create(Value *Func,
4163  BasicBlock *IfNormal, BasicBlock *IfException,
4164  ArrayRef<Value *> Args, const Twine &NameStr,
4165  BasicBlock *InsertAtEnd) {
4166  unsigned Values = unsigned(Args.size()) + 3;
4167  return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
4168  Values, NameStr, InsertAtEnd);
4169  }
4170 
4171  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
4172  BasicBlock *IfException, ArrayRef<Value *> Args,
4174  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4175  unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
4176  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4177 
4178  return new (Values, DescriptorBytes)
4179  InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
4180  InsertAtEnd);
4181  }
4182 
4183  /// Create a clone of \p II with a different set of operand bundles and
4184  /// insert it before \p InsertPt.
4185  ///
4186  /// The returned invoke instruction is identical to \p II in every way except
4187  /// that the operand bundles for the new instruction are set to the operand
4188  /// bundles in \p Bundles.
4189  static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
4190  Instruction *InsertPt = nullptr);
4191 
4192  /// Determine if the call should not perform indirect branch tracking.
4193  bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
4194 
4195  /// Determine if the call cannot unwind.
4196  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
4198  addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
4199  }
4200 
4201  /// Return the function called, or null if this is an
4202  /// indirect function invocation.
4203  ///
4205  return dyn_cast<Function>(Op<-3>());
4206  }
4207 
4208  /// Get a pointer to the function that is invoked by this
4209  /// instruction
4210  const Value *getCalledValue() const { return Op<-3>(); }
4211  Value *getCalledValue() { return Op<-3>(); }
4212 
4213  /// Set the function called.
4214  void setCalledFunction(Value* Fn) {
4215  setCalledFunction(
4216  cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
4217  Fn);
4218  }
4219  void setCalledFunction(FunctionType *FTy, Value *Fn) {
4220  this->FTy = FTy;
4221  assert(FTy == cast<FunctionType>(
4222  cast<PointerType>(Fn->getType())->getElementType()));
4223  Op<-3>() = Fn;
4224  }
4225 
4226  // get*Dest - Return the destination basic blocks...
4228  return cast<BasicBlock>(Op<-2>());
4229  }
4231  return cast<BasicBlock>(Op<-1>());
4232  }
4234  Op<-2>() = reinterpret_cast<Value*>(B);
4235  }
4237  Op<-1>() = reinterpret_cast<Value*>(B);
4238  }
4239 
4240  /// Get the landingpad instruction from the landing pad
4241  /// block (the unwind destination).
4242  LandingPadInst *getLandingPadInst() const;
4243 
4244  BasicBlock *getSuccessor(unsigned i) const {
4245  assert(i < 2 && "Successor # out of range for invoke!");
4246  return i == 0 ? getNormalDest() : getUnwindDest();
4247  }
4248 
4249  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4250  assert(idx < 2 && "Successor # out of range for invoke!");
4251  *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
4252  }
4253 
4254  unsigned getNumSuccessors() const { return 2; }
4255 
4256  // Methods for support type inquiry through isa, cast, and dyn_cast:
4257  static bool classof(const Instruction *I) {
4258  return (I->getOpcode() == Instruction::Invoke);
4259  }
4260  static bool classof(const Value *V) {
4261  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4262  }
4263 
4264 private:
4265 
4266  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4267  // method so that subclasses cannot accidentally use it.
4268  void setInstructionSubclassData(unsigned short D) {
4270  }
4271 };
4272 
4273 template <>
4275  : public VariadicOperandTraits<CallBase<InvokeInst>, 3> {};
4276 
4277 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4278  BasicBlock *IfException, ArrayRef<Value *> Args,
4279  ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4280  const Twine &NameStr, Instruction *InsertBefore)
4281  : CallBase<InvokeInst>(Ty->getReturnType(), Instruction::Invoke,
4283  Values,
4284  Values, InsertBefore) {
4285  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
4286 }
4287 
4288 InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
4289  BasicBlock *IfException, ArrayRef<Value *> Args,
4290  ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4291  const Twine &NameStr, BasicBlock *InsertAtEnd)
4293  cast<FunctionType>(
4294  cast<PointerType>(Func->getType())->getElementType())
4295  ->getReturnType(),
4296  Instruction::Invoke,
4297  OperandTraits<CallBase<InvokeInst>>::op_end(this) - Values, Values,
4298  InsertAtEnd) {
4299  init(Func, IfNormal, IfException, Args, Bundles, NameStr);
4300 }
4301 
4302 
4303 //===----------------------------------------------------------------------===//
4304 // ResumeInst Class
4305 //===----------------------------------------------------------------------===//
4306 
4307 //===---------------------------------------------------------------------------
4308 /// Resume the propagation of an exception.
4309 ///
4310 class ResumeInst : public Instruction {
4311  ResumeInst(const ResumeInst &RI);
4312 
4313  explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4314  ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4315 
4316 protected:
4317  // Note: Instruction needs to be a friend here to call cloneImpl.
4318  friend class Instruction;
4319 
4320  ResumeInst *cloneImpl() const;
4321 
4322 public:
4323  static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4324  return new(1) ResumeInst(Exn, InsertBefore);
4325  }
4326 
4327  static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4328  return new(1) ResumeInst(Exn, InsertAtEnd);
4329  }
4330 
4331  /// Provide fast operand accessors
4333 
4334  /// Convenience accessor.
4335  Value *getValue() const { return Op<0>(); }
4336 
4337  unsigned getNumSuccessors() const { return 0; }
4338 
4339  // Methods for support type inquiry through isa, cast, and dyn_cast:
4340  static bool classof(const Instruction *I) {
4341  return I->getOpcode() == Instruction::Resume;
4342  }
4343  static bool classof(const Value *V) {
4344  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4345  }
4346 
4347 private:
4348  BasicBlock *getSuccessor(unsigned idx) const {
4349  llvm_unreachable("ResumeInst has no successors!");
4350  }
4351 
4352  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4353  llvm_unreachable("ResumeInst has no successors!");
4354  }
4355 };
4356 
4357 template <>
4359  public FixedNumOperandTraits<ResumeInst, 1> {
4360 };
4361 
4362 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4363 
4364 //===----------------------------------------------------------------------===//
4365 // CatchSwitchInst Class
4366 //===----------------------------------------------------------------------===//
4368  /// The number of operands actually allocated. NumOperands is
4369  /// the number actually in use.
4370  unsigned ReservedSpace;
4371 
4372  // Operand[0] = Outer scope
4373  // Operand[1] = Unwind block destination
4374  // Operand[n] = BasicBlock to go to on match
4375  CatchSwitchInst(const CatchSwitchInst &CSI);
4376 
4377  /// Create a new switch instruction, specifying a
4378  /// default destination. The number of additional handlers can be specified
4379  /// here to make memory allocation more efficient.
4380  /// This constructor can also autoinsert before another instruction.
4381  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4382  unsigned NumHandlers, const Twine &NameStr,
4383  Instruction *InsertBefore);
4384 
4385  /// Create a new switch instruction, specifying a
4386  /// default destination. The number of additional handlers can be specified
4387  /// here to make memory allocation more efficient.
4388  /// This constructor also autoinserts at the end of the specified BasicBlock.
4389  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4390  unsigned NumHandlers, const Twine &NameStr,
4391  BasicBlock *InsertAtEnd);
4392 
4393  // allocate space for exactly zero operands
4394  void *operator new(size_t s) { return User::operator new(s); }
4395 
4396  void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4397  void growOperands(unsigned Size);
4398 
4399 protected:
4400  // Note: Instruction needs to be a friend here to call cloneImpl.
4401  friend class Instruction;
4402 
4403  CatchSwitchInst *cloneImpl() const;
4404 
4405 public:
4406  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4407  unsigned NumHandlers,
4408  const Twine &NameStr = "",
4409  Instruction *InsertBefore = nullptr) {
4410  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4411  InsertBefore);
4412  }
4413 
4414  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4415  unsigned NumHandlers, const Twine &NameStr,
4416  BasicBlock *InsertAtEnd) {
4417  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4418  InsertAtEnd);
4419  }
4420 
4421  /// Provide fast operand accessors
4423 
4424  // Accessor Methods for CatchSwitch stmt
4425  Value *getParentPad() const { return getOperand(0); }
4426  void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4427 
4428  // Accessor Methods for CatchSwitch stmt
4429  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4430  bool unwindsToCaller() const { return !hasUnwindDest(); }
4432  if (hasUnwindDest())
4433  return cast<BasicBlock>(getOperand(1));
4434  return nullptr;
4435  }
4436  void setUnwindDest(BasicBlock *UnwindDest) {
4437  assert(UnwindDest);
4438  assert(hasUnwindDest());
4439  setOperand(1, UnwindDest);
4440  }
4441 
4442  /// return the number of 'handlers' in this catchswitch
4443  /// instruction, except the default handler
4444  unsigned getNumHandlers() const {
4445  if (hasUnwindDest())
4446  return getNumOperands() - 2;
4447  return getNumOperands() - 1;
4448  }
4449 
4450 private:
4451  static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4452  static const BasicBlock *handler_helper(const Value *V) {
4453  return cast<BasicBlock>(V);
4454  }
4455 
4456 public:
4457  using DerefFnTy = BasicBlock *(*)(Value *);
4460  using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4461  using const_handler_iterator =
4464 
4465  /// Returns an iterator that points to the first handler in CatchSwitchInst.
4467  op_iterator It = op_begin() + 1;
4468  if (hasUnwindDest())
4469  ++It;
4470  return handler_iterator(It, DerefFnTy(handler_helper));
4471  }
4472 
4473  /// Returns an iterator that points to the first handler in the
4474  /// CatchSwitchInst.
4475  const_handler_iterator handler_begin() const {
4476  const_op_iterator It = op_begin() + 1;
4477  if (hasUnwindDest())
4478  ++It;
4479  return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4480  }
4481 
4482  /// Returns a read-only iterator that points one past the last
4483  /// handler in the CatchSwitchInst.
4485  return handler_iterator(op_end(), DerefFnTy(handler_helper));
4486  }
4487 
4488  /// Returns an iterator that points one past the last handler in the
4489  /// CatchSwitchInst.
4490  const_handler_iterator handler_end() const {
4491  return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4492  }
4493 
4494  /// iteration adapter for range-for loops.
4496  return make_range(handler_begin(), handler_end());
4497  }
4498 
4499  /// iteration adapter for range-for loops.
4501  return make_range(handler_begin(), handler_end());
4502  }
4503 
4504  /// Add an entry to the switch instruction...
4505  /// Note:
4506  /// This action invalidates handler_end(). Old handler_end() iterator will
4507  /// point to the added handler.
4508  void addHandler(BasicBlock *Dest);
4509 
4510  void removeHandler(handler_iterator HI);
4511 
4512  unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4513  BasicBlock *getSuccessor(unsigned Idx) const {
4514  assert(Idx < getNumSuccessors() &&
4515  "Successor # out of range for catchswitch!");
4516  return cast<BasicBlock>(getOperand(Idx + 1));
4517  }
4518  void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4519  assert(Idx < getNumSuccessors() &&
4520  "Successor # out of range for catchswitch!");
4521  setOperand(Idx + 1, NewSucc);
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::CatchSwitch;
4527  }
4528  static bool classof(const Value *V) {
4529  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4530  }
4531 };
4532 
4533 template <>
4535 
4536 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4537 
4538 //===----------------------------------------------------------------------===//
4539 // CleanupPadInst Class
4540 //===----------------------------------------------------------------------===//
4542 private:
4543  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4544  unsigned Values, const Twine &NameStr,
4545  Instruction *InsertBefore)
4546  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4547  NameStr, InsertBefore) {}
4548  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4549  unsigned Values, const Twine &NameStr,
4550  BasicBlock *InsertAtEnd)
4551  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4552  NameStr, InsertAtEnd) {}
4553 
4554 public:
4555  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4556  const Twine &NameStr = "",
4557  Instruction *InsertBefore = nullptr) {
4558  unsigned Values = 1 + Args.size();
4559  return new (Values)
4560  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4561  }
4562 
4563  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4564  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4565  unsigned Values = 1 + Args.size();
4566  return new (Values)
4567  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4568  }
4569 
4570  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4571  static bool classof(const Instruction *I) {
4572  return I->getOpcode() == Instruction::CleanupPad;
4573  }
4574  static bool classof(const Value *V) {
4575  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4576  }
4577 };
4578 
4579 //===----------------------------------------------------------------------===//
4580 // CatchPadInst Class
4581 //===----------------------------------------------------------------------===//
4583 private:
4584  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4585  unsigned Values, const Twine &NameStr,
4586  Instruction *InsertBefore)
4587  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4588  NameStr, InsertBefore) {}
4589  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4590  unsigned Values, const Twine &NameStr,
4591  BasicBlock *InsertAtEnd)
4592  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4593  NameStr, InsertAtEnd) {}
4594 
4595 public:
4596  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4597  const Twine &NameStr = "",
4598  Instruction *InsertBefore = nullptr) {
4599  unsigned Values = 1 + Args.size();
4600  return new (Values)
4601  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4602  }
4603 
4604  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4605  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4606  unsigned Values = 1 + Args.size();
4607  return new (Values)
4608  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4609  }
4610 
4611  /// Convenience accessors
4612  CatchSwitchInst *getCatchSwitch() const {
4613  return cast<CatchSwitchInst>(Op<-1>());
4614  }
4615  void setCatchSwitch(Value *CatchSwitch) {
4616  assert(CatchSwitch);
4617  Op<-1>() = CatchSwitch;
4618  }
4619 
4620  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4621  static bool classof(const Instruction *I) {
4622  return I->getOpcode() == Instruction::CatchPad;
4623  }
4624  static bool classof(const Value *V) {
4625  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4626  }
4627 };
4628 
4629 //===----------------------------------------------------------------------===//
4630 // CatchReturnInst Class
4631 //===----------------------------------------------------------------------===//
4632 
4634  CatchReturnInst(const CatchReturnInst &RI);
4635  CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4636  CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4637 
4638  void init(Value *CatchPad, BasicBlock *BB);
4639 
4640 protected:
4641  // Note: Instruction needs to be a friend here to call cloneImpl.
4642  friend class Instruction;
4643 
4644  CatchReturnInst *cloneImpl() const;
4645 
4646 public:
4647  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4648  Instruction *InsertBefore = nullptr) {
4649  assert(CatchPad);
4650  assert(BB);
4651  return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4652  }
4653 
4654  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4655  BasicBlock *InsertAtEnd) {
4656  assert(CatchPad);
4657  assert(BB);
4658  return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4659  }
4660 
4661  /// Provide fast operand accessors
4663 
4664  /// Convenience accessors.
4665  CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4666  void setCatchPad(CatchPadInst *CatchPad) {
4667  assert(CatchPad);
4668  Op<0>() = CatchPad;
4669  }
4670 
4671  BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4672  void setSuccessor(BasicBlock *NewSucc) {
4673  assert(NewSucc);
4674  Op<1>() = NewSucc;
4675  }
4676  unsigned getNumSuccessors() const { return 1; }
4677 
4678  /// Get the parentPad of this catchret's catchpad's catchswitch.
4679  /// The successor block is implicitly a member of this funclet.
4680  Value *getCatchSwitchParentPad() const {
4681  return getCatchPad()->getCatchSwitch()->getParentPad();
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::CatchRet);
4687  }
4688  static bool classof(const Value *V) {
4689  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4690  }
4691 
4692 private:
4693  BasicBlock *getSuccessor(unsigned Idx) const {
4694  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4695  return getSuccessor();
4696  }
4697 
4698  void setSuccessor(unsigned Idx, BasicBlock *B) {
4699  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4700  setSuccessor(B);
4701  }
4702 };
4703 
4704 template <>
4706  : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4707 
4708 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4709 
4710 //===----------------------------------------------------------------------===//
4711 // CleanupReturnInst Class
4712 //===----------------------------------------------------------------------===//
4713 
4715 private:
4717  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4718  Instruction *InsertBefore = nullptr);
4719  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4720  BasicBlock *InsertAtEnd);
4721 
4722  void init(Value *CleanupPad, BasicBlock *UnwindBB);
4723 
4724 protected:
4725  // Note: Instruction needs to be a friend here to call cloneImpl.
4726  friend class Instruction;
4727 
4728  CleanupReturnInst *cloneImpl() const;
4729 
4730 public:
4731  static CleanupReturnInst *Create(Value *CleanupPad,
4732  BasicBlock *UnwindBB = nullptr,
4733  Instruction *InsertBefore = nullptr) {
4734  assert(CleanupPad);
4735  unsigned Values = 1;
4736  if (UnwindBB)
4737  ++Values;
4738  return new (Values)
4739  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4740  }
4741 
4742  static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4743  BasicBlock *InsertAtEnd) {
4744  assert(CleanupPad);
4745  unsigned Values = 1;
4746  if (UnwindBB)
4747  ++Values;
4748  return new (Values)
4749  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4750  }
4751 
4752  /// Provide fast operand accessors
4754 
4755  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4756  bool unwindsToCaller() const { return !hasUnwindDest(); }
4757 
4758  /// Convenience accessor.
4760  return cast<CleanupPadInst>(Op<0>());
4761  }
4762  void setCleanupPad(CleanupPadInst *CleanupPad) {
4763  assert(CleanupPad);
4764  Op<0>() = CleanupPad;
4765  }
4766 
4767  unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4768 
4770  return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4771  }
4772  void setUnwindDest(BasicBlock *NewDest) {
4773  assert(NewDest);
4774  assert(hasUnwindDest());
4775  Op<1>() = NewDest;
4776  }
4777 
4778  // Methods for support type inquiry through isa, cast, and dyn_cast:
4779  static bool classof(const Instruction *I) {
4780  return (I->getOpcode() == Instruction::CleanupRet);
4781  }
4782  static bool classof(const Value *V) {
4783  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4784  }
4785 
4786 private:
4787  BasicBlock *getSuccessor(unsigned Idx) const {
4788  assert(Idx == 0);
4789  return getUnwindDest();
4790  }
4791 
4792  void setSuccessor(unsigned Idx, BasicBlock *B) {
4793  assert(Idx == 0);
4794  setUnwindDest(B);
4795  }
4796 
4797  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4798  // method so that subclasses cannot accidentally use it.
4799  void setInstructionSubclassData(unsigned short D) {
4801  }
4802 };
4803 
4804 template <>
4806  : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4807 
4808 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4809 
4810 //===----------------------------------------------------------------------===//
4811 // UnreachableInst Class
4812 //===----------------------------------------------------------------------===//
4813 
4814 //===---------------------------------------------------------------------------
4815 /// This function has undefined behavior. In particular, the
4816 /// presence of this instruction indicates some higher level knowledge that the
4817 /// end of the block cannot be reached.
4818 ///
4820 protected:
4821  // Note: Instruction needs to be a friend here to call cloneImpl.
4822  friend class Instruction;
4823 
4824  UnreachableInst *cloneImpl() const;
4825 
4826 public:
4827  explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4828  explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4829 
4830  // allocate space for exactly zero operands
4831  void *operator new(size_t s) {
4832  return User::operator new(s, 0);
4833  }
4834 
4835  unsigned getNumSuccessors() const { return 0; }
4836 
4837  // Methods for support type inquiry through isa, cast, and dyn_cast:
4838  static bool classof(const Instruction *I) {
4839  return I->getOpcode() == Instruction::Unreachable;
4840  }
4841  static bool classof(const Value *V) {
4842  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4843  }
4844 
4845 private:
4846  BasicBlock *getSuccessor(unsigned idx) const {
4847  llvm_unreachable("UnreachableInst has no successors!");
4848  }
4849 
4850  void setSuccessor(unsigned idx, BasicBlock *B) {
4851  llvm_unreachable("UnreachableInst has no successors!");
4852  }
4853 };
4854 
4855 //===----------------------------------------------------------------------===//
4856 // TruncInst Class
4857 //===----------------------------------------------------------------------===//
4858 
4859 /// This class represents a truncation of integer types.
4860 class TruncInst : public CastInst {
4861 protected:
4862  // Note: Instruction needs to be a friend here to call cloneImpl.
4863  friend class Instruction;
4864 
4865  /// Clone an identical TruncInst
4866  TruncInst *cloneImpl() const;
4867 
4868 public:
4869  /// Constructor with insert-before-instruction semantics
4870  TruncInst(
4871  Value *S, ///< The value to be truncated
4872  Type *Ty, ///< The (smaller) type to truncate to
4873  const Twine &NameStr = "", ///< A name for the new instruction
4874  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4875  );
4876 
4877  /// Constructor with insert-at-end-of-block semantics
4878  TruncInst(
4879  Value *S, ///< The value to be truncated
4880  Type *Ty, ///< The (smaller) type to truncate to
4881  const Twine &NameStr, ///< A name for the new instruction
4882  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4883  );
4884 
4885  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4886  static bool classof(const Instruction *I) {
4887  return I->getOpcode() == Trunc;
4888  }
4889  static bool classof(const Value *V) {
4890  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4891  }
4892 };
4893 
4894 //===----------------------------------------------------------------------===//