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