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