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 // ICmpInst Class
1138 //===----------------------------------------------------------------------===//
1139 
1140 /// This instruction compares its operands according to the predicate given
1141 /// to the constructor. It only operates on integers or pointers. The operands
1142 /// must be identical types.
1143 /// Represent an integer comparison operator.
1144 class ICmpInst: public CmpInst {
1145  void AssertOK() {
1146  assert(isIntPredicate() &&
1147  "Invalid ICmp predicate value");
1148  assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1149  "Both operands to ICmp instruction are not of the same type!");
1150  // Check that the operands are the right type
1151  assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1152  getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1153  "Invalid operand types for ICmp instruction");
1154  }
1155 
1156 protected:
1157  // Note: Instruction needs to be a friend here to call cloneImpl.
1158  friend class Instruction;
1159 
1160  /// Clone an identical ICmpInst
1161  ICmpInst *cloneImpl() const;
1162 
1163 public:
1164  /// Constructor with insert-before-instruction semantics.
1166  Instruction *InsertBefore, ///< Where to insert
1167  Predicate pred, ///< The predicate to use for the comparison
1168  Value *LHS, ///< The left-hand-side of the expression
1169  Value *RHS, ///< The right-hand-side of the expression
1170  const Twine &NameStr = "" ///< Name of the instruction
1171  ) : CmpInst(makeCmpResultType(LHS->getType()),
1172  Instruction::ICmp, pred, LHS, RHS, NameStr,
1173  InsertBefore) {
1174 #ifndef NDEBUG
1175  AssertOK();
1176 #endif
1177  }
1178 
1179  /// Constructor with insert-at-end semantics.
1181  BasicBlock &InsertAtEnd, ///< Block to insert into.
1182  Predicate pred, ///< The predicate to use for the comparison
1183  Value *LHS, ///< The left-hand-side of the expression
1184  Value *RHS, ///< The right-hand-side of the expression
1185  const Twine &NameStr = "" ///< Name of the instruction
1186  ) : CmpInst(makeCmpResultType(LHS->getType()),
1187  Instruction::ICmp, pred, LHS, RHS, NameStr,
1188  &InsertAtEnd) {
1189 #ifndef NDEBUG
1190  AssertOK();
1191 #endif
1192  }
1193 
1194  /// Constructor with no-insertion semantics
1196  Predicate pred, ///< The predicate to use for the comparison
1197  Value *LHS, ///< The left-hand-side of the expression
1198  Value *RHS, ///< The right-hand-side of the expression
1199  const Twine &NameStr = "" ///< Name of the instruction
1200  ) : CmpInst(makeCmpResultType(LHS->getType()),
1201  Instruction::ICmp, pred, LHS, RHS, NameStr) {
1202 #ifndef NDEBUG
1203  AssertOK();
1204 #endif
1205  }
1206 
1207  /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1208  /// @returns the predicate that would be the result if the operand were
1209  /// regarded as signed.
1210  /// Return the signed version of the predicate
1212  return getSignedPredicate(getPredicate());
1213  }
1214 
1215  /// This is a static version that you can use without an instruction.
1216  /// Return the signed version of the predicate.
1217  static Predicate getSignedPredicate(Predicate pred);
1218 
1219  /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1220  /// @returns the predicate that would be the result if the operand were
1221  /// regarded as unsigned.
1222  /// Return the unsigned version of the predicate
1224  return getUnsignedPredicate(getPredicate());
1225  }
1226 
1227  /// This is a static version that you can use without an instruction.
1228  /// Return the unsigned version of the predicate.
1229  static Predicate getUnsignedPredicate(Predicate pred);
1230 
1231  /// Return true if this predicate is either EQ or NE. This also
1232  /// tests for commutativity.
1233  static bool isEquality(Predicate P) {
1234  return P == ICMP_EQ || P == ICMP_NE;
1235  }
1236 
1237  /// Return true if this predicate is either EQ or NE. This also
1238  /// tests for commutativity.
1239  bool isEquality() const {
1240  return isEquality(getPredicate());
1241  }
1242 
1243  /// @returns true if the predicate of this ICmpInst is commutative
1244  /// Determine if this relation is commutative.
1245  bool isCommutative() const { return isEquality(); }
1246 
1247  /// Return true if the predicate is relational (not EQ or NE).
1248  ///
1249  bool isRelational() const {
1250  return !isEquality();
1251  }
1252 
1253  /// Return true if the predicate is relational (not EQ or NE).
1254  ///
1255  static bool isRelational(Predicate P) {
1256  return !isEquality(P);
1257  }
1258 
1259  /// Exchange the two operands to this instruction in such a way that it does
1260  /// not modify the semantics of the instruction. The predicate value may be
1261  /// changed to retain the same result if the predicate is order dependent
1262  /// (e.g. ult).
1263  /// Swap operands and adjust predicate.
1264  void swapOperands() {
1265  setPredicate(getSwappedPredicate());
1266  Op<0>().swap(Op<1>());
1267  }
1268 
1269  // Methods for support type inquiry through isa, cast, and dyn_cast:
1270  static bool classof(const Instruction *I) {
1271  return I->getOpcode() == Instruction::ICmp;
1272  }
1273  static bool classof(const Value *V) {
1274  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1275  }
1276 };
1277 
1278 //===----------------------------------------------------------------------===//
1279 // FCmpInst Class
1280 //===----------------------------------------------------------------------===//
1281 
1282 /// This instruction compares its operands according to the predicate given
1283 /// to the constructor. It only operates on floating point values or packed
1284 /// vectors of floating point values. The operands must be identical types.
1285 /// Represents a floating point comparison operator.
1286 class FCmpInst: public CmpInst {
1287  void AssertOK() {
1288  assert(isFPPredicate() && "Invalid FCmp predicate value");
1289  assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1290  "Both operands to FCmp instruction are not of the same type!");
1291  // Check that the operands are the right type
1292  assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1293  "Invalid operand types for FCmp instruction");
1294  }
1295 
1296 protected:
1297  // Note: Instruction needs to be a friend here to call cloneImpl.
1298  friend class Instruction;
1299 
1300  /// Clone an identical FCmpInst
1301  FCmpInst *cloneImpl() const;
1302 
1303 public:
1304  /// Constructor with insert-before-instruction semantics.
1306  Instruction *InsertBefore, ///< Where to insert
1307  Predicate pred, ///< The predicate to use for the comparison
1308  Value *LHS, ///< The left-hand-side of the expression
1309  Value *RHS, ///< The right-hand-side of the expression
1310  const Twine &NameStr = "" ///< Name of the instruction
1311  ) : CmpInst(makeCmpResultType(LHS->getType()),
1312  Instruction::FCmp, pred, LHS, RHS, NameStr,
1313  InsertBefore) {
1314  AssertOK();
1315  }
1316 
1317  /// Constructor with insert-at-end semantics.
1319  BasicBlock &InsertAtEnd, ///< Block to insert into.
1320  Predicate pred, ///< The predicate to use for the comparison
1321  Value *LHS, ///< The left-hand-side of the expression
1322  Value *RHS, ///< The right-hand-side of the expression
1323  const Twine &NameStr = "" ///< Name of the instruction
1324  ) : CmpInst(makeCmpResultType(LHS->getType()),
1325  Instruction::FCmp, pred, LHS, RHS, NameStr,
1326  &InsertAtEnd) {
1327  AssertOK();
1328  }
1329 
1330  /// Constructor with no-insertion semantics
1332  Predicate Pred, ///< The predicate to use for the comparison
1333  Value *LHS, ///< The left-hand-side of the expression
1334  Value *RHS, ///< The right-hand-side of the expression
1335  const Twine &NameStr = "", ///< Name of the instruction
1336  Instruction *FlagsSource = nullptr
1337  ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1338  RHS, NameStr, nullptr, FlagsSource) {
1339  AssertOK();
1340  }
1341 
1342  /// @returns true if the predicate of this instruction is EQ or NE.
1343  /// Determine if this is an equality predicate.
1344  static bool isEquality(Predicate Pred) {
1345  return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1346  Pred == FCMP_UNE;
1347  }
1348 
1349  /// @returns true if the predicate of this instruction is EQ or NE.
1350  /// Determine if this is an equality predicate.
1351  bool isEquality() const { return isEquality(getPredicate()); }
1352 
1353  /// @returns true if the predicate of this instruction is commutative.
1354  /// Determine if this is a commutative predicate.
1355  bool isCommutative() const {
1356  return isEquality() ||
1357  getPredicate() == FCMP_FALSE ||
1358  getPredicate() == FCMP_TRUE ||
1359  getPredicate() == FCMP_ORD ||
1360  getPredicate() == FCMP_UNO;
1361  }
1362 
1363  /// @returns true if the predicate is relational (not EQ or NE).
1364  /// Determine if this a relational predicate.
1365  bool isRelational() const { return !isEquality(); }
1366 
1367  /// Exchange the two operands to this instruction in such a way that it does
1368  /// not modify the semantics of the instruction. The predicate value may be
1369  /// changed to retain the same result if the predicate is order dependent
1370  /// (e.g. ult).
1371  /// Swap operands and adjust predicate.
1372  void swapOperands() {
1373  setPredicate(getSwappedPredicate());
1374  Op<0>().swap(Op<1>());
1375  }
1376 
1377  /// Methods for support type inquiry through isa, cast, and dyn_cast:
1378  static bool classof(const Instruction *I) {
1379  return I->getOpcode() == Instruction::FCmp;
1380  }
1381  static bool classof(const Value *V) {
1382  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1383  }
1384 };
1385 
1386 //===----------------------------------------------------------------------===//
1387 /// This class represents a function call, abstracting a target
1388 /// machine's calling convention. This class uses low bit of the SubClassData
1389 /// field to indicate whether or not this is a tail call. The rest of the bits
1390 /// hold the calling convention of the call.
1391 ///
1392 class CallInst : public CallBase {
1393  CallInst(const CallInst &CI);
1394 
1395  /// Construct a CallInst given a range of arguments.
1396  /// Construct a CallInst from a range of arguments
1397  inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1398  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1399  Instruction *InsertBefore);
1400 
1401  inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1402  const Twine &NameStr, Instruction *InsertBefore)
1403  : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1404 
1405  /// Construct a CallInst given a range of arguments.
1406  /// Construct a CallInst from a range of arguments
1407  inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1408  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1409  BasicBlock *InsertAtEnd);
1410 
1411  explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1412  Instruction *InsertBefore);
1413 
1414  CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1415  BasicBlock *InsertAtEnd);
1416 
1417  void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1418  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1419  void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1420 
1421  /// Compute the number of operands to allocate.
1422  static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1423  // We need one operand for the called function, plus the input operand
1424  // counts provided.
1425  return 1 + NumArgs + NumBundleInputs;
1426  }
1427 
1428 protected:
1429  // Note: Instruction needs to be a friend here to call cloneImpl.
1430  friend class Instruction;
1431 
1432  CallInst *cloneImpl() const;
1433 
1434 public:
1435  static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1436  Instruction *InsertBefore = nullptr) {
1437  return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1438  }
1439 
1441  const Twine &NameStr,
1442  Instruction *InsertBefore = nullptr) {
1443  return new (ComputeNumOperands(Args.size()))
1444  CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1445  }
1446 
1448  ArrayRef<OperandBundleDef> Bundles = None,
1449  const Twine &NameStr = "",
1450  Instruction *InsertBefore = nullptr) {
1451  const int NumOperands =
1452  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1453  const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1454 
1455  return new (NumOperands, DescriptorBytes)
1456  CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1457  }
1458 
1459  static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1460  BasicBlock *InsertAtEnd) {
1461  return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1462  }
1463 
1465  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1466  return new (ComputeNumOperands(Args.size()))
1467  CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1468  }
1469 
1472  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1473  const int NumOperands =
1474  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1475  const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1476 
1477  return new (NumOperands, DescriptorBytes)
1478  CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1479  }
1480 
1481  static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1482  Instruction *InsertBefore = nullptr) {
1483  return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1484  InsertBefore);
1485  }
1486 
1488  ArrayRef<OperandBundleDef> Bundles = None,
1489  const Twine &NameStr = "",
1490  Instruction *InsertBefore = nullptr) {
1491  return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1492  NameStr, InsertBefore);
1493  }
1494 
1496  const Twine &NameStr,
1497  Instruction *InsertBefore = nullptr) {
1498  return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1499  InsertBefore);
1500  }
1501 
1502  static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1503  BasicBlock *InsertAtEnd) {
1504  return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1505  InsertAtEnd);
1506  }
1507 
1509  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1510  return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1511  InsertAtEnd);
1512  }
1513 
1516  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1517  return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1518  NameStr, InsertAtEnd);
1519  }
1520 
1521  // Deprecated [opaque pointer types]
1522  static CallInst *Create(Value *Func, const Twine &NameStr = "",
1523  Instruction *InsertBefore = nullptr) {
1524  return Create(cast<FunctionType>(
1525  cast<PointerType>(Func->getType())->getElementType()),
1526  Func, NameStr, InsertBefore);
1527  }
1528 
1529  // Deprecated [opaque pointer types]
1531  const Twine &NameStr,
1532  Instruction *InsertBefore = nullptr) {
1533  return Create(cast<FunctionType>(
1534  cast<PointerType>(Func->getType())->getElementType()),
1535  Func, Args, NameStr, InsertBefore);
1536  }
1537 
1538  // Deprecated [opaque pointer types]
1540  ArrayRef<OperandBundleDef> Bundles = None,
1541  const Twine &NameStr = "",
1542  Instruction *InsertBefore = nullptr) {
1543  return Create(cast<FunctionType>(
1544  cast<PointerType>(Func->getType())->getElementType()),
1545  Func, Args, Bundles, NameStr, InsertBefore);
1546  }
1547 
1548  // Deprecated [opaque pointer types]
1549  static CallInst *Create(Value *Func, const Twine &NameStr,
1550  BasicBlock *InsertAtEnd) {
1551  return Create(cast<FunctionType>(
1552  cast<PointerType>(Func->getType())->getElementType()),
1553  Func, NameStr, InsertAtEnd);
1554  }
1555 
1556  // Deprecated [opaque pointer types]
1558  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1559  return Create(cast<FunctionType>(
1560  cast<PointerType>(Func->getType())->getElementType()),
1561  Func, Args, NameStr, InsertAtEnd);
1562  }
1563 
1564  // Deprecated [opaque pointer types]
1567  const Twine &NameStr, BasicBlock *InsertAtEnd) {
1568  return Create(cast<FunctionType>(
1569  cast<PointerType>(Func->getType())->getElementType()),
1570  Func, Args, Bundles, NameStr, InsertAtEnd);
1571  }
1572 
1573  /// Create a clone of \p CI with a different set of operand bundles and
1574  /// insert it before \p InsertPt.
1575  ///
1576  /// The returned call instruction is identical \p CI in every way except that
1577  /// the operand bundles for the new instruction are set to the operand bundles
1578  /// in \p Bundles.
1579  static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1580  Instruction *InsertPt = nullptr);
1581 
1582  /// Generate the IR for a call to malloc:
1583  /// 1. Compute the malloc call's argument as the specified type's size,
1584  /// possibly multiplied by the array size if the array size is not
1585  /// constant 1.
1586  /// 2. Call malloc with that argument.
1587  /// 3. Bitcast the result of the malloc call to the specified type.
1588  static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1589  Type *AllocTy, Value *AllocSize,
1590  Value *ArraySize = nullptr,
1591  Function *MallocF = nullptr,
1592  const Twine &Name = "");
1593  static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1594  Type *AllocTy, Value *AllocSize,
1595  Value *ArraySize = nullptr,
1596  Function *MallocF = nullptr,
1597  const Twine &Name = "");
1598  static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1599  Type *AllocTy, Value *AllocSize,
1600  Value *ArraySize = nullptr,
1601  ArrayRef<OperandBundleDef> Bundles = None,
1602  Function *MallocF = nullptr,
1603  const Twine &Name = "");
1604  static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1605  Type *AllocTy, Value *AllocSize,
1606  Value *ArraySize = nullptr,
1607  ArrayRef<OperandBundleDef> Bundles = None,
1608  Function *MallocF = nullptr,
1609  const Twine &Name = "");
1610  /// Generate the IR for a call to the builtin free function.
1611  static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1612  static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1613  static Instruction *CreateFree(Value *Source,
1615  Instruction *InsertBefore);
1616  static Instruction *CreateFree(Value *Source,
1618  BasicBlock *InsertAtEnd);
1619 
1620  // Note that 'musttail' implies 'tail'.
1622  TCK_None = 0,
1623  TCK_Tail = 1,
1624  TCK_MustTail = 2,
1625  TCK_NoTail = 3
1626  };
1629  }
1630 
1631  bool isTailCall() const {
1632  unsigned Kind = getSubclassDataFromInstruction() & 3;
1633  return Kind == TCK_Tail || Kind == TCK_MustTail;
1634  }
1635 
1636  bool isMustTailCall() const {
1637  return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1638  }
1639 
1640  bool isNoTailCall() const {
1641  return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1642  }
1643 
1644  void setTailCall(bool isTC = true) {
1645  setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1646  unsigned(isTC ? TCK_Tail : TCK_None));
1647  }
1648 
1650  setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1651  unsigned(TCK));
1652  }
1653 
1654  /// Return true if the call can return twice
1655  bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1657  addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1658  }
1659 
1660  // Methods for support type inquiry through isa, cast, and dyn_cast:
1661  static bool classof(const Instruction *I) {
1662  return I->getOpcode() == Instruction::Call;
1663  }
1664  static bool classof(const Value *V) {
1665  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1666  }
1667 
1668  /// Updates profile metadata by scaling it by \p S / \p T.
1669  void updateProfWeight(uint64_t S, uint64_t T);
1670 
1671 private:
1672  // Shadow Instruction::setInstructionSubclassData with a private forwarding
1673  // method so that subclasses cannot accidentally use it.
1674  void setInstructionSubclassData(unsigned short D) {
1676  }
1677 };
1678 
1679 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1680  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1681  BasicBlock *InsertAtEnd)
1684  (Args.size() + CountBundleInputs(Bundles) + 1),
1685  unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1686  InsertAtEnd) {
1687  init(Ty, Func, Args, Bundles, NameStr);
1688 }
1689 
1690 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1691  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1692  Instruction *InsertBefore)
1695  (Args.size() + CountBundleInputs(Bundles) + 1),
1696  unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1697  InsertBefore) {
1698  init(Ty, Func, Args, Bundles, NameStr);
1699 }
1700 
1701 //===----------------------------------------------------------------------===//
1702 // SelectInst Class
1703 //===----------------------------------------------------------------------===//
1704 
1705 /// This class represents the LLVM 'select' instruction.
1706 ///
1707 class SelectInst : public Instruction {
1708  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1709  Instruction *InsertBefore)
1711  &Op<0>(), 3, InsertBefore) {
1712  init(C, S1, S2);
1713  setName(NameStr);
1714  }
1715 
1716  SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1717  BasicBlock *InsertAtEnd)
1719  &Op<0>(), 3, InsertAtEnd) {
1720  init(C, S1, S2);
1721  setName(NameStr);
1722  }
1723 
1724  void init(Value *C, Value *S1, Value *S2) {
1725  assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1726  Op<0>() = C;
1727  Op<1>() = S1;
1728  Op<2>() = S2;
1729  }
1730 
1731 protected:
1732  // Note: Instruction needs to be a friend here to call cloneImpl.
1733  friend class Instruction;
1734 
1735  SelectInst *cloneImpl() const;
1736 
1737 public:
1738  static SelectInst *Create(Value *C, Value *S1, Value *S2,
1739  const Twine &NameStr = "",
1740  Instruction *InsertBefore = nullptr,
1741  Instruction *MDFrom = nullptr) {
1742  SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1743  if (MDFrom)
1744  Sel->copyMetadata(*MDFrom);
1745  return Sel;
1746  }
1747 
1748  static SelectInst *Create(Value *C, Value *S1, Value *S2,
1749  const Twine &NameStr,
1750  BasicBlock *InsertAtEnd) {
1751  return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1752  }
1753 
1754  const Value *getCondition() const { return Op<0>(); }
1755  const Value *getTrueValue() const { return Op<1>(); }
1756  const Value *getFalseValue() const { return Op<2>(); }
1757  Value *getCondition() { return Op<0>(); }
1758  Value *getTrueValue() { return Op<1>(); }
1759  Value *getFalseValue() { return Op<2>(); }
1760 
1761  void setCondition(Value *V) { Op<0>() = V; }
1762  void setTrueValue(Value *V) { Op<1>() = V; }
1763  void setFalseValue(Value *V) { Op<2>() = V; }
1764 
1765  /// Return a string if the specified operands are invalid
1766  /// for a select operation, otherwise return null.
1767  static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1768 
1769  /// Transparently provide more efficient getOperand methods.
1771 
1773  return static_cast<OtherOps>(Instruction::getOpcode());
1774  }
1775 
1776  // Methods for support type inquiry through isa, cast, and dyn_cast:
1777  static bool classof(const Instruction *I) {
1778  return I->getOpcode() == Instruction::Select;
1779  }
1780  static bool classof(const Value *V) {
1781  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1782  }
1783 };
1784 
1785 template <>
1786 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1787 };
1788 
1790 
1791 //===----------------------------------------------------------------------===//
1792 // VAArgInst Class
1793 //===----------------------------------------------------------------------===//
1794 
1795 /// This class represents the va_arg llvm instruction, which returns
1796 /// an argument of the specified type given a va_list and increments that list
1797 ///
1798 class VAArgInst : public UnaryInstruction {
1799 protected:
1800  // Note: Instruction needs to be a friend here to call cloneImpl.
1801  friend class Instruction;
1802 
1803  VAArgInst *cloneImpl() const;
1804 
1805 public:
1806  VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1807  Instruction *InsertBefore = nullptr)
1808  : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1809  setName(NameStr);
1810  }
1811 
1812  VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1813  BasicBlock *InsertAtEnd)
1814  : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1815  setName(NameStr);
1816  }
1817 
1819  const Value *getPointerOperand() const { return getOperand(0); }
1820  static unsigned getPointerOperandIndex() { return 0U; }
1821 
1822  // Methods for support type inquiry through isa, cast, and dyn_cast:
1823  static bool classof(const Instruction *I) {
1824  return I->getOpcode() == VAArg;
1825  }
1826  static bool classof(const Value *V) {
1827  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1828  }
1829 };
1830 
1831 //===----------------------------------------------------------------------===//
1832 // ExtractElementInst Class
1833 //===----------------------------------------------------------------------===//
1834 
1835 /// This instruction extracts a single (scalar)
1836 /// element from a VectorType value
1837 ///
1839  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1840  Instruction *InsertBefore = nullptr);
1841  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1842  BasicBlock *InsertAtEnd);
1843 
1844 protected:
1845  // Note: Instruction needs to be a friend here to call cloneImpl.
1846  friend class Instruction;
1847 
1848  ExtractElementInst *cloneImpl() const;
1849 
1850 public:
1851  static ExtractElementInst *Create(Value *Vec, Value *Idx,
1852  const Twine &NameStr = "",
1853  Instruction *InsertBefore = nullptr) {
1854  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1855  }
1856 
1857  static ExtractElementInst *Create(Value *Vec, Value *Idx,
1858  const Twine &NameStr,
1859  BasicBlock *InsertAtEnd) {
1860  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1861  }
1862 
1863  /// Return true if an extractelement instruction can be
1864  /// formed with the specified operands.
1865  static bool isValidOperands(const Value *Vec, const Value *Idx);
1866 
1867  Value *getVectorOperand() { return Op<0>(); }
1868  Value *getIndexOperand() { return Op<1>(); }
1869  const Value *getVectorOperand() const { return Op<0>(); }
1870  const Value *getIndexOperand() const { return Op<1>(); }
1871 
1873  return cast<VectorType>(getVectorOperand()->getType());
1874  }
1875 
1876  /// Transparently provide more efficient getOperand methods.
1878 
1879  // Methods for support type inquiry through isa, cast, and dyn_cast:
1880  static bool classof(const Instruction *I) {
1881  return I->getOpcode() == Instruction::ExtractElement;
1882  }
1883  static bool classof(const Value *V) {
1884  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1885  }
1886 };
1887 
1888 template <>
1890  public FixedNumOperandTraits<ExtractElementInst, 2> {
1891 };
1892 
1893 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1894 
1895 //===----------------------------------------------------------------------===//
1896 // InsertElementInst Class
1897 //===----------------------------------------------------------------------===//
1898 
1899 /// This instruction inserts a single (scalar)
1900 /// element into a VectorType value
1901 ///
1903  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1904  const Twine &NameStr = "",
1905  Instruction *InsertBefore = nullptr);
1906  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1907  BasicBlock *InsertAtEnd);
1908 
1909 protected:
1910  // Note: Instruction needs to be a friend here to call cloneImpl.
1911  friend class Instruction;
1912 
1913  InsertElementInst *cloneImpl() const;
1914 
1915 public:
1916  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1917  const Twine &NameStr = "",
1918  Instruction *InsertBefore = nullptr) {
1919  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1920  }
1921 
1922  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1923  const Twine &NameStr,
1924  BasicBlock *InsertAtEnd) {
1925  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1926  }
1927 
1928  /// Return true if an insertelement instruction can be
1929  /// formed with the specified operands.
1930  static bool isValidOperands(const Value *Vec, const Value *NewElt,
1931  const Value *Idx);
1932 
1933  /// Overload to return most specific vector type.
1934  ///
1935  VectorType *getType() const {
1936  return cast<VectorType>(Instruction::getType());
1937  }
1938 
1939  /// Transparently provide more efficient getOperand methods.
1941 
1942  // Methods for support type inquiry through isa, cast, and dyn_cast:
1943  static bool classof(const Instruction *I) {
1944  return I->getOpcode() == Instruction::InsertElement;
1945  }
1946  static bool classof(const Value *V) {
1947  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1948  }
1949 };
1950 
1951 template <>
1953  public FixedNumOperandTraits<InsertElementInst, 3> {
1954 };
1955 
1956 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1957 
1958 //===----------------------------------------------------------------------===//
1959 // ShuffleVectorInst Class
1960 //===----------------------------------------------------------------------===//
1961 
1962 /// This instruction constructs a fixed permutation of two
1963 /// input vectors.
1964 ///
1966 protected:
1967  // Note: Instruction needs to be a friend here to call cloneImpl.
1968  friend class Instruction;
1969 
1970  ShuffleVectorInst *cloneImpl() const;
1971 
1972 public:
1974  const Twine &NameStr = "",
1975  Instruction *InsertBefor = nullptr);
1977  const Twine &NameStr, BasicBlock *InsertAtEnd);
1978 
1979  // allocate space for exactly three operands
1980  void *operator new(size_t s) {
1981  return User::operator new(s, 3);
1982  }
1983 
1984  /// Swap the first 2 operands and adjust the mask to preserve the semantics
1985  /// of the instruction.
1986  void commute();
1987 
1988  /// Return true if a shufflevector instruction can be
1989  /// formed with the specified operands.
1990  static bool isValidOperands(const Value *V1, const Value *V2,
1991  const Value *Mask);
1992 
1993  /// Overload to return most specific vector type.
1994  ///
1995  VectorType *getType() const {
1996  return cast<VectorType>(Instruction::getType());
1997  }
1998 
1999  /// Transparently provide more efficient getOperand methods.
2001 
2002  Constant *getMask() const {
2003  return cast<Constant>(getOperand(2));
2004  }
2005 
2006  /// Return the shuffle mask value for the specified element of the mask.
2007  /// Return -1 if the element is undef.
2008  static int getMaskValue(const Constant *Mask, unsigned Elt);
2009 
2010  /// Return the shuffle mask value of this instruction for the given element
2011  /// index. Return -1 if the element is undef.
2012  int getMaskValue(unsigned Elt) const {
2013  return getMaskValue(getMask(), Elt);
2014  }
2015 
2016  /// Convert the input shuffle mask operand to a vector of integers. Undefined
2017  /// elements of the mask are returned as -1.
2018  static void getShuffleMask(const Constant *Mask,
2019  SmallVectorImpl<int> &Result);
2020 
2021  /// Return the mask for this instruction as a vector of integers. Undefined
2022  /// elements of the mask are returned as -1.
2023  void getShuffleMask(SmallVectorImpl<int> &Result) const {
2024  return getShuffleMask(getMask(), Result);
2025  }
2026 
2029  getShuffleMask(Mask);
2030  return Mask;
2031  }
2032 
2033  /// Return true if this shuffle returns a vector with a different number of
2034  /// elements than its source vectors.
2035  /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2036  /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2037  bool changesLength() const {
2038  unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2039  unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2040  return NumSourceElts != NumMaskElts;
2041  }
2042 
2043  /// Return true if this shuffle returns a vector with a greater number of
2044  /// elements than its source vectors.
2045  /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2046  bool increasesLength() const {
2047  unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2048  unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2049  return NumSourceElts < NumMaskElts;
2050  }
2051 
2052  /// Return true if this shuffle mask chooses elements from exactly one source
2053  /// vector.
2054  /// Example: <7,5,undef,7>
2055  /// This assumes that vector operands are the same length as the mask.
2056  static bool isSingleSourceMask(ArrayRef<int> Mask);
2057  static bool isSingleSourceMask(const Constant *Mask) {
2058  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2059  SmallVector<int, 16> MaskAsInts;
2060  getShuffleMask(Mask, MaskAsInts);
2061  return isSingleSourceMask(MaskAsInts);
2062  }
2063 
2064  /// Return true if this shuffle chooses elements from exactly one source
2065  /// vector without changing the length of that vector.
2066  /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2067  /// TODO: Optionally allow length-changing shuffles.
2068  bool isSingleSource() const {
2069  return !changesLength() && isSingleSourceMask(getMask());
2070  }
2071 
2072  /// Return true if this shuffle mask chooses elements from exactly one source
2073  /// vector without lane crossings. A shuffle using this mask is not
2074  /// necessarily a no-op because it may change the number of elements from its
2075  /// input vectors or it may provide demanded bits knowledge via undef lanes.
2076  /// Example: <undef,undef,2,3>
2077  static bool isIdentityMask(ArrayRef<int> Mask);
2078  static bool isIdentityMask(const Constant *Mask) {
2079  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2080  SmallVector<int, 16> MaskAsInts;
2081  getShuffleMask(Mask, MaskAsInts);
2082  return isIdentityMask(MaskAsInts);
2083  }
2084 
2085  /// Return true if this shuffle chooses elements from exactly one source
2086  /// vector without lane crossings and does not change the number of elements
2087  /// from its input vectors.
2088  /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2089  bool isIdentity() const {
2090  return !changesLength() && isIdentityMask(getShuffleMask());
2091  }
2092 
2093  /// Return true if this shuffle lengthens exactly one source vector with
2094  /// undefs in the high elements.
2095  bool isIdentityWithPadding() const;
2096 
2097  /// Return true if this shuffle extracts the first N elements of exactly one
2098  /// source vector.
2099  bool isIdentityWithExtract() const;
2100 
2101  /// Return true if this shuffle concatenates its 2 source vectors. This
2102  /// returns false if either input is undefined. In that case, the shuffle is
2103  /// is better classified as an identity with padding operation.
2104  bool isConcat() const;
2105 
2106  /// Return true if this shuffle mask chooses elements from its source vectors
2107  /// without lane crossings. A shuffle using this mask would be
2108  /// equivalent to a vector select with a constant condition operand.
2109  /// Example: <4,1,6,undef>
2110  /// This returns false if the mask does not choose from both input vectors.
2111  /// In that case, the shuffle is better classified as an identity shuffle.
2112  /// This assumes that vector operands are the same length as the mask
2113  /// (a length-changing shuffle can never be equivalent to a vector select).
2114  static bool isSelectMask(ArrayRef<int> Mask);
2115  static bool isSelectMask(const Constant *Mask) {
2116  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2117  SmallVector<int, 16> MaskAsInts;
2118  getShuffleMask(Mask, MaskAsInts);
2119  return isSelectMask(MaskAsInts);
2120  }
2121 
2122  /// Return true if this shuffle chooses elements from its source vectors
2123  /// without lane crossings and all operands have the same number of elements.
2124  /// In other words, this shuffle is equivalent to a vector select with a
2125  /// constant condition operand.
2126  /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2127  /// This returns false if the mask does not choose from both input vectors.
2128  /// In that case, the shuffle is better classified as an identity shuffle.
2129  /// TODO: Optionally allow length-changing shuffles.
2130  bool isSelect() const {
2131  return !changesLength() && isSelectMask(getMask());
2132  }
2133 
2134  /// Return true if this shuffle mask swaps the order of elements from exactly
2135  /// one source vector.
2136  /// Example: <7,6,undef,4>
2137  /// This assumes that vector operands are the same length as the mask.
2138  static bool isReverseMask(ArrayRef<int> Mask);
2139  static bool isReverseMask(const Constant *Mask) {
2140  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2141  SmallVector<int, 16> MaskAsInts;
2142  getShuffleMask(Mask, MaskAsInts);
2143  return isReverseMask(MaskAsInts);
2144  }
2145 
2146  /// Return true if this shuffle swaps the order of elements from exactly
2147  /// one source vector.
2148  /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2149  /// TODO: Optionally allow length-changing shuffles.
2150  bool isReverse() const {
2151  return !changesLength() && isReverseMask(getMask());
2152  }
2153 
2154  /// Return true if this shuffle mask chooses all elements with the same value
2155  /// as the first element of exactly one source vector.
2156  /// Example: <4,undef,undef,4>
2157  /// This assumes that vector operands are the same length as the mask.
2158  static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2159  static bool isZeroEltSplatMask(const Constant *Mask) {
2160  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2161  SmallVector<int, 16> MaskAsInts;
2162  getShuffleMask(Mask, MaskAsInts);
2163  return isZeroEltSplatMask(MaskAsInts);
2164  }
2165 
2166  /// Return true if all elements of this shuffle are the same value as the
2167  /// first element of exactly one source vector without changing the length
2168  /// of that vector.
2169  /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2170  /// TODO: Optionally allow length-changing shuffles.
2171  /// TODO: Optionally allow splats from other elements.
2172  bool isZeroEltSplat() const {
2173  return !changesLength() && isZeroEltSplatMask(getMask());
2174  }
2175 
2176  /// Return true if this shuffle mask is a transpose mask.
2177  /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2178  /// even- or odd-numbered vector elements from two n-dimensional source
2179  /// vectors and write each result into consecutive elements of an
2180  /// n-dimensional destination vector. Two shuffles are necessary to complete
2181  /// the transpose, one for the even elements and another for the odd elements.
2182  /// This description closely follows how the TRN1 and TRN2 AArch64
2183  /// instructions operate.
2184  ///
2185  /// For example, a simple 2x2 matrix can be transposed with:
2186  ///
2187  /// ; Original matrix
2188  /// m0 = < a, b >
2189  /// m1 = < c, d >
2190  ///
2191  /// ; Transposed matrix
2192  /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2193  /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2194  ///
2195  /// For matrices having greater than n columns, the resulting nx2 transposed
2196  /// matrix is stored in two result vectors such that one vector contains
2197  /// interleaved elements from all the even-numbered rows and the other vector
2198  /// contains interleaved elements from all the odd-numbered rows. For example,
2199  /// a 2x4 matrix can be transposed with:
2200  ///
2201  /// ; Original matrix
2202  /// m0 = < a, b, c, d >
2203  /// m1 = < e, f, g, h >
2204  ///
2205  /// ; Transposed matrix
2206  /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2207  /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2208  static bool isTransposeMask(ArrayRef<int> Mask);
2209  static bool isTransposeMask(const Constant *Mask) {
2210  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2211  SmallVector<int, 16> MaskAsInts;
2212  getShuffleMask(Mask, MaskAsInts);
2213  return isTransposeMask(MaskAsInts);
2214  }
2215 
2216  /// Return true if this shuffle transposes the elements of its inputs without
2217  /// changing the length of the vectors. This operation may also be known as a
2218  /// merge or interleave. See the description for isTransposeMask() for the
2219  /// exact specification.
2220  /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2221  bool isTranspose() const {
2222  return !changesLength() && isTransposeMask(getMask());
2223  }
2224 
2225  /// Return true if this shuffle mask is an extract subvector mask.
2226  /// A valid extract subvector mask returns a smaller vector from a single
2227  /// source operand. The base extraction index is returned as well.
2228  static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2229  int &Index);
2230  static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2231  int &Index) {
2232  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2233  SmallVector<int, 16> MaskAsInts;
2234  getShuffleMask(Mask, MaskAsInts);
2235  return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2236  }
2237 
2238  /// Return true if this shuffle mask is an extract subvector mask.
2239  bool isExtractSubvectorMask(int &Index) const {
2240  int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2241  return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2242  }
2243 
2244  /// Change values in a shuffle permute mask assuming the two vector operands
2245  /// of length InVecNumElts have swapped position.
2247  unsigned InVecNumElts) {
2248  for (int &Idx : Mask) {
2249  if (Idx == -1)
2250  continue;
2251  Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2252  assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2253  "shufflevector mask index out of range");
2254  }
2255  }
2256 
2257  // Methods for support type inquiry through isa, cast, and dyn_cast:
2258  static bool classof(const Instruction *I) {
2259  return I->getOpcode() == Instruction::ShuffleVector;
2260  }
2261  static bool classof(const Value *V) {
2262  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2263  }
2264 };
2265 
2266 template <>
2268  public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2269 };
2270 
2271 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2272 
2273 //===----------------------------------------------------------------------===//
2274 // ExtractValueInst Class
2275 //===----------------------------------------------------------------------===//
2276 
2277 /// This instruction extracts a struct member or array
2278 /// element value from an aggregate value.
2279 ///
2281  SmallVector<unsigned, 4> Indices;
2282 
2283  ExtractValueInst(const ExtractValueInst &EVI);
2284 
2285  /// Constructors - Create a extractvalue instruction with a base aggregate
2286  /// value and a list of indices. The first ctor can optionally insert before
2287  /// an existing instruction, the second appends the new instruction to the
2288  /// specified BasicBlock.
2289  inline ExtractValueInst(Value *Agg,
2290  ArrayRef<unsigned> Idxs,
2291  const Twine &NameStr,
2292  Instruction *InsertBefore);
2293  inline ExtractValueInst(Value *Agg,
2294  ArrayRef<unsigned> Idxs,
2295  const Twine &NameStr, BasicBlock *InsertAtEnd);
2296 
2297  void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2298 
2299 protected:
2300  // Note: Instruction needs to be a friend here to call cloneImpl.
2301  friend class Instruction;
2302 
2303  ExtractValueInst *cloneImpl() const;
2304 
2305 public:
2307  ArrayRef<unsigned> Idxs,
2308  const Twine &NameStr = "",
2309  Instruction *InsertBefore = nullptr) {
2310  return new
2311  ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2312  }
2313 
2315  ArrayRef<unsigned> Idxs,
2316  const Twine &NameStr,
2317  BasicBlock *InsertAtEnd) {
2318  return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2319  }
2320 
2321  /// Returns the type of the element that would be extracted
2322  /// with an extractvalue instruction with the specified parameters.
2323  ///
2324  /// Null is returned if the indices are invalid for the specified type.
2325  static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2326 
2327  using idx_iterator = const unsigned*;
2328 
2329  inline idx_iterator idx_begin() const { return Indices.begin(); }
2330  inline idx_iterator idx_end() const { return Indices.end(); }
2332  return make_range(idx_begin(), idx_end());
2333  }
2334 
2336  return getOperand(0);
2337  }
2338  const Value *getAggregateOperand() const {
2339  return getOperand(0);
2340  }
2341  static unsigned getAggregateOperandIndex() {
2342  return 0U; // get index for modifying correct operand
2343  }
2344 
2346  return Indices;
2347  }
2348 
2349  unsigned getNumIndices() const {
2350  return (unsigned)Indices.size();
2351  }
2352 
2353  bool hasIndices() const {
2354  return true;
2355  }
2356 
2357  // Methods for support type inquiry through isa, cast, and dyn_cast:
2358  static bool classof(const Instruction *I) {
2359  return I->getOpcode() == Instruction::ExtractValue;
2360  }
2361  static bool classof(const Value *V) {
2362  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2363  }
2364 };
2365 
2366 ExtractValueInst::ExtractValueInst(Value *Agg,
2367  ArrayRef<unsigned> Idxs,
2368  const Twine &NameStr,
2369  Instruction *InsertBefore)
2370  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2371  ExtractValue, Agg, InsertBefore) {
2372  init(Idxs, NameStr);
2373 }
2374 
2375 ExtractValueInst::ExtractValueInst(Value *Agg,
2376  ArrayRef<unsigned> Idxs,
2377  const Twine &NameStr,
2378  BasicBlock *InsertAtEnd)
2379  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2380  ExtractValue, Agg, InsertAtEnd) {
2381  init(Idxs, NameStr);
2382 }
2383 
2384 //===----------------------------------------------------------------------===//
2385 // InsertValueInst Class
2386 //===----------------------------------------------------------------------===//
2387 
2388 /// This instruction inserts a struct field of array element
2389 /// value into an aggregate value.
2390 ///
2392  SmallVector<unsigned, 4> Indices;
2393 
2394  InsertValueInst(const InsertValueInst &IVI);
2395 
2396  /// Constructors - Create a insertvalue instruction with a base aggregate
2397  /// value, a value to insert, and a list of indices. The first ctor can
2398  /// optionally insert before an existing instruction, the second appends
2399  /// the new instruction to the specified BasicBlock.
2400  inline InsertValueInst(Value *Agg, Value *Val,
2401  ArrayRef<unsigned> Idxs,
2402  const Twine &NameStr,
2403  Instruction *InsertBefore);
2404  inline InsertValueInst(Value *Agg, Value *Val,
2405  ArrayRef<unsigned> Idxs,
2406  const Twine &NameStr, BasicBlock *InsertAtEnd);
2407 
2408  /// Constructors - These two constructors are convenience methods because one
2409  /// and two index insertvalue instructions are so common.
2410  InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2411  const Twine &NameStr = "",
2412  Instruction *InsertBefore = nullptr);
2413  InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2414  BasicBlock *InsertAtEnd);
2415 
2416  void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2417  const Twine &NameStr);
2418 
2419 protected:
2420  // Note: Instruction needs to be a friend here to call cloneImpl.
2421  friend class Instruction;
2422 
2423  InsertValueInst *cloneImpl() const;
2424 
2425 public:
2426  // allocate space for exactly two operands
2427  void *operator new(size_t s) {
2428  return User::operator new(s, 2);
2429  }
2430 
2431  static InsertValueInst *Create(Value *Agg, Value *Val,
2432  ArrayRef<unsigned> Idxs,
2433  const Twine &NameStr = "",
2434  Instruction *InsertBefore = nullptr) {
2435  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2436  }
2437 
2438  static InsertValueInst *Create(Value *Agg, Value *Val,
2439  ArrayRef<unsigned> Idxs,
2440  const Twine &NameStr,
2441  BasicBlock *InsertAtEnd) {
2442  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2443  }
2444 
2445  /// Transparently provide more efficient getOperand methods.
2447 
2448  using idx_iterator = const unsigned*;
2449 
2450  inline idx_iterator idx_begin() const { return Indices.begin(); }
2451  inline idx_iterator idx_end() const { return Indices.end(); }
2453  return make_range(idx_begin(), idx_end());
2454  }
2455 
2457  return getOperand(0);
2458  }
2459  const Value *getAggregateOperand() const {
2460  return getOperand(0);
2461  }
2462  static unsigned getAggregateOperandIndex() {
2463  return 0U; // get index for modifying correct operand
2464  }
2465 
2467  return getOperand(1);
2468  }
2470  return getOperand(1);
2471  }
2472  static unsigned getInsertedValueOperandIndex() {
2473  return 1U; // get index for modifying correct operand
2474  }
2475 
2477  return Indices;
2478  }
2479 
2480  unsigned getNumIndices() const {
2481  return (unsigned)Indices.size();
2482  }
2483 
2484  bool hasIndices() const {
2485  return true;
2486  }
2487 
2488  // Methods for support type inquiry through isa, cast, and dyn_cast:
2489  static bool classof(const Instruction *I) {
2490  return I->getOpcode() == Instruction::InsertValue;
2491  }
2492  static bool classof(const Value *V) {
2493  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2494  }
2495 };
2496 
2497 template <>
2499  public FixedNumOperandTraits<InsertValueInst, 2> {
2500 };
2501 
2502 InsertValueInst::InsertValueInst(Value *Agg,
2503  Value *Val,
2504  ArrayRef<unsigned> Idxs,
2505  const Twine &NameStr,
2506  Instruction *InsertBefore)
2507  : Instruction(Agg->getType(), InsertValue,
2509  2, InsertBefore) {
2510  init(Agg, Val, Idxs, NameStr);
2511 }
2512 
2513 InsertValueInst::InsertValueInst(Value *Agg,
2514  Value *Val,
2515  ArrayRef<unsigned> Idxs,
2516  const Twine &NameStr,
2517  BasicBlock *InsertAtEnd)
2518  : Instruction(Agg->getType(), InsertValue,
2520  2, InsertAtEnd) {
2521  init(Agg, Val, Idxs, NameStr);
2522 }
2523 
2525 
2526 //===----------------------------------------------------------------------===//
2527 // PHINode Class
2528 //===----------------------------------------------------------------------===//
2529 
2530 // PHINode - The PHINode class is used to represent the magical mystical PHI
2531 // node, that can not exist in nature, but can be synthesized in a computer
2532 // scientist's overactive imagination.
2533 //
2534 class PHINode : public Instruction {
2535  /// The number of operands actually allocated. NumOperands is
2536  /// the number actually in use.
2537  unsigned ReservedSpace;
2538 
2539  PHINode(const PHINode &PN);
2540 
2541  explicit PHINode(Type *Ty, unsigned NumReservedValues,
2542  const Twine &NameStr = "",
2543  Instruction *InsertBefore = nullptr)
2544  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2545  ReservedSpace(NumReservedValues) {
2546  setName(NameStr);
2547  allocHungoffUses(ReservedSpace);
2548  }
2549 
2550  PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2551  BasicBlock *InsertAtEnd)
2552  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2553  ReservedSpace(NumReservedValues) {
2554  setName(NameStr);
2555  allocHungoffUses(ReservedSpace);
2556  }
2557 
2558 protected:
2559  // Note: Instruction needs to be a friend here to call cloneImpl.
2560  friend class Instruction;
2561 
2562  PHINode *cloneImpl() const;
2563 
2564  // allocHungoffUses - this is more complicated than the generic
2565  // User::allocHungoffUses, because we have to allocate Uses for the incoming
2566  // values and pointers to the incoming blocks, all in one allocation.
2567  void allocHungoffUses(unsigned N) {
2568  User::allocHungoffUses(N, /* IsPhi */ true);
2569  }
2570 
2571 public:
2572  /// Constructors - NumReservedValues is a hint for the number of incoming
2573  /// edges that this phi node will have (use 0 if you really have no idea).
2574  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2575  const Twine &NameStr = "",
2576  Instruction *InsertBefore = nullptr) {
2577  return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2578  }
2579 
2580  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2581  const Twine &NameStr, BasicBlock *InsertAtEnd) {
2582  return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2583  }
2584 
2585  /// Provide fast operand accessors
2587 
2588  // Block iterator interface. This provides access to the list of incoming
2589  // basic blocks, which parallels the list of incoming values.
2590 
2593 
2595  Use::UserRef *ref =
2596  reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2597  return reinterpret_cast<block_iterator>(ref + 1);
2598  }
2599 
2601  const Use::UserRef *ref =
2602  reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2603  return reinterpret_cast<const_block_iterator>(ref + 1);
2604  }
2605 
2607  return block_begin() + getNumOperands();
2608  }
2609 
2611  return block_begin() + getNumOperands();
2612  }
2613 
2615  return make_range(block_begin(), block_end());
2616  }
2617 
2619  return make_range(block_begin(), block_end());
2620  }
2621 
2623 
2625 
2626  /// Return the number of incoming edges
2627  ///
2628  unsigned getNumIncomingValues() const { return getNumOperands(); }
2629 
2630  /// Return incoming value number x
2631  ///
2632  Value *getIncomingValue(unsigned i) const {
2633  return getOperand(i);
2634  }
2635  void setIncomingValue(unsigned i, Value *V) {
2636  assert(V && "PHI node got a null value!");
2637  assert(getType() == V->getType() &&
2638  "All operands to PHI node must be the same type as the PHI node!");
2639  setOperand(i, V);
2640  }
2641 
2642  static unsigned getOperandNumForIncomingValue(unsigned i) {
2643  return i;
2644  }
2645 
2646  static unsigned getIncomingValueNumForOperand(unsigned i) {
2647  return i;
2648  }
2649 
2650  /// Return incoming basic block number @p i.
2651  ///
2652  BasicBlock *getIncomingBlock(unsigned i) const {
2653  return block_begin()[i];
2654  }
2655 
2656  /// Return incoming basic block corresponding
2657  /// to an operand of the PHI.
2658  ///
2659  BasicBlock *getIncomingBlock(const Use &U) const {
2660  assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2661  return getIncomingBlock(unsigned(&U - op_begin()));
2662  }
2663 
2664  /// Return incoming basic block corresponding
2665  /// to value use iterator.
2666  ///
2668  return getIncomingBlock(I.getUse());
2669  }
2670 
2671  void setIncomingBlock(unsigned i, BasicBlock *BB) {
2672  assert(BB && "PHI node got a null basic block!");
2673  block_begin()[i] = BB;
2674  }
2675 
2676  /// Replace every incoming basic block \p Old to basic block \p New.
2678  assert(New && Old && "PHI node got a null basic block!");
2679  for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2680  if (getIncomingBlock(Op) == Old)
2681  setIncomingBlock(Op, New);
2682  }
2683 
2684  /// Add an incoming value to the end of the PHI list
2685  ///
2686  void addIncoming(Value *V, BasicBlock *BB) {
2687  if (getNumOperands() == ReservedSpace)
2688  growOperands(); // Get more space!
2689  // Initialize some new operands.
2691  setIncomingValue(getNumOperands() - 1, V);
2692  setIncomingBlock(getNumOperands() - 1, BB);
2693  }
2694 
2695  /// Remove an incoming value. This is useful if a
2696  /// predecessor basic block is deleted. The value removed is returned.
2697  ///
2698  /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2699  /// is true), the PHI node is destroyed and any uses of it are replaced with
2700  /// dummy values. The only time there should be zero incoming values to a PHI
2701  /// node is when the block is dead, so this strategy is sound.
2702  ///
2703  Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2704 
2705  Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2706  int Idx = getBasicBlockIndex(BB);
2707  assert(Idx >= 0 && "Invalid basic block argument to remove!");
2708  return removeIncomingValue(Idx, DeletePHIIfEmpty);
2709  }
2710 
2711  /// Return the first index of the specified basic
2712  /// block in the value list for this PHI. Returns -1 if no instance.
2713  ///
2714  int getBasicBlockIndex(const BasicBlock *BB) const {
2715  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2716  if (block_begin()[i] == BB)
2717  return i;
2718  return -1;
2719  }
2720 
2722  int Idx = getBasicBlockIndex(BB);
2723  assert(Idx >= 0 && "Invalid basic block argument!");
2724  return getIncomingValue(Idx);
2725  }
2726 
2727  /// If the specified PHI node always merges together the
2728  /// same value, return the value, otherwise return null.
2729  Value *hasConstantValue() const;
2730 
2731  /// Whether the specified PHI node always merges
2732  /// together the same value, assuming undefs are equal to a unique
2733  /// non-undef value.
2734  bool hasConstantOrUndefValue() const;
2735 
2736  /// Methods for support type inquiry through isa, cast, and dyn_cast:
2737  static bool classof(const Instruction *I) {
2738  return I->getOpcode() == Instruction::PHI;
2739  }
2740  static bool classof(const Value *V) {
2741  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2742  }
2743 
2744 private:
2745  void growOperands();
2746 };
2747 
2748 template <>
2750 };
2751 
2753 
2754 //===----------------------------------------------------------------------===//
2755 // LandingPadInst Class
2756 //===----------------------------------------------------------------------===//
2757 
2758 //===---------------------------------------------------------------------------
2759 /// The landingpad instruction holds all of the information
2760 /// necessary to generate correct exception handling. The landingpad instruction
2761 /// cannot be moved from the top of a landing pad block, which itself is
2762 /// accessible only from the 'unwind' edge of an invoke. This uses the
2763 /// SubclassData field in Value to store whether or not the landingpad is a
2764 /// cleanup.
2765 ///
2766 class LandingPadInst : public Instruction {
2767  /// The number of operands actually allocated. NumOperands is
2768  /// the number actually in use.
2769  unsigned ReservedSpace;
2770 
2771  LandingPadInst(const LandingPadInst &LP);
2772 
2773 public:
2775 
2776 private:
2777  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2778  const Twine &NameStr, Instruction *InsertBefore);
2779  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2780  const Twine &NameStr, BasicBlock *InsertAtEnd);
2781 
2782  // Allocate space for exactly zero operands.
2783  void *operator new(size_t s) {
2784  return User::operator new(s);
2785  }
2786 
2787  void growOperands(unsigned Size);
2788  void init(unsigned NumReservedValues, const Twine &NameStr);
2789 
2790 protected:
2791  // Note: Instruction needs to be a friend here to call cloneImpl.
2792  friend class Instruction;
2793 
2794  LandingPadInst *cloneImpl() const;
2795 
2796 public:
2797  /// Constructors - NumReservedClauses is a hint for the number of incoming
2798  /// clauses that this landingpad will have (use 0 if you really have no idea).
2799  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2800  const Twine &NameStr = "",
2801  Instruction *InsertBefore = nullptr);
2802  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2803  const Twine &NameStr, BasicBlock *InsertAtEnd);
2804 
2805  /// Provide fast operand accessors
2807 
2808  /// Return 'true' if this landingpad instruction is a
2809  /// cleanup. I.e., it should be run when unwinding even if its landing pad
2810  /// doesn't catch the exception.
2811  bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2812 
2813  /// Indicate that this landingpad instruction is a cleanup.
2814  void setCleanup(bool V) {
2815  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2816  (V ? 1 : 0));
2817  }
2818 
2819  /// Add a catch or filter clause to the landing pad.
2820  void addClause(Constant *ClauseVal);
2821 
2822  /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2823  /// determine what type of clause this is.
2824  Constant *getClause(unsigned Idx) const {
2825  return cast<Constant>(getOperandList()[Idx]);
2826  }
2827 
2828  /// Return 'true' if the clause and index Idx is a catch clause.
2829  bool isCatch(unsigned Idx) const {
2830  return !isa<ArrayType>(getOperandList()[Idx]->getType());
2831  }
2832 
2833  /// Return 'true' if the clause and index Idx is a filter clause.
2834  bool isFilter(unsigned Idx) const {
2835  return isa<ArrayType>(getOperandList()[Idx]->getType());
2836  }
2837 
2838  /// Get the number of clauses for this landing pad.
2839  unsigned getNumClauses() const { return getNumOperands(); }
2840 
2841  /// Grow the size of the operand list to accommodate the new
2842  /// number of clauses.
2843  void reserveClauses(unsigned Size) { growOperands(Size); }
2844 
2845  // Methods for support type inquiry through isa, cast, and dyn_cast:
2846  static bool classof(const Instruction *I) {
2847  return I->getOpcode() == Instruction::LandingPad;
2848  }
2849  static bool classof(const Value *V) {
2850  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2851  }
2852 };
2853 
2854 template <>
2856 };
2857 
2859 
2860 //===----------------------------------------------------------------------===//
2861 // ReturnInst Class
2862 //===----------------------------------------------------------------------===//
2863 
2864 //===---------------------------------------------------------------------------
2865 /// Return a value (possibly void), from a function. Execution
2866 /// does not continue in this function any longer.
2867 ///
2868 class ReturnInst : public Instruction {
2869  ReturnInst(const ReturnInst &RI);
2870 
2871 private:
2872  // ReturnInst constructors:
2873  // ReturnInst() - 'ret void' instruction
2874  // ReturnInst( null) - 'ret void' instruction
2875  // ReturnInst(Value* X) - 'ret X' instruction
2876  // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2877  // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2878  // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2879  // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2880  //
2881  // NOTE: If the Value* passed is of type void then the constructor behaves as
2882  // if it was passed NULL.
2883  explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2884  Instruction *InsertBefore = nullptr);
2885  ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2886  explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2887 
2888 protected:
2889  // Note: Instruction needs to be a friend here to call cloneImpl.
2890  friend class Instruction;
2891 
2892  ReturnInst *cloneImpl() const;
2893 
2894 public:
2895  static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2896  Instruction *InsertBefore = nullptr) {
2897  return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2898  }
2899 
2900  static ReturnInst* Create(LLVMContext &C, Value *retVal,
2901  BasicBlock *InsertAtEnd) {
2902  return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2903  }
2904 
2905  static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2906  return new(0) ReturnInst(C, InsertAtEnd);
2907  }
2908 
2909  /// Provide fast operand accessors
2911 
2912  /// Convenience accessor. Returns null if there is no return value.
2914  return getNumOperands() != 0 ? getOperand(0) : nullptr;
2915  }
2916 
2917  unsigned getNumSuccessors() const { return 0; }
2918 
2919  // Methods for support type inquiry through isa, cast, and dyn_cast:
2920  static bool classof(const Instruction *I) {
2921  return (I->getOpcode() == Instruction::Ret);
2922  }
2923  static bool classof(const Value *V) {
2924  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2925  }
2926 
2927 private:
2928  BasicBlock *getSuccessor(unsigned idx) const {
2929  llvm_unreachable("ReturnInst has no successors!");
2930  }
2931 
2932  void setSuccessor(unsigned idx, BasicBlock *B) {
2933  llvm_unreachable("ReturnInst has no successors!");
2934  }
2935 };
2936 
2937 template <>
2938 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2939 };
2940 
2942 
2943 //===----------------------------------------------------------------------===//
2944 // BranchInst Class
2945 //===----------------------------------------------------------------------===//
2946 
2947 //===---------------------------------------------------------------------------
2948 /// Conditional or Unconditional Branch instruction.
2949 ///
2950 class BranchInst : public Instruction {
2951  /// Ops list - Branches are strange. The operands are ordered:
2952  /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2953  /// they don't have to check for cond/uncond branchness. These are mostly
2954  /// accessed relative from op_end().
2955  BranchInst(const BranchInst &BI);
2956  // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2957  // BranchInst(BB *B) - 'br B'
2958  // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2959  // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2960  // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2961  // BranchInst(BB* B, BB *I) - 'br B' insert at end
2962  // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2963  explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2964  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2965  Instruction *InsertBefore = nullptr);
2966  BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2967  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2968  BasicBlock *InsertAtEnd);
2969 
2970  void AssertOK();
2971 
2972 protected:
2973  // Note: Instruction needs to be a friend here to call cloneImpl.
2974  friend class Instruction;
2975 
2976  BranchInst *cloneImpl() const;
2977 
2978 public:
2979  /// Iterator type that casts an operand to a basic block.
2980  ///
2981  /// This only makes sense because the successors are stored as adjacent
2982  /// operands for branch instructions.
2984  : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
2985  std::random_access_iterator_tag, BasicBlock *,
2986  ptrdiff_t, BasicBlock *, BasicBlock *> {
2988 
2989  BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
2990  BasicBlock *operator->() const { return operator*(); }
2991  };
2992 
2993  /// The const version of `succ_op_iterator`.
2995  : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
2996  std::random_access_iterator_tag,
2997  const BasicBlock *, ptrdiff_t, const BasicBlock *,
2998  const BasicBlock *> {
3000  : iterator_adaptor_base(I) {}
3001 
3002  const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3003  const BasicBlock *operator->() const { return operator*(); }
3004  };
3005 
3006  static BranchInst *Create(BasicBlock *IfTrue,
3007  Instruction *InsertBefore = nullptr) {
3008  return new(1) BranchInst(IfTrue, InsertBefore);
3009  }
3010 
3011  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3012  Value *Cond, Instruction *InsertBefore = nullptr) {
3013  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3014  }
3015 
3016  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3017  return new(1) BranchInst(IfTrue, InsertAtEnd);
3018  }
3019 
3020  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3021  Value *Cond, BasicBlock *InsertAtEnd) {
3022  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3023  }
3024 
3025  /// Transparently provide more efficient getOperand methods.
3027 
3028  bool isUnconditional() const { return getNumOperands() == 1; }
3029  bool isConditional() const { return getNumOperands() == 3; }
3030 
3031  Value *getCondition() const {
3032  assert(isConditional() && "Cannot get condition of an uncond branch!");
3033  return Op<-3>();
3034  }
3035 
3036  void setCondition(Value *V) {
3037  assert(isConditional() && "Cannot set condition of unconditional branch!");
3038  Op<-3>() = V;
3039  }
3040 
3041  unsigned getNumSuccessors() const { return 1+isConditional(); }
3042 
3043  BasicBlock *getSuccessor(unsigned i) const {
3044  assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3045  return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3046  }
3047 
3048  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3049  assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3050  *(&Op<-1>() - idx) = NewSucc;
3051  }
3052 
3053  /// Swap the successors of this branch instruction.
3054  ///
3055  /// Swaps the successors of the branch instruction. This also swaps any
3056  /// branch weight metadata associated with the instruction so that it
3057  /// continues to map correctly to each operand.
3058  void swapSuccessors();
3059 
3061  return make_range(
3062  succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3064  }
3065 
3068  std::next(value_op_begin(), isConditional() ? 1 : 0)),
3070  }
3071 
3072  // Methods for support type inquiry through isa, cast, and dyn_cast:
3073  static bool classof(const Instruction *I) {
3074  return (I->getOpcode() == Instruction::Br);
3075  }
3076  static bool classof(const Value *V) {
3077  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3078  }
3079 };
3080 
3081 template <>
3082 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3083 };
3084 
3086 
3087 //===----------------------------------------------------------------------===//
3088 // SwitchInst Class
3089 //===----------------------------------------------------------------------===//
3090 
3091 //===---------------------------------------------------------------------------
3092 /// Multiway switch
3093 ///
3094 class SwitchInst : public Instruction {
3095  unsigned ReservedSpace;
3096 
3097  // Operand[0] = Value to switch on
3098  // Operand[1] = Default basic block destination
3099  // Operand[2n ] = Value to match
3100  // Operand[2n+1] = BasicBlock to go to on match
3101  SwitchInst(const SwitchInst &SI);
3102 
3103  /// Create a new switch instruction, specifying a value to switch on and a
3104  /// default destination. The number of additional cases can be specified here
3105  /// to make memory allocation more efficient. This constructor can also
3106  /// auto-insert before another instruction.
3107  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3108  Instruction *InsertBefore);
3109 
3110  /// Create a new switch instruction, specifying a value to switch on and a
3111  /// default destination. The number of additional cases can be specified here
3112  /// to make memory allocation more efficient. This constructor also
3113  /// auto-inserts at the end of the specified BasicBlock.
3114  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3115  BasicBlock *InsertAtEnd);
3116 
3117  // allocate space for exactly zero operands
3118  void *operator new(size_t s) {
3119  return User::operator new(s);
3120  }
3121 
3122  void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3123  void growOperands();
3124 
3125 protected:
3126  // Note: Instruction needs to be a friend here to call cloneImpl.
3127  friend class Instruction;
3128 
3129  SwitchInst *cloneImpl() const;
3130 
3131 public:
3132  // -2
3133  static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3134 
3135  template <typename CaseHandleT> class CaseIteratorImpl;
3136 
3137  /// A handle to a particular switch case. It exposes a convenient interface
3138  /// to both the case value and the successor block.
3139  ///
3140  /// We define this as a template and instantiate it to form both a const and
3141  /// non-const handle.
3142  template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3144  // Directly befriend both const and non-const iterators.
3145  friend class SwitchInst::CaseIteratorImpl<
3146  CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3147 
3148  protected:
3149  // Expose the switch type we're parameterized with to the iterator.
3150  using SwitchInstType = SwitchInstT;
3151 
3152  SwitchInstT *SI;
3154 
3155  CaseHandleImpl() = default;
3156  CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3157 
3158  public:
3159  /// Resolves case value for current case.
3160  ConstantIntT *getCaseValue() const {
3161  assert((unsigned)Index < SI->getNumCases() &&
3162  "Index out the number of cases.");
3163  return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3164  }
3165 
3166  /// Resolves successor for current case.
3167  BasicBlockT *getCaseSuccessor() const {
3168  assert(((unsigned)Index < SI->getNumCases() ||
3169  (unsigned)Index == DefaultPseudoIndex) &&
3170  "Index out the number of cases.");
3171  return SI->getSuccessor(getSuccessorIndex());
3172  }
3173 
3174  /// Returns number of current case.
3175  unsigned getCaseIndex() const { return Index; }
3176 
3177  /// Returns successor index for current case successor.
3178  unsigned getSuccessorIndex() const {
3179  assert(((unsigned)Index == DefaultPseudoIndex ||
3180  (unsigned)Index < SI->getNumCases()) &&
3181  "Index out the number of cases.");
3182  return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3183  }
3184 
3185  bool operator==(const CaseHandleImpl &RHS) const {
3186  assert(SI == RHS.SI && "Incompatible operators.");
3187  return Index == RHS.Index;
3188  }
3189  };
3190 
3191  using ConstCaseHandle =
3193 
3195  : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3197 
3198  public:
3200 
3201  /// Sets the new value for current case.
3203  assert((unsigned)Index < SI->getNumCases() &&
3204  "Index out the number of cases.");
3205  SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3206  }
3207 
3208  /// Sets the new successor for current case.
3210  SI->setSuccessor(getSuccessorIndex(), S);
3211  }
3212  };
3213 
3214  template <typename CaseHandleT>
3215  class CaseIteratorImpl
3216  : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3217  std::random_access_iterator_tag,
3218  CaseHandleT> {
3219  using SwitchInstT = typename CaseHandleT::SwitchInstType;
3220 
3221  CaseHandleT Case;
3222 
3223  public:
3224  /// Default constructed iterator is in an invalid state until assigned to
3225  /// a case for a particular switch.
3226  CaseIteratorImpl() = default;
3227 
3228  /// Initializes case iterator for given SwitchInst and for given
3229  /// case number.
3230  CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3231 
3232  /// Initializes case iterator for given SwitchInst and for given
3233  /// successor index.
3234  static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3235  unsigned SuccessorIndex) {
3236  assert(SuccessorIndex < SI->getNumSuccessors() &&
3237  "Successor index # out of range!");
3238  return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3239  : CaseIteratorImpl(SI, DefaultPseudoIndex);
3240  }
3241 
3242  /// Support converting to the const variant. This will be a no-op for const
3243  /// variant.
3245  return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3246  }
3247 
3249  // Check index correctness after addition.
3250  // Note: Index == getNumCases() means end().
3251  assert(Case.Index + N >= 0 &&
3252  (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3253  "Case.Index out the number of cases.");
3254  Case.Index += N;
3255  return *this;
3256  }
3258  // Check index correctness after subtraction.
3259  // Note: Case.Index == getNumCases() means end().
3260  assert(Case.Index - N >= 0 &&
3261  (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3262  "Case.Index out the number of cases.");
3263  Case.Index -= N;
3264  return *this;
3265  }
3267  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3268  return Case.Index - RHS.Case.Index;
3269  }
3270  bool operator==(const CaseIteratorImpl &RHS) const {
3271  return Case == RHS.Case;
3272  }
3273  bool operator<(const CaseIteratorImpl &RHS) const {
3274  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3275  return Case.Index < RHS.Case.Index;
3276  }
3277  CaseHandleT &operator*() { return Case; }
3278  const CaseHandleT &operator*() const { return Case; }
3279  };
3280 
3283 
3284  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3285  unsigned NumCases,
3286  Instruction *InsertBefore = nullptr) {
3287  return new SwitchInst(Value, Default, NumCases, InsertBefore);
3288  }
3289 
3290  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3291  unsigned NumCases, BasicBlock *InsertAtEnd) {
3292  return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3293  }
3294 
3295  /// Provide fast operand accessors
3297 
3298  // Accessor Methods for Switch stmt
3299  Value *getCondition() const { return getOperand(0); }
3300  void setCondition(Value *V) { setOperand(0, V); }
3301 
3303  return cast<BasicBlock>(getOperand(1));
3304  }
3305 
3306  void setDefaultDest(BasicBlock *DefaultCase) {
3307  setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3308  }
3309 
3310  /// Return the number of 'cases' in this switch instruction, excluding the
3311  /// default case.
3312  unsigned getNumCases() const {
3313  return getNumOperands()/2 - 1;
3314  }
3315 
3316  /// Returns a read/write iterator that points to the first case in the
3317  /// SwitchInst.
3319  return CaseIt(this, 0);
3320  }
3321 
3322  /// Returns a read-only iterator that points to the first case in the
3323  /// SwitchInst.
3325  return ConstCaseIt(this, 0);
3326  }
3327 
3328  /// Returns a read/write iterator that points one past the last in the
3329  /// SwitchInst.
3331  return CaseIt(this, getNumCases());
3332  }
3333 
3334  /// Returns a read-only iterator that points one past the last in the
3335  /// SwitchInst.
3337  return ConstCaseIt(this, getNumCases());
3338  }
3339 
3340  /// Iteration adapter for range-for loops.
3342  return make_range(case_begin(), case_end());
3343  }
3344 
3345  /// Constant iteration adapter for range-for loops.
3347  return make_range(case_begin(), case_end());
3348  }
3349 
3350  /// Returns an iterator that points to the default case.
3351  /// Note: this iterator allows to resolve successor only. Attempt
3352  /// to resolve case value causes an assertion.
3353  /// Also note, that increment and decrement also causes an assertion and
3354  /// makes iterator invalid.
3356  return CaseIt(this, DefaultPseudoIndex);
3357  }
3359  return ConstCaseIt(this, DefaultPseudoIndex);
3360  }
3361 
3362  /// Search all of the case values for the specified constant. If it is
3363  /// explicitly handled, return the case iterator of it, otherwise return
3364  /// default case iterator to indicate that it is handled by the default
3365  /// handler.
3368  cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3369  if (I != case_end())
3370  return I;
3371 
3372  return case_default();
3373  }
3375  ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3376  return Case.getCaseValue() == C;
3377  });
3378  if (I != case_end())
3379  return I;
3380 
3381  return case_default();
3382  }
3383 
3384  /// Finds the unique case value for a given successor. Returns null if the
3385  /// successor is not found, not unique, or is the default case.
3387  if (BB == getDefaultDest())
3388  return nullptr;
3389 
3390  ConstantInt *CI = nullptr;
3391  for (auto Case : cases()) {
3392  if (Case.getCaseSuccessor() != BB)
3393  continue;
3394 
3395  if (CI)
3396  return nullptr; // Multiple cases lead to BB.
3397 
3398  CI = Case.getCaseValue();
3399  }
3400 
3401  return CI;
3402  }
3403 
3404  /// Add an entry to the switch instruction.
3405  /// Note:
3406  /// This action invalidates case_end(). Old case_end() iterator will
3407  /// point to the added case.
3408  void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3409 
3410  /// This method removes the specified case and its successor from the switch
3411  /// instruction. Note that this operation may reorder the remaining cases at
3412  /// index idx and above.
3413  /// Note:
3414  /// This action invalidates iterators for all cases following the one removed,
3415  /// including the case_end() iterator. It returns an iterator for the next
3416  /// case.
3417  CaseIt removeCase(CaseIt I);
3418 
3419  unsigned getNumSuccessors() const { return getNumOperands()/2; }
3420  BasicBlock *getSuccessor(unsigned idx) const {
3421  assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3422  return cast<BasicBlock>(getOperand(idx*2+1));
3423  }
3424  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3425  assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3426  setOperand(idx * 2 + 1, NewSucc);
3427  }
3428 
3429  // Methods for support type inquiry through isa, cast, and dyn_cast:
3430  static bool classof(const Instruction *I) {
3431  return I->getOpcode() == Instruction::Switch;
3432  }
3433  static bool classof(const Value *V) {
3434  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3435  }
3436 };
3437 
3438 template <>
3440 };
3441 
3442 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3443 
3444 //===----------------------------------------------------------------------===//
3445 // IndirectBrInst Class
3446 //===----------------------------------------------------------------------===//
3447 
3448 //===---------------------------------------------------------------------------
3449 /// Indirect Branch Instruction.
3450 ///
3451 class IndirectBrInst : public Instruction {
3452  unsigned ReservedSpace;
3453 
3454  // Operand[0] = Address to jump to
3455  // Operand[n+1] = n-th destination
3456  IndirectBrInst(const IndirectBrInst &IBI);
3457 
3458  /// Create a new indirectbr instruction, specifying an
3459  /// Address to jump to. The number of expected destinations can be specified
3460  /// here to make memory allocation more efficient. This constructor can also
3461  /// autoinsert before another instruction.
3462  IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3463 
3464  /// Create a new indirectbr instruction, specifying an
3465  /// Address to jump to. The number of expected destinations can be specified
3466  /// here to make memory allocation more efficient. This constructor also
3467  /// autoinserts at the end of the specified BasicBlock.
3468  IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3469 
3470  // allocate space for exactly zero operands
3471  void *operator new(size_t s) {
3472  return User::operator new(s);
3473  }
3474 
3475  void init(Value *Address, unsigned NumDests);
3476  void growOperands();
3477 
3478 protected:
3479  // Note: Instruction needs to be a friend here to call cloneImpl.
3480  friend class Instruction;
3481 
3482  IndirectBrInst *cloneImpl() const;
3483 
3484 public:
3485  /// Iterator type that casts an operand to a basic block.
3486  ///
3487  /// This only makes sense because the successors are stored as adjacent
3488  /// operands for indirectbr instructions.
3490  : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3491  std::random_access_iterator_tag, BasicBlock *,
3492  ptrdiff_t, BasicBlock *, BasicBlock *> {
3494 
3495  BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3496  BasicBlock *operator->() const { return operator*(); }
3497  };
3498 
3499  /// The const version of `succ_op_iterator`.
3501  : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3502  std::random_access_iterator_tag,
3503  const BasicBlock *, ptrdiff_t, const BasicBlock *,
3504  const BasicBlock *> {
3506  : iterator_adaptor_base(I) {}
3507 
3508  const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3509  const BasicBlock *operator->() const { return operator*(); }
3510  };
3511 
3512  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3513  Instruction *InsertBefore = nullptr) {
3514  return new IndirectBrInst(Address, NumDests, InsertBefore);
3515  }
3516 
3517  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3518  BasicBlock *InsertAtEnd) {
3519  return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3520  }
3521 
3522  /// Provide fast operand accessors.
3524 
3525  // Accessor Methods for IndirectBrInst instruction.
3526  Value *getAddress() { return getOperand(0); }
3527  const Value *getAddress() const { return getOperand(0); }
3528  void setAddress(Value *V) { setOperand(0, V); }
3529 
3530  /// return the number of possible destinations in this
3531  /// indirectbr instruction.
3532  unsigned getNumDestinations() const { return getNumOperands()-1; }
3533 
3534  /// Return the specified destination.
3535  BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3536  const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3537 
3538  /// Add a destination.
3539  ///
3540  void addDestination(BasicBlock *Dest);
3541 
3542  /// This method removes the specified successor from the
3543  /// indirectbr instruction.
3544  void removeDestination(unsigned i);
3545 
3546  unsigned getNumSuccessors() const { return getNumOperands()-1; }
3547  BasicBlock *getSuccessor(unsigned i) const {
3548  return cast<BasicBlock>(getOperand(i+1));
3549  }
3550  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3551  setOperand(i + 1, NewSucc);
3552  }
3553 
3555  return make_range(succ_op_iterator(std::next(value_op_begin())),
3557  }
3558 
3560  return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3562  }
3563 
3564  // Methods for support type inquiry through isa, cast, and dyn_cast:
3565  static bool classof(const Instruction *I) {
3566  return I->getOpcode() == Instruction::IndirectBr;
3567  }
3568  static bool classof(const Value *V) {
3569  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3570  }
3571 };
3572 
3573 template <>
3575 };
3576 
3577 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3578 
3579 //===----------------------------------------------------------------------===//
3580 // InvokeInst Class
3581 //===----------------------------------------------------------------------===//
3582 
3583 /// Invoke instruction. The SubclassData field is used to hold the
3584 /// calling convention of the call.
3585 ///
3586 class InvokeInst : public CallBase {
3587  /// The number of operands for this call beyond the called function,
3588  /// arguments, and operand bundles.
3589  static constexpr int NumExtraOperands = 2;
3590 
3591  /// The index from the end of the operand array to the normal destination.
3592  static constexpr int NormalDestOpEndIdx = -3;
3593 
3594  /// The index from the end of the operand array to the unwind destination.
3595  static constexpr int UnwindDestOpEndIdx = -2;
3596 
3597  InvokeInst(const InvokeInst &BI);
3598 
3599  /// Construct an InvokeInst given a range of arguments.
3600  ///
3601  /// Construct an InvokeInst from a range of arguments
3602  inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3603  BasicBlock *IfException, ArrayRef<Value *> Args,
3604  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3605  const Twine &NameStr, Instruction *InsertBefore);
3606 
3607  inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3608  BasicBlock *IfException, ArrayRef<Value *> Args,
3609  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3610  const Twine &NameStr, BasicBlock *InsertAtEnd);
3611 
3612  void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3613  BasicBlock *IfException, ArrayRef<Value *> Args,
3614  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3615 
3616  /// Compute the number of operands to allocate.
3617  static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3618  // We need one operand for the called function, plus our extra operands and
3619  // the input operand counts provided.
3620  return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3621  }
3622 
3623 protected:
3624  // Note: Instruction needs to be a friend here to call cloneImpl.
3625  friend class Instruction;
3626 
3627  InvokeInst *cloneImpl() const;
3628 
3629 public:
3630  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3631  BasicBlock *IfException, ArrayRef<Value *> Args,
3632  const Twine &NameStr,
3633  Instruction *InsertBefore = nullptr) {
3634  int NumOperands = ComputeNumOperands(Args.size());
3635  return new (NumOperands)
3636  InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3637  NameStr, InsertBefore);
3638  }
3639 
3640  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3641  BasicBlock *IfException, ArrayRef<Value *> Args,
3642  ArrayRef<OperandBundleDef> Bundles = None,
3643  const Twine &NameStr = "",
3644  Instruction *InsertBefore = nullptr) {
3645  int NumOperands =
3646  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3647  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3648 
3649  return new (NumOperands, DescriptorBytes)
3650  InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3651  NameStr, InsertBefore);
3652  }
3653 
3654  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3655  BasicBlock *IfException, ArrayRef<Value *> Args,
3656  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3657  int NumOperands = ComputeNumOperands(Args.size());
3658  return new (NumOperands)
3659  InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3660  NameStr, InsertAtEnd);
3661  }
3662 
3663  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3664  BasicBlock *IfException, ArrayRef<Value *> Args,
3666  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3667  int NumOperands =
3668  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3669  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3670 
3671  return new (NumOperands, DescriptorBytes)
3672  InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3673  NameStr, InsertAtEnd);
3674  }
3675 
3676  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3677  BasicBlock *IfException, ArrayRef<Value *> Args,
3678  const Twine &NameStr,
3679  Instruction *InsertBefore = nullptr) {
3680  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3681  IfException, Args, None, NameStr, InsertBefore);
3682  }
3683 
3684  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3685  BasicBlock *IfException, ArrayRef<Value *> Args,
3686  ArrayRef<OperandBundleDef> Bundles = None,
3687  const Twine &NameStr = "",
3688  Instruction *InsertBefore = nullptr) {
3689  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3690  IfException, Args, Bundles, NameStr, InsertBefore);
3691  }
3692 
3693  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3694  BasicBlock *IfException, ArrayRef<Value *> Args,
3695  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3696  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3697  IfException, Args, NameStr, InsertAtEnd);
3698  }
3699 
3700  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3701  BasicBlock *IfException, ArrayRef<Value *> Args,
3703  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3704  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3705  IfException, Args, Bundles, NameStr, InsertAtEnd);
3706  }
3707 
3708  // Deprecated [opaque pointer types]
3709  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3710  BasicBlock *IfException, ArrayRef<Value *> Args,
3711  const Twine &NameStr,
3712  Instruction *InsertBefore = nullptr) {
3713  return Create(cast<FunctionType>(
3714  cast<PointerType>(Func->getType())->getElementType()),
3715  Func, IfNormal, IfException, Args, None, NameStr,
3716  InsertBefore);
3717  }
3718 
3719  // Deprecated [opaque pointer types]
3720  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3721  BasicBlock *IfException, ArrayRef<Value *> Args,
3722  ArrayRef<OperandBundleDef> Bundles = None,
3723  const Twine &NameStr = "",
3724  Instruction *InsertBefore = nullptr) {
3725  return Create(cast<FunctionType>(
3726  cast<PointerType>(Func->getType())->getElementType()),
3727  Func, IfNormal, IfException, Args, Bundles, NameStr,
3728  InsertBefore);
3729  }
3730 
3731  // Deprecated [opaque pointer types]
3732  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3733  BasicBlock *IfException, ArrayRef<Value *> Args,
3734  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3735  return Create(cast<FunctionType>(
3736  cast<PointerType>(Func->getType())->getElementType()),
3737  Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3738  }
3739 
3740  // Deprecated [opaque pointer types]
3741  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3742  BasicBlock *IfException, ArrayRef<Value *> Args,
3744  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3745  return Create(cast<FunctionType>(
3746  cast<PointerType>(Func->getType())->getElementType()),
3747  Func, IfNormal, IfException, Args, Bundles, NameStr,
3748  InsertAtEnd);
3749  }
3750 
3751  /// Create a clone of \p II with a different set of operand bundles and
3752  /// insert it before \p InsertPt.
3753  ///
3754  /// The returned invoke instruction is identical to \p II in every way except
3755  /// that the operand bundles for the new instruction are set to the operand
3756  /// bundles in \p Bundles.
3757  static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3758  Instruction *InsertPt = nullptr);
3759 
3760  /// Determine if the call should not perform indirect branch tracking.
3761  bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3762 
3763  /// Determine if the call cannot unwind.
3764  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3766  addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3767  }
3768 
3769  // get*Dest - Return the destination basic blocks...
3771  return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3772  }
3774  return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3775  }
3777  Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3778  }
3780  Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3781  }
3782 
3783  /// Get the landingpad instruction from the landing pad
3784  /// block (the unwind destination).
3785  LandingPadInst *getLandingPadInst() const;
3786 
3787  BasicBlock *getSuccessor(unsigned i) const {
3788  assert(i < 2 && "Successor # out of range for invoke!");
3789  return i == 0 ? getNormalDest() : getUnwindDest();
3790  }
3791 
3792  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3793  assert(i < 2 && "Successor # out of range for invoke!");
3794  if (i == 0)
3795  setNormalDest(NewSucc);
3796  else
3797  setUnwindDest(NewSucc);
3798  }
3799 
3800  unsigned getNumSuccessors() const { return 2; }
3801 
3802  // Methods for support type inquiry through isa, cast, and dyn_cast:
3803  static bool classof(const Instruction *I) {
3804  return (I->getOpcode() == Instruction::Invoke);
3805  }
3806  static bool classof(const Value *V) {
3807  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3808  }
3809 
3810 private:
3811 
3812  // Shadow Instruction::setInstructionSubclassData with a private forwarding
3813  // method so that subclasses cannot accidentally use it.
3814  void setInstructionSubclassData(unsigned short D) {
3816  }
3817 };
3818 
3819 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3820  BasicBlock *IfException, ArrayRef<Value *> Args,
3821  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3822  const Twine &NameStr, Instruction *InsertBefore)
3823  : CallBase(Ty->getReturnType(), Instruction::Invoke,
3824  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3825  InsertBefore) {
3826  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3827 }
3828 
3829 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3830  BasicBlock *IfException, ArrayRef<Value *> Args,
3831  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3832  const Twine &NameStr, BasicBlock *InsertAtEnd)
3833  : CallBase(Ty->getReturnType(), Instruction::Invoke,
3834  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3835  InsertAtEnd) {
3836  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3837 }
3838 
3839 //===----------------------------------------------------------------------===//
3840 // CallBrInst Class
3841 //===----------------------------------------------------------------------===//
3842 
3843 /// CallBr instruction, tracking function calls that may not return control but
3844 /// instead transfer it to a third location. The SubclassData field is used to
3845 /// hold the calling convention of the call.
3846 ///
3847 class CallBrInst : public CallBase {
3848 
3849  unsigned NumIndirectDests;
3850 
3851  CallBrInst(const CallBrInst &BI);
3852 
3853  /// Construct a CallBrInst given a range of arguments.
3854  ///
3855  /// Construct a CallBrInst from a range of arguments
3856  inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3857  ArrayRef<BasicBlock *> IndirectDests,
3858  ArrayRef<Value *> Args,
3859  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3860  const Twine &NameStr, Instruction *InsertBefore);
3861 
3862  inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3863  ArrayRef<BasicBlock *> IndirectDests,
3864  ArrayRef<Value *> Args,
3865  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3866  const Twine &NameStr, BasicBlock *InsertAtEnd);
3867 
3868  void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3869  ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3870  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3871 
3872  /// Compute the number of operands to allocate.
3873  static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3874  int NumBundleInputs = 0) {
3875  // We need one operand for the called function, plus our extra operands and
3876  // the input operand counts provided.
3877  return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3878  }
3879 
3880 protected:
3881  // Note: Instruction needs to be a friend here to call cloneImpl.
3882  friend class Instruction;
3883 
3884  CallBrInst *cloneImpl() const;
3885 
3886 public:
3887  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3888  BasicBlock *DefaultDest,
3889  ArrayRef<BasicBlock *> IndirectDests,
3890  ArrayRef<Value *> Args, const Twine &NameStr,
3891  Instruction *InsertBefore = nullptr) {
3892  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3893  return new (NumOperands)
3894  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3895  NumOperands, NameStr, InsertBefore);
3896  }
3897 
3898  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3899  BasicBlock *DefaultDest,
3900  ArrayRef<BasicBlock *> IndirectDests,
3901  ArrayRef<Value *> Args,
3902  ArrayRef<OperandBundleDef> Bundles = None,
3903  const Twine &NameStr = "",
3904  Instruction *InsertBefore = nullptr) {
3905  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3906  CountBundleInputs(Bundles));
3907  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3908 
3909  return new (NumOperands, DescriptorBytes)
3910  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3911  NumOperands, NameStr, InsertBefore);
3912  }
3913 
3914  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3915  BasicBlock *DefaultDest,
3916  ArrayRef<BasicBlock *> IndirectDests,
3917  ArrayRef<Value *> Args, const Twine &NameStr,
3918  BasicBlock *InsertAtEnd) {
3919  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3920  return new (NumOperands)
3921  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3922  NumOperands, NameStr, InsertAtEnd);
3923  }
3924 
3925  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3926  BasicBlock *DefaultDest,
3927  ArrayRef<BasicBlock *> IndirectDests,
3928  ArrayRef<Value *> Args,
3930  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3931  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3932  CountBundleInputs(Bundles));
3933  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3934 
3935  return new (NumOperands, DescriptorBytes)
3936  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3937  NumOperands, NameStr, InsertAtEnd);
3938  }
3939 
3940  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
3941  ArrayRef<BasicBlock *> IndirectDests,
3942  ArrayRef<Value *> Args, const Twine &NameStr,
3943  Instruction *InsertBefore = nullptr) {
3944  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
3945  IndirectDests, Args, NameStr, InsertBefore);
3946  }
3947 
3948  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
3949  ArrayRef<BasicBlock *> IndirectDests,
3950  ArrayRef<Value *> Args,
3951  ArrayRef<OperandBundleDef> Bundles = None,
3952  const Twine &NameStr = "",
3953  Instruction *InsertBefore = nullptr) {
3954  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
3955  IndirectDests, Args, Bundles, NameStr, InsertBefore);
3956  }
3957 
3958  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
3959  ArrayRef<BasicBlock *> IndirectDests,
3960  ArrayRef<Value *> Args, const Twine &NameStr,
3961  BasicBlock *InsertAtEnd) {
3962  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
3963  IndirectDests, Args, NameStr, InsertAtEnd);
3964  }
3965 
3967  BasicBlock *DefaultDest,
3968  ArrayRef<BasicBlock *> IndirectDests,
3969  ArrayRef<Value *> Args,
3971  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3972  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
3973  IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
3974  }
3975 
3976  /// Create a clone of \p CBI with a different set of operand bundles and
3977  /// insert it before \p InsertPt.
3978  ///
3979  /// The returned callbr instruction is identical to \p CBI in every way
3980  /// except that the operand bundles for the new instruction are set to the
3981  /// operand bundles in \p Bundles.
3982  static CallBrInst *Create(CallBrInst *CBI,
3984  Instruction *InsertPt = nullptr);
3985 
3986  /// Return the number of callbr indirect dest labels.
3987  ///
3988  unsigned getNumIndirectDests() const { return NumIndirectDests; }
3989 
3990  /// getIndirectDestLabel - Return the i-th indirect dest label.
3991  ///
3992  Value *getIndirectDestLabel(unsigned i) const {
3993  assert(i < getNumIndirectDests() && "Out of bounds!");
3994  return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
3995  1);
3996  }
3997 
3998  Value *getIndirectDestLabelUse(unsigned i) const {
3999  assert(i < getNumIndirectDests() && "Out of bounds!");
4000  return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4001  1);
4002  }
4003 
4004  // Return the destination basic blocks...
4006  return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4007  }
4008  BasicBlock *getIndirectDest(unsigned i) const {
4009  return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4010  }
4012  SmallVector<BasicBlock *, 16> IndirectDests;
4013  for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4014  IndirectDests.push_back(getIndirectDest(i));
4015  return IndirectDests;
4016  }
4018  *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4019  }
4020  void setIndirectDest(unsigned i, BasicBlock *B) {
4021  *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4022  }
4023 
4024  BasicBlock *getSuccessor(unsigned i) const {
4025  assert(i < getNumSuccessors() + 1 &&
4026  "Successor # out of range for callbr!");
4027  return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4028  }
4029 
4030  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4031  assert(idx < getNumIndirectDests() + 1 &&
4032  "Successor # out of range for callbr!");
4033  *(&Op<-1>() - getNumIndirectDests() -1 + idx) =
4034  reinterpret_cast<Value *>(NewSucc);
4035  }
4036 
4037  unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4038 
4039  // Methods for support type inquiry through isa, cast, and dyn_cast:
4040  static bool classof(const Instruction *I) {
4041  return (I->getOpcode() == Instruction::CallBr);
4042  }
4043  static bool classof(const Value *V) {
4044  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4045  }
4046 
4047 private:
4048 
4049  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4050  // method so that subclasses cannot accidentally use it.
4051  void setInstructionSubclassData(unsigned short D) {
4053  }
4054 };
4055 
4056 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4057  ArrayRef<BasicBlock *> IndirectDests,
4058  ArrayRef<Value *> Args,
4059  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4060  const Twine &NameStr, Instruction *InsertBefore)
4061  : CallBase(Ty->getReturnType(), Instruction::CallBr,
4062  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4063  InsertBefore) {
4064  init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4065 }
4066 
4067 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4068  ArrayRef<BasicBlock *> IndirectDests,
4069  ArrayRef<Value *> Args,
4070  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4071  const Twine &NameStr, BasicBlock *InsertAtEnd)
4072  : CallBase(
4073  cast<FunctionType>(
4074  cast<PointerType>(Func->getType())->getElementType())
4075  ->getReturnType(),
4076  Instruction::CallBr,
4077  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4078  InsertAtEnd) {
4079  init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4080 }
4081 
4082 //===----------------------------------------------------------------------===//
4083 // ResumeInst Class
4084 //===----------------------------------------------------------------------===//
4085 
4086 //===---------------------------------------------------------------------------
4087 /// Resume the propagation of an exception.
4088 ///
4089 class ResumeInst : public Instruction {
4090  ResumeInst(const ResumeInst &RI);
4091 
4092  explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4093  ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4094 
4095 protected:
4096  // Note: Instruction needs to be a friend here to call cloneImpl.
4097  friend class Instruction;
4098 
4099  ResumeInst *cloneImpl() const;
4100 
4101 public:
4102  static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4103  return new(1) ResumeInst(Exn, InsertBefore);
4104  }
4105 
4106  static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4107  return new(1) ResumeInst(Exn, InsertAtEnd);
4108  }
4109 
4110  /// Provide fast operand accessors
4112 
4113  /// Convenience accessor.
4114  Value *getValue() const { return Op<0>(); }
4115 
4116  unsigned getNumSuccessors() const { return 0; }
4117 
4118  // Methods for support type inquiry through isa, cast, and dyn_cast:
4119  static bool classof(const Instruction *I) {
4120  return I->getOpcode() == Instruction::Resume;
4121  }
4122  static bool classof(const Value *V) {
4123  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4124  }
4125 
4126 private:
4127  BasicBlock *getSuccessor(unsigned idx) const {
4128  llvm_unreachable("ResumeInst has no successors!");
4129  }
4130 
4131  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4132  llvm_unreachable("ResumeInst has no successors!");
4133  }
4134 };
4135 
4136 template <>
4138  public FixedNumOperandTraits<ResumeInst, 1> {
4139 };
4140 
4141 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4142 
4143 //===----------------------------------------------------------------------===//
4144 // CatchSwitchInst Class
4145 //===----------------------------------------------------------------------===//
4147  /// The number of operands actually allocated. NumOperands is
4148  /// the number actually in use.
4149  unsigned ReservedSpace;
4150 
4151  // Operand[0] = Outer scope
4152  // Operand[1] = Unwind block destination
4153  // Operand[n] = BasicBlock to go to on match
4154  CatchSwitchInst(const CatchSwitchInst &CSI);
4155 
4156  /// Create a new switch instruction, specifying a
4157  /// default destination. The number of additional handlers can be specified
4158  /// here to make memory allocation more efficient.
4159  /// This constructor can also autoinsert before another instruction.
4160  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4161  unsigned NumHandlers, const Twine &NameStr,
4162  Instruction *InsertBefore);
4163 
4164  /// Create a new switch instruction, specifying a
4165  /// default destination. The number of additional handlers can be specified
4166  /// here to make memory allocation more efficient.
4167  /// This constructor also autoinserts at the end of the specified BasicBlock.
4168  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4169  unsigned NumHandlers, const Twine &NameStr,
4170  BasicBlock *InsertAtEnd);
4171 
4172  // allocate space for exactly zero operands
4173  void *operator new(size_t s) { return User::operator new(s); }
4174 
4175  void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4176  void growOperands(unsigned Size);
4177 
4178 protected:
4179  // Note: Instruction needs to be a friend here to call cloneImpl.
4180  friend class Instruction;
4181 
4182  CatchSwitchInst *cloneImpl() const;
4183 
4184 public:
4185  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4186  unsigned NumHandlers,
4187  const Twine &NameStr = "",
4188  Instruction *InsertBefore = nullptr) {
4189  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4190  InsertBefore);
4191  }
4192 
4193  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4194  unsigned NumHandlers, const Twine &NameStr,
4195  BasicBlock *InsertAtEnd) {
4196  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4197  InsertAtEnd);
4198  }
4199 
4200  /// Provide fast operand accessors
4202 
4203  // Accessor Methods for CatchSwitch stmt
4204  Value *getParentPad() const { return getOperand(0); }
4205  void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4206 
4207  // Accessor Methods for CatchSwitch stmt
4208  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4209  bool unwindsToCaller() const { return !hasUnwindDest(); }
4211  if (hasUnwindDest())
4212  return cast<BasicBlock>(getOperand(1));
4213  return nullptr;
4214  }
4215  void setUnwindDest(BasicBlock *UnwindDest) {
4216  assert(UnwindDest);
4217  assert(hasUnwindDest());
4218  setOperand(1, UnwindDest);
4219  }
4220 
4221  /// return the number of 'handlers' in this catchswitch
4222  /// instruction, except the default handler
4223  unsigned getNumHandlers() const {
4224  if (hasUnwindDest())
4225  return getNumOperands() - 2;
4226  return getNumOperands() - 1;
4227  }
4228 
4229 private:
4230  static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4231  static const BasicBlock *handler_helper(const Value *V) {
4232  return cast<BasicBlock>(V);
4233  }
4234 
4235 public:
4236  using DerefFnTy = BasicBlock *(*)(Value *);
4239  using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4240  using const_handler_iterator =
4243 
4244  /// Returns an iterator that points to the first handler in CatchSwitchInst.
4246  op_iterator It = op_begin() + 1;
4247  if (hasUnwindDest())
4248  ++It;
4249  return handler_iterator(It, DerefFnTy(handler_helper));
4250  }
4251 
4252  /// Returns an iterator that points to the first handler in the
4253  /// CatchSwitchInst.
4254  const_handler_iterator handler_begin() const {
4255  const_op_iterator It = op_begin() + 1;
4256  if (hasUnwindDest())
4257  ++It;
4258  return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4259  }
4260 
4261  /// Returns a read-only iterator that points one past the last
4262  /// handler in the CatchSwitchInst.
4264  return handler_iterator(op_end(), DerefFnTy(handler_helper));
4265  }
4266 
4267  /// Returns an iterator that points one past the last handler in the
4268  /// CatchSwitchInst.
4269  const_handler_iterator handler_end() const {
4270  return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4271  }
4272 
4273  /// iteration adapter for range-for loops.
4275  return make_range(handler_begin(), handler_end());
4276  }
4277 
4278  /// iteration adapter for range-for loops.
4280  return make_range(handler_begin(), handler_end());
4281  }
4282 
4283  /// Add an entry to the switch instruction...
4284  /// Note:
4285  /// This action invalidates handler_end(). Old handler_end() iterator will
4286  /// point to the added handler.
4287  void addHandler(BasicBlock *Dest);
4288 
4289  void removeHandler(handler_iterator HI);
4290 
4291  unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4292  BasicBlock *getSuccessor(unsigned Idx) const {
4293  assert(Idx < getNumSuccessors() &&
4294  "Successor # out of range for catchswitch!");
4295  return cast<BasicBlock>(getOperand(Idx + 1));
4296  }
4297  void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4298  assert(Idx < getNumSuccessors() &&
4299  "Successor # out of range for catchswitch!");
4300  setOperand(Idx + 1, NewSucc);
4301  }
4302 
4303  // Methods for support type inquiry through isa, cast, and dyn_cast:
4304  static bool classof(const Instruction *I) {
4305  return I->getOpcode() == Instruction::CatchSwitch;
4306  }
4307  static bool classof(const Value *V) {
4308  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4309  }
4310 };
4311 
4312 template <>
4314 
4315 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4316 
4317 //===----------------------------------------------------------------------===//
4318 // CleanupPadInst Class
4319 //===----------------------------------------------------------------------===//
4321 private:
4322  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4323  unsigned Values, const Twine &NameStr,
4324  Instruction *InsertBefore)
4325  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4326  NameStr, InsertBefore) {}
4327  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4328  unsigned Values, const Twine &NameStr,
4329  BasicBlock *InsertAtEnd)
4330  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4331  NameStr, InsertAtEnd) {}
4332 
4333 public:
4334  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4335  const Twine &NameStr = "",
4336  Instruction *InsertBefore = nullptr) {
4337  unsigned Values = 1 + Args.size();
4338  return new (Values)
4339  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4340  }
4341 
4342  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4343  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4344  unsigned Values = 1 + Args.size();
4345  return new (Values)
4346  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4347  }
4348 
4349  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4350  static bool classof(const Instruction *I) {
4351  return I->getOpcode() == Instruction::CleanupPad;
4352  }
4353  static bool classof(const Value *V) {
4354  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4355  }
4356 };
4357 
4358 //===----------------------------------------------------------------------===//
4359 // CatchPadInst Class
4360 //===----------------------------------------------------------------------===//
4362 private:
4363  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4364  unsigned Values, const Twine &NameStr,
4365  Instruction *InsertBefore)
4366  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4367  NameStr, InsertBefore) {}
4368  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4369  unsigned Values, const Twine &NameStr,
4370  BasicBlock *InsertAtEnd)
4371  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4372  NameStr, InsertAtEnd) {}
4373 
4374 public:
4375  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4376  const Twine &NameStr = "",
4377  Instruction *InsertBefore = nullptr) {
4378  unsigned Values = 1 + Args.size();
4379  return new (Values)
4380  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4381  }
4382 
4383  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4384  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4385  unsigned Values = 1 + Args.size();
4386  return new (Values)
4387  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4388  }
4389 
4390  /// Convenience accessors
4391  CatchSwitchInst *getCatchSwitch() const {
4392  return cast<CatchSwitchInst>(Op<-1>());
4393  }
4394  void setCatchSwitch(Value *CatchSwitch) {
4395  assert(CatchSwitch);
4396  Op<-1>() = CatchSwitch;
4397  }
4398 
4399  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4400  static bool classof(const Instruction *I) {
4401  return I->getOpcode() == Instruction::CatchPad;
4402  }
4403  static bool classof(const Value *V) {
4404  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4405  }
4406 };
4407 
4408 //===----------------------------------------------------------------------===//
4409 // CatchReturnInst Class
4410 //===----------------------------------------------------------------------===//
4411 
4413  CatchReturnInst(const CatchReturnInst &RI);
4414  CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4415  CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4416 
4417  void init(Value *CatchPad, BasicBlock *BB);
4418 
4419 protected:
4420  // Note: Instruction needs to be a friend here to call cloneImpl.
4421  friend class Instruction;
4422 
4423  CatchReturnInst *cloneImpl() const;
4424 
4425 public:
4426  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4427  Instruction *InsertBefore = nullptr) {
4428  assert(CatchPad);
4429  assert(BB);
4430  return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4431  }
4432 
4433  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4434  BasicBlock *InsertAtEnd) {
4435  assert(CatchPad);
4436  assert(BB);
4437  return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4438  }
4439 
4440  /// Provide fast operand accessors
4442 
4443  /// Convenience accessors.
4444  CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4445  void setCatchPad(CatchPadInst *CatchPad) {
4446  assert(CatchPad);
4447  Op<0>() = CatchPad;
4448  }
4449 
4450  BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4451  void setSuccessor(BasicBlock *NewSucc) {
4452  assert(NewSucc);
4453  Op<1>() = NewSucc;
4454  }
4455  unsigned getNumSuccessors() const { return 1; }
4456 
4457  /// Get the parentPad of this catchret's catchpad's catchswitch.
4458  /// The successor block is implicitly a member of this funclet.
4459  Value *getCatchSwitchParentPad() const {
4460  return getCatchPad()->getCatchSwitch()->getParentPad();
4461  }
4462 
4463  // Methods for support type inquiry through isa, cast, and dyn_cast:
4464  static bool classof(const Instruction *I) {
4465  return (I->getOpcode() == Instruction::CatchRet);
4466  }
4467  static bool classof(const Value *V) {
4468  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4469  }
4470 
4471 private:
4472  BasicBlock *getSuccessor(unsigned Idx) const {
4473  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4474  return getSuccessor();
4475  }
4476 
4477  void setSuccessor(unsigned Idx, BasicBlock *B) {
4478  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4479  setSuccessor(B);
4480  }
4481 };
4482 
4483 template <>
4485  : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4486 
4487 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4488 
4489 //===----------------------------------------------------------------------===//
4490 // CleanupReturnInst Class
4491 //===----------------------------------------------------------------------===//
4492 
4494 private:
4496  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4497  Instruction *InsertBefore = nullptr);
4498  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4499  BasicBlock *InsertAtEnd);
4500 
4501  void init(Value *CleanupPad, BasicBlock *UnwindBB);
4502 
4503 protected:
4504  // Note: Instruction needs to be a friend here to call cloneImpl.
4505  friend class Instruction;
4506 
4507  CleanupReturnInst *cloneImpl() const;
4508 
4509 public:
4510  static CleanupReturnInst *Create(Value *CleanupPad,
4511  BasicBlock *UnwindBB = nullptr,
4512  Instruction *InsertBefore = nullptr) {
4513  assert(CleanupPad);
4514  unsigned Values = 1;
4515  if (UnwindBB)
4516  ++Values;
4517  return new (Values)
4518  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4519  }
4520 
4521  static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4522  BasicBlock *InsertAtEnd) {
4523  assert(CleanupPad);
4524  unsigned Values = 1;
4525  if (UnwindBB)
4526  ++Values;
4527  return new (Values)
4528  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4529  }
4530 
4531  /// Provide fast operand accessors
4533 
4534  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4535  bool unwindsToCaller() const { return !hasUnwindDest(); }
4536 
4537  /// Convenience accessor.
4539  return cast<CleanupPadInst>(Op<0>());
4540  }
4541  void setCleanupPad(CleanupPadInst *CleanupPad) {
4542  assert(CleanupPad);
4543  Op<0>() = CleanupPad;
4544  }
4545 
4546  unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4547 
4549  return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4550  }
4551  void setUnwindDest(BasicBlock *NewDest) {
4552  assert(NewDest);
4553  assert(hasUnwindDest());
4554  Op<1>() = NewDest;
4555  }
4556 
4557  // Methods for support type inquiry through isa, cast, and dyn_cast:
4558  static bool classof(const Instruction *I) {
4559  return (I->getOpcode() == Instruction::CleanupRet);
4560  }
4561  static bool classof(const Value *V) {
4562  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4563  }
4564 
4565 private:
4566  BasicBlock *getSuccessor(unsigned Idx) const {
4567  assert(Idx == 0);
4568  return getUnwindDest();
4569  }
4570 
4571  void setSuccessor(unsigned Idx, BasicBlock *B) {
4572  assert(Idx == 0);
4573  setUnwindDest(B);
4574  }
4575 
4576  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4577  // method so that subclasses cannot accidentally use it.
4578  void setInstructionSubclassData(unsigned short D) {
4580  }
4581 };
4582 
4583 template <>
4585  : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4586 
4587 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4588 
4589 //===----------------------------------------------------------------------===//
4590 // UnreachableInst Class
4591 //===----------------------------------------------------------------------===//
4592 
4593 //===---------------------------------------------------------------------------
4594 /// This function has undefined behavior. In particular, the
4595 /// presence of this instruction indicates some higher level knowledge that the
4596 /// end of the block cannot be reached.
4597 ///
4599 protected:
4600  // Note: Instruction needs to be a friend here to call cloneImpl.
4601  friend class Instruction;
4602 
4603  UnreachableInst *cloneImpl() const;
4604 
4605 public:
4606  explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4607  explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4608 
4609  // allocate space for exactly zero operands
4610  void *operator new(size_t s) {
4611  return User::operator new(s, 0);
4612  }
4613 
4614  unsigned getNumSuccessors() const { return 0; }
4615 
4616  // Methods for support type inquiry through isa, cast, and dyn_cast:
4617  static bool classof(const Instruction *I) {
4618  return I->getOpcode() == Instruction::Unreachable;
4619  }
4620  static bool classof(const Value *V) {
4621  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4622  }
4623 
4624 private:
4625  BasicBlock *getSuccessor(unsigned idx) const {
4626  llvm_unreachable("UnreachableInst has no successors!");
4627  }
4628 
4629  void setSuccessor(unsigned idx, BasicBlock *B) {
4630  llvm_unreachable("UnreachableInst has no successors!");
4631  }
4632 };
4633 
4634 //===----------------------------------------------------------------------===//
4635 // TruncInst Class
4636 //===----------------------------------------------------------------------===//
4637 
4638 /// This class represents a truncation of integer types.
4639 class TruncInst : public CastInst {
4640 protected:
4641  // Note: Instruction needs to be a friend here to call cloneImpl.
4642  friend class Instruction;
4643 
4644  /// Clone an identical TruncInst
4645  TruncInst *cloneImpl() const;
4646 
4647 public:
4648  /// Constructor with insert-before-instruction semantics
4649  TruncInst(
4650  Value *S, ///< The value to be truncated
4651  Type *Ty, ///< The (smaller) type to truncate to
4652  const Twine &NameStr = "", ///< A name for the new instruction
4653  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4654  );
4655 
4656  /// Constructor with insert-at-end-of-block semantics
4657  TruncInst(
4658  Value *S, ///< The value to be truncated
4659  Type *Ty, ///< The (smaller) type to truncate to
4660  const Twine &NameStr, ///< A name for the new instruction
4661  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4662  );
4663 
4664  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4665  static bool classof(const Instruction *I) {
4666  return I->getOpcode() == Trunc;
4667  }
4668  static bool classof(const Value *V) {
4669  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4670  }
4671 };
4672 
4673 //===----------------------------------------------------------------------===//
4674 // ZExtInst Class
4675 //===----------------------------------------------------------------------===//
4676 
4677 /// This class represents zero extension of integer types.
4678 class ZExtInst : public CastInst {
4679 protected:
4680  // Note: Instruction needs to be a friend here to call cloneImpl.
4681  friend class Instruction;
4682 
4683  /// Clone an identical ZExtInst
4684  ZExtInst *cloneImpl() const;
4685 
4686 public:
4687  /// Constructor with insert-before-instruction semantics
4688  ZExtInst(
4689  Value *S, ///< The value to be zero extended
4690  Type *Ty, ///< The type to zero extend to
4691  const Twine &NameStr = "", ///< A name for the new instruction
4692  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4693  );
4694 
4695  /// Constructor with insert-at-end semantics.
4696  ZExtInst(
4697  Value *S, ///< The value to be zero extended
4698  Type *Ty, ///< The type to zero extend to
4699  const Twine &NameStr, ///< A name for the new instruction
4700  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4701  );
4702 
4703  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4704  static bool classof(const Instruction *I) {
4705  return I->getOpcode() == ZExt;
4706  }
4707  static bool classof(const Value *V) {
4708  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4709  }
4710 };
4711 
4712 //===----------------------------------------------------------------------===//
4713 // SExtInst Class
4714 //===----------------------------------------------------------------------===//
4715 
4716 /// This class represents a sign extension of integer types.
4717 class SExtInst : public CastInst {
4718 protected:
4719  // Note: Instruction needs to be a friend here to call cloneImpl.
4720  friend class Instruction;
4721 
4722  /// Clone an identical SExtInst
4723  SExtInst *cloneImpl() const;
4724 
4725 public:
4726  /// Constructor with insert-before-instruction semantics
4727  SExtInst(
4728  Value *S, ///< The value to be sign extended
4729  Type *Ty, ///< The type to sign extend to
4730  const Twine &NameStr = "", ///< A name for the new instruction
4731  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4732  );
4733 
4734  /// Constructor with insert-at-end-of-block semantics
4735  SExtInst(
4736  Value *S, ///< The value to be sign extended
4737  Type *Ty, ///< The type to sign extend to
4738  const Twine &NameStr, ///< A name for the new instruction
4739  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4740  );
4741 
4742  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4743  static bool classof(const Instruction *I) {
4744  return I->getOpcode() == SExt;
4745  }
4746  static bool classof(const Value *V) {
4747  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4748  }
4749 };
4750 
4751 //===----------------------------------------------------------------------===//
4752 // FPTruncInst Class
4753 //===----------------------------------------------------------------------===//
4754 
4755 /// This class represents a truncation of floating point types.
4756 class FPTruncInst : public CastInst {
4757 protected:
4758  // Note: Instruction needs to be a friend here to call cloneImpl.
4759  friend class Instruction;
4760 
4761  /// Clone an identical FPTruncInst
4762  FPTruncInst *cloneImpl() const;
4763 
4764 public:
4765  /// Constructor with insert-before-instruction semantics
4766  FPTruncInst(
4767  Value *S, ///< The value to be truncated
4768  Type *Ty, ///< The type to truncate to
4769  const Twine &NameStr = "", ///< A name for the new instruction
4770  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4771  );
4772 
4773  /// Constructor with insert-before-instruction semantics
4774  FPTruncInst(
4775  Value *S, ///< The value to be truncated
4776  Type *Ty, ///< The type to truncate to
4777  const Twine &NameStr, ///< A name for the new instruction
4778  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4779  );
4780 
4781  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4782  static bool classof(const Instruction *I) {
4783  return I->getOpcode() == FPTrunc;
4784  }
4785  static bool classof(const Value *V) {
4786  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4787  }
4788 };
4789 
4790 //===----------------------------------------------------------------------===//
4791 // FPExtInst Class
4792 //===----------------------------------------------------------------------===//
4793 
4794 /// This class represents an extension of floating point types.
4795 class FPExtInst : public CastInst {
4796 protected:
4797  // Note: Instruction needs to be a friend here to call cloneImpl.
4798  friend class Instruction;
4799 
4800  /// Clone an identical FPExtInst
4801  FPExtInst *cloneImpl() const;
4802 
4803 public:
4804  /// Constructor with insert-before-instruction semantics
4805  FPExtInst(
4806  Value *S, ///< The value to be extended
4807  Type *Ty, ///< The type to extend to
4808  const Twine &NameStr = "", ///< A name for the new instruction
4809  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4810  );
4811 
4812  /// Constructor with insert-at-end-of-block semantics
4813  FPExtInst(
4814  Value *S, ///< The value to be extended
4815  Type *Ty, ///< The type to extend to
4816  const Twine &NameStr, ///< A name for the new instruction
4817  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4818  );
4819 
4820  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4821  static bool classof(const Instruction *I) {
4822  return I->getOpcode() == FPExt;
4823  }
4824  static bool classof(const Value *V) {
4825  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4826  }
4827 };
4828 
4829 //===----------------------------------------------------------------------===//
4830 // UIToFPInst Class
4831 //===----------------------------------------------------------------------===//
4832 
4833 /// This class represents a cast unsigned integer to floating point.
4834 class UIToFPInst : public CastInst {
4835 protected:
4836  // Note: Instruction needs to be a friend here to call cloneImpl.
4837  friend class Instruction;
4838 
4839  /// Clone an identical UIToFPInst
4840  UIToFPInst *cloneImpl() const;
4841 
4842 public:
4843  /// Constructor with insert-before-instruction semantics
4844  UIToFPInst(
4845  Value *S, ///< The value to be converted
4846  Type *Ty, ///< The type to convert to
4847  const Twine &NameStr = "", ///< A name for the new instruction
4848  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4849  );
4850 
4851  /// Constructor with insert-at-end-of-block semantics
4852  UIToFPInst(
4853  Value *S, ///< The value to be converted
4854  Type *Ty, ///< The type to convert to
4855  const Twine &NameStr, ///< A name for the new instruction
4856  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4857  );
4858 
4859  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4860  static bool classof(const Instruction *I) {
4861  return I->getOpcode() == UIToFP;
4862  }
4863  static bool classof(const Value *V) {
4864  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4865  }
4866 };
4867 
4868 //===----------------------------------------------------------------------===//
4869 // SIToFPInst Class
4870 //===----------------------------------------------------------------------===//
4871 
4872 /// This class represents a cast from signed integer to floating point.
4873 class SIToFPInst : public CastInst {
4874 protected:
4875  // Note: Instruction needs to be a friend here to call cloneImpl.
4876  friend class Instruction;
4877 
4878  /// Clone an identical SIToFPInst
4879  SIToFPInst *cloneImpl() const;
4880 
4881 public:
4882  /// Constructor with insert-before-instruction semantics
4883  SIToFPInst(
4884  Value *S, ///< The value to be converted
4885  Type *Ty, ///< The type to convert to
4886  const Twine &NameStr = "", ///< A name for the new instruction
4887  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4888  );
4889 
4890  /// Constructor with insert-at-end-of-block semantics
4891  SIToFPInst(
4892  Value *S, ///< The value to be converted
4893  Type *Ty, ///< The type to convert to
4894  const Twine &NameStr, ///< A name for the new instruction
4895  BasicBlock *InsertAtEnd ///< The block to insert the instruction into