LLVM  10.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  /// Swap the true and false values of the select instruction.
1768  /// This doesn't swap prof metadata.
1769  void swapValues() { Op<1>().swap(Op<2>()); }
1770 
1771  /// Return a string if the specified operands are invalid
1772  /// for a select operation, otherwise return null.
1773  static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1774 
1775  /// Transparently provide more efficient getOperand methods.
1777 
1779  return static_cast<OtherOps>(Instruction::getOpcode());
1780  }
1781 
1782  // Methods for support type inquiry through isa, cast, and dyn_cast:
1783  static bool classof(const Instruction *I) {
1784  return I->getOpcode() == Instruction::Select;
1785  }
1786  static bool classof(const Value *V) {
1787  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1788  }
1789 };
1790 
1791 template <>
1792 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1793 };
1794 
1796 
1797 //===----------------------------------------------------------------------===//
1798 // VAArgInst Class
1799 //===----------------------------------------------------------------------===//
1800 
1801 /// This class represents the va_arg llvm instruction, which returns
1802 /// an argument of the specified type given a va_list and increments that list
1803 ///
1804 class VAArgInst : public UnaryInstruction {
1805 protected:
1806  // Note: Instruction needs to be a friend here to call cloneImpl.
1807  friend class Instruction;
1808 
1809  VAArgInst *cloneImpl() const;
1810 
1811 public:
1812  VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1813  Instruction *InsertBefore = nullptr)
1814  : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1815  setName(NameStr);
1816  }
1817 
1818  VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1819  BasicBlock *InsertAtEnd)
1820  : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1821  setName(NameStr);
1822  }
1823 
1825  const Value *getPointerOperand() const { return getOperand(0); }
1826  static unsigned getPointerOperandIndex() { return 0U; }
1827 
1828  // Methods for support type inquiry through isa, cast, and dyn_cast:
1829  static bool classof(const Instruction *I) {
1830  return I->getOpcode() == VAArg;
1831  }
1832  static bool classof(const Value *V) {
1833  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1834  }
1835 };
1836 
1837 //===----------------------------------------------------------------------===//
1838 // ExtractElementInst Class
1839 //===----------------------------------------------------------------------===//
1840 
1841 /// This instruction extracts a single (scalar)
1842 /// element from a VectorType value
1843 ///
1845  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1846  Instruction *InsertBefore = nullptr);
1847  ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1848  BasicBlock *InsertAtEnd);
1849 
1850 protected:
1851  // Note: Instruction needs to be a friend here to call cloneImpl.
1852  friend class Instruction;
1853 
1854  ExtractElementInst *cloneImpl() const;
1855 
1856 public:
1857  static ExtractElementInst *Create(Value *Vec, Value *Idx,
1858  const Twine &NameStr = "",
1859  Instruction *InsertBefore = nullptr) {
1860  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1861  }
1862 
1863  static ExtractElementInst *Create(Value *Vec, Value *Idx,
1864  const Twine &NameStr,
1865  BasicBlock *InsertAtEnd) {
1866  return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1867  }
1868 
1869  /// Return true if an extractelement instruction can be
1870  /// formed with the specified operands.
1871  static bool isValidOperands(const Value *Vec, const Value *Idx);
1872 
1873  Value *getVectorOperand() { return Op<0>(); }
1874  Value *getIndexOperand() { return Op<1>(); }
1875  const Value *getVectorOperand() const { return Op<0>(); }
1876  const Value *getIndexOperand() const { return Op<1>(); }
1877 
1879  return cast<VectorType>(getVectorOperand()->getType());
1880  }
1881 
1882  /// Transparently provide more efficient getOperand methods.
1884 
1885  // Methods for support type inquiry through isa, cast, and dyn_cast:
1886  static bool classof(const Instruction *I) {
1887  return I->getOpcode() == Instruction::ExtractElement;
1888  }
1889  static bool classof(const Value *V) {
1890  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1891  }
1892 };
1893 
1894 template <>
1896  public FixedNumOperandTraits<ExtractElementInst, 2> {
1897 };
1898 
1899 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1900 
1901 //===----------------------------------------------------------------------===//
1902 // InsertElementInst Class
1903 //===----------------------------------------------------------------------===//
1904 
1905 /// This instruction inserts a single (scalar)
1906 /// element into a VectorType value
1907 ///
1909  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1910  const Twine &NameStr = "",
1911  Instruction *InsertBefore = nullptr);
1912  InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1913  BasicBlock *InsertAtEnd);
1914 
1915 protected:
1916  // Note: Instruction needs to be a friend here to call cloneImpl.
1917  friend class Instruction;
1918 
1919  InsertElementInst *cloneImpl() const;
1920 
1921 public:
1922  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1923  const Twine &NameStr = "",
1924  Instruction *InsertBefore = nullptr) {
1925  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1926  }
1927 
1928  static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1929  const Twine &NameStr,
1930  BasicBlock *InsertAtEnd) {
1931  return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1932  }
1933 
1934  /// Return true if an insertelement instruction can be
1935  /// formed with the specified operands.
1936  static bool isValidOperands(const Value *Vec, const Value *NewElt,
1937  const Value *Idx);
1938 
1939  /// Overload to return most specific vector type.
1940  ///
1941  VectorType *getType() const {
1942  return cast<VectorType>(Instruction::getType());
1943  }
1944 
1945  /// Transparently provide more efficient getOperand methods.
1947 
1948  // Methods for support type inquiry through isa, cast, and dyn_cast:
1949  static bool classof(const Instruction *I) {
1950  return I->getOpcode() == Instruction::InsertElement;
1951  }
1952  static bool classof(const Value *V) {
1953  return isa<Instruction>(V) && classof(cast<Instruction>(V));
1954  }
1955 };
1956 
1957 template <>
1959  public FixedNumOperandTraits<InsertElementInst, 3> {
1960 };
1961 
1962 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1963 
1964 //===----------------------------------------------------------------------===//
1965 // ShuffleVectorInst Class
1966 //===----------------------------------------------------------------------===//
1967 
1968 /// This instruction constructs a fixed permutation of two
1969 /// input vectors.
1970 ///
1972 protected:
1973  // Note: Instruction needs to be a friend here to call cloneImpl.
1974  friend class Instruction;
1975 
1976  ShuffleVectorInst *cloneImpl() const;
1977 
1978 public:
1980  const Twine &NameStr = "",
1981  Instruction *InsertBefor = nullptr);
1983  const Twine &NameStr, BasicBlock *InsertAtEnd);
1984 
1985  // allocate space for exactly three operands
1986  void *operator new(size_t s) {
1987  return User::operator new(s, 3);
1988  }
1989 
1990  /// Swap the first 2 operands and adjust the mask to preserve the semantics
1991  /// of the instruction.
1992  void commute();
1993 
1994  /// Return true if a shufflevector instruction can be
1995  /// formed with the specified operands.
1996  static bool isValidOperands(const Value *V1, const Value *V2,
1997  const Value *Mask);
1998 
1999  /// Overload to return most specific vector type.
2000  ///
2001  VectorType *getType() const {
2002  return cast<VectorType>(Instruction::getType());
2003  }
2004 
2005  /// Transparently provide more efficient getOperand methods.
2007 
2008  Constant *getMask() const {
2009  return cast<Constant>(getOperand(2));
2010  }
2011 
2012  /// Return the shuffle mask value for the specified element of the mask.
2013  /// Return -1 if the element is undef.
2014  static int getMaskValue(const Constant *Mask, unsigned Elt);
2015 
2016  /// Return the shuffle mask value of this instruction for the given element
2017  /// index. Return -1 if the element is undef.
2018  int getMaskValue(unsigned Elt) const {
2019  return getMaskValue(getMask(), Elt);
2020  }
2021 
2022  /// Convert the input shuffle mask operand to a vector of integers. Undefined
2023  /// elements of the mask are returned as -1.
2024  static void getShuffleMask(const Constant *Mask,
2025  SmallVectorImpl<int> &Result);
2026 
2027  /// Return the mask for this instruction as a vector of integers. Undefined
2028  /// elements of the mask are returned as -1.
2029  void getShuffleMask(SmallVectorImpl<int> &Result) const {
2030  return getShuffleMask(getMask(), Result);
2031  }
2032 
2035  getShuffleMask(Mask);
2036  return Mask;
2037  }
2038 
2039  /// Return true if this shuffle returns a vector with a different number of
2040  /// elements than its source vectors.
2041  /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2042  /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2043  bool changesLength() const {
2044  unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2045  unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2046  return NumSourceElts != NumMaskElts;
2047  }
2048 
2049  /// Return true if this shuffle returns a vector with a greater number of
2050  /// elements than its source vectors.
2051  /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2052  bool increasesLength() const {
2053  unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2054  unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2055  return NumSourceElts < NumMaskElts;
2056  }
2057 
2058  /// Return true if this shuffle mask chooses elements from exactly one source
2059  /// vector.
2060  /// Example: <7,5,undef,7>
2061  /// This assumes that vector operands are the same length as the mask.
2062  static bool isSingleSourceMask(ArrayRef<int> Mask);
2063  static bool isSingleSourceMask(const Constant *Mask) {
2064  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2065  SmallVector<int, 16> MaskAsInts;
2066  getShuffleMask(Mask, MaskAsInts);
2067  return isSingleSourceMask(MaskAsInts);
2068  }
2069 
2070  /// Return true if this shuffle chooses elements from exactly one source
2071  /// vector without changing the length of that vector.
2072  /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2073  /// TODO: Optionally allow length-changing shuffles.
2074  bool isSingleSource() const {
2075  return !changesLength() && isSingleSourceMask(getMask());
2076  }
2077 
2078  /// Return true if this shuffle mask chooses elements from exactly one source
2079  /// vector without lane crossings. A shuffle using this mask is not
2080  /// necessarily a no-op because it may change the number of elements from its
2081  /// input vectors or it may provide demanded bits knowledge via undef lanes.
2082  /// Example: <undef,undef,2,3>
2083  static bool isIdentityMask(ArrayRef<int> Mask);
2084  static bool isIdentityMask(const Constant *Mask) {
2085  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2086  SmallVector<int, 16> MaskAsInts;
2087  getShuffleMask(Mask, MaskAsInts);
2088  return isIdentityMask(MaskAsInts);
2089  }
2090 
2091  /// Return true if this shuffle chooses elements from exactly one source
2092  /// vector without lane crossings and does not change the number of elements
2093  /// from its input vectors.
2094  /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2095  bool isIdentity() const {
2096  return !changesLength() && isIdentityMask(getShuffleMask());
2097  }
2098 
2099  /// Return true if this shuffle lengthens exactly one source vector with
2100  /// undefs in the high elements.
2101  bool isIdentityWithPadding() const;
2102 
2103  /// Return true if this shuffle extracts the first N elements of exactly one
2104  /// source vector.
2105  bool isIdentityWithExtract() const;
2106 
2107  /// Return true if this shuffle concatenates its 2 source vectors. This
2108  /// returns false if either input is undefined. In that case, the shuffle is
2109  /// is better classified as an identity with padding operation.
2110  bool isConcat() const;
2111 
2112  /// Return true if this shuffle mask chooses elements from its source vectors
2113  /// without lane crossings. A shuffle using this mask would be
2114  /// equivalent to a vector select with a constant condition operand.
2115  /// Example: <4,1,6,undef>
2116  /// This returns false if the mask does not choose from both input vectors.
2117  /// In that case, the shuffle is better classified as an identity shuffle.
2118  /// This assumes that vector operands are the same length as the mask
2119  /// (a length-changing shuffle can never be equivalent to a vector select).
2120  static bool isSelectMask(ArrayRef<int> Mask);
2121  static bool isSelectMask(const Constant *Mask) {
2122  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2123  SmallVector<int, 16> MaskAsInts;
2124  getShuffleMask(Mask, MaskAsInts);
2125  return isSelectMask(MaskAsInts);
2126  }
2127 
2128  /// Return true if this shuffle chooses elements from its source vectors
2129  /// without lane crossings and all operands have the same number of elements.
2130  /// In other words, this shuffle is equivalent to a vector select with a
2131  /// constant condition operand.
2132  /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2133  /// This returns false if the mask does not choose from both input vectors.
2134  /// In that case, the shuffle is better classified as an identity shuffle.
2135  /// TODO: Optionally allow length-changing shuffles.
2136  bool isSelect() const {
2137  return !changesLength() && isSelectMask(getMask());
2138  }
2139 
2140  /// Return true if this shuffle mask swaps the order of elements from exactly
2141  /// one source vector.
2142  /// Example: <7,6,undef,4>
2143  /// This assumes that vector operands are the same length as the mask.
2144  static bool isReverseMask(ArrayRef<int> Mask);
2145  static bool isReverseMask(const Constant *Mask) {
2146  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2147  SmallVector<int, 16> MaskAsInts;
2148  getShuffleMask(Mask, MaskAsInts);
2149  return isReverseMask(MaskAsInts);
2150  }
2151 
2152  /// Return true if this shuffle swaps the order of elements from exactly
2153  /// one source vector.
2154  /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2155  /// TODO: Optionally allow length-changing shuffles.
2156  bool isReverse() const {
2157  return !changesLength() && isReverseMask(getMask());
2158  }
2159 
2160  /// Return true if this shuffle mask chooses all elements with the same value
2161  /// as the first element of exactly one source vector.
2162  /// Example: <4,undef,undef,4>
2163  /// This assumes that vector operands are the same length as the mask.
2164  static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2165  static bool isZeroEltSplatMask(const Constant *Mask) {
2166  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2167  SmallVector<int, 16> MaskAsInts;
2168  getShuffleMask(Mask, MaskAsInts);
2169  return isZeroEltSplatMask(MaskAsInts);
2170  }
2171 
2172  /// Return true if all elements of this shuffle are the same value as the
2173  /// first element of exactly one source vector without changing the length
2174  /// of that vector.
2175  /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2176  /// TODO: Optionally allow length-changing shuffles.
2177  /// TODO: Optionally allow splats from other elements.
2178  bool isZeroEltSplat() const {
2179  return !changesLength() && isZeroEltSplatMask(getMask());
2180  }
2181 
2182  /// Return true if this shuffle mask is a transpose mask.
2183  /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2184  /// even- or odd-numbered vector elements from two n-dimensional source
2185  /// vectors and write each result into consecutive elements of an
2186  /// n-dimensional destination vector. Two shuffles are necessary to complete
2187  /// the transpose, one for the even elements and another for the odd elements.
2188  /// This description closely follows how the TRN1 and TRN2 AArch64
2189  /// instructions operate.
2190  ///
2191  /// For example, a simple 2x2 matrix can be transposed with:
2192  ///
2193  /// ; Original matrix
2194  /// m0 = < a, b >
2195  /// m1 = < c, d >
2196  ///
2197  /// ; Transposed matrix
2198  /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2199  /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2200  ///
2201  /// For matrices having greater than n columns, the resulting nx2 transposed
2202  /// matrix is stored in two result vectors such that one vector contains
2203  /// interleaved elements from all the even-numbered rows and the other vector
2204  /// contains interleaved elements from all the odd-numbered rows. For example,
2205  /// a 2x4 matrix can be transposed with:
2206  ///
2207  /// ; Original matrix
2208  /// m0 = < a, b, c, d >
2209  /// m1 = < e, f, g, h >
2210  ///
2211  /// ; Transposed matrix
2212  /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2213  /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2214  static bool isTransposeMask(ArrayRef<int> Mask);
2215  static bool isTransposeMask(const Constant *Mask) {
2216  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2217  SmallVector<int, 16> MaskAsInts;
2218  getShuffleMask(Mask, MaskAsInts);
2219  return isTransposeMask(MaskAsInts);
2220  }
2221 
2222  /// Return true if this shuffle transposes the elements of its inputs without
2223  /// changing the length of the vectors. This operation may also be known as a
2224  /// merge or interleave. See the description for isTransposeMask() for the
2225  /// exact specification.
2226  /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2227  bool isTranspose() const {
2228  return !changesLength() && isTransposeMask(getMask());
2229  }
2230 
2231  /// Return true if this shuffle mask is an extract subvector mask.
2232  /// A valid extract subvector mask returns a smaller vector from a single
2233  /// source operand. The base extraction index is returned as well.
2234  static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2235  int &Index);
2236  static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2237  int &Index) {
2238  assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2239  SmallVector<int, 16> MaskAsInts;
2240  getShuffleMask(Mask, MaskAsInts);
2241  return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2242  }
2243 
2244  /// Return true if this shuffle mask is an extract subvector mask.
2245  bool isExtractSubvectorMask(int &Index) const {
2246  int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2247  return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2248  }
2249 
2250  /// Change values in a shuffle permute mask assuming the two vector operands
2251  /// of length InVecNumElts have swapped position.
2253  unsigned InVecNumElts) {
2254  for (int &Idx : Mask) {
2255  if (Idx == -1)
2256  continue;
2257  Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2258  assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2259  "shufflevector mask index out of range");
2260  }
2261  }
2262 
2263  // Methods for support type inquiry through isa, cast, and dyn_cast:
2264  static bool classof(const Instruction *I) {
2265  return I->getOpcode() == Instruction::ShuffleVector;
2266  }
2267  static bool classof(const Value *V) {
2268  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2269  }
2270 };
2271 
2272 template <>
2274  public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2275 };
2276 
2277 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2278 
2279 //===----------------------------------------------------------------------===//
2280 // ExtractValueInst Class
2281 //===----------------------------------------------------------------------===//
2282 
2283 /// This instruction extracts a struct member or array
2284 /// element value from an aggregate value.
2285 ///
2287  SmallVector<unsigned, 4> Indices;
2288 
2289  ExtractValueInst(const ExtractValueInst &EVI);
2290 
2291  /// Constructors - Create a extractvalue instruction with a base aggregate
2292  /// value and a list of indices. The first ctor can optionally insert before
2293  /// an existing instruction, the second appends the new instruction to the
2294  /// specified BasicBlock.
2295  inline ExtractValueInst(Value *Agg,
2296  ArrayRef<unsigned> Idxs,
2297  const Twine &NameStr,
2298  Instruction *InsertBefore);
2299  inline ExtractValueInst(Value *Agg,
2300  ArrayRef<unsigned> Idxs,
2301  const Twine &NameStr, BasicBlock *InsertAtEnd);
2302 
2303  void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2304 
2305 protected:
2306  // Note: Instruction needs to be a friend here to call cloneImpl.
2307  friend class Instruction;
2308 
2309  ExtractValueInst *cloneImpl() const;
2310 
2311 public:
2313  ArrayRef<unsigned> Idxs,
2314  const Twine &NameStr = "",
2315  Instruction *InsertBefore = nullptr) {
2316  return new
2317  ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2318  }
2319 
2321  ArrayRef<unsigned> Idxs,
2322  const Twine &NameStr,
2323  BasicBlock *InsertAtEnd) {
2324  return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2325  }
2326 
2327  /// Returns the type of the element that would be extracted
2328  /// with an extractvalue instruction with the specified parameters.
2329  ///
2330  /// Null is returned if the indices are invalid for the specified type.
2331  static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2332 
2333  using idx_iterator = const unsigned*;
2334 
2335  inline idx_iterator idx_begin() const { return Indices.begin(); }
2336  inline idx_iterator idx_end() const { return Indices.end(); }
2338  return make_range(idx_begin(), idx_end());
2339  }
2340 
2342  return getOperand(0);
2343  }
2344  const Value *getAggregateOperand() const {
2345  return getOperand(0);
2346  }
2347  static unsigned getAggregateOperandIndex() {
2348  return 0U; // get index for modifying correct operand
2349  }
2350 
2352  return Indices;
2353  }
2354 
2355  unsigned getNumIndices() const {
2356  return (unsigned)Indices.size();
2357  }
2358 
2359  bool hasIndices() const {
2360  return true;
2361  }
2362 
2363  // Methods for support type inquiry through isa, cast, and dyn_cast:
2364  static bool classof(const Instruction *I) {
2365  return I->getOpcode() == Instruction::ExtractValue;
2366  }
2367  static bool classof(const Value *V) {
2368  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2369  }
2370 };
2371 
2372 ExtractValueInst::ExtractValueInst(Value *Agg,
2373  ArrayRef<unsigned> Idxs,
2374  const Twine &NameStr,
2375  Instruction *InsertBefore)
2376  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2377  ExtractValue, Agg, InsertBefore) {
2378  init(Idxs, NameStr);
2379 }
2380 
2381 ExtractValueInst::ExtractValueInst(Value *Agg,
2382  ArrayRef<unsigned> Idxs,
2383  const Twine &NameStr,
2384  BasicBlock *InsertAtEnd)
2385  : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2386  ExtractValue, Agg, InsertAtEnd) {
2387  init(Idxs, NameStr);
2388 }
2389 
2390 //===----------------------------------------------------------------------===//
2391 // InsertValueInst Class
2392 //===----------------------------------------------------------------------===//
2393 
2394 /// This instruction inserts a struct field of array element
2395 /// value into an aggregate value.
2396 ///
2398  SmallVector<unsigned, 4> Indices;
2399 
2400  InsertValueInst(const InsertValueInst &IVI);
2401 
2402  /// Constructors - Create a insertvalue instruction with a base aggregate
2403  /// value, a value to insert, and a list of indices. The first ctor can
2404  /// optionally insert before an existing instruction, the second appends
2405  /// the new instruction to the specified BasicBlock.
2406  inline InsertValueInst(Value *Agg, Value *Val,
2407  ArrayRef<unsigned> Idxs,
2408  const Twine &NameStr,
2409  Instruction *InsertBefore);
2410  inline InsertValueInst(Value *Agg, Value *Val,
2411  ArrayRef<unsigned> Idxs,
2412  const Twine &NameStr, BasicBlock *InsertAtEnd);
2413 
2414  /// Constructors - These two constructors are convenience methods because one
2415  /// and two index insertvalue instructions are so common.
2416  InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2417  const Twine &NameStr = "",
2418  Instruction *InsertBefore = nullptr);
2419  InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2420  BasicBlock *InsertAtEnd);
2421 
2422  void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2423  const Twine &NameStr);
2424 
2425 protected:
2426  // Note: Instruction needs to be a friend here to call cloneImpl.
2427  friend class Instruction;
2428 
2429  InsertValueInst *cloneImpl() const;
2430 
2431 public:
2432  // allocate space for exactly two operands
2433  void *operator new(size_t s) {
2434  return User::operator new(s, 2);
2435  }
2436 
2437  static InsertValueInst *Create(Value *Agg, Value *Val,
2438  ArrayRef<unsigned> Idxs,
2439  const Twine &NameStr = "",
2440  Instruction *InsertBefore = nullptr) {
2441  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2442  }
2443 
2444  static InsertValueInst *Create(Value *Agg, Value *Val,
2445  ArrayRef<unsigned> Idxs,
2446  const Twine &NameStr,
2447  BasicBlock *InsertAtEnd) {
2448  return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2449  }
2450 
2451  /// Transparently provide more efficient getOperand methods.
2453 
2454  using idx_iterator = const unsigned*;
2455 
2456  inline idx_iterator idx_begin() const { return Indices.begin(); }
2457  inline idx_iterator idx_end() const { return Indices.end(); }
2459  return make_range(idx_begin(), idx_end());
2460  }
2461 
2463  return getOperand(0);
2464  }
2465  const Value *getAggregateOperand() const {
2466  return getOperand(0);
2467  }
2468  static unsigned getAggregateOperandIndex() {
2469  return 0U; // get index for modifying correct operand
2470  }
2471 
2473  return getOperand(1);
2474  }
2476  return getOperand(1);
2477  }
2478  static unsigned getInsertedValueOperandIndex() {
2479  return 1U; // get index for modifying correct operand
2480  }
2481 
2483  return Indices;
2484  }
2485 
2486  unsigned getNumIndices() const {
2487  return (unsigned)Indices.size();
2488  }
2489 
2490  bool hasIndices() const {
2491  return true;
2492  }
2493 
2494  // Methods for support type inquiry through isa, cast, and dyn_cast:
2495  static bool classof(const Instruction *I) {
2496  return I->getOpcode() == Instruction::InsertValue;
2497  }
2498  static bool classof(const Value *V) {
2499  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2500  }
2501 };
2502 
2503 template <>
2505  public FixedNumOperandTraits<InsertValueInst, 2> {
2506 };
2507 
2508 InsertValueInst::InsertValueInst(Value *Agg,
2509  Value *Val,
2510  ArrayRef<unsigned> Idxs,
2511  const Twine &NameStr,
2512  Instruction *InsertBefore)
2513  : Instruction(Agg->getType(), InsertValue,
2515  2, InsertBefore) {
2516  init(Agg, Val, Idxs, NameStr);
2517 }
2518 
2519 InsertValueInst::InsertValueInst(Value *Agg,
2520  Value *Val,
2521  ArrayRef<unsigned> Idxs,
2522  const Twine &NameStr,
2523  BasicBlock *InsertAtEnd)
2524  : Instruction(Agg->getType(), InsertValue,
2526  2, InsertAtEnd) {
2527  init(Agg, Val, Idxs, NameStr);
2528 }
2529 
2531 
2532 //===----------------------------------------------------------------------===//
2533 // PHINode Class
2534 //===----------------------------------------------------------------------===//
2535 
2536 // PHINode - The PHINode class is used to represent the magical mystical PHI
2537 // node, that can not exist in nature, but can be synthesized in a computer
2538 // scientist's overactive imagination.
2539 //
2540 class PHINode : public Instruction {
2541  /// The number of operands actually allocated. NumOperands is
2542  /// the number actually in use.
2543  unsigned ReservedSpace;
2544 
2545  PHINode(const PHINode &PN);
2546 
2547  explicit PHINode(Type *Ty, unsigned NumReservedValues,
2548  const Twine &NameStr = "",
2549  Instruction *InsertBefore = nullptr)
2550  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2551  ReservedSpace(NumReservedValues) {
2552  setName(NameStr);
2553  allocHungoffUses(ReservedSpace);
2554  }
2555 
2556  PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2557  BasicBlock *InsertAtEnd)
2558  : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2559  ReservedSpace(NumReservedValues) {
2560  setName(NameStr);
2561  allocHungoffUses(ReservedSpace);
2562  }
2563 
2564 protected:
2565  // Note: Instruction needs to be a friend here to call cloneImpl.
2566  friend class Instruction;
2567 
2568  PHINode *cloneImpl() const;
2569 
2570  // allocHungoffUses - this is more complicated than the generic
2571  // User::allocHungoffUses, because we have to allocate Uses for the incoming
2572  // values and pointers to the incoming blocks, all in one allocation.
2573  void allocHungoffUses(unsigned N) {
2574  User::allocHungoffUses(N, /* IsPhi */ true);
2575  }
2576 
2577 public:
2578  /// Constructors - NumReservedValues is a hint for the number of incoming
2579  /// edges that this phi node will have (use 0 if you really have no idea).
2580  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2581  const Twine &NameStr = "",
2582  Instruction *InsertBefore = nullptr) {
2583  return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2584  }
2585 
2586  static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2587  const Twine &NameStr, BasicBlock *InsertAtEnd) {
2588  return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2589  }
2590 
2591  /// Provide fast operand accessors
2593 
2594  // Block iterator interface. This provides access to the list of incoming
2595  // basic blocks, which parallels the list of incoming values.
2596 
2599 
2601  Use::UserRef *ref =
2602  reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2603  return reinterpret_cast<block_iterator>(ref + 1);
2604  }
2605 
2607  const Use::UserRef *ref =
2608  reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2609  return reinterpret_cast<const_block_iterator>(ref + 1);
2610  }
2611 
2613  return block_begin() + getNumOperands();
2614  }
2615 
2617  return block_begin() + getNumOperands();
2618  }
2619 
2621  return make_range(block_begin(), block_end());
2622  }
2623 
2625  return make_range(block_begin(), block_end());
2626  }
2627 
2629 
2631 
2632  /// Return the number of incoming edges
2633  ///
2634  unsigned getNumIncomingValues() const { return getNumOperands(); }
2635 
2636  /// Return incoming value number x
2637  ///
2638  Value *getIncomingValue(unsigned i) const {
2639  return getOperand(i);
2640  }
2641  void setIncomingValue(unsigned i, Value *V) {
2642  assert(V && "PHI node got a null value!");
2643  assert(getType() == V->getType() &&
2644  "All operands to PHI node must be the same type as the PHI node!");
2645  setOperand(i, V);
2646  }
2647 
2648  static unsigned getOperandNumForIncomingValue(unsigned i) {
2649  return i;
2650  }
2651 
2652  static unsigned getIncomingValueNumForOperand(unsigned i) {
2653  return i;
2654  }
2655 
2656  /// Return incoming basic block number @p i.
2657  ///
2658  BasicBlock *getIncomingBlock(unsigned i) const {
2659  return block_begin()[i];
2660  }
2661 
2662  /// Return incoming basic block corresponding
2663  /// to an operand of the PHI.
2664  ///
2665  BasicBlock *getIncomingBlock(const Use &U) const {
2666  assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2667  return getIncomingBlock(unsigned(&U - op_begin()));
2668  }
2669 
2670  /// Return incoming basic block corresponding
2671  /// to value use iterator.
2672  ///
2674  return getIncomingBlock(I.getUse());
2675  }
2676 
2677  void setIncomingBlock(unsigned i, BasicBlock *BB) {
2678  assert(BB && "PHI node got a null basic block!");
2679  block_begin()[i] = BB;
2680  }
2681 
2682  /// Replace every incoming basic block \p Old to basic block \p New.
2684  assert(New && Old && "PHI node got a null basic block!");
2685  for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2686  if (getIncomingBlock(Op) == Old)
2687  setIncomingBlock(Op, New);
2688  }
2689 
2690  /// Add an incoming value to the end of the PHI list
2691  ///
2692  void addIncoming(Value *V, BasicBlock *BB) {
2693  if (getNumOperands() == ReservedSpace)
2694  growOperands(); // Get more space!
2695  // Initialize some new operands.
2697  setIncomingValue(getNumOperands() - 1, V);
2698  setIncomingBlock(getNumOperands() - 1, BB);
2699  }
2700 
2701  /// Remove an incoming value. This is useful if a
2702  /// predecessor basic block is deleted. The value removed is returned.
2703  ///
2704  /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2705  /// is true), the PHI node is destroyed and any uses of it are replaced with
2706  /// dummy values. The only time there should be zero incoming values to a PHI
2707  /// node is when the block is dead, so this strategy is sound.
2708  ///
2709  Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2710 
2711  Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2712  int Idx = getBasicBlockIndex(BB);
2713  assert(Idx >= 0 && "Invalid basic block argument to remove!");
2714  return removeIncomingValue(Idx, DeletePHIIfEmpty);
2715  }
2716 
2717  /// Return the first index of the specified basic
2718  /// block in the value list for this PHI. Returns -1 if no instance.
2719  ///
2720  int getBasicBlockIndex(const BasicBlock *BB) const {
2721  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2722  if (block_begin()[i] == BB)
2723  return i;
2724  return -1;
2725  }
2726 
2728  int Idx = getBasicBlockIndex(BB);
2729  assert(Idx >= 0 && "Invalid basic block argument!");
2730  return getIncomingValue(Idx);
2731  }
2732 
2733  /// Set every incoming value(s) for block \p BB to \p V.
2735  assert(BB && "PHI node got a null basic block!");
2736  bool Found = false;
2737  for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2738  if (getIncomingBlock(Op) == BB) {
2739  Found = true;
2740  setIncomingValue(Op, V);
2741  }
2742  (void)Found;
2743  assert(Found && "Invalid basic block argument to set!");
2744  }
2745 
2746  /// If the specified PHI node always merges together the
2747  /// same value, return the value, otherwise return null.
2748  Value *hasConstantValue() const;
2749 
2750  /// Whether the specified PHI node always merges
2751  /// together the same value, assuming undefs are equal to a unique
2752  /// non-undef value.
2753  bool hasConstantOrUndefValue() const;
2754 
2755  /// Methods for support type inquiry through isa, cast, and dyn_cast:
2756  static bool classof(const Instruction *I) {
2757  return I->getOpcode() == Instruction::PHI;
2758  }
2759  static bool classof(const Value *V) {
2760  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2761  }
2762 
2763 private:
2764  void growOperands();
2765 };
2766 
2767 template <>
2769 };
2770 
2772 
2773 //===----------------------------------------------------------------------===//
2774 // LandingPadInst Class
2775 //===----------------------------------------------------------------------===//
2776 
2777 //===---------------------------------------------------------------------------
2778 /// The landingpad instruction holds all of the information
2779 /// necessary to generate correct exception handling. The landingpad instruction
2780 /// cannot be moved from the top of a landing pad block, which itself is
2781 /// accessible only from the 'unwind' edge of an invoke. This uses the
2782 /// SubclassData field in Value to store whether or not the landingpad is a
2783 /// cleanup.
2784 ///
2785 class LandingPadInst : public Instruction {
2786  /// The number of operands actually allocated. NumOperands is
2787  /// the number actually in use.
2788  unsigned ReservedSpace;
2789 
2790  LandingPadInst(const LandingPadInst &LP);
2791 
2792 public:
2794 
2795 private:
2796  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2797  const Twine &NameStr, Instruction *InsertBefore);
2798  explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2799  const Twine &NameStr, BasicBlock *InsertAtEnd);
2800 
2801  // Allocate space for exactly zero operands.
2802  void *operator new(size_t s) {
2803  return User::operator new(s);
2804  }
2805 
2806  void growOperands(unsigned Size);
2807  void init(unsigned NumReservedValues, const Twine &NameStr);
2808 
2809 protected:
2810  // Note: Instruction needs to be a friend here to call cloneImpl.
2811  friend class Instruction;
2812 
2813  LandingPadInst *cloneImpl() const;
2814 
2815 public:
2816  /// Constructors - NumReservedClauses is a hint for the number of incoming
2817  /// clauses that this landingpad will have (use 0 if you really have no idea).
2818  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2819  const Twine &NameStr = "",
2820  Instruction *InsertBefore = nullptr);
2821  static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2822  const Twine &NameStr, BasicBlock *InsertAtEnd);
2823 
2824  /// Provide fast operand accessors
2826 
2827  /// Return 'true' if this landingpad instruction is a
2828  /// cleanup. I.e., it should be run when unwinding even if its landing pad
2829  /// doesn't catch the exception.
2830  bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2831 
2832  /// Indicate that this landingpad instruction is a cleanup.
2833  void setCleanup(bool V) {
2834  setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2835  (V ? 1 : 0));
2836  }
2837 
2838  /// Add a catch or filter clause to the landing pad.
2839  void addClause(Constant *ClauseVal);
2840 
2841  /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2842  /// determine what type of clause this is.
2843  Constant *getClause(unsigned Idx) const {
2844  return cast<Constant>(getOperandList()[Idx]);
2845  }
2846 
2847  /// Return 'true' if the clause and index Idx is a catch clause.
2848  bool isCatch(unsigned Idx) const {
2849  return !isa<ArrayType>(getOperandList()[Idx]->getType());
2850  }
2851 
2852  /// Return 'true' if the clause and index Idx is a filter clause.
2853  bool isFilter(unsigned Idx) const {
2854  return isa<ArrayType>(getOperandList()[Idx]->getType());
2855  }
2856 
2857  /// Get the number of clauses for this landing pad.
2858  unsigned getNumClauses() const { return getNumOperands(); }
2859 
2860  /// Grow the size of the operand list to accommodate the new
2861  /// number of clauses.
2862  void reserveClauses(unsigned Size) { growOperands(Size); }
2863 
2864  // Methods for support type inquiry through isa, cast, and dyn_cast:
2865  static bool classof(const Instruction *I) {
2866  return I->getOpcode() == Instruction::LandingPad;
2867  }
2868  static bool classof(const Value *V) {
2869  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2870  }
2871 };
2872 
2873 template <>
2875 };
2876 
2878 
2879 //===----------------------------------------------------------------------===//
2880 // ReturnInst Class
2881 //===----------------------------------------------------------------------===//
2882 
2883 //===---------------------------------------------------------------------------
2884 /// Return a value (possibly void), from a function. Execution
2885 /// does not continue in this function any longer.
2886 ///
2887 class ReturnInst : public Instruction {
2888  ReturnInst(const ReturnInst &RI);
2889 
2890 private:
2891  // ReturnInst constructors:
2892  // ReturnInst() - 'ret void' instruction
2893  // ReturnInst( null) - 'ret void' instruction
2894  // ReturnInst(Value* X) - 'ret X' instruction
2895  // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2896  // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2897  // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2898  // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2899  //
2900  // NOTE: If the Value* passed is of type void then the constructor behaves as
2901  // if it was passed NULL.
2902  explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2903  Instruction *InsertBefore = nullptr);
2904  ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2905  explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2906 
2907 protected:
2908  // Note: Instruction needs to be a friend here to call cloneImpl.
2909  friend class Instruction;
2910 
2911  ReturnInst *cloneImpl() const;
2912 
2913 public:
2914  static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2915  Instruction *InsertBefore = nullptr) {
2916  return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2917  }
2918 
2919  static ReturnInst* Create(LLVMContext &C, Value *retVal,
2920  BasicBlock *InsertAtEnd) {
2921  return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2922  }
2923 
2924  static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2925  return new(0) ReturnInst(C, InsertAtEnd);
2926  }
2927 
2928  /// Provide fast operand accessors
2930 
2931  /// Convenience accessor. Returns null if there is no return value.
2933  return getNumOperands() != 0 ? getOperand(0) : nullptr;
2934  }
2935 
2936  unsigned getNumSuccessors() const { return 0; }
2937 
2938  // Methods for support type inquiry through isa, cast, and dyn_cast:
2939  static bool classof(const Instruction *I) {
2940  return (I->getOpcode() == Instruction::Ret);
2941  }
2942  static bool classof(const Value *V) {
2943  return isa<Instruction>(V) && classof(cast<Instruction>(V));
2944  }
2945 
2946 private:
2947  BasicBlock *getSuccessor(unsigned idx) const {
2948  llvm_unreachable("ReturnInst has no successors!");
2949  }
2950 
2951  void setSuccessor(unsigned idx, BasicBlock *B) {
2952  llvm_unreachable("ReturnInst has no successors!");
2953  }
2954 };
2955 
2956 template <>
2957 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2958 };
2959 
2961 
2962 //===----------------------------------------------------------------------===//
2963 // BranchInst Class
2964 //===----------------------------------------------------------------------===//
2965 
2966 //===---------------------------------------------------------------------------
2967 /// Conditional or Unconditional Branch instruction.
2968 ///
2969 class BranchInst : public Instruction {
2970  /// Ops list - Branches are strange. The operands are ordered:
2971  /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2972  /// they don't have to check for cond/uncond branchness. These are mostly
2973  /// accessed relative from op_end().
2974  BranchInst(const BranchInst &BI);
2975  // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2976  // BranchInst(BB *B) - 'br B'
2977  // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2978  // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2979  // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2980  // BranchInst(BB* B, BB *I) - 'br B' insert at end
2981  // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2982  explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2983  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2984  Instruction *InsertBefore = nullptr);
2985  BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2986  BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2987  BasicBlock *InsertAtEnd);
2988 
2989  void AssertOK();
2990 
2991 protected:
2992  // Note: Instruction needs to be a friend here to call cloneImpl.
2993  friend class Instruction;
2994 
2995  BranchInst *cloneImpl() const;
2996 
2997 public:
2998  /// Iterator type that casts an operand to a basic block.
2999  ///
3000  /// This only makes sense because the successors are stored as adjacent
3001  /// operands for branch instructions.
3003  : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3004  std::random_access_iterator_tag, BasicBlock *,
3005  ptrdiff_t, BasicBlock *, BasicBlock *> {
3007 
3008  BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3009  BasicBlock *operator->() const { return operator*(); }
3010  };
3011 
3012  /// The const version of `succ_op_iterator`.
3014  : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3015  std::random_access_iterator_tag,
3016  const BasicBlock *, ptrdiff_t, const BasicBlock *,
3017  const BasicBlock *> {
3019  : iterator_adaptor_base(I) {}
3020 
3021  const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3022  const BasicBlock *operator->() const { return operator*(); }
3023  };
3024 
3025  static BranchInst *Create(BasicBlock *IfTrue,
3026  Instruction *InsertBefore = nullptr) {
3027  return new(1) BranchInst(IfTrue, InsertBefore);
3028  }
3029 
3030  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3031  Value *Cond, Instruction *InsertBefore = nullptr) {
3032  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3033  }
3034 
3035  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3036  return new(1) BranchInst(IfTrue, InsertAtEnd);
3037  }
3038 
3039  static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3040  Value *Cond, BasicBlock *InsertAtEnd) {
3041  return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3042  }
3043 
3044  /// Transparently provide more efficient getOperand methods.
3046 
3047  bool isUnconditional() const { return getNumOperands() == 1; }
3048  bool isConditional() const { return getNumOperands() == 3; }
3049 
3050  Value *getCondition() const {
3051  assert(isConditional() && "Cannot get condition of an uncond branch!");
3052  return Op<-3>();
3053  }
3054 
3055  void setCondition(Value *V) {
3056  assert(isConditional() && "Cannot set condition of unconditional branch!");
3057  Op<-3>() = V;
3058  }
3059 
3060  unsigned getNumSuccessors() const { return 1+isConditional(); }
3061 
3062  BasicBlock *getSuccessor(unsigned i) const {
3063  assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3064  return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3065  }
3066 
3067  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3068  assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3069  *(&Op<-1>() - idx) = NewSucc;
3070  }
3071 
3072  /// Swap the successors of this branch instruction.
3073  ///
3074  /// Swaps the successors of the branch instruction. This also swaps any
3075  /// branch weight metadata associated with the instruction so that it
3076  /// continues to map correctly to each operand.
3077  void swapSuccessors();
3078 
3080  return make_range(
3081  succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3083  }
3084 
3087  std::next(value_op_begin(), isConditional() ? 1 : 0)),
3089  }
3090 
3091  // Methods for support type inquiry through isa, cast, and dyn_cast:
3092  static bool classof(const Instruction *I) {
3093  return (I->getOpcode() == Instruction::Br);
3094  }
3095  static bool classof(const Value *V) {
3096  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3097  }
3098 };
3099 
3100 template <>
3101 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3102 };
3103 
3105 
3106 //===----------------------------------------------------------------------===//
3107 // SwitchInst Class
3108 //===----------------------------------------------------------------------===//
3109 
3110 //===---------------------------------------------------------------------------
3111 /// Multiway switch
3112 ///
3113 class SwitchInst : public Instruction {
3114  unsigned ReservedSpace;
3115 
3116  // Operand[0] = Value to switch on
3117  // Operand[1] = Default basic block destination
3118  // Operand[2n ] = Value to match
3119  // Operand[2n+1] = BasicBlock to go to on match
3120  SwitchInst(const SwitchInst &SI);
3121 
3122  /// Create a new switch instruction, specifying a value to switch on and a
3123  /// default destination. The number of additional cases can be specified here
3124  /// to make memory allocation more efficient. This constructor can also
3125  /// auto-insert before another instruction.
3126  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3127  Instruction *InsertBefore);
3128 
3129  /// Create a new switch instruction, specifying a value to switch on and a
3130  /// default destination. The number of additional cases can be specified here
3131  /// to make memory allocation more efficient. This constructor also
3132  /// auto-inserts at the end of the specified BasicBlock.
3133  SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3134  BasicBlock *InsertAtEnd);
3135 
3136  // allocate space for exactly zero operands
3137  void *operator new(size_t s) {
3138  return User::operator new(s);
3139  }
3140 
3141  void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3142  void growOperands();
3143 
3144 protected:
3145  // Note: Instruction needs to be a friend here to call cloneImpl.
3146  friend class Instruction;
3147 
3148  SwitchInst *cloneImpl() const;
3149 
3150 public:
3151  // -2
3152  static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3153 
3154  template <typename CaseHandleT> class CaseIteratorImpl;
3155 
3156  /// A handle to a particular switch case. It exposes a convenient interface
3157  /// to both the case value and the successor block.
3158  ///
3159  /// We define this as a template and instantiate it to form both a const and
3160  /// non-const handle.
3161  template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3163  // Directly befriend both const and non-const iterators.
3164  friend class SwitchInst::CaseIteratorImpl<
3165  CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3166 
3167  protected:
3168  // Expose the switch type we're parameterized with to the iterator.
3169  using SwitchInstType = SwitchInstT;
3170 
3171  SwitchInstT *SI;
3173 
3174  CaseHandleImpl() = default;
3175  CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3176 
3177  public:
3178  /// Resolves case value for current case.
3179  ConstantIntT *getCaseValue() const {
3180  assert((unsigned)Index < SI->getNumCases() &&
3181  "Index out the number of cases.");
3182  return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3183  }
3184 
3185  /// Resolves successor for current case.
3186  BasicBlockT *getCaseSuccessor() const {
3187  assert(((unsigned)Index < SI->getNumCases() ||
3188  (unsigned)Index == DefaultPseudoIndex) &&
3189  "Index out the number of cases.");
3190  return SI->getSuccessor(getSuccessorIndex());
3191  }
3192 
3193  /// Returns number of current case.
3194  unsigned getCaseIndex() const { return Index; }
3195 
3196  /// Returns successor index for current case successor.
3197  unsigned getSuccessorIndex() const {
3198  assert(((unsigned)Index == DefaultPseudoIndex ||
3199  (unsigned)Index < SI->getNumCases()) &&
3200  "Index out the number of cases.");
3201  return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3202  }
3203 
3204  bool operator==(const CaseHandleImpl &RHS) const {
3205  assert(SI == RHS.SI && "Incompatible operators.");
3206  return Index == RHS.Index;
3207  }
3208  };
3209 
3210  using ConstCaseHandle =
3212 
3214  : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3216 
3217  public:
3219 
3220  /// Sets the new value for current case.
3222  assert((unsigned)Index < SI->getNumCases() &&
3223  "Index out the number of cases.");
3224  SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3225  }
3226 
3227  /// Sets the new successor for current case.
3229  SI->setSuccessor(getSuccessorIndex(), S);
3230  }
3231  };
3232 
3233  template <typename CaseHandleT>
3234  class CaseIteratorImpl
3235  : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3236  std::random_access_iterator_tag,
3237  CaseHandleT> {
3238  using SwitchInstT = typename CaseHandleT::SwitchInstType;
3239 
3240  CaseHandleT Case;
3241 
3242  public:
3243  /// Default constructed iterator is in an invalid state until assigned to
3244  /// a case for a particular switch.
3245  CaseIteratorImpl() = default;
3246 
3247  /// Initializes case iterator for given SwitchInst and for given
3248  /// case number.
3249  CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3250 
3251  /// Initializes case iterator for given SwitchInst and for given
3252  /// successor index.
3253  static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3254  unsigned SuccessorIndex) {
3255  assert(SuccessorIndex < SI->getNumSuccessors() &&
3256  "Successor index # out of range!");
3257  return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3258  : CaseIteratorImpl(SI, DefaultPseudoIndex);
3259  }
3260 
3261  /// Support converting to the const variant. This will be a no-op for const
3262  /// variant.
3264  return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3265  }
3266 
3268  // Check index correctness after addition.
3269  // Note: Index == getNumCases() means end().
3270  assert(Case.Index + N >= 0 &&
3271  (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3272  "Case.Index out the number of cases.");
3273  Case.Index += N;
3274  return *this;
3275  }
3277  // Check index correctness after subtraction.
3278  // Note: Case.Index == getNumCases() means end().
3279  assert(Case.Index - N >= 0 &&
3280  (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3281  "Case.Index out the number of cases.");
3282  Case.Index -= N;
3283  return *this;
3284  }
3286  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3287  return Case.Index - RHS.Case.Index;
3288  }
3289  bool operator==(const CaseIteratorImpl &RHS) const {
3290  return Case == RHS.Case;
3291  }
3292  bool operator<(const CaseIteratorImpl &RHS) const {
3293  assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3294  return Case.Index < RHS.Case.Index;
3295  }
3296  CaseHandleT &operator*() { return Case; }
3297  const CaseHandleT &operator*() const { return Case; }
3298  };
3299 
3302 
3303  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3304  unsigned NumCases,
3305  Instruction *InsertBefore = nullptr) {
3306  return new SwitchInst(Value, Default, NumCases, InsertBefore);
3307  }
3308 
3309  static SwitchInst *Create(Value *Value, BasicBlock *Default,
3310  unsigned NumCases, BasicBlock *InsertAtEnd) {
3311  return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3312  }
3313 
3314  /// Provide fast operand accessors
3316 
3317  // Accessor Methods for Switch stmt
3318  Value *getCondition() const { return getOperand(0); }
3319  void setCondition(Value *V) { setOperand(0, V); }
3320 
3322  return cast<BasicBlock>(getOperand(1));
3323  }
3324 
3325  void setDefaultDest(BasicBlock *DefaultCase) {
3326  setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3327  }
3328 
3329  /// Return the number of 'cases' in this switch instruction, excluding the
3330  /// default case.
3331  unsigned getNumCases() const {
3332  return getNumOperands()/2 - 1;
3333  }
3334 
3335  /// Returns a read/write iterator that points to the first case in the
3336  /// SwitchInst.
3338  return CaseIt(this, 0);
3339  }
3340 
3341  /// Returns a read-only iterator that points to the first case in the
3342  /// SwitchInst.
3344  return ConstCaseIt(this, 0);
3345  }
3346 
3347  /// Returns a read/write iterator that points one past the last in the
3348  /// SwitchInst.
3350  return CaseIt(this, getNumCases());
3351  }
3352 
3353  /// Returns a read-only iterator that points one past the last in the
3354  /// SwitchInst.
3356  return ConstCaseIt(this, getNumCases());
3357  }
3358 
3359  /// Iteration adapter for range-for loops.
3361  return make_range(case_begin(), case_end());
3362  }
3363 
3364  /// Constant iteration adapter for range-for loops.
3366  return make_range(case_begin(), case_end());
3367  }
3368 
3369  /// Returns an iterator that points to the default case.
3370  /// Note: this iterator allows to resolve successor only. Attempt
3371  /// to resolve case value causes an assertion.
3372  /// Also note, that increment and decrement also causes an assertion and
3373  /// makes iterator invalid.
3375  return CaseIt(this, DefaultPseudoIndex);
3376  }
3378  return ConstCaseIt(this, DefaultPseudoIndex);
3379  }
3380 
3381  /// Search all of the case values for the specified constant. If it is
3382  /// explicitly handled, return the case iterator of it, otherwise return
3383  /// default case iterator to indicate that it is handled by the default
3384  /// handler.
3387  cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3388  if (I != case_end())
3389  return I;
3390 
3391  return case_default();
3392  }
3394  ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3395  return Case.getCaseValue() == C;
3396  });
3397  if (I != case_end())
3398  return I;
3399 
3400  return case_default();
3401  }
3402 
3403  /// Finds the unique case value for a given successor. Returns null if the
3404  /// successor is not found, not unique, or is the default case.
3406  if (BB == getDefaultDest())
3407  return nullptr;
3408 
3409  ConstantInt *CI = nullptr;
3410  for (auto Case : cases()) {
3411  if (Case.getCaseSuccessor() != BB)
3412  continue;
3413 
3414  if (CI)
3415  return nullptr; // Multiple cases lead to BB.
3416 
3417  CI = Case.getCaseValue();
3418  }
3419 
3420  return CI;
3421  }
3422 
3423  /// Add an entry to the switch instruction.
3424  /// Note:
3425  /// This action invalidates case_end(). Old case_end() iterator will
3426  /// point to the added case.
3427  void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3428 
3429  /// This method removes the specified case and its successor from the switch
3430  /// instruction. Note that this operation may reorder the remaining cases at
3431  /// index idx and above.
3432  /// Note:
3433  /// This action invalidates iterators for all cases following the one removed,
3434  /// including the case_end() iterator. It returns an iterator for the next
3435  /// case.
3436  CaseIt removeCase(CaseIt I);
3437 
3438  unsigned getNumSuccessors() const { return getNumOperands()/2; }
3439  BasicBlock *getSuccessor(unsigned idx) const {
3440  assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3441  return cast<BasicBlock>(getOperand(idx*2+1));
3442  }
3443  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3444  assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3445  setOperand(idx * 2 + 1, NewSucc);
3446  }
3447 
3448  // Methods for support type inquiry through isa, cast, and dyn_cast:
3449  static bool classof(const Instruction *I) {
3450  return I->getOpcode() == Instruction::Switch;
3451  }
3452  static bool classof(const Value *V) {
3453  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3454  }
3455 };
3456 
3457 /// A wrapper class to simplify modification of SwitchInst cases along with
3458 /// their prof branch_weights metadata.
3460  SwitchInst &SI;
3462  bool Changed = false;
3463 
3464 protected:
3465  static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3466 
3467  MDNode *buildProfBranchWeightsMD();
3468 
3469  void init();
3470 
3471 public:
3473  SwitchInst *operator->() { return &SI; }
3474  SwitchInst &operator*() { return SI; }
3475  operator SwitchInst *() { return &SI; }
3476 
3478 
3480  if (Changed)
3481  SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3482  }
3483 
3484  /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3485  /// correspondent branch weight.
3486  SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3487 
3488  /// Delegate the call to the underlying SwitchInst::addCase() and set the
3489  /// specified branch weight for the added case.
3490  void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3491 
3492  /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3493  /// this object to not touch the underlying SwitchInst in destructor.
3495 
3496  void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3497  CaseWeightOpt getSuccessorWeight(unsigned idx);
3498 
3499  static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3500 };
3501 
3502 template <>
3504 };
3505 
3506 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3507 
3508 //===----------------------------------------------------------------------===//
3509 // IndirectBrInst Class
3510 //===----------------------------------------------------------------------===//
3511 
3512 //===---------------------------------------------------------------------------
3513 /// Indirect Branch Instruction.
3514 ///
3515 class IndirectBrInst : public Instruction {
3516  unsigned ReservedSpace;
3517 
3518  // Operand[0] = Address to jump to
3519  // Operand[n+1] = n-th destination
3520  IndirectBrInst(const IndirectBrInst &IBI);
3521 
3522  /// Create a new indirectbr instruction, specifying an
3523  /// Address to jump to. The number of expected destinations can be specified
3524  /// here to make memory allocation more efficient. This constructor can also
3525  /// autoinsert before another instruction.
3526  IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3527 
3528  /// Create a new indirectbr instruction, specifying an
3529  /// Address to jump to. The number of expected destinations can be specified
3530  /// here to make memory allocation more efficient. This constructor also
3531  /// autoinserts at the end of the specified BasicBlock.
3532  IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3533 
3534  // allocate space for exactly zero operands
3535  void *operator new(size_t s) {
3536  return User::operator new(s);
3537  }
3538 
3539  void init(Value *Address, unsigned NumDests);
3540  void growOperands();
3541 
3542 protected:
3543  // Note: Instruction needs to be a friend here to call cloneImpl.
3544  friend class Instruction;
3545 
3546  IndirectBrInst *cloneImpl() const;
3547 
3548 public:
3549  /// Iterator type that casts an operand to a basic block.
3550  ///
3551  /// This only makes sense because the successors are stored as adjacent
3552  /// operands for indirectbr instructions.
3554  : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3555  std::random_access_iterator_tag, BasicBlock *,
3556  ptrdiff_t, BasicBlock *, BasicBlock *> {
3558 
3559  BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3560  BasicBlock *operator->() const { return operator*(); }
3561  };
3562 
3563  /// The const version of `succ_op_iterator`.
3565  : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3566  std::random_access_iterator_tag,
3567  const BasicBlock *, ptrdiff_t, const BasicBlock *,
3568  const BasicBlock *> {
3570  : iterator_adaptor_base(I) {}
3571 
3572  const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3573  const BasicBlock *operator->() const { return operator*(); }
3574  };
3575 
3576  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3577  Instruction *InsertBefore = nullptr) {
3578  return new IndirectBrInst(Address, NumDests, InsertBefore);
3579  }
3580 
3581  static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3582  BasicBlock *InsertAtEnd) {
3583  return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3584  }
3585 
3586  /// Provide fast operand accessors.
3588 
3589  // Accessor Methods for IndirectBrInst instruction.
3590  Value *getAddress() { return getOperand(0); }
3591  const Value *getAddress() const { return getOperand(0); }
3592  void setAddress(Value *V) { setOperand(0, V); }
3593 
3594  /// return the number of possible destinations in this
3595  /// indirectbr instruction.
3596  unsigned getNumDestinations() const { return getNumOperands()-1; }
3597 
3598  /// Return the specified destination.
3599  BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3600  const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3601 
3602  /// Add a destination.
3603  ///
3604  void addDestination(BasicBlock *Dest);
3605 
3606  /// This method removes the specified successor from the
3607  /// indirectbr instruction.
3608  void removeDestination(unsigned i);
3609 
3610  unsigned getNumSuccessors() const { return getNumOperands()-1; }
3611  BasicBlock *getSuccessor(unsigned i) const {
3612  return cast<BasicBlock>(getOperand(i+1));
3613  }
3614  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3615  setOperand(i + 1, NewSucc);
3616  }
3617 
3619  return make_range(succ_op_iterator(std::next(value_op_begin())),
3621  }
3622 
3624  return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3626  }
3627 
3628  // Methods for support type inquiry through isa, cast, and dyn_cast:
3629  static bool classof(const Instruction *I) {
3630  return I->getOpcode() == Instruction::IndirectBr;
3631  }
3632  static bool classof(const Value *V) {
3633  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3634  }
3635 };
3636 
3637 template <>
3639 };
3640 
3641 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3642 
3643 //===----------------------------------------------------------------------===//
3644 // InvokeInst Class
3645 //===----------------------------------------------------------------------===//
3646 
3647 /// Invoke instruction. The SubclassData field is used to hold the
3648 /// calling convention of the call.
3649 ///
3650 class InvokeInst : public CallBase {
3651  /// The number of operands for this call beyond the called function,
3652  /// arguments, and operand bundles.
3653  static constexpr int NumExtraOperands = 2;
3654 
3655  /// The index from the end of the operand array to the normal destination.
3656  static constexpr int NormalDestOpEndIdx = -3;
3657 
3658  /// The index from the end of the operand array to the unwind destination.
3659  static constexpr int UnwindDestOpEndIdx = -2;
3660 
3661  InvokeInst(const InvokeInst &BI);
3662 
3663  /// Construct an InvokeInst given a range of arguments.
3664  ///
3665  /// Construct an InvokeInst from a range of arguments
3666  inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3667  BasicBlock *IfException, ArrayRef<Value *> Args,
3668  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3669  const Twine &NameStr, Instruction *InsertBefore);
3670 
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, BasicBlock *InsertAtEnd);
3675 
3676  void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3677  BasicBlock *IfException, ArrayRef<Value *> Args,
3678  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3679 
3680  /// Compute the number of operands to allocate.
3681  static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3682  // We need one operand for the called function, plus our extra operands and
3683  // the input operand counts provided.
3684  return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3685  }
3686 
3687 protected:
3688  // Note: Instruction needs to be a friend here to call cloneImpl.
3689  friend class Instruction;
3690 
3691  InvokeInst *cloneImpl() const;
3692 
3693 public:
3694  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3695  BasicBlock *IfException, ArrayRef<Value *> Args,
3696  const Twine &NameStr,
3697  Instruction *InsertBefore = nullptr) {
3698  int NumOperands = ComputeNumOperands(Args.size());
3699  return new (NumOperands)
3700  InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3701  NameStr, InsertBefore);
3702  }
3703 
3704  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3705  BasicBlock *IfException, ArrayRef<Value *> Args,
3706  ArrayRef<OperandBundleDef> Bundles = None,
3707  const Twine &NameStr = "",
3708  Instruction *InsertBefore = nullptr) {
3709  int NumOperands =
3710  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3711  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3712 
3713  return new (NumOperands, DescriptorBytes)
3714  InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3715  NameStr, InsertBefore);
3716  }
3717 
3718  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3719  BasicBlock *IfException, ArrayRef<Value *> Args,
3720  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3721  int NumOperands = ComputeNumOperands(Args.size());
3722  return new (NumOperands)
3723  InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3724  NameStr, InsertAtEnd);
3725  }
3726 
3727  static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3728  BasicBlock *IfException, ArrayRef<Value *> Args,
3730  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3731  int NumOperands =
3732  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3733  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3734 
3735  return new (NumOperands, DescriptorBytes)
3736  InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3737  NameStr, InsertAtEnd);
3738  }
3739 
3740  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3741  BasicBlock *IfException, ArrayRef<Value *> Args,
3742  const Twine &NameStr,
3743  Instruction *InsertBefore = nullptr) {
3744  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3745  IfException, Args, None, NameStr, InsertBefore);
3746  }
3747 
3748  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3749  BasicBlock *IfException, ArrayRef<Value *> Args,
3750  ArrayRef<OperandBundleDef> Bundles = None,
3751  const Twine &NameStr = "",
3752  Instruction *InsertBefore = nullptr) {
3753  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3754  IfException, Args, Bundles, NameStr, InsertBefore);
3755  }
3756 
3757  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3758  BasicBlock *IfException, ArrayRef<Value *> Args,
3759  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3760  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3761  IfException, Args, NameStr, InsertAtEnd);
3762  }
3763 
3764  static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3765  BasicBlock *IfException, ArrayRef<Value *> Args,
3767  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3768  return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3769  IfException, Args, Bundles, NameStr, InsertAtEnd);
3770  }
3771 
3772  // Deprecated [opaque pointer types]
3773  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3774  BasicBlock *IfException, ArrayRef<Value *> Args,
3775  const Twine &NameStr,
3776  Instruction *InsertBefore = nullptr) {
3777  return Create(cast<FunctionType>(
3778  cast<PointerType>(Func->getType())->getElementType()),
3779  Func, IfNormal, IfException, Args, None, NameStr,
3780  InsertBefore);
3781  }
3782 
3783  // Deprecated [opaque pointer types]
3784  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3785  BasicBlock *IfException, ArrayRef<Value *> Args,
3786  ArrayRef<OperandBundleDef> Bundles = None,
3787  const Twine &NameStr = "",
3788  Instruction *InsertBefore = nullptr) {
3789  return Create(cast<FunctionType>(
3790  cast<PointerType>(Func->getType())->getElementType()),
3791  Func, IfNormal, IfException, Args, Bundles, NameStr,
3792  InsertBefore);
3793  }
3794 
3795  // Deprecated [opaque pointer types]
3796  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3797  BasicBlock *IfException, ArrayRef<Value *> Args,
3798  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3799  return Create(cast<FunctionType>(
3800  cast<PointerType>(Func->getType())->getElementType()),
3801  Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3802  }
3803 
3804  // Deprecated [opaque pointer types]
3805  static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3806  BasicBlock *IfException, ArrayRef<Value *> Args,
3808  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3809  return Create(cast<FunctionType>(
3810  cast<PointerType>(Func->getType())->getElementType()),
3811  Func, IfNormal, IfException, Args, Bundles, NameStr,
3812  InsertAtEnd);
3813  }
3814 
3815  /// Create a clone of \p II with a different set of operand bundles and
3816  /// insert it before \p InsertPt.
3817  ///
3818  /// The returned invoke instruction is identical to \p II in every way except
3819  /// that the operand bundles for the new instruction are set to the operand
3820  /// bundles in \p Bundles.
3821  static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3822  Instruction *InsertPt = nullptr);
3823 
3824  /// Determine if the call should not perform indirect branch tracking.
3825  bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3826 
3827  /// Determine if the call cannot unwind.
3828  bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3830  addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3831  }
3832 
3833  // get*Dest - Return the destination basic blocks...
3835  return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3836  }
3838  return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3839  }
3841  Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3842  }
3844  Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3845  }
3846 
3847  /// Get the landingpad instruction from the landing pad
3848  /// block (the unwind destination).
3849  LandingPadInst *getLandingPadInst() const;
3850 
3851  BasicBlock *getSuccessor(unsigned i) const {
3852  assert(i < 2 && "Successor # out of range for invoke!");
3853  return i == 0 ? getNormalDest() : getUnwindDest();
3854  }
3855 
3856  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3857  assert(i < 2 && "Successor # out of range for invoke!");
3858  if (i == 0)
3859  setNormalDest(NewSucc);
3860  else
3861  setUnwindDest(NewSucc);
3862  }
3863 
3864  unsigned getNumSuccessors() const { return 2; }
3865 
3866  // Methods for support type inquiry through isa, cast, and dyn_cast:
3867  static bool classof(const Instruction *I) {
3868  return (I->getOpcode() == Instruction::Invoke);
3869  }
3870  static bool classof(const Value *V) {
3871  return isa<Instruction>(V) && classof(cast<Instruction>(V));
3872  }
3873 
3874 private:
3875 
3876  // Shadow Instruction::setInstructionSubclassData with a private forwarding
3877  // method so that subclasses cannot accidentally use it.
3878  void setInstructionSubclassData(unsigned short D) {
3880  }
3881 };
3882 
3883 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3884  BasicBlock *IfException, ArrayRef<Value *> Args,
3885  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3886  const Twine &NameStr, Instruction *InsertBefore)
3887  : CallBase(Ty->getReturnType(), Instruction::Invoke,
3888  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3889  InsertBefore) {
3890  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3891 }
3892 
3893 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3894  BasicBlock *IfException, ArrayRef<Value *> Args,
3895  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3896  const Twine &NameStr, BasicBlock *InsertAtEnd)
3897  : CallBase(Ty->getReturnType(), Instruction::Invoke,
3898  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3899  InsertAtEnd) {
3900  init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3901 }
3902 
3903 //===----------------------------------------------------------------------===//
3904 // CallBrInst Class
3905 //===----------------------------------------------------------------------===//
3906 
3907 /// CallBr instruction, tracking function calls that may not return control but
3908 /// instead transfer it to a third location. The SubclassData field is used to
3909 /// hold the calling convention of the call.
3910 ///
3911 class CallBrInst : public CallBase {
3912 
3913  unsigned NumIndirectDests;
3914 
3915  CallBrInst(const CallBrInst &BI);
3916 
3917  /// Construct a CallBrInst given a range of arguments.
3918  ///
3919  /// Construct a CallBrInst from a range of arguments
3920  inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3921  ArrayRef<BasicBlock *> IndirectDests,
3922  ArrayRef<Value *> Args,
3923  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3924  const Twine &NameStr, Instruction *InsertBefore);
3925 
3926  inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3927  ArrayRef<BasicBlock *> IndirectDests,
3928  ArrayRef<Value *> Args,
3929  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3930  const Twine &NameStr, BasicBlock *InsertAtEnd);
3931 
3932  void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3933  ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3934  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3935 
3936  /// Should the Indirect Destinations change, scan + update the Arg list.
3937  void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3938 
3939  /// Compute the number of operands to allocate.
3940  static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3941  int NumBundleInputs = 0) {
3942  // We need one operand for the called function, plus our extra operands and
3943  // the input operand counts provided.
3944  return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3945  }
3946 
3947 protected:
3948  // Note: Instruction needs to be a friend here to call cloneImpl.
3949  friend class Instruction;
3950 
3951  CallBrInst *cloneImpl() const;
3952 
3953 public:
3954  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3955  BasicBlock *DefaultDest,
3956  ArrayRef<BasicBlock *> IndirectDests,
3957  ArrayRef<Value *> Args, const Twine &NameStr,
3958  Instruction *InsertBefore = nullptr) {
3959  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3960  return new (NumOperands)
3961  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3962  NumOperands, NameStr, InsertBefore);
3963  }
3964 
3965  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3966  BasicBlock *DefaultDest,
3967  ArrayRef<BasicBlock *> IndirectDests,
3968  ArrayRef<Value *> Args,
3969  ArrayRef<OperandBundleDef> Bundles = None,
3970  const Twine &NameStr = "",
3971  Instruction *InsertBefore = nullptr) {
3972  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3973  CountBundleInputs(Bundles));
3974  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3975 
3976  return new (NumOperands, DescriptorBytes)
3977  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3978  NumOperands, NameStr, InsertBefore);
3979  }
3980 
3981  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3982  BasicBlock *DefaultDest,
3983  ArrayRef<BasicBlock *> IndirectDests,
3984  ArrayRef<Value *> Args, const Twine &NameStr,
3985  BasicBlock *InsertAtEnd) {
3986  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3987  return new (NumOperands)
3988  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3989  NumOperands, NameStr, InsertAtEnd);
3990  }
3991 
3992  static CallBrInst *Create(FunctionType *Ty, Value *Func,
3993  BasicBlock *DefaultDest,
3994  ArrayRef<BasicBlock *> IndirectDests,
3995  ArrayRef<Value *> Args,
3997  const Twine &NameStr, BasicBlock *InsertAtEnd) {
3998  int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3999  CountBundleInputs(Bundles));
4000  unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4001 
4002  return new (NumOperands, DescriptorBytes)
4003  CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
4004  NumOperands, NameStr, InsertAtEnd);
4005  }
4006 
4007  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4008  ArrayRef<BasicBlock *> IndirectDests,
4009  ArrayRef<Value *> Args, const Twine &NameStr,
4010  Instruction *InsertBefore = nullptr) {
4011  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4012  IndirectDests, Args, NameStr, InsertBefore);
4013  }
4014 
4015  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4016  ArrayRef<BasicBlock *> IndirectDests,
4017  ArrayRef<Value *> Args,
4018  ArrayRef<OperandBundleDef> Bundles = None,
4019  const Twine &NameStr = "",
4020  Instruction *InsertBefore = nullptr) {
4021  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4022  IndirectDests, Args, Bundles, NameStr, InsertBefore);
4023  }
4024 
4025  static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4026  ArrayRef<BasicBlock *> IndirectDests,
4027  ArrayRef<Value *> Args, const Twine &NameStr,
4028  BasicBlock *InsertAtEnd) {
4029  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4030  IndirectDests, Args, NameStr, InsertAtEnd);
4031  }
4032 
4034  BasicBlock *DefaultDest,
4035  ArrayRef<BasicBlock *> IndirectDests,
4036  ArrayRef<Value *> Args,
4038  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4039  return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4040  IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4041  }
4042 
4043  /// Create a clone of \p CBI with a different set of operand bundles and
4044  /// insert it before \p InsertPt.
4045  ///
4046  /// The returned callbr instruction is identical to \p CBI in every way
4047  /// except that the operand bundles for the new instruction are set to the
4048  /// operand bundles in \p Bundles.
4049  static CallBrInst *Create(CallBrInst *CBI,
4051  Instruction *InsertPt = nullptr);
4052 
4053  /// Return the number of callbr indirect dest labels.
4054  ///
4055  unsigned getNumIndirectDests() const { return NumIndirectDests; }
4056 
4057  /// getIndirectDestLabel - Return the i-th indirect dest label.
4058  ///
4059  Value *getIndirectDestLabel(unsigned i) const {
4060  assert(i < getNumIndirectDests() && "Out of bounds!");
4061  return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4062  1);
4063  }
4064 
4065  Value *getIndirectDestLabelUse(unsigned i) const {
4066  assert(i < getNumIndirectDests() && "Out of bounds!");
4067  return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4068  1);
4069  }
4070 
4071  // Return the destination basic blocks...
4073  return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4074  }
4075  BasicBlock *getIndirectDest(unsigned i) const {
4076  return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4077  }
4079  SmallVector<BasicBlock *, 16> IndirectDests;
4080  for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4081  IndirectDests.push_back(getIndirectDest(i));
4082  return IndirectDests;
4083  }
4085  *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4086  }
4087  void setIndirectDest(unsigned i, BasicBlock *B) {
4088  updateArgBlockAddresses(i, B);
4089  *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4090  }
4091 
4092  BasicBlock *getSuccessor(unsigned i) const {
4093  assert(i < getNumSuccessors() + 1 &&
4094  "Successor # out of range for callbr!");
4095  return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4096  }
4097 
4098  void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4099  assert(i < getNumIndirectDests() + 1 &&
4100  "Successor # out of range for callbr!");
4101  return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4102  }
4103 
4104  unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4105 
4106  // Methods for support type inquiry through isa, cast, and dyn_cast:
4107  static bool classof(const Instruction *I) {
4108  return (I->getOpcode() == Instruction::CallBr);
4109  }
4110  static bool classof(const Value *V) {
4111  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4112  }
4113 
4114 private:
4115 
4116  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4117  // method so that subclasses cannot accidentally use it.
4118  void setInstructionSubclassData(unsigned short D) {
4120  }
4121 };
4122 
4123 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4124  ArrayRef<BasicBlock *> IndirectDests,
4125  ArrayRef<Value *> Args,
4126  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4127  const Twine &NameStr, Instruction *InsertBefore)
4128  : CallBase(Ty->getReturnType(), Instruction::CallBr,
4129  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4130  InsertBefore) {
4131  init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4132 }
4133 
4134 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4135  ArrayRef<BasicBlock *> IndirectDests,
4136  ArrayRef<Value *> Args,
4137  ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4138  const Twine &NameStr, BasicBlock *InsertAtEnd)
4139  : CallBase(
4140  cast<FunctionType>(
4141  cast<PointerType>(Func->getType())->getElementType())
4142  ->getReturnType(),
4143  Instruction::CallBr,
4144  OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4145  InsertAtEnd) {
4146  init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4147 }
4148 
4149 //===----------------------------------------------------------------------===//
4150 // ResumeInst Class
4151 //===----------------------------------------------------------------------===//
4152 
4153 //===---------------------------------------------------------------------------
4154 /// Resume the propagation of an exception.
4155 ///
4156 class ResumeInst : public Instruction {
4157  ResumeInst(const ResumeInst &RI);
4158 
4159  explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4160  ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4161 
4162 protected:
4163  // Note: Instruction needs to be a friend here to call cloneImpl.
4164  friend class Instruction;
4165 
4166  ResumeInst *cloneImpl() const;
4167 
4168 public:
4169  static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4170  return new(1) ResumeInst(Exn, InsertBefore);
4171  }
4172 
4173  static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4174  return new(1) ResumeInst(Exn, InsertAtEnd);
4175  }
4176 
4177  /// Provide fast operand accessors
4179 
4180  /// Convenience accessor.
4181  Value *getValue() const { return Op<0>(); }
4182 
4183  unsigned getNumSuccessors() const { return 0; }
4184 
4185  // Methods for support type inquiry through isa, cast, and dyn_cast:
4186  static bool classof(const Instruction *I) {
4187  return I->getOpcode() == Instruction::Resume;
4188  }
4189  static bool classof(const Value *V) {
4190  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4191  }
4192 
4193 private:
4194  BasicBlock *getSuccessor(unsigned idx) const {
4195  llvm_unreachable("ResumeInst has no successors!");
4196  }
4197 
4198  void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4199  llvm_unreachable("ResumeInst has no successors!");
4200  }
4201 };
4202 
4203 template <>
4205  public FixedNumOperandTraits<ResumeInst, 1> {
4206 };
4207 
4208 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4209 
4210 //===----------------------------------------------------------------------===//
4211 // CatchSwitchInst Class
4212 //===----------------------------------------------------------------------===//
4214  /// The number of operands actually allocated. NumOperands is
4215  /// the number actually in use.
4216  unsigned ReservedSpace;
4217 
4218  // Operand[0] = Outer scope
4219  // Operand[1] = Unwind block destination
4220  // Operand[n] = BasicBlock to go to on match
4221  CatchSwitchInst(const CatchSwitchInst &CSI);
4222 
4223  /// Create a new switch instruction, specifying a
4224  /// default destination. The number of additional handlers can be specified
4225  /// here to make memory allocation more efficient.
4226  /// This constructor can also autoinsert before another instruction.
4227  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4228  unsigned NumHandlers, const Twine &NameStr,
4229  Instruction *InsertBefore);
4230 
4231  /// Create a new switch instruction, specifying a
4232  /// default destination. The number of additional handlers can be specified
4233  /// here to make memory allocation more efficient.
4234  /// This constructor also autoinserts at the end of the specified BasicBlock.
4235  CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4236  unsigned NumHandlers, const Twine &NameStr,
4237  BasicBlock *InsertAtEnd);
4238 
4239  // allocate space for exactly zero operands
4240  void *operator new(size_t s) { return User::operator new(s); }
4241 
4242  void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4243  void growOperands(unsigned Size);
4244 
4245 protected:
4246  // Note: Instruction needs to be a friend here to call cloneImpl.
4247  friend class Instruction;
4248 
4249  CatchSwitchInst *cloneImpl() const;
4250 
4251 public:
4252  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4253  unsigned NumHandlers,
4254  const Twine &NameStr = "",
4255  Instruction *InsertBefore = nullptr) {
4256  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4257  InsertBefore);
4258  }
4259 
4260  static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4261  unsigned NumHandlers, const Twine &NameStr,
4262  BasicBlock *InsertAtEnd) {
4263  return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4264  InsertAtEnd);
4265  }
4266 
4267  /// Provide fast operand accessors
4269 
4270  // Accessor Methods for CatchSwitch stmt
4271  Value *getParentPad() const { return getOperand(0); }
4272  void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4273 
4274  // Accessor Methods for CatchSwitch stmt
4275  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4276  bool unwindsToCaller() const { return !hasUnwindDest(); }
4278  if (hasUnwindDest())
4279  return cast<BasicBlock>(getOperand(1));
4280  return nullptr;
4281  }
4282  void setUnwindDest(BasicBlock *UnwindDest) {
4283  assert(UnwindDest);
4284  assert(hasUnwindDest());
4285  setOperand(1, UnwindDest);
4286  }
4287 
4288  /// return the number of 'handlers' in this catchswitch
4289  /// instruction, except the default handler
4290  unsigned getNumHandlers() const {
4291  if (hasUnwindDest())
4292  return getNumOperands() - 2;
4293  return getNumOperands() - 1;
4294  }
4295 
4296 private:
4297  static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4298  static const BasicBlock *handler_helper(const Value *V) {
4299  return cast<BasicBlock>(V);
4300  }
4301 
4302 public:
4303  using DerefFnTy = BasicBlock *(*)(Value *);
4306  using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4307  using const_handler_iterator =
4310 
4311  /// Returns an iterator that points to the first handler in CatchSwitchInst.
4313  op_iterator It = op_begin() + 1;
4314  if (hasUnwindDest())
4315  ++It;
4316  return handler_iterator(It, DerefFnTy(handler_helper));
4317  }
4318 
4319  /// Returns an iterator that points to the first handler in the
4320  /// CatchSwitchInst.
4321  const_handler_iterator handler_begin() const {
4322  const_op_iterator It = op_begin() + 1;
4323  if (hasUnwindDest())
4324  ++It;
4325  return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4326  }
4327 
4328  /// Returns a read-only iterator that points one past the last
4329  /// handler in the CatchSwitchInst.
4331  return handler_iterator(op_end(), DerefFnTy(handler_helper));
4332  }
4333 
4334  /// Returns an iterator that points one past the last handler in the
4335  /// CatchSwitchInst.
4336  const_handler_iterator handler_end() const {
4337  return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4338  }
4339 
4340  /// iteration adapter for range-for loops.
4342  return make_range(handler_begin(), handler_end());
4343  }
4344 
4345  /// iteration adapter for range-for loops.
4347  return make_range(handler_begin(), handler_end());
4348  }
4349 
4350  /// Add an entry to the switch instruction...
4351  /// Note:
4352  /// This action invalidates handler_end(). Old handler_end() iterator will
4353  /// point to the added handler.
4354  void addHandler(BasicBlock *Dest);
4355 
4356  void removeHandler(handler_iterator HI);
4357 
4358  unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4359  BasicBlock *getSuccessor(unsigned Idx) const {
4360  assert(Idx < getNumSuccessors() &&
4361  "Successor # out of range for catchswitch!");
4362  return cast<BasicBlock>(getOperand(Idx + 1));
4363  }
4364  void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4365  assert(Idx < getNumSuccessors() &&
4366  "Successor # out of range for catchswitch!");
4367  setOperand(Idx + 1, NewSucc);
4368  }
4369 
4370  // Methods for support type inquiry through isa, cast, and dyn_cast:
4371  static bool classof(const Instruction *I) {
4372  return I->getOpcode() == Instruction::CatchSwitch;
4373  }
4374  static bool classof(const Value *V) {
4375  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4376  }
4377 };
4378 
4379 template <>
4381 
4382 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4383 
4384 //===----------------------------------------------------------------------===//
4385 // CleanupPadInst Class
4386 //===----------------------------------------------------------------------===//
4388 private:
4389  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4390  unsigned Values, const Twine &NameStr,
4391  Instruction *InsertBefore)
4392  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4393  NameStr, InsertBefore) {}
4394  explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4395  unsigned Values, const Twine &NameStr,
4396  BasicBlock *InsertAtEnd)
4397  : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4398  NameStr, InsertAtEnd) {}
4399 
4400 public:
4401  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4402  const Twine &NameStr = "",
4403  Instruction *InsertBefore = nullptr) {
4404  unsigned Values = 1 + Args.size();
4405  return new (Values)
4406  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4407  }
4408 
4409  static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4410  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4411  unsigned Values = 1 + Args.size();
4412  return new (Values)
4413  CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4414  }
4415 
4416  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4417  static bool classof(const Instruction *I) {
4418  return I->getOpcode() == Instruction::CleanupPad;
4419  }
4420  static bool classof(const Value *V) {
4421  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4422  }
4423 };
4424 
4425 //===----------------------------------------------------------------------===//
4426 // CatchPadInst Class
4427 //===----------------------------------------------------------------------===//
4429 private:
4430  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4431  unsigned Values, const Twine &NameStr,
4432  Instruction *InsertBefore)
4433  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4434  NameStr, InsertBefore) {}
4435  explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4436  unsigned Values, const Twine &NameStr,
4437  BasicBlock *InsertAtEnd)
4438  : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4439  NameStr, InsertAtEnd) {}
4440 
4441 public:
4442  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4443  const Twine &NameStr = "",
4444  Instruction *InsertBefore = nullptr) {
4445  unsigned Values = 1 + Args.size();
4446  return new (Values)
4447  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4448  }
4449 
4450  static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4451  const Twine &NameStr, BasicBlock *InsertAtEnd) {
4452  unsigned Values = 1 + Args.size();
4453  return new (Values)
4454  CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4455  }
4456 
4457  /// Convenience accessors
4458  CatchSwitchInst *getCatchSwitch() const {
4459  return cast<CatchSwitchInst>(Op<-1>());
4460  }
4461  void setCatchSwitch(Value *CatchSwitch) {
4462  assert(CatchSwitch);
4463  Op<-1>() = CatchSwitch;
4464  }
4465 
4466  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4467  static bool classof(const Instruction *I) {
4468  return I->getOpcode() == Instruction::CatchPad;
4469  }
4470  static bool classof(const Value *V) {
4471  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4472  }
4473 };
4474 
4475 //===----------------------------------------------------------------------===//
4476 // CatchReturnInst Class
4477 //===----------------------------------------------------------------------===//
4478 
4480  CatchReturnInst(const CatchReturnInst &RI);
4481  CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4482  CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4483 
4484  void init(Value *CatchPad, BasicBlock *BB);
4485 
4486 protected:
4487  // Note: Instruction needs to be a friend here to call cloneImpl.
4488  friend class Instruction;
4489 
4490  CatchReturnInst *cloneImpl() const;
4491 
4492 public:
4493  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4494  Instruction *InsertBefore = nullptr) {
4495  assert(CatchPad);
4496  assert(BB);
4497  return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4498  }
4499 
4500  static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4501  BasicBlock *InsertAtEnd) {
4502  assert(CatchPad);
4503  assert(BB);
4504  return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4505  }
4506 
4507  /// Provide fast operand accessors
4509 
4510  /// Convenience accessors.
4511  CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4512  void setCatchPad(CatchPadInst *CatchPad) {
4513  assert(CatchPad);
4514  Op<0>() = CatchPad;
4515  }
4516 
4517  BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4518  void setSuccessor(BasicBlock *NewSucc) {
4519  assert(NewSucc);
4520  Op<1>() = NewSucc;
4521  }
4522  unsigned getNumSuccessors() const { return 1; }
4523 
4524  /// Get the parentPad of this catchret's catchpad's catchswitch.
4525  /// The successor block is implicitly a member of this funclet.
4526  Value *getCatchSwitchParentPad() const {
4527  return getCatchPad()->getCatchSwitch()->getParentPad();
4528  }
4529 
4530  // Methods for support type inquiry through isa, cast, and dyn_cast:
4531  static bool classof(const Instruction *I) {
4532  return (I->getOpcode() == Instruction::CatchRet);
4533  }
4534  static bool classof(const Value *V) {
4535  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4536  }
4537 
4538 private:
4539  BasicBlock *getSuccessor(unsigned Idx) const {
4540  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4541  return getSuccessor();
4542  }
4543 
4544  void setSuccessor(unsigned Idx, BasicBlock *B) {
4545  assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4546  setSuccessor(B);
4547  }
4548 };
4549 
4550 template <>
4552  : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4553 
4554 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4555 
4556 //===----------------------------------------------------------------------===//
4557 // CleanupReturnInst Class
4558 //===----------------------------------------------------------------------===//
4559 
4561 private:
4563  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4564  Instruction *InsertBefore = nullptr);
4565  CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4566  BasicBlock *InsertAtEnd);
4567 
4568  void init(Value *CleanupPad, BasicBlock *UnwindBB);
4569 
4570 protected:
4571  // Note: Instruction needs to be a friend here to call cloneImpl.
4572  friend class Instruction;
4573 
4574  CleanupReturnInst *cloneImpl() const;
4575 
4576 public:
4577  static CleanupReturnInst *Create(Value *CleanupPad,
4578  BasicBlock *UnwindBB = nullptr,
4579  Instruction *InsertBefore = nullptr) {
4580  assert(CleanupPad);
4581  unsigned Values = 1;
4582  if (UnwindBB)
4583  ++Values;
4584  return new (Values)
4585  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4586  }
4587 
4588  static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4589  BasicBlock *InsertAtEnd) {
4590  assert(CleanupPad);
4591  unsigned Values = 1;
4592  if (UnwindBB)
4593  ++Values;
4594  return new (Values)
4595  CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4596  }
4597 
4598  /// Provide fast operand accessors
4600 
4601  bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4602  bool unwindsToCaller() const { return !hasUnwindDest(); }
4603 
4604  /// Convenience accessor.
4606  return cast<CleanupPadInst>(Op<0>());
4607  }
4608  void setCleanupPad(CleanupPadInst *CleanupPad) {
4609  assert(CleanupPad);
4610  Op<0>() = CleanupPad;
4611  }
4612 
4613  unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4614 
4616  return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4617  }
4618  void setUnwindDest(BasicBlock *NewDest) {
4619  assert(NewDest);
4620  assert(hasUnwindDest());
4621  Op<1>() = NewDest;
4622  }
4623 
4624  // Methods for support type inquiry through isa, cast, and dyn_cast:
4625  static bool classof(const Instruction *I) {
4626  return (I->getOpcode() == Instruction::CleanupRet);
4627  }
4628  static bool classof(const Value *V) {
4629  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4630  }
4631 
4632 private:
4633  BasicBlock *getSuccessor(unsigned Idx) const {
4634  assert(Idx == 0);
4635  return getUnwindDest();
4636  }
4637 
4638  void setSuccessor(unsigned Idx, BasicBlock *B) {
4639  assert(Idx == 0);
4640  setUnwindDest(B);
4641  }
4642 
4643  // Shadow Instruction::setInstructionSubclassData with a private forwarding
4644  // method so that subclasses cannot accidentally use it.
4645  void setInstructionSubclassData(unsigned short D) {
4647  }
4648 };
4649 
4650 template <>
4652  : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4653 
4654 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4655 
4656 //===----------------------------------------------------------------------===//
4657 // UnreachableInst Class
4658 //===----------------------------------------------------------------------===//
4659 
4660 //===---------------------------------------------------------------------------
4661 /// This function has undefined behavior. In particular, the
4662 /// presence of this instruction indicates some higher level knowledge that the
4663 /// end of the block cannot be reached.
4664 ///
4666 protected:
4667  // Note: Instruction needs to be a friend here to call cloneImpl.
4668  friend class Instruction;
4669 
4670  UnreachableInst *cloneImpl() const;
4671 
4672 public:
4673  explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4674  explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4675 
4676  // allocate space for exactly zero operands
4677  void *operator new(size_t s) {
4678  return User::operator new(s, 0);
4679  }
4680 
4681  unsigned getNumSuccessors() const { return 0; }
4682 
4683  // Methods for support type inquiry through isa, cast, and dyn_cast:
4684  static bool classof(const Instruction *I) {
4685  return I->getOpcode() == Instruction::Unreachable;
4686  }
4687  static bool classof(const Value *V) {
4688  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4689  }
4690 
4691 private:
4692  BasicBlock *getSuccessor(unsigned idx) const {
4693  llvm_unreachable("UnreachableInst has no successors!");
4694  }
4695 
4696  void setSuccessor(unsigned idx, BasicBlock *B) {
4697  llvm_unreachable("UnreachableInst has no successors!");
4698  }
4699 };
4700 
4701 //===----------------------------------------------------------------------===//
4702 // TruncInst Class
4703 //===----------------------------------------------------------------------===//
4704 
4705 /// This class represents a truncation of integer types.
4706 class TruncInst : public CastInst {
4707 protected:
4708  // Note: Instruction needs to be a friend here to call cloneImpl.
4709  friend class Instruction;
4710 
4711  /// Clone an identical TruncInst
4712  TruncInst *cloneImpl() const;
4713 
4714 public:
4715  /// Constructor with insert-before-instruction semantics
4716  TruncInst(
4717  Value *S, ///< The value to be truncated
4718  Type *Ty, ///< The (smaller) type to truncate to
4719  const Twine &NameStr = "", ///< A name for the new instruction
4720  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4721  );
4722 
4723  /// Constructor with insert-at-end-of-block semantics
4724  TruncInst(
4725  Value *S, ///< The value to be truncated
4726  Type *Ty, ///< The (smaller) type to truncate to
4727  const Twine &NameStr, ///< A name for the new instruction
4728  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4729  );
4730 
4731  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4732  static bool classof(const Instruction *I) {
4733  return I->getOpcode() == Trunc;
4734  }
4735  static bool classof(const Value *V) {
4736  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4737  }
4738 };
4739 
4740 //===----------------------------------------------------------------------===//
4741 // ZExtInst Class
4742 //===----------------------------------------------------------------------===//
4743 
4744 /// This class represents zero extension of integer types.
4745 class ZExtInst : public CastInst {
4746 protected:
4747  // Note: Instruction needs to be a friend here to call cloneImpl.
4748  friend class Instruction;
4749 
4750  /// Clone an identical ZExtInst
4751  ZExtInst *cloneImpl() const;
4752 
4753 public:
4754  /// Constructor with insert-before-instruction semantics
4755  ZExtInst(
4756  Value *S, ///< The value to be zero extended
4757  Type *Ty, ///< The type to zero extend to
4758  const Twine &NameStr = "", ///< A name for the new instruction
4759  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4760  );
4761 
4762  /// Constructor with insert-at-end semantics.
4763  ZExtInst(
4764  Value *S, ///< The value to be zero extended
4765  Type *Ty, ///< The type to zero extend to
4766  const Twine &NameStr, ///< A name for the new instruction
4767  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4768  );
4769 
4770  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4771  static bool classof(const Instruction *I) {
4772  return I->getOpcode() == ZExt;
4773  }
4774  static bool classof(const Value *V) {
4775  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4776  }
4777 };
4778 
4779 //===----------------------------------------------------------------------===//
4780 // SExtInst Class
4781 //===----------------------------------------------------------------------===//
4782 
4783 /// This class represents a sign extension of integer types.
4784 class SExtInst : public CastInst {
4785 protected:
4786  // Note: Instruction needs to be a friend here to call cloneImpl.
4787  friend class Instruction;
4788 
4789  /// Clone an identical SExtInst
4790  SExtInst *cloneImpl() const;
4791 
4792 public:
4793  /// Constructor with insert-before-instruction semantics
4794  SExtInst(
4795  Value *S, ///< The value to be sign extended
4796  Type *Ty, ///< The type to sign extend to
4797  const Twine &NameStr = "", ///< A name for the new instruction
4798  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4799  );
4800 
4801  /// Constructor with insert-at-end-of-block semantics
4802  SExtInst(
4803  Value *S, ///< The value to be sign extended
4804  Type *Ty, ///< The type to sign extend to
4805  const Twine &NameStr, ///< A name for the new instruction
4806  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4807  );
4808 
4809  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4810  static bool classof(const Instruction *I) {
4811  return I->getOpcode() == SExt;
4812  }
4813  static bool classof(const Value *V) {
4814  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4815  }
4816 };
4817 
4818 //===----------------------------------------------------------------------===//
4819 // FPTruncInst Class
4820 //===----------------------------------------------------------------------===//
4821 
4822 /// This class represents a truncation of floating point types.
4823 class FPTruncInst : public CastInst {
4824 protected:
4825  // Note: Instruction needs to be a friend here to call cloneImpl.
4826  friend class Instruction;
4827 
4828  /// Clone an identical FPTruncInst
4829  FPTruncInst *cloneImpl() const;
4830 
4831 public:
4832  /// Constructor with insert-before-instruction semantics
4833  FPTruncInst(
4834  Value *S, ///< The value to be truncated
4835  Type *Ty, ///< The type to truncate to
4836  const Twine &NameStr = "", ///< A name for the new instruction
4837  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4838  );
4839 
4840  /// Constructor with insert-before-instruction semantics
4841  FPTruncInst(
4842  Value *S, ///< The value to be truncated
4843  Type *Ty, ///< The type to truncate to
4844  const Twine &NameStr, ///< A name for the new instruction
4845  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4846  );
4847 
4848  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4849  static bool classof(const Instruction *I) {
4850  return I->getOpcode() == FPTrunc;
4851  }
4852  static bool classof(const Value *V) {
4853  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4854  }
4855 };
4856 
4857 //===----------------------------------------------------------------------===//
4858 // FPExtInst Class
4859 //===----------------------------------------------------------------------===//
4860 
4861 /// This class represents an extension of floating point types.
4862 class FPExtInst : public CastInst {
4863 protected:
4864  // Note: Instruction needs to be a friend here to call cloneImpl.
4865  friend class Instruction;
4866 
4867  /// Clone an identical FPExtInst
4868  FPExtInst *cloneImpl() const;
4869 
4870 public:
4871  /// Constructor with insert-before-instruction semantics
4872  FPExtInst(
4873  Value *S, ///< The value to be extended
4874  Type *Ty, ///< The type to extend to
4875  const Twine &NameStr = "", ///< A name for the new instruction
4876  Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4877  );
4878 
4879  /// Constructor with insert-at-end-of-block semantics
4880  FPExtInst(
4881  Value *S, ///< The value to be extended
4882  Type *Ty, ///< The type to extend to
4883  const Twine &NameStr, ///< A name for the new instruction
4884  BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4885  );
4886 
4887  /// Methods for support type inquiry through isa, cast, and dyn_cast:
4888  static bool classof(const Instruction *I) {
4889  return I->getOpcode() == FPExt;
4890  }
4891  static bool classof(const Value *V) {
4892  return isa<Instruction>(V) && classof(cast<Instruction>(V));
4893  }
4894 };
4895 
4896