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