1 //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file exposes the class definitions of all of the subclasses of the
11 // Instruction class. This is meant to be an easy way to get access to all
12 // instruction subclasses.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_IR_INSTRUCTIONS_H
17 #define LLVM_IR_INSTRUCTIONS_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/ADT/iterator.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/InstrTypes.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/OperandTraits.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Use.h"
38 #include "llvm/IR/User.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Support/AtomicOrdering.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/ErrorHandling.h"
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// an instruction to allocate memory on the stack
60 class AllocaInst : public UnaryInstruction {
64 // Note: Instruction needs to be a friend here to call cloneImpl.
65 friend class Instruction;
67 AllocaInst *cloneImpl() const;
70 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
71 Value *ArraySize = nullptr,
72 const Twine &Name = "",
73 Instruction *InsertBefore = nullptr);
74 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
75 const Twine &Name, BasicBlock *InsertAtEnd);
77 AllocaInst(Type *Ty, unsigned AddrSpace,
78 const Twine &Name, Instruction *InsertBefore = nullptr);
79 AllocaInst(Type *Ty, unsigned AddrSpace,
80 const Twine &Name, BasicBlock *InsertAtEnd);
82 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
83 const Twine &Name = "", Instruction *InsertBefore = nullptr);
84 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
85 const Twine &Name, BasicBlock *InsertAtEnd);
87 /// Return true if there is an allocation size parameter to the allocation
88 /// instruction that is not 1.
89 bool isArrayAllocation() const;
91 /// Get the number of elements allocated. For a simple allocation of a single
92 /// element, this will return a constant 1 value.
93 const Value *getArraySize() const { return getOperand(0); }
94 Value *getArraySize() { return getOperand(0); }
96 /// Overload to return most specific pointer type.
97 PointerType *getType() const {
98 return cast<PointerType>(Instruction::getType());
101 /// Return the type that is being allocated by the instruction.
102 Type *getAllocatedType() const { return AllocatedType; }
103 /// for use only in special circumstances that need to generically
104 /// transform a whole instruction (eg: IR linking and vectorization).
105 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
107 /// Return the alignment of the memory that is being allocated by the
109 unsigned getAlignment() const {
110 return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
112 void setAlignment(unsigned Align);
114 /// Return true if this alloca is in the entry block of the function and is a
115 /// constant size. If so, the code generator will fold it into the
116 /// prolog/epilog code, so it is basically free.
117 bool isStaticAlloca() const;
119 /// Return true if this alloca is used as an inalloca argument to a call. Such
120 /// allocas are never considered static even if they are in the entry block.
121 bool isUsedWithInAlloca() const {
122 return getSubclassDataFromInstruction() & 32;
125 /// Specify whether this alloca is used to represent the arguments to a call.
126 void setUsedWithInAlloca(bool V) {
127 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
131 /// Return true if this alloca is used as a swifterror argument to a call.
132 bool isSwiftError() const {
133 return getSubclassDataFromInstruction() & 64;
136 /// Specify whether this alloca is used to represent a swifterror.
137 void setSwiftError(bool V) {
138 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
142 // Methods for support type inquiry through isa, cast, and dyn_cast:
143 static bool classof(const Instruction *I) {
144 return (I->getOpcode() == Instruction::Alloca);
146 static bool classof(const Value *V) {
147 return isa<Instruction>(V) && classof(cast<Instruction>(V));
151 // Shadow Instruction::setInstructionSubclassData with a private forwarding
152 // method so that subclasses cannot accidentally use it.
153 void setInstructionSubclassData(unsigned short D) {
154 Instruction::setInstructionSubclassData(D);
158 //===----------------------------------------------------------------------===//
160 //===----------------------------------------------------------------------===//
162 /// An instruction for reading from memory. This uses the SubclassData field in
163 /// Value to store whether or not the load is volatile.
164 class LoadInst : public UnaryInstruction {
168 // Note: Instruction needs to be a friend here to call cloneImpl.
169 friend class Instruction;
171 LoadInst *cloneImpl() const;
174 LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
175 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
176 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile = false,
177 Instruction *InsertBefore = nullptr);
178 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
179 Instruction *InsertBefore = nullptr)
180 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
181 NameStr, isVolatile, InsertBefore) {}
182 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
183 BasicBlock *InsertAtEnd);
184 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
185 Instruction *InsertBefore = nullptr)
186 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
187 NameStr, isVolatile, Align, InsertBefore) {}
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 unsigned Align, Instruction *InsertBefore = nullptr);
190 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
191 unsigned Align, BasicBlock *InsertAtEnd);
192 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
193 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
194 Instruction *InsertBefore = nullptr)
195 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
196 NameStr, isVolatile, Align, Order, SSID, InsertBefore) {}
197 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
198 unsigned Align, AtomicOrdering Order,
199 SyncScope::ID SSID = SyncScope::System,
200 Instruction *InsertBefore = nullptr);
201 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
202 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
203 BasicBlock *InsertAtEnd);
204 LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
205 LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
206 LoadInst(Type *Ty, Value *Ptr, const char *NameStr = nullptr,
207 bool isVolatile = false, Instruction *InsertBefore = nullptr);
208 explicit LoadInst(Value *Ptr, const char *NameStr = nullptr,
209 bool isVolatile = false,
210 Instruction *InsertBefore = nullptr)
211 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
212 NameStr, isVolatile, InsertBefore) {}
213 LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
214 BasicBlock *InsertAtEnd);
216 /// Return true if this is a load from a volatile memory location.
217 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
219 /// Specify whether this is a volatile load or not.
220 void setVolatile(bool V) {
221 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
225 /// Return the alignment of the access that is being performed.
226 unsigned getAlignment() const {
227 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
230 void setAlignment(unsigned Align);
232 /// Returns the ordering constraint of this load instruction.
233 AtomicOrdering getOrdering() const {
234 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
237 /// Sets the ordering constraint of this load instruction. May not be Release
238 /// or AcquireRelease.
239 void setOrdering(AtomicOrdering Ordering) {
240 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
241 ((unsigned)Ordering << 7));
244 /// Returns the synchronization scope ID of this load instruction.
245 SyncScope::ID getSyncScopeID() const {
249 /// Sets the synchronization scope ID of this load instruction.
250 void setSyncScopeID(SyncScope::ID SSID) {
254 /// Sets the ordering constraint and the synchronization scope ID of this load
256 void setAtomic(AtomicOrdering Ordering,
257 SyncScope::ID SSID = SyncScope::System) {
258 setOrdering(Ordering);
259 setSyncScopeID(SSID);
262 bool isSimple() const { return !isAtomic() && !isVolatile(); }
264 bool isUnordered() const {
265 return (getOrdering() == AtomicOrdering::NotAtomic ||
266 getOrdering() == AtomicOrdering::Unordered) &&
270 Value *getPointerOperand() { return getOperand(0); }
271 const Value *getPointerOperand() const { return getOperand(0); }
272 static unsigned getPointerOperandIndex() { return 0U; }
273 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
275 /// Returns the address space of the pointer operand.
276 unsigned getPointerAddressSpace() const {
277 return getPointerOperandType()->getPointerAddressSpace();
280 // Methods for support type inquiry through isa, cast, and dyn_cast:
281 static bool classof(const Instruction *I) {
282 return I->getOpcode() == Instruction::Load;
284 static bool classof(const Value *V) {
285 return isa<Instruction>(V) && classof(cast<Instruction>(V));
289 // Shadow Instruction::setInstructionSubclassData with a private forwarding
290 // method so that subclasses cannot accidentally use it.
291 void setInstructionSubclassData(unsigned short D) {
292 Instruction::setInstructionSubclassData(D);
295 /// The synchronization scope ID of this load instruction. Not quite enough
296 /// room in SubClassData for everything, so synchronization scope ID gets its
301 //===----------------------------------------------------------------------===//
303 //===----------------------------------------------------------------------===//
305 /// An instruction for storing to memory.
306 class StoreInst : public Instruction {
310 // Note: Instruction needs to be a friend here to call cloneImpl.
311 friend class Instruction;
313 StoreInst *cloneImpl() const;
316 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
317 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
318 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
319 Instruction *InsertBefore = nullptr);
320 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
321 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
322 unsigned Align, Instruction *InsertBefore = nullptr);
323 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
324 unsigned Align, BasicBlock *InsertAtEnd);
325 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
326 unsigned Align, AtomicOrdering Order,
327 SyncScope::ID SSID = SyncScope::System,
328 Instruction *InsertBefore = nullptr);
329 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
330 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
331 BasicBlock *InsertAtEnd);
333 // allocate space for exactly two operands
334 void *operator new(size_t s) {
335 return User::operator new(s, 2);
338 /// Return true if this is a store to a volatile memory location.
339 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
341 /// Specify whether this is a volatile store or not.
342 void setVolatile(bool V) {
343 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
347 /// Transparently provide more efficient getOperand methods.
348 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
350 /// Return the alignment of the access that is being performed
351 unsigned getAlignment() const {
352 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
355 void setAlignment(unsigned Align);
357 /// Returns the ordering constraint of this store instruction.
358 AtomicOrdering getOrdering() const {
359 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
362 /// Sets the ordering constraint of this store instruction. May not be
363 /// Acquire or AcquireRelease.
364 void setOrdering(AtomicOrdering Ordering) {
365 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
366 ((unsigned)Ordering << 7));
369 /// Returns the synchronization scope ID of this store instruction.
370 SyncScope::ID getSyncScopeID() const {
374 /// Sets the synchronization scope ID of this store instruction.
375 void setSyncScopeID(SyncScope::ID SSID) {
379 /// Sets the ordering constraint and the synchronization scope ID of this
380 /// store instruction.
381 void setAtomic(AtomicOrdering Ordering,
382 SyncScope::ID SSID = SyncScope::System) {
383 setOrdering(Ordering);
384 setSyncScopeID(SSID);
387 bool isSimple() const { return !isAtomic() && !isVolatile(); }
389 bool isUnordered() const {
390 return (getOrdering() == AtomicOrdering::NotAtomic ||
391 getOrdering() == AtomicOrdering::Unordered) &&
395 Value *getValueOperand() { return getOperand(0); }
396 const Value *getValueOperand() const { return getOperand(0); }
398 Value *getPointerOperand() { return getOperand(1); }
399 const Value *getPointerOperand() const { return getOperand(1); }
400 static unsigned getPointerOperandIndex() { return 1U; }
401 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
403 /// Returns the address space of the pointer operand.
404 unsigned getPointerAddressSpace() const {
405 return getPointerOperandType()->getPointerAddressSpace();
408 // Methods for support type inquiry through isa, cast, and dyn_cast:
409 static bool classof(const Instruction *I) {
410 return I->getOpcode() == Instruction::Store;
412 static bool classof(const Value *V) {
413 return isa<Instruction>(V) && classof(cast<Instruction>(V));
417 // Shadow Instruction::setInstructionSubclassData with a private forwarding
418 // method so that subclasses cannot accidentally use it.
419 void setInstructionSubclassData(unsigned short D) {
420 Instruction::setInstructionSubclassData(D);
423 /// The synchronization scope ID of this store instruction. Not quite enough
424 /// room in SubClassData for everything, so synchronization scope ID gets its
430 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
433 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
435 //===----------------------------------------------------------------------===//
437 //===----------------------------------------------------------------------===//
439 /// An instruction for ordering other memory operations.
440 class FenceInst : public Instruction {
441 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
444 // Note: Instruction needs to be a friend here to call cloneImpl.
445 friend class Instruction;
447 FenceInst *cloneImpl() const;
450 // Ordering may only be Acquire, Release, AcquireRelease, or
451 // SequentiallyConsistent.
452 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
453 SyncScope::ID SSID = SyncScope::System,
454 Instruction *InsertBefore = nullptr);
455 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
456 BasicBlock *InsertAtEnd);
458 // allocate space for exactly zero operands
459 void *operator new(size_t s) {
460 return User::operator new(s, 0);
463 /// Returns the ordering constraint of this fence instruction.
464 AtomicOrdering getOrdering() const {
465 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
468 /// Sets the ordering constraint of this fence instruction. May only be
469 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
470 void setOrdering(AtomicOrdering Ordering) {
471 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
472 ((unsigned)Ordering << 1));
475 /// Returns the synchronization scope ID of this fence instruction.
476 SyncScope::ID getSyncScopeID() const {
480 /// Sets the synchronization scope ID of this fence instruction.
481 void setSyncScopeID(SyncScope::ID SSID) {
485 // Methods for support type inquiry through isa, cast, and dyn_cast:
486 static bool classof(const Instruction *I) {
487 return I->getOpcode() == Instruction::Fence;
489 static bool classof(const Value *V) {
490 return isa<Instruction>(V) && classof(cast<Instruction>(V));
494 // Shadow Instruction::setInstructionSubclassData with a private forwarding
495 // method so that subclasses cannot accidentally use it.
496 void setInstructionSubclassData(unsigned short D) {
497 Instruction::setInstructionSubclassData(D);
500 /// The synchronization scope ID of this fence instruction. Not quite enough
501 /// room in SubClassData for everything, so synchronization scope ID gets its
506 //===----------------------------------------------------------------------===//
507 // AtomicCmpXchgInst Class
508 //===----------------------------------------------------------------------===//
510 /// an instruction that atomically checks whether a
511 /// specified value is in a memory location, and, if it is, stores a new value
512 /// there. Returns the value that was loaded.
514 class AtomicCmpXchgInst : public Instruction {
515 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
516 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
520 // Note: Instruction needs to be a friend here to call cloneImpl.
521 friend class Instruction;
523 AtomicCmpXchgInst *cloneImpl() const;
526 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
527 AtomicOrdering SuccessOrdering,
528 AtomicOrdering FailureOrdering,
529 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
530 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
531 AtomicOrdering SuccessOrdering,
532 AtomicOrdering FailureOrdering,
533 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
535 // allocate space for exactly three operands
536 void *operator new(size_t s) {
537 return User::operator new(s, 3);
540 /// Return true if this is a cmpxchg from a volatile memory
543 bool isVolatile() const {
544 return getSubclassDataFromInstruction() & 1;
547 /// Specify whether this is a volatile cmpxchg.
549 void setVolatile(bool V) {
550 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
554 /// Return true if this cmpxchg may spuriously fail.
555 bool isWeak() const {
556 return getSubclassDataFromInstruction() & 0x100;
559 void setWeak(bool IsWeak) {
560 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
564 /// Transparently provide more efficient getOperand methods.
565 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
567 /// Returns the success ordering constraint of this cmpxchg instruction.
568 AtomicOrdering getSuccessOrdering() const {
569 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
572 /// Sets the success ordering constraint of this cmpxchg instruction.
573 void setSuccessOrdering(AtomicOrdering Ordering) {
574 assert(Ordering != AtomicOrdering::NotAtomic &&
575 "CmpXchg instructions can only be atomic.");
576 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
577 ((unsigned)Ordering << 2));
580 /// Returns the failure ordering constraint of this cmpxchg instruction.
581 AtomicOrdering getFailureOrdering() const {
582 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
585 /// Sets the failure ordering constraint of this cmpxchg instruction.
586 void setFailureOrdering(AtomicOrdering Ordering) {
587 assert(Ordering != AtomicOrdering::NotAtomic &&
588 "CmpXchg instructions can only be atomic.");
589 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
590 ((unsigned)Ordering << 5));
593 /// Returns the synchronization scope ID of this cmpxchg instruction.
594 SyncScope::ID getSyncScopeID() const {
598 /// Sets the synchronization scope ID of this cmpxchg instruction.
599 void setSyncScopeID(SyncScope::ID SSID) {
603 Value *getPointerOperand() { return getOperand(0); }
604 const Value *getPointerOperand() const { return getOperand(0); }
605 static unsigned getPointerOperandIndex() { return 0U; }
607 Value *getCompareOperand() { return getOperand(1); }
608 const Value *getCompareOperand() const { return getOperand(1); }
610 Value *getNewValOperand() { return getOperand(2); }
611 const Value *getNewValOperand() const { return getOperand(2); }
613 /// Returns the address space of the pointer operand.
614 unsigned getPointerAddressSpace() const {
615 return getPointerOperand()->getType()->getPointerAddressSpace();
618 /// Returns the strongest permitted ordering on failure, given the
619 /// desired ordering on success.
621 /// If the comparison in a cmpxchg operation fails, there is no atomic store
622 /// so release semantics cannot be provided. So this function drops explicit
623 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
624 /// operation would remain SequentiallyConsistent.
625 static AtomicOrdering
626 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
627 switch (SuccessOrdering) {
629 llvm_unreachable("invalid cmpxchg success ordering");
630 case AtomicOrdering::Release:
631 case AtomicOrdering::Monotonic:
632 return AtomicOrdering::Monotonic;
633 case AtomicOrdering::AcquireRelease:
634 case AtomicOrdering::Acquire:
635 return AtomicOrdering::Acquire;
636 case AtomicOrdering::SequentiallyConsistent:
637 return AtomicOrdering::SequentiallyConsistent;
641 // Methods for support type inquiry through isa, cast, and dyn_cast:
642 static bool classof(const Instruction *I) {
643 return I->getOpcode() == Instruction::AtomicCmpXchg;
645 static bool classof(const Value *V) {
646 return isa<Instruction>(V) && classof(cast<Instruction>(V));
650 // Shadow Instruction::setInstructionSubclassData with a private forwarding
651 // method so that subclasses cannot accidentally use it.
652 void setInstructionSubclassData(unsigned short D) {
653 Instruction::setInstructionSubclassData(D);
656 /// The synchronization scope ID of this cmpxchg instruction. Not quite
657 /// enough room in SubClassData for everything, so synchronization scope ID
658 /// gets its own field.
663 struct OperandTraits<AtomicCmpXchgInst> :
664 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
667 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
669 //===----------------------------------------------------------------------===//
670 // AtomicRMWInst Class
671 //===----------------------------------------------------------------------===//
673 /// an instruction that atomically reads a memory location,
674 /// combines it with another value, and then stores the result back. Returns
677 class AtomicRMWInst : public Instruction {
679 // Note: Instruction needs to be a friend here to call cloneImpl.
680 friend class Instruction;
682 AtomicRMWInst *cloneImpl() const;
685 /// This enumeration lists the possible modifications atomicrmw can make. In
686 /// the descriptions, 'p' is the pointer to the instruction's memory location,
687 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
688 /// instruction. These instructions always return 'old'.
704 /// *p = old >signed v ? old : v
706 /// *p = old <signed v ? old : v
708 /// *p = old >unsigned v ? old : v
710 /// *p = old <unsigned v ? old : v
718 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
719 AtomicOrdering Ordering, SyncScope::ID SSID,
720 Instruction *InsertBefore = nullptr);
721 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
722 AtomicOrdering Ordering, SyncScope::ID SSID,
723 BasicBlock *InsertAtEnd);
725 // allocate space for exactly two operands
726 void *operator new(size_t s) {
727 return User::operator new(s, 2);
730 BinOp getOperation() const {
731 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
734 void setOperation(BinOp Operation) {
735 unsigned short SubclassData = getSubclassDataFromInstruction();
736 setInstructionSubclassData((SubclassData & 31) |
740 /// Return true if this is a RMW on a volatile memory location.
742 bool isVolatile() const {
743 return getSubclassDataFromInstruction() & 1;
746 /// Specify whether this is a volatile RMW or not.
748 void setVolatile(bool V) {
749 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
753 /// Transparently provide more efficient getOperand methods.
754 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
756 /// Returns the ordering constraint of this rmw instruction.
757 AtomicOrdering getOrdering() const {
758 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
761 /// Sets the ordering constraint of this rmw instruction.
762 void setOrdering(AtomicOrdering Ordering) {
763 assert(Ordering != AtomicOrdering::NotAtomic &&
764 "atomicrmw instructions can only be atomic.");
765 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
766 ((unsigned)Ordering << 2));
769 /// Returns the synchronization scope ID of this rmw instruction.
770 SyncScope::ID getSyncScopeID() const {
774 /// Sets the synchronization scope ID of this rmw instruction.
775 void setSyncScopeID(SyncScope::ID SSID) {
779 Value *getPointerOperand() { return getOperand(0); }
780 const Value *getPointerOperand() const { return getOperand(0); }
781 static unsigned getPointerOperandIndex() { return 0U; }
783 Value *getValOperand() { return getOperand(1); }
784 const Value *getValOperand() const { return getOperand(1); }
786 /// Returns the address space of the pointer operand.
787 unsigned getPointerAddressSpace() const {
788 return getPointerOperand()->getType()->getPointerAddressSpace();
791 // Methods for support type inquiry through isa, cast, and dyn_cast:
792 static bool classof(const Instruction *I) {
793 return I->getOpcode() == Instruction::AtomicRMW;
795 static bool classof(const Value *V) {
796 return isa<Instruction>(V) && classof(cast<Instruction>(V));
800 void Init(BinOp Operation, Value *Ptr, Value *Val,
801 AtomicOrdering Ordering, SyncScope::ID SSID);
803 // Shadow Instruction::setInstructionSubclassData with a private forwarding
804 // method so that subclasses cannot accidentally use it.
805 void setInstructionSubclassData(unsigned short D) {
806 Instruction::setInstructionSubclassData(D);
809 /// The synchronization scope ID of this rmw instruction. Not quite enough
810 /// room in SubClassData for everything, so synchronization scope ID gets its
816 struct OperandTraits<AtomicRMWInst>
817 : public FixedNumOperandTraits<AtomicRMWInst,2> {
820 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
822 //===----------------------------------------------------------------------===//
823 // GetElementPtrInst Class
824 //===----------------------------------------------------------------------===//
826 // checkGEPType - Simple wrapper function to give a better assertion failure
827 // message on bad indexes for a gep instruction.
829 inline Type *checkGEPType(Type *Ty) {
830 assert(Ty && "Invalid GetElementPtrInst indices for type!");
834 /// an instruction for type-safe pointer arithmetic to
835 /// access elements of arrays and structs
837 class GetElementPtrInst : public Instruction {
838 Type *SourceElementType;
839 Type *ResultElementType;
841 GetElementPtrInst(const GetElementPtrInst &GEPI);
843 /// Constructors - Create a getelementptr instruction with a base pointer an
844 /// list of indices. The first ctor can optionally insert before an existing
845 /// instruction, the second appends the new instruction to the specified
847 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
848 ArrayRef<Value *> IdxList, unsigned Values,
849 const Twine &NameStr, Instruction *InsertBefore);
850 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
851 ArrayRef<Value *> IdxList, unsigned Values,
852 const Twine &NameStr, BasicBlock *InsertAtEnd);
854 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
857 // Note: Instruction needs to be a friend here to call cloneImpl.
858 friend class Instruction;
860 GetElementPtrInst *cloneImpl() const;
863 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
864 ArrayRef<Value *> IdxList,
865 const Twine &NameStr = "",
866 Instruction *InsertBefore = nullptr) {
867 unsigned Values = 1 + unsigned(IdxList.size());
870 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
874 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
875 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
876 NameStr, InsertBefore);
879 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
880 ArrayRef<Value *> IdxList,
881 const Twine &NameStr,
882 BasicBlock *InsertAtEnd) {
883 unsigned Values = 1 + unsigned(IdxList.size());
886 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
890 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
891 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
892 NameStr, InsertAtEnd);
895 /// Create an "inbounds" getelementptr. See the documentation for the
896 /// "inbounds" flag in LangRef.html for details.
897 static GetElementPtrInst *CreateInBounds(Value *Ptr,
898 ArrayRef<Value *> IdxList,
899 const Twine &NameStr = "",
900 Instruction *InsertBefore = nullptr){
901 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
904 static GetElementPtrInst *
905 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
906 const Twine &NameStr = "",
907 Instruction *InsertBefore = nullptr) {
908 GetElementPtrInst *GEP =
909 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
910 GEP->setIsInBounds(true);
914 static GetElementPtrInst *CreateInBounds(Value *Ptr,
915 ArrayRef<Value *> IdxList,
916 const Twine &NameStr,
917 BasicBlock *InsertAtEnd) {
918 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
921 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
922 ArrayRef<Value *> IdxList,
923 const Twine &NameStr,
924 BasicBlock *InsertAtEnd) {
925 GetElementPtrInst *GEP =
926 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
927 GEP->setIsInBounds(true);
931 /// Transparently provide more efficient getOperand methods.
932 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
934 Type *getSourceElementType() const { return SourceElementType; }
936 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
937 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
939 Type *getResultElementType() const {
940 assert(ResultElementType ==
941 cast<PointerType>(getType()->getScalarType())->getElementType());
942 return ResultElementType;
945 /// Returns the address space of this instruction's pointer type.
946 unsigned getAddressSpace() const {
947 // Note that this is always the same as the pointer operand's address space
948 // and that is cheaper to compute, so cheat here.
949 return getPointerAddressSpace();
952 /// Returns the type of the element that would be loaded with
953 /// a load instruction with the specified parameters.
955 /// Null is returned if the indices are invalid for the specified
958 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
959 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
960 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
962 inline op_iterator idx_begin() { return op_begin()+1; }
963 inline const_op_iterator idx_begin() const { return op_begin()+1; }
964 inline op_iterator idx_end() { return op_end(); }
965 inline const_op_iterator idx_end() const { return op_end(); }
967 inline iterator_range<op_iterator> indices() {
968 return make_range(idx_begin(), idx_end());
971 inline iterator_range<const_op_iterator> indices() const {
972 return make_range(idx_begin(), idx_end());
975 Value *getPointerOperand() {
976 return getOperand(0);
978 const Value *getPointerOperand() const {
979 return getOperand(0);
981 static unsigned getPointerOperandIndex() {
982 return 0U; // get index for modifying correct operand.
985 /// Method to return the pointer operand as a
987 Type *getPointerOperandType() const {
988 return getPointerOperand()->getType();
991 /// Returns the address space of the pointer operand.
992 unsigned getPointerAddressSpace() const {
993 return getPointerOperandType()->getPointerAddressSpace();
996 /// Returns the pointer type returned by the GEP
997 /// instruction, which may be a vector of pointers.
998 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
999 return getGEPReturnType(
1000 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1003 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1004 ArrayRef<Value *> IdxList) {
1005 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1006 Ptr->getType()->getPointerAddressSpace());
1008 if (Ptr->getType()->isVectorTy()) {
1009 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1010 return VectorType::get(PtrTy, NumElem);
1012 for (Value *Index : IdxList)
1013 if (Index->getType()->isVectorTy()) {
1014 unsigned NumElem = Index->getType()->getVectorNumElements();
1015 return VectorType::get(PtrTy, NumElem);
1021 unsigned getNumIndices() const { // Note: always non-negative
1022 return getNumOperands() - 1;
1025 bool hasIndices() const {
1026 return getNumOperands() > 1;
1029 /// Return true if all of the indices of this GEP are
1030 /// zeros. If so, the result pointer and the first operand have the same
1031 /// value, just potentially different types.
1032 bool hasAllZeroIndices() const;
1034 /// Return true if all of the indices of this GEP are
1035 /// constant integers. If so, the result pointer and the first operand have
1036 /// a constant offset between them.
1037 bool hasAllConstantIndices() const;
1039 /// Set or clear the inbounds flag on this GEP instruction.
1040 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1041 void setIsInBounds(bool b = true);
1043 /// Determine whether the GEP has the inbounds flag.
1044 bool isInBounds() const;
1046 /// Accumulate the constant address offset of this GEP if possible.
1048 /// This routine accepts an APInt into which it will accumulate the constant
1049 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1050 /// all-constant, it returns false and the value of the offset APInt is
1051 /// undefined (it is *not* preserved!). The APInt passed into this routine
1052 /// must be at least as wide as the IntPtr type for the address space of
1053 /// the base GEP pointer.
1054 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1056 // Methods for support type inquiry through isa, cast, and dyn_cast:
1057 static bool classof(const Instruction *I) {
1058 return (I->getOpcode() == Instruction::GetElementPtr);
1060 static bool classof(const Value *V) {
1061 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1066 struct OperandTraits<GetElementPtrInst> :
1067 public VariadicOperandTraits<GetElementPtrInst, 1> {
1070 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1071 ArrayRef<Value *> IdxList, unsigned Values,
1072 const Twine &NameStr,
1073 Instruction *InsertBefore)
1074 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1075 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1076 Values, InsertBefore),
1077 SourceElementType(PointeeType),
1078 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1079 assert(ResultElementType ==
1080 cast<PointerType>(getType()->getScalarType())->getElementType());
1081 init(Ptr, IdxList, NameStr);
1084 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1085 ArrayRef<Value *> IdxList, unsigned Values,
1086 const Twine &NameStr,
1087 BasicBlock *InsertAtEnd)
1088 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1089 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1090 Values, InsertAtEnd),
1091 SourceElementType(PointeeType),
1092 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1093 assert(ResultElementType ==
1094 cast<PointerType>(getType()->getScalarType())->getElementType());
1095 init(Ptr, IdxList, NameStr);
1098 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1100 //===----------------------------------------------------------------------===//
1102 //===----------------------------------------------------------------------===//
1104 /// This instruction compares its operands according to the predicate given
1105 /// to the constructor. It only operates on integers or pointers. The operands
1106 /// must be identical types.
1107 /// Represent an integer comparison operator.
1108 class ICmpInst: public CmpInst {
1110 assert(isIntPredicate() &&
1111 "Invalid ICmp predicate value");
1112 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1113 "Both operands to ICmp instruction are not of the same type!");
1114 // Check that the operands are the right type
1115 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1116 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1117 "Invalid operand types for ICmp instruction");
1121 // Note: Instruction needs to be a friend here to call cloneImpl.
1122 friend class Instruction;
1124 /// Clone an identical ICmpInst
1125 ICmpInst *cloneImpl() const;
1128 /// Constructor with insert-before-instruction semantics.
1130 Instruction *InsertBefore, ///< Where to insert
1131 Predicate pred, ///< The predicate to use for the comparison
1132 Value *LHS, ///< The left-hand-side of the expression
1133 Value *RHS, ///< The right-hand-side of the expression
1134 const Twine &NameStr = "" ///< Name of the instruction
1135 ) : CmpInst(makeCmpResultType(LHS->getType()),
1136 Instruction::ICmp, pred, LHS, RHS, NameStr,
1143 /// Constructor with insert-at-end semantics.
1145 BasicBlock &InsertAtEnd, ///< Block to insert into.
1146 Predicate pred, ///< The predicate to use for the comparison
1147 Value *LHS, ///< The left-hand-side of the expression
1148 Value *RHS, ///< The right-hand-side of the expression
1149 const Twine &NameStr = "" ///< Name of the instruction
1150 ) : CmpInst(makeCmpResultType(LHS->getType()),
1151 Instruction::ICmp, pred, LHS, RHS, NameStr,
1158 /// Constructor with no-insertion semantics
1160 Predicate pred, ///< The predicate to use for the comparison
1161 Value *LHS, ///< The left-hand-side of the expression
1162 Value *RHS, ///< The right-hand-side of the expression
1163 const Twine &NameStr = "" ///< Name of the instruction
1164 ) : CmpInst(makeCmpResultType(LHS->getType()),
1165 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1171 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1172 /// @returns the predicate that would be the result if the operand were
1173 /// regarded as signed.
1174 /// Return the signed version of the predicate
1175 Predicate getSignedPredicate() const {
1176 return getSignedPredicate(getPredicate());
1179 /// This is a static version that you can use without an instruction.
1180 /// Return the signed version of the predicate.
1181 static Predicate getSignedPredicate(Predicate pred);
1183 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1184 /// @returns the predicate that would be the result if the operand were
1185 /// regarded as unsigned.
1186 /// Return the unsigned version of the predicate
1187 Predicate getUnsignedPredicate() const {
1188 return getUnsignedPredicate(getPredicate());
1191 /// This is a static version that you can use without an instruction.
1192 /// Return the unsigned version of the predicate.
1193 static Predicate getUnsignedPredicate(Predicate pred);
1195 /// Return true if this predicate is either EQ or NE. This also
1196 /// tests for commutativity.
1197 static bool isEquality(Predicate P) {
1198 return P == ICMP_EQ || P == ICMP_NE;
1201 /// Return true if this predicate is either EQ or NE. This also
1202 /// tests for commutativity.
1203 bool isEquality() const {
1204 return isEquality(getPredicate());
1207 /// @returns true if the predicate of this ICmpInst is commutative
1208 /// Determine if this relation is commutative.
1209 bool isCommutative() const { return isEquality(); }
1211 /// Return true if the predicate is relational (not EQ or NE).
1213 bool isRelational() const {
1214 return !isEquality();
1217 /// Return true if the predicate is relational (not EQ or NE).
1219 static bool isRelational(Predicate P) {
1220 return !isEquality(P);
1223 /// Exchange the two operands to this instruction in such a way that it does
1224 /// not modify the semantics of the instruction. The predicate value may be
1225 /// changed to retain the same result if the predicate is order dependent
1227 /// Swap operands and adjust predicate.
1228 void swapOperands() {
1229 setPredicate(getSwappedPredicate());
1230 Op<0>().swap(Op<1>());
1233 // Methods for support type inquiry through isa, cast, and dyn_cast:
1234 static bool classof(const Instruction *I) {
1235 return I->getOpcode() == Instruction::ICmp;
1237 static bool classof(const Value *V) {
1238 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1242 //===----------------------------------------------------------------------===//
1244 //===----------------------------------------------------------------------===//
1246 /// This instruction compares its operands according to the predicate given
1247 /// to the constructor. It only operates on floating point values or packed
1248 /// vectors of floating point values. The operands must be identical types.
1249 /// Represents a floating point comparison operator.
1250 class FCmpInst: public CmpInst {
1252 assert(isFPPredicate() && "Invalid FCmp predicate value");
1253 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1254 "Both operands to FCmp instruction are not of the same type!");
1255 // Check that the operands are the right type
1256 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1257 "Invalid operand types for FCmp instruction");
1261 // Note: Instruction needs to be a friend here to call cloneImpl.
1262 friend class Instruction;
1264 /// Clone an identical FCmpInst
1265 FCmpInst *cloneImpl() const;
1268 /// Constructor with insert-before-instruction semantics.
1270 Instruction *InsertBefore, ///< Where to insert
1271 Predicate pred, ///< The predicate to use for the comparison
1272 Value *LHS, ///< The left-hand-side of the expression
1273 Value *RHS, ///< The right-hand-side of the expression
1274 const Twine &NameStr = "" ///< Name of the instruction
1275 ) : CmpInst(makeCmpResultType(LHS->getType()),
1276 Instruction::FCmp, pred, LHS, RHS, NameStr,
1281 /// Constructor with insert-at-end semantics.
1283 BasicBlock &InsertAtEnd, ///< Block to insert into.
1284 Predicate pred, ///< The predicate to use for the comparison
1285 Value *LHS, ///< The left-hand-side of the expression
1286 Value *RHS, ///< The right-hand-side of the expression
1287 const Twine &NameStr = "" ///< Name of the instruction
1288 ) : CmpInst(makeCmpResultType(LHS->getType()),
1289 Instruction::FCmp, pred, LHS, RHS, NameStr,
1294 /// Constructor with no-insertion semantics
1296 Predicate pred, ///< The predicate to use for the comparison
1297 Value *LHS, ///< The left-hand-side of the expression
1298 Value *RHS, ///< The right-hand-side of the expression
1299 const Twine &NameStr = "" ///< Name of the instruction
1300 ) : CmpInst(makeCmpResultType(LHS->getType()),
1301 Instruction::FCmp, pred, LHS, RHS, NameStr) {
1305 /// @returns true if the predicate of this instruction is EQ or NE.
1306 /// Determine if this is an equality predicate.
1307 static bool isEquality(Predicate Pred) {
1308 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1312 /// @returns true if the predicate of this instruction is EQ or NE.
1313 /// Determine if this is an equality predicate.
1314 bool isEquality() const { return isEquality(getPredicate()); }
1316 /// @returns true if the predicate of this instruction is commutative.
1317 /// Determine if this is a commutative predicate.
1318 bool isCommutative() const {
1319 return isEquality() ||
1320 getPredicate() == FCMP_FALSE ||
1321 getPredicate() == FCMP_TRUE ||
1322 getPredicate() == FCMP_ORD ||
1323 getPredicate() == FCMP_UNO;
1326 /// @returns true if the predicate is relational (not EQ or NE).
1327 /// Determine if this a relational predicate.
1328 bool isRelational() const { return !isEquality(); }
1330 /// Exchange the two operands to this instruction in such a way that it does
1331 /// not modify the semantics of the instruction. The predicate value may be
1332 /// changed to retain the same result if the predicate is order dependent
1334 /// Swap operands and adjust predicate.
1335 void swapOperands() {
1336 setPredicate(getSwappedPredicate());
1337 Op<0>().swap(Op<1>());
1340 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1341 static bool classof(const Instruction *I) {
1342 return I->getOpcode() == Instruction::FCmp;
1344 static bool classof(const Value *V) {
1345 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1349 //===----------------------------------------------------------------------===//
1350 /// This class represents a function call, abstracting a target
1351 /// machine's calling convention. This class uses low bit of the SubClassData
1352 /// field to indicate whether or not this is a tail call. The rest of the bits
1353 /// hold the calling convention of the call.
1355 class CallInst : public Instruction,
1356 public OperandBundleUser<CallInst, User::op_iterator> {
1357 friend class OperandBundleUser<CallInst, User::op_iterator>;
1359 AttributeList Attrs; ///< parameter attributes for call
1362 CallInst(const CallInst &CI);
1364 /// Construct a CallInst given a range of arguments.
1365 /// Construct a CallInst from a range of arguments
1366 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1367 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1368 Instruction *InsertBefore);
1370 inline CallInst(Value *Func, ArrayRef<Value *> Args,
1371 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1372 Instruction *InsertBefore)
1373 : CallInst(cast<FunctionType>(
1374 cast<PointerType>(Func->getType())->getElementType()),
1375 Func, Args, Bundles, NameStr, InsertBefore) {}
1377 inline CallInst(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr,
1378 Instruction *InsertBefore)
1379 : CallInst(Func, Args, None, NameStr, InsertBefore) {}
1381 /// Construct a CallInst given a range of arguments.
1382 /// Construct a CallInst from a range of arguments
1383 inline CallInst(Value *Func, ArrayRef<Value *> Args,
1384 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1385 BasicBlock *InsertAtEnd);
1387 explicit CallInst(Value *F, const Twine &NameStr,
1388 Instruction *InsertBefore);
1390 CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1392 void init(Value *Func, ArrayRef<Value *> Args,
1393 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
1394 init(cast<FunctionType>(
1395 cast<PointerType>(Func->getType())->getElementType()),
1396 Func, Args, Bundles, NameStr);
1398 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1399 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1400 void init(Value *Func, const Twine &NameStr);
1402 bool hasDescriptor() const { return HasDescriptor; }
1405 // Note: Instruction needs to be a friend here to call cloneImpl.
1406 friend class Instruction;
1408 CallInst *cloneImpl() const;
1411 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1412 ArrayRef<OperandBundleDef> Bundles = None,
1413 const Twine &NameStr = "",
1414 Instruction *InsertBefore = nullptr) {
1415 return Create(cast<FunctionType>(
1416 cast<PointerType>(Func->getType())->getElementType()),
1417 Func, Args, Bundles, NameStr, InsertBefore);
1420 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1421 const Twine &NameStr,
1422 Instruction *InsertBefore = nullptr) {
1423 return Create(cast<FunctionType>(
1424 cast<PointerType>(Func->getType())->getElementType()),
1425 Func, Args, None, NameStr, InsertBefore);
1428 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1429 const Twine &NameStr,
1430 Instruction *InsertBefore = nullptr) {
1431 return new (unsigned(Args.size() + 1))
1432 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1435 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1436 ArrayRef<OperandBundleDef> Bundles = None,
1437 const Twine &NameStr = "",
1438 Instruction *InsertBefore = nullptr) {
1439 const unsigned TotalOps =
1440 unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1441 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1443 return new (TotalOps, DescriptorBytes)
1444 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1447 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1448 ArrayRef<OperandBundleDef> Bundles,
1449 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1450 const unsigned TotalOps =
1451 unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1452 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1454 return new (TotalOps, DescriptorBytes)
1455 CallInst(Func, Args, Bundles, NameStr, InsertAtEnd);
1458 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1459 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1460 return new (unsigned(Args.size() + 1))
1461 CallInst(Func, Args, None, NameStr, InsertAtEnd);
1464 static CallInst *Create(Value *F, const Twine &NameStr = "",
1465 Instruction *InsertBefore = nullptr) {
1466 return new(1) CallInst(F, NameStr, InsertBefore);
1469 static CallInst *Create(Value *F, const Twine &NameStr,
1470 BasicBlock *InsertAtEnd) {
1471 return new(1) CallInst(F, NameStr, InsertAtEnd);
1474 /// Create a clone of \p CI with a different set of operand bundles and
1475 /// insert it before \p InsertPt.
1477 /// The returned call instruction is identical \p CI in every way except that
1478 /// the operand bundles for the new instruction are set to the operand bundles
1480 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1481 Instruction *InsertPt = nullptr);
1483 /// Generate the IR for a call to malloc:
1484 /// 1. Compute the malloc call's argument as the specified type's size,
1485 /// possibly multiplied by the array size if the array size is not
1487 /// 2. Call malloc with that argument.
1488 /// 3. Bitcast the result of the malloc call to the specified type.
1489 static Instruction *CreateMalloc(Instruction *InsertBefore,
1490 Type *IntPtrTy, Type *AllocTy,
1491 Value *AllocSize, Value *ArraySize = nullptr,
1492 Function* MallocF = nullptr,
1493 const Twine &Name = "");
1494 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1495 Type *IntPtrTy, Type *AllocTy,
1496 Value *AllocSize, Value *ArraySize = nullptr,
1497 Function* MallocF = nullptr,
1498 const Twine &Name = "");
1499 static Instruction *CreateMalloc(Instruction *InsertBefore,
1500 Type *IntPtrTy, Type *AllocTy,
1501 Value *AllocSize, Value *ArraySize = nullptr,
1502 ArrayRef<OperandBundleDef> Bundles = None,
1503 Function* MallocF = nullptr,
1504 const Twine &Name = "");
1505 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1506 Type *IntPtrTy, Type *AllocTy,
1507 Value *AllocSize, Value *ArraySize = nullptr,
1508 ArrayRef<OperandBundleDef> Bundles = None,
1509 Function* MallocF = nullptr,
1510 const Twine &Name = "");
1511 /// Generate the IR for a call to the builtin free function.
1512 static Instruction *CreateFree(Value *Source,
1513 Instruction *InsertBefore);
1514 static Instruction *CreateFree(Value *Source,
1515 BasicBlock *InsertAtEnd);
1516 static Instruction *CreateFree(Value *Source,
1517 ArrayRef<OperandBundleDef> Bundles,
1518 Instruction *InsertBefore);
1519 static Instruction *CreateFree(Value *Source,
1520 ArrayRef<OperandBundleDef> Bundles,
1521 BasicBlock *InsertAtEnd);
1523 FunctionType *getFunctionType() const { return FTy; }
1525 void mutateFunctionType(FunctionType *FTy) {
1526 mutateType(FTy->getReturnType());
1530 // Note that 'musttail' implies 'tail'.
1531 enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2,
1533 TailCallKind getTailCallKind() const {
1534 return TailCallKind(getSubclassDataFromInstruction() & 3);
1537 bool isTailCall() const {
1538 unsigned Kind = getSubclassDataFromInstruction() & 3;
1539 return Kind == TCK_Tail || Kind == TCK_MustTail;
1542 bool isMustTailCall() const {
1543 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1546 bool isNoTailCall() const {
1547 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1550 void setTailCall(bool isTC = true) {
1551 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1552 unsigned(isTC ? TCK_Tail : TCK_None));
1555 void setTailCallKind(TailCallKind TCK) {
1556 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1560 /// Provide fast operand accessors
1561 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1563 /// Return the number of call arguments.
1565 unsigned getNumArgOperands() const {
1566 return getNumOperands() - getNumTotalBundleOperands() - 1;
1569 /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1571 Value *getArgOperand(unsigned i) const {
1572 assert(i < getNumArgOperands() && "Out of bounds!");
1573 return getOperand(i);
1575 void setArgOperand(unsigned i, Value *v) {
1576 assert(i < getNumArgOperands() && "Out of bounds!");
1580 /// Return the iterator pointing to the beginning of the argument list.
1581 op_iterator arg_begin() { return op_begin(); }
1583 /// Return the iterator pointing to the end of the argument list.
1584 op_iterator arg_end() {
1585 // [ call args ], [ operand bundles ], callee
1586 return op_end() - getNumTotalBundleOperands() - 1;
1589 /// Iteration adapter for range-for loops.
1590 iterator_range<op_iterator> arg_operands() {
1591 return make_range(arg_begin(), arg_end());
1594 /// Return the iterator pointing to the beginning of the argument list.
1595 const_op_iterator arg_begin() const { return op_begin(); }
1597 /// Return the iterator pointing to the end of the argument list.
1598 const_op_iterator arg_end() const {
1599 // [ call args ], [ operand bundles ], callee
1600 return op_end() - getNumTotalBundleOperands() - 1;
1603 /// Iteration adapter for range-for loops.
1604 iterator_range<const_op_iterator> arg_operands() const {
1605 return make_range(arg_begin(), arg_end());
1608 /// Wrappers for getting the \c Use of a call argument.
1609 const Use &getArgOperandUse(unsigned i) const {
1610 assert(i < getNumArgOperands() && "Out of bounds!");
1611 return getOperandUse(i);
1613 Use &getArgOperandUse(unsigned i) {
1614 assert(i < getNumArgOperands() && "Out of bounds!");
1615 return getOperandUse(i);
1618 /// If one of the arguments has the 'returned' attribute, return its
1619 /// operand value. Otherwise, return nullptr.
1620 Value *getReturnedArgOperand() const;
1622 /// getCallingConv/setCallingConv - Get or set the calling convention of this
1624 CallingConv::ID getCallingConv() const {
1625 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1627 void setCallingConv(CallingConv::ID CC) {
1628 auto ID = static_cast<unsigned>(CC);
1629 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1630 setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1634 /// Return the parameter attributes for this call.
1636 AttributeList getAttributes() const { return Attrs; }
1638 /// Set the parameter attributes for this call.
1640 void setAttributes(AttributeList A) { Attrs = A; }
1642 /// adds the attribute to the list of attributes.
1643 void addAttribute(unsigned i, Attribute::AttrKind Kind);
1645 /// adds the attribute to the list of attributes.
1646 void addAttribute(unsigned i, Attribute Attr);
1648 /// Adds the attribute to the indicated argument
1649 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1651 /// Adds the attribute to the indicated argument
1652 void addParamAttr(unsigned ArgNo, Attribute Attr);
1654 /// removes the attribute from the list of attributes.
1655 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
1657 /// removes the attribute from the list of attributes.
1658 void removeAttribute(unsigned i, StringRef Kind);
1660 /// Removes the attribute from the given argument
1661 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1663 /// Removes the attribute from the given argument
1664 void removeParamAttr(unsigned ArgNo, StringRef Kind);
1666 /// adds the dereferenceable attribute to the list of attributes.
1667 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1669 /// adds the dereferenceable_or_null attribute to the list of
1671 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1673 /// Determine whether this call has the given attribute.
1674 bool hasFnAttr(Attribute::AttrKind Kind) const {
1675 assert(Kind != Attribute::NoBuiltin &&
1676 "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1677 return hasFnAttrImpl(Kind);
1680 /// Determine whether this call has the given attribute.
1681 bool hasFnAttr(StringRef Kind) const {
1682 return hasFnAttrImpl(Kind);
1685 /// Determine whether the return value has the given attribute.
1686 bool hasRetAttr(Attribute::AttrKind Kind) const;
1688 /// Determine whether the argument or parameter has the given attribute.
1689 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1691 /// Get the attribute of a given kind at a position.
1692 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1693 return getAttributes().getAttribute(i, Kind);
1696 /// Get the attribute of a given kind at a position.
1697 Attribute getAttribute(unsigned i, StringRef Kind) const {
1698 return getAttributes().getAttribute(i, Kind);
1701 /// Get the attribute of a given kind from a given arg
1702 Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1703 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1704 return getAttributes().getParamAttr(ArgNo, Kind);
1707 /// Get the attribute of a given kind from a given arg
1708 Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1709 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1710 return getAttributes().getParamAttr(ArgNo, Kind);
1713 /// Return true if the data operand at index \p i has the attribute \p
1716 /// Data operands include call arguments and values used in operand bundles,
1717 /// but does not include the callee operand. This routine dispatches to the
1718 /// underlying AttributeList or the OperandBundleUser as appropriate.
1720 /// The index \p i is interpreted as
1722 /// \p i == Attribute::ReturnIndex -> the return value
1723 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
1724 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1725 /// (\p i - 1) in the operand list.
1726 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
1728 /// Extract the alignment of the return value.
1729 unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
1731 /// Extract the alignment for a call or parameter (0=unknown).
1732 unsigned getParamAlignment(unsigned ArgNo) const {
1733 return Attrs.getParamAlignment(ArgNo);
1736 /// Extract the number of dereferenceable bytes for a call or
1737 /// parameter (0=unknown).
1738 uint64_t getDereferenceableBytes(unsigned i) const {
1739 return Attrs.getDereferenceableBytes(i);
1742 /// Extract the number of dereferenceable_or_null bytes for a call or
1743 /// parameter (0=unknown).
1744 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1745 return Attrs.getDereferenceableOrNullBytes(i);
1748 /// @brief Determine if the return value is marked with NoAlias attribute.
1749 bool returnDoesNotAlias() const {
1750 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1753 /// Return true if the call should not be treated as a call to a
1755 bool isNoBuiltin() const {
1756 return hasFnAttrImpl(Attribute::NoBuiltin) &&
1757 !hasFnAttrImpl(Attribute::Builtin);
1760 /// Determine if the call requires strict floating point semantics.
1761 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1763 /// Return true if the call should not be inlined.
1764 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1765 void setIsNoInline() {
1766 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1769 /// Return true if the call can return twice
1770 bool canReturnTwice() const {
1771 return hasFnAttr(Attribute::ReturnsTwice);
1773 void setCanReturnTwice() {
1774 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1777 /// Determine if the call does not access memory.
1778 bool doesNotAccessMemory() const {
1779 return hasFnAttr(Attribute::ReadNone);
1781 void setDoesNotAccessMemory() {
1782 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1785 /// Determine if the call does not access or only reads memory.
1786 bool onlyReadsMemory() const {
1787 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1789 void setOnlyReadsMemory() {
1790 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1793 /// Determine if the call does not access or only writes memory.
1794 bool doesNotReadMemory() const {
1795 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1797 void setDoesNotReadMemory() {
1798 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1801 /// @brief Determine if the call can access memmory only using pointers based
1802 /// on its arguments.
1803 bool onlyAccessesArgMemory() const {
1804 return hasFnAttr(Attribute::ArgMemOnly);
1806 void setOnlyAccessesArgMemory() {
1807 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1810 /// @brief Determine if the function may only access memory that is
1811 /// inaccessible from the IR.
1812 bool onlyAccessesInaccessibleMemory() const {
1813 return hasFnAttr(Attribute::InaccessibleMemOnly);
1815 void setOnlyAccessesInaccessibleMemory() {
1816 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
1819 /// @brief Determine if the function may only access memory that is
1820 /// either inaccessible from the IR or pointed to by its arguments.
1821 bool onlyAccessesInaccessibleMemOrArgMem() const {
1822 return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
1824 void setOnlyAccessesInaccessibleMemOrArgMem() {
1825 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOrArgMemOnly);
1828 /// Determine if the call cannot return.
1829 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1830 void setDoesNotReturn() {
1831 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1834 /// Determine if the call cannot unwind.
1835 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1836 void setDoesNotThrow() {
1837 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1840 /// Determine if the call cannot be duplicated.
1841 bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1842 void setCannotDuplicate() {
1843 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1846 /// Determine if the call is convergent
1847 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1848 void setConvergent() {
1849 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1851 void setNotConvergent() {
1852 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1855 /// Determine if the call returns a structure through first
1856 /// pointer argument.
1857 bool hasStructRetAttr() const {
1858 if (getNumArgOperands() == 0)
1861 // Be friendly and also check the callee.
1862 return paramHasAttr(0, Attribute::StructRet);
1865 /// Determine if any call argument is an aggregate passed by value.
1866 bool hasByValArgument() const {
1867 return Attrs.hasAttrSomewhere(Attribute::ByVal);
1870 /// Return the function called, or null if this is an
1871 /// indirect function invocation.
1873 Function *getCalledFunction() const {
1874 return dyn_cast<Function>(Op<-1>());
1877 /// Get a pointer to the function that is invoked by this
1879 const Value *getCalledValue() const { return Op<-1>(); }
1880 Value *getCalledValue() { return Op<-1>(); }
1882 /// Set the function called.
1883 void setCalledFunction(Value* Fn) {
1885 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1888 void setCalledFunction(FunctionType *FTy, Value *Fn) {
1890 assert(FTy == cast<FunctionType>(
1891 cast<PointerType>(Fn->getType())->getElementType()));
1895 /// Check if this call is an inline asm statement.
1896 bool isInlineAsm() const {
1897 return isa<InlineAsm>(Op<-1>());
1900 // Methods for support type inquiry through isa, cast, and dyn_cast:
1901 static bool classof(const Instruction *I) {
1902 return I->getOpcode() == Instruction::Call;
1904 static bool classof(const Value *V) {
1905 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1909 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
1910 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
1913 // Operand bundles override attributes on the called function, but don't
1914 // override attributes directly present on the call instruction.
1915 if (isFnAttrDisallowedByOpBundle(Kind))
1918 if (const Function *F = getCalledFunction())
1919 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
1924 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1925 // method so that subclasses cannot accidentally use it.
1926 void setInstructionSubclassData(unsigned short D) {
1927 Instruction::setInstructionSubclassData(D);
1932 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1935 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1936 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1937 BasicBlock *InsertAtEnd)
1939 cast<FunctionType>(cast<PointerType>(Func->getType())
1940 ->getElementType())->getReturnType(),
1941 Instruction::Call, OperandTraits<CallInst>::op_end(this) -
1942 (Args.size() + CountBundleInputs(Bundles) + 1),
1943 unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1944 init(Func, Args, Bundles, NameStr);
1947 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1948 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1949 Instruction *InsertBefore)
1950 : Instruction(Ty->getReturnType(), Instruction::Call,
1951 OperandTraits<CallInst>::op_end(this) -
1952 (Args.size() + CountBundleInputs(Bundles) + 1),
1953 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1955 init(Ty, Func, Args, Bundles, NameStr);
1958 // Note: if you get compile errors about private methods then
1959 // please update your code to use the high-level operand
1960 // interfaces. See line 943 above.
1961 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1963 //===----------------------------------------------------------------------===//
1965 //===----------------------------------------------------------------------===//
1967 /// This class represents the LLVM 'select' instruction.
1969 class SelectInst : public Instruction {
1970 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1971 Instruction *InsertBefore)
1972 : Instruction(S1->getType(), Instruction::Select,
1973 &Op<0>(), 3, InsertBefore) {
1978 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1979 BasicBlock *InsertAtEnd)
1980 : Instruction(S1->getType(), Instruction::Select,
1981 &Op<0>(), 3, InsertAtEnd) {
1986 void init(Value *C, Value *S1, Value *S2) {
1987 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1994 // Note: Instruction needs to be a friend here to call cloneImpl.
1995 friend class Instruction;
1997 SelectInst *cloneImpl() const;
2000 static SelectInst *Create(Value *C, Value *S1, Value *S2,
2001 const Twine &NameStr = "",
2002 Instruction *InsertBefore = nullptr,
2003 Instruction *MDFrom = nullptr) {
2004 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
2006 Sel->copyMetadata(*MDFrom);
2010 static SelectInst *Create(Value *C, Value *S1, Value *S2,
2011 const Twine &NameStr,
2012 BasicBlock *InsertAtEnd) {
2013 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
2016 const Value *getCondition() const { return Op<0>(); }
2017 const Value *getTrueValue() const { return Op<1>(); }
2018 const Value *getFalseValue() const { return Op<2>(); }
2019 Value *getCondition() { return Op<0>(); }
2020 Value *getTrueValue() { return Op<1>(); }
2021 Value *getFalseValue() { return Op<2>(); }
2023 void setCondition(Value *V) { Op<0>() = V; }
2024 void setTrueValue(Value *V) { Op<1>() = V; }
2025 void setFalseValue(Value *V) { Op<2>() = V; }
2027 /// Return a string if the specified operands are invalid
2028 /// for a select operation, otherwise return null.
2029 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
2031 /// Transparently provide more efficient getOperand methods.
2032 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2034 OtherOps getOpcode() const {
2035 return static_cast<OtherOps>(Instruction::getOpcode());
2038 // Methods for support type inquiry through isa, cast, and dyn_cast:
2039 static bool classof(const Instruction *I) {
2040 return I->getOpcode() == Instruction::Select;
2042 static bool classof(const Value *V) {
2043 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2048 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
2051 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
2053 //===----------------------------------------------------------------------===//
2055 //===----------------------------------------------------------------------===//
2057 /// This class represents the va_arg llvm instruction, which returns
2058 /// an argument of the specified type given a va_list and increments that list
2060 class VAArgInst : public UnaryInstruction {
2062 // Note: Instruction needs to be a friend here to call cloneImpl.
2063 friend class Instruction;
2065 VAArgInst *cloneImpl() const;
2068 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
2069 Instruction *InsertBefore = nullptr)
2070 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
2074 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
2075 BasicBlock *InsertAtEnd)
2076 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
2080 Value *getPointerOperand() { return getOperand(0); }
2081 const Value *getPointerOperand() const { return getOperand(0); }
2082 static unsigned getPointerOperandIndex() { return 0U; }
2084 // Methods for support type inquiry through isa, cast, and dyn_cast:
2085 static bool classof(const Instruction *I) {
2086 return I->getOpcode() == VAArg;
2088 static bool classof(const Value *V) {
2089 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2093 //===----------------------------------------------------------------------===//
2094 // ExtractElementInst Class
2095 //===----------------------------------------------------------------------===//
2097 /// This instruction extracts a single (scalar)
2098 /// element from a VectorType value
2100 class ExtractElementInst : public Instruction {
2101 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
2102 Instruction *InsertBefore = nullptr);
2103 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
2104 BasicBlock *InsertAtEnd);
2107 // Note: Instruction needs to be a friend here to call cloneImpl.
2108 friend class Instruction;
2110 ExtractElementInst *cloneImpl() const;
2113 static ExtractElementInst *Create(Value *Vec, Value *Idx,
2114 const Twine &NameStr = "",
2115 Instruction *InsertBefore = nullptr) {
2116 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
2119 static ExtractElementInst *Create(Value *Vec, Value *Idx,
2120 const Twine &NameStr,
2121 BasicBlock *InsertAtEnd) {
2122 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
2125 /// Return true if an extractelement instruction can be
2126 /// formed with the specified operands.
2127 static bool isValidOperands(const Value *Vec, const Value *Idx);
2129 Value *getVectorOperand() { return Op<0>(); }
2130 Value *getIndexOperand() { return Op<1>(); }
2131 const Value *getVectorOperand() const { return Op<0>(); }
2132 const Value *getIndexOperand() const { return Op<1>(); }
2134 VectorType *getVectorOperandType() const {
2135 return cast<VectorType>(getVectorOperand()->getType());
2138 /// Transparently provide more efficient getOperand methods.
2139 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2141 // Methods for support type inquiry through isa, cast, and dyn_cast:
2142 static bool classof(const Instruction *I) {
2143 return I->getOpcode() == Instruction::ExtractElement;
2145 static bool classof(const Value *V) {
2146 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2151 struct OperandTraits<ExtractElementInst> :
2152 public FixedNumOperandTraits<ExtractElementInst, 2> {
2155 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
2157 //===----------------------------------------------------------------------===//
2158 // InsertElementInst Class
2159 //===----------------------------------------------------------------------===//
2161 /// This instruction inserts a single (scalar)
2162 /// element into a VectorType value
2164 class InsertElementInst : public Instruction {
2165 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2166 const Twine &NameStr = "",
2167 Instruction *InsertBefore = nullptr);
2168 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2169 BasicBlock *InsertAtEnd);
2172 // Note: Instruction needs to be a friend here to call cloneImpl.
2173 friend class Instruction;
2175 InsertElementInst *cloneImpl() const;
2178 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2179 const Twine &NameStr = "",
2180 Instruction *InsertBefore = nullptr) {
2181 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2184 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2185 const Twine &NameStr,
2186 BasicBlock *InsertAtEnd) {
2187 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2190 /// Return true if an insertelement instruction can be
2191 /// formed with the specified operands.
2192 static bool isValidOperands(const Value *Vec, const Value *NewElt,
2195 /// Overload to return most specific vector type.
2197 VectorType *getType() const {
2198 return cast<VectorType>(Instruction::getType());
2201 /// Transparently provide more efficient getOperand methods.
2202 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2204 // Methods for support type inquiry through isa, cast, and dyn_cast:
2205 static bool classof(const Instruction *I) {
2206 return I->getOpcode() == Instruction::InsertElement;
2208 static bool classof(const Value *V) {
2209 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2214 struct OperandTraits<InsertElementInst> :
2215 public FixedNumOperandTraits<InsertElementInst, 3> {
2218 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2220 //===----------------------------------------------------------------------===//
2221 // ShuffleVectorInst Class
2222 //===----------------------------------------------------------------------===//
2224 /// This instruction constructs a fixed permutation of two
2227 class ShuffleVectorInst : public Instruction {
2229 // Note: Instruction needs to be a friend here to call cloneImpl.
2230 friend class Instruction;
2232 ShuffleVectorInst *cloneImpl() const;
2235 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2236 const Twine &NameStr = "",
2237 Instruction *InsertBefor = nullptr);
2238 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2239 const Twine &NameStr, BasicBlock *InsertAtEnd);
2241 // allocate space for exactly three operands
2242 void *operator new(size_t s) {
2243 return User::operator new(s, 3);
2246 /// Return true if a shufflevector instruction can be
2247 /// formed with the specified operands.
2248 static bool isValidOperands(const Value *V1, const Value *V2,
2251 /// Overload to return most specific vector type.
2253 VectorType *getType() const {
2254 return cast<VectorType>(Instruction::getType());
2257 /// Transparently provide more efficient getOperand methods.
2258 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2260 Constant *getMask() const {
2261 return cast<Constant>(getOperand(2));
2264 /// Return the shuffle mask value for the specified element of the mask.
2265 /// Return -1 if the element is undef.
2266 static int getMaskValue(Constant *Mask, unsigned Elt);
2268 /// Return the shuffle mask value of this instruction for the given element
2269 /// index. Return -1 if the element is undef.
2270 int getMaskValue(unsigned Elt) const {
2271 return getMaskValue(getMask(), Elt);
2274 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2275 /// elements of the mask are returned as -1.
2276 static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2278 /// Return the mask for this instruction as a vector of integers. Undefined
2279 /// elements of the mask are returned as -1.
2280 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2281 return getShuffleMask(getMask(), Result);
2284 SmallVector<int, 16> getShuffleMask() const {
2285 SmallVector<int, 16> Mask;
2286 getShuffleMask(Mask);
2290 /// Change values in a shuffle permute mask assuming the two vector operands
2291 /// of length InVecNumElts have swapped position.
2292 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2293 unsigned InVecNumElts) {
2294 for (int &Idx : Mask) {
2297 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2298 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2299 "shufflevector mask index out of range");
2303 // Methods for support type inquiry through isa, cast, and dyn_cast:
2304 static bool classof(const Instruction *I) {
2305 return I->getOpcode() == Instruction::ShuffleVector;
2307 static bool classof(const Value *V) {
2308 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2313 struct OperandTraits<ShuffleVectorInst> :
2314 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2317 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2319 //===----------------------------------------------------------------------===//
2320 // ExtractValueInst Class
2321 //===----------------------------------------------------------------------===//
2323 /// This instruction extracts a struct member or array
2324 /// element value from an aggregate value.
2326 class ExtractValueInst : public UnaryInstruction {
2327 SmallVector<unsigned, 4> Indices;
2329 ExtractValueInst(const ExtractValueInst &EVI);
2331 /// Constructors - Create a extractvalue instruction with a base aggregate
2332 /// value and a list of indices. The first ctor can optionally insert before
2333 /// an existing instruction, the second appends the new instruction to the
2334 /// specified BasicBlock.
2335 inline ExtractValueInst(Value *Agg,
2336 ArrayRef<unsigned> Idxs,
2337 const Twine &NameStr,
2338 Instruction *InsertBefore);
2339 inline ExtractValueInst(Value *Agg,
2340 ArrayRef<unsigned> Idxs,
2341 const Twine &NameStr, BasicBlock *InsertAtEnd);
2343 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2346 // Note: Instruction needs to be a friend here to call cloneImpl.
2347 friend class Instruction;
2349 ExtractValueInst *cloneImpl() const;
2352 static ExtractValueInst *Create(Value *Agg,
2353 ArrayRef<unsigned> Idxs,
2354 const Twine &NameStr = "",
2355 Instruction *InsertBefore = nullptr) {
2357 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2360 static ExtractValueInst *Create(Value *Agg,
2361 ArrayRef<unsigned> Idxs,
2362 const Twine &NameStr,
2363 BasicBlock *InsertAtEnd) {
2364 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2367 /// Returns the type of the element that would be extracted
2368 /// with an extractvalue instruction with the specified parameters.
2370 /// Null is returned if the indices are invalid for the specified type.
2371 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2373 using idx_iterator = const unsigned*;
2375 inline idx_iterator idx_begin() const { return Indices.begin(); }
2376 inline idx_iterator idx_end() const { return Indices.end(); }
2377 inline iterator_range<idx_iterator> indices() const {
2378 return make_range(idx_begin(), idx_end());
2381 Value *getAggregateOperand() {
2382 return getOperand(0);
2384 const Value *getAggregateOperand() const {
2385 return getOperand(0);
2387 static unsigned getAggregateOperandIndex() {
2388 return 0U; // get index for modifying correct operand
2391 ArrayRef<unsigned> getIndices() const {
2395 unsigned getNumIndices() const {
2396 return (unsigned)Indices.size();
2399 bool hasIndices() const {
2403 // Methods for support type inquiry through isa, cast, and dyn_cast:
2404 static bool classof(const Instruction *I) {
2405 return I->getOpcode() == Instruction::ExtractValue;
2407 static bool classof(const Value *V) {
2408 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2412 ExtractValueInst::ExtractValueInst(Value *Agg,
2413 ArrayRef<unsigned> Idxs,
2414 const Twine &NameStr,
2415 Instruction *InsertBefore)
2416 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2417 ExtractValue, Agg, InsertBefore) {
2418 init(Idxs, NameStr);
2421 ExtractValueInst::ExtractValueInst(Value *Agg,
2422 ArrayRef<unsigned> Idxs,
2423 const Twine &NameStr,
2424 BasicBlock *InsertAtEnd)
2425 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2426 ExtractValue, Agg, InsertAtEnd) {
2427 init(Idxs, NameStr);
2430 //===----------------------------------------------------------------------===//
2431 // InsertValueInst Class
2432 //===----------------------------------------------------------------------===//
2434 /// This instruction inserts a struct field of array element
2435 /// value into an aggregate value.
2437 class InsertValueInst : public Instruction {
2438 SmallVector<unsigned, 4> Indices;
2440 InsertValueInst(const InsertValueInst &IVI);
2442 /// Constructors - Create a insertvalue instruction with a base aggregate
2443 /// value, a value to insert, and a list of indices. The first ctor can
2444 /// optionally insert before an existing instruction, the second appends
2445 /// the new instruction to the specified BasicBlock.
2446 inline InsertValueInst(Value *Agg, Value *Val,
2447 ArrayRef<unsigned> Idxs,
2448 const Twine &NameStr,
2449 Instruction *InsertBefore);
2450 inline InsertValueInst(Value *Agg, Value *Val,
2451 ArrayRef<unsigned> Idxs,
2452 const Twine &NameStr, BasicBlock *InsertAtEnd);
2454 /// Constructors - These two constructors are convenience methods because one
2455 /// and two index insertvalue instructions are so common.
2456 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2457 const Twine &NameStr = "",
2458 Instruction *InsertBefore = nullptr);
2459 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2460 BasicBlock *InsertAtEnd);
2462 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2463 const Twine &NameStr);
2466 // Note: Instruction needs to be a friend here to call cloneImpl.
2467 friend class Instruction;
2469 InsertValueInst *cloneImpl() const;
2472 // allocate space for exactly two operands
2473 void *operator new(size_t s) {
2474 return User::operator new(s, 2);
2477 static InsertValueInst *Create(Value *Agg, Value *Val,
2478 ArrayRef<unsigned> Idxs,
2479 const Twine &NameStr = "",
2480 Instruction *InsertBefore = nullptr) {
2481 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2484 static InsertValueInst *Create(Value *Agg, Value *Val,
2485 ArrayRef<unsigned> Idxs,
2486 const Twine &NameStr,
2487 BasicBlock *InsertAtEnd) {
2488 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2491 /// Transparently provide more efficient getOperand methods.
2492 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2494 using idx_iterator = const unsigned*;
2496 inline idx_iterator idx_begin() const { return Indices.begin(); }
2497 inline idx_iterator idx_end() const { return Indices.end(); }
2498 inline iterator_range<idx_iterator> indices() const {
2499 return make_range(idx_begin(), idx_end());
2502 Value *getAggregateOperand() {
2503 return getOperand(0);
2505 const Value *getAggregateOperand() const {
2506 return getOperand(0);
2508 static unsigned getAggregateOperandIndex() {
2509 return 0U; // get index for modifying correct operand
2512 Value *getInsertedValueOperand() {
2513 return getOperand(1);
2515 const Value *getInsertedValueOperand() const {
2516 return getOperand(1);
2518 static unsigned getInsertedValueOperandIndex() {
2519 return 1U; // get index for modifying correct operand
2522 ArrayRef<unsigned> getIndices() const {
2526 unsigned getNumIndices() const {
2527 return (unsigned)Indices.size();
2530 bool hasIndices() const {
2534 // Methods for support type inquiry through isa, cast, and dyn_cast:
2535 static bool classof(const Instruction *I) {
2536 return I->getOpcode() == Instruction::InsertValue;
2538 static bool classof(const Value *V) {
2539 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2544 struct OperandTraits<InsertValueInst> :
2545 public FixedNumOperandTraits<InsertValueInst, 2> {
2548 InsertValueInst::InsertValueInst(Value *Agg,
2550 ArrayRef<unsigned> Idxs,
2551 const Twine &NameStr,
2552 Instruction *InsertBefore)
2553 : Instruction(Agg->getType(), InsertValue,
2554 OperandTraits<InsertValueInst>::op_begin(this),
2556 init(Agg, Val, Idxs, NameStr);
2559 InsertValueInst::InsertValueInst(Value *Agg,
2561 ArrayRef<unsigned> Idxs,
2562 const Twine &NameStr,
2563 BasicBlock *InsertAtEnd)
2564 : Instruction(Agg->getType(), InsertValue,
2565 OperandTraits<InsertValueInst>::op_begin(this),
2567 init(Agg, Val, Idxs, NameStr);
2570 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2572 //===----------------------------------------------------------------------===//
2574 //===----------------------------------------------------------------------===//
2576 // PHINode - The PHINode class is used to represent the magical mystical PHI
2577 // node, that can not exist in nature, but can be synthesized in a computer
2578 // scientist's overactive imagination.
2580 class PHINode : public Instruction {
2581 /// The number of operands actually allocated. NumOperands is
2582 /// the number actually in use.
2583 unsigned ReservedSpace;
2585 PHINode(const PHINode &PN);
2587 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2588 const Twine &NameStr = "",
2589 Instruction *InsertBefore = nullptr)
2590 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2591 ReservedSpace(NumReservedValues) {
2593 allocHungoffUses(ReservedSpace);
2596 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2597 BasicBlock *InsertAtEnd)
2598 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2599 ReservedSpace(NumReservedValues) {
2601 allocHungoffUses(ReservedSpace);
2605 // Note: Instruction needs to be a friend here to call cloneImpl.
2606 friend class Instruction;
2608 PHINode *cloneImpl() const;
2610 // allocHungoffUses - this is more complicated than the generic
2611 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2612 // values and pointers to the incoming blocks, all in one allocation.
2613 void allocHungoffUses(unsigned N) {
2614 User::allocHungoffUses(N, /* IsPhi */ true);
2618 /// Constructors - NumReservedValues is a hint for the number of incoming
2619 /// edges that this phi node will have (use 0 if you really have no idea).
2620 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2621 const Twine &NameStr = "",
2622 Instruction *InsertBefore = nullptr) {
2623 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2626 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2627 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2628 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2631 /// Provide fast operand accessors
2632 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2634 // Block iterator interface. This provides access to the list of incoming
2635 // basic blocks, which parallels the list of incoming values.
2637 using block_iterator = BasicBlock **;
2638 using const_block_iterator = BasicBlock * const *;
2640 block_iterator block_begin() {
2642 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2643 return reinterpret_cast<block_iterator>(ref + 1);
2646 const_block_iterator block_begin() const {
2647 const Use::UserRef *ref =
2648 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2649 return reinterpret_cast<const_block_iterator>(ref + 1);
2652 block_iterator block_end() {
2653 return block_begin() + getNumOperands();
2656 const_block_iterator block_end() const {
2657 return block_begin() + getNumOperands();
2660 iterator_range<block_iterator> blocks() {
2661 return make_range(block_begin(), block_end());
2664 iterator_range<const_block_iterator> blocks() const {
2665 return make_range(block_begin(), block_end());
2668 op_range incoming_values() { return operands(); }
2670 const_op_range incoming_values() const { return operands(); }
2672 /// Return the number of incoming edges
2674 unsigned getNumIncomingValues() const { return getNumOperands(); }
2676 /// Return incoming value number x
2678 Value *getIncomingValue(unsigned i) const {
2679 return getOperand(i);
2681 void setIncomingValue(unsigned i, Value *V) {
2682 assert(V && "PHI node got a null value!");
2683 assert(getType() == V->getType() &&
2684 "All operands to PHI node must be the same type as the PHI node!");
2688 static unsigned getOperandNumForIncomingValue(unsigned i) {
2692 static unsigned getIncomingValueNumForOperand(unsigned i) {
2696 /// Return incoming basic block number @p i.
2698 BasicBlock *getIncomingBlock(unsigned i) const {
2699 return block_begin()[i];
2702 /// Return incoming basic block corresponding
2703 /// to an operand of the PHI.
2705 BasicBlock *getIncomingBlock(const Use &U) const {
2706 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2707 return getIncomingBlock(unsigned(&U - op_begin()));
2710 /// Return incoming basic block corresponding
2711 /// to value use iterator.
2713 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2714 return getIncomingBlock(I.getUse());
2717 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2718 assert(BB && "PHI node got a null basic block!");
2719 block_begin()[i] = BB;
2722 /// Add an incoming value to the end of the PHI list
2724 void addIncoming(Value *V, BasicBlock *BB) {
2725 if (getNumOperands() == ReservedSpace)
2726 growOperands(); // Get more space!
2727 // Initialize some new operands.
2728 setNumHungOffUseOperands(getNumOperands() + 1);
2729 setIncomingValue(getNumOperands() - 1, V);
2730 setIncomingBlock(getNumOperands() - 1, BB);
2733 /// Remove an incoming value. This is useful if a
2734 /// predecessor basic block is deleted. The value removed is returned.
2736 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2737 /// is true), the PHI node is destroyed and any uses of it are replaced with
2738 /// dummy values. The only time there should be zero incoming values to a PHI
2739 /// node is when the block is dead, so this strategy is sound.
2741 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2743 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2744 int Idx = getBasicBlockIndex(BB);
2745 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2746 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2749 /// Return the first index of the specified basic
2750 /// block in the value list for this PHI. Returns -1 if no instance.
2752 int getBasicBlockIndex(const BasicBlock *BB) const {
2753 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2754 if (block_begin()[i] == BB)
2759 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2760 int Idx = getBasicBlockIndex(BB);
2761 assert(Idx >= 0 && "Invalid basic block argument!");
2762 return getIncomingValue(Idx);
2765 /// If the specified PHI node always merges together the
2766 /// same value, return the value, otherwise return null.
2767 Value *hasConstantValue() const;
2769 /// Whether the specified PHI node always merges
2770 /// together the same value, assuming undefs are equal to a unique
2771 /// non-undef value.
2772 bool hasConstantOrUndefValue() const;
2774 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2775 static bool classof(const Instruction *I) {
2776 return I->getOpcode() == Instruction::PHI;
2778 static bool classof(const Value *V) {
2779 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2783 void growOperands();
2787 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2790 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2792 //===----------------------------------------------------------------------===//
2793 // LandingPadInst Class
2794 //===----------------------------------------------------------------------===//
2796 //===---------------------------------------------------------------------------
2797 /// The landingpad instruction holds all of the information
2798 /// necessary to generate correct exception handling. The landingpad instruction
2799 /// cannot be moved from the top of a landing pad block, which itself is
2800 /// accessible only from the 'unwind' edge of an invoke. This uses the
2801 /// SubclassData field in Value to store whether or not the landingpad is a
2804 class LandingPadInst : public Instruction {
2805 /// The number of operands actually allocated. NumOperands is
2806 /// the number actually in use.
2807 unsigned ReservedSpace;
2809 LandingPadInst(const LandingPadInst &LP);
2812 enum ClauseType { Catch, Filter };
2815 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2816 const Twine &NameStr, Instruction *InsertBefore);
2817 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2818 const Twine &NameStr, BasicBlock *InsertAtEnd);
2820 // Allocate space for exactly zero operands.
2821 void *operator new(size_t s) {
2822 return User::operator new(s);
2825 void growOperands(unsigned Size);
2826 void init(unsigned NumReservedValues, const Twine &NameStr);
2829 // Note: Instruction needs to be a friend here to call cloneImpl.
2830 friend class Instruction;
2832 LandingPadInst *cloneImpl() const;
2835 /// Constructors - NumReservedClauses is a hint for the number of incoming
2836 /// clauses that this landingpad will have (use 0 if you really have no idea).
2837 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2838 const Twine &NameStr = "",
2839 Instruction *InsertBefore = nullptr);
2840 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2841 const Twine &NameStr, BasicBlock *InsertAtEnd);
2843 /// Provide fast operand accessors
2844 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2846 /// Return 'true' if this landingpad instruction is a
2847 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2848 /// doesn't catch the exception.
2849 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2851 /// Indicate that this landingpad instruction is a cleanup.
2852 void setCleanup(bool V) {
2853 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2857 /// Add a catch or filter clause to the landing pad.
2858 void addClause(Constant *ClauseVal);
2860 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2861 /// determine what type of clause this is.
2862 Constant *getClause(unsigned Idx) const {
2863 return cast<Constant>(getOperandList()[Idx]);
2866 /// Return 'true' if the clause and index Idx is a catch clause.
2867 bool isCatch(unsigned Idx) const {
2868 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2871 /// Return 'true' if the clause and index Idx is a filter clause.
2872 bool isFilter(unsigned Idx) const {
2873 return isa<ArrayType>(getOperandList()[Idx]->getType());
2876 /// Get the number of clauses for this landing pad.
2877 unsigned getNumClauses() const { return getNumOperands(); }
2879 /// Grow the size of the operand list to accommodate the new
2880 /// number of clauses.
2881 void reserveClauses(unsigned Size) { growOperands(Size); }
2883 // Methods for support type inquiry through isa, cast, and dyn_cast:
2884 static bool classof(const Instruction *I) {
2885 return I->getOpcode() == Instruction::LandingPad;
2887 static bool classof(const Value *V) {
2888 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2893 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2896 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2898 //===----------------------------------------------------------------------===//
2900 //===----------------------------------------------------------------------===//
2902 //===---------------------------------------------------------------------------
2903 /// Return a value (possibly void), from a function. Execution
2904 /// does not continue in this function any longer.
2906 class ReturnInst : public TerminatorInst {
2907 ReturnInst(const ReturnInst &RI);
2910 // ReturnInst constructors:
2911 // ReturnInst() - 'ret void' instruction
2912 // ReturnInst( null) - 'ret void' instruction
2913 // ReturnInst(Value* X) - 'ret X' instruction
2914 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2915 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2916 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2917 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2919 // NOTE: If the Value* passed is of type void then the constructor behaves as
2920 // if it was passed NULL.
2921 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2922 Instruction *InsertBefore = nullptr);
2923 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2924 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2927 // Note: Instruction needs to be a friend here to call cloneImpl.
2928 friend class Instruction;
2930 ReturnInst *cloneImpl() const;
2933 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2934 Instruction *InsertBefore = nullptr) {
2935 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2938 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2939 BasicBlock *InsertAtEnd) {
2940 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2943 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2944 return new(0) ReturnInst(C, InsertAtEnd);
2947 /// Provide fast operand accessors
2948 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2950 /// Convenience accessor. Returns null if there is no return value.
2951 Value *getReturnValue() const {
2952 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2955 unsigned getNumSuccessors() const { return 0; }
2957 // Methods for support type inquiry through isa, cast, and dyn_cast:
2958 static bool classof(const Instruction *I) {
2959 return (I->getOpcode() == Instruction::Ret);
2961 static bool classof(const Value *V) {
2962 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2966 friend TerminatorInst;
2968 BasicBlock *getSuccessor(unsigned idx) const {
2969 llvm_unreachable("ReturnInst has no successors!");
2972 void setSuccessor(unsigned idx, BasicBlock *B) {
2973 llvm_unreachable("ReturnInst has no successors!");
2978 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2981 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2983 //===----------------------------------------------------------------------===//
2985 //===----------------------------------------------------------------------===//
2987 //===---------------------------------------------------------------------------
2988 /// Conditional or Unconditional Branch instruction.
2990 class BranchInst : public TerminatorInst {
2991 /// Ops list - Branches are strange. The operands are ordered:
2992 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2993 /// they don't have to check for cond/uncond branchness. These are mostly
2994 /// accessed relative from op_end().
2995 BranchInst(const BranchInst &BI);
2996 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2997 // BranchInst(BB *B) - 'br B'
2998 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2999 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
3000 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3001 // BranchInst(BB* B, BB *I) - 'br B' insert at end
3002 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
3003 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3004 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3005 Instruction *InsertBefore = nullptr);
3006 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3007 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3008 BasicBlock *InsertAtEnd);
3013 // Note: Instruction needs to be a friend here to call cloneImpl.
3014 friend class Instruction;
3016 BranchInst *cloneImpl() const;
3019 static BranchInst *Create(BasicBlock *IfTrue,
3020 Instruction *InsertBefore = nullptr) {
3021 return new(1) BranchInst(IfTrue, InsertBefore);
3024 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3025 Value *Cond, Instruction *InsertBefore = nullptr) {
3026 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3029 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3030 return new(1) BranchInst(IfTrue, InsertAtEnd);
3033 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3034 Value *Cond, BasicBlock *InsertAtEnd) {
3035 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3038 /// Transparently provide more efficient getOperand methods.
3039 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3041 bool isUnconditional() const { return getNumOperands() == 1; }
3042 bool isConditional() const { return getNumOperands() == 3; }
3044 Value *getCondition() const {
3045 assert(isConditional() && "Cannot get condition of an uncond branch!");
3049 void setCondition(Value *V) {
3050 assert(isConditional() && "Cannot set condition of unconditional branch!");
3054 unsigned getNumSuccessors() const { return 1+isConditional(); }
3056 BasicBlock *getSuccessor(unsigned i) const {
3057 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3058 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3061 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3062 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3063 *(&Op<-1>() - idx) = NewSucc;
3066 /// Swap the successors of this branch instruction.
3068 /// Swaps the successors of the branch instruction. This also swaps any
3069 /// branch weight metadata associated with the instruction so that it
3070 /// continues to map correctly to each operand.
3071 void swapSuccessors();
3073 // Methods for support type inquiry through isa, cast, and dyn_cast:
3074 static bool classof(const Instruction *I) {
3075 return (I->getOpcode() == Instruction::Br);
3077 static bool classof(const Value *V) {
3078 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3083 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3086 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3088 //===----------------------------------------------------------------------===//
3090 //===----------------------------------------------------------------------===//
3092 //===---------------------------------------------------------------------------
3095 class SwitchInst : public TerminatorInst {
3096 unsigned ReservedSpace;
3098 // Operand[0] = Value to switch on
3099 // Operand[1] = Default basic block destination
3100 // Operand[2n ] = Value to match
3101 // Operand[2n+1] = BasicBlock to go to on match
3102 SwitchInst(const SwitchInst &SI);
3104 /// Create a new switch instruction, specifying a value to switch on and a
3105 /// default destination. The number of additional cases can be specified here
3106 /// to make memory allocation more efficient. This constructor can also
3107 /// auto-insert before another instruction.
3108 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3109 Instruction *InsertBefore);
3111 /// Create a new switch instruction, specifying a value to switch on and a
3112 /// default destination. The number of additional cases can be specified here
3113 /// to make memory allocation more efficient. This constructor also
3114 /// auto-inserts at the end of the specified BasicBlock.
3115 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3116 BasicBlock *InsertAtEnd);
3118 // allocate space for exactly zero operands
3119 void *operator new(size_t s) {
3120 return User::operator new(s);
3123 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3124 void growOperands();
3127 // Note: Instruction needs to be a friend here to call cloneImpl.
3128 friend class Instruction;
3130 SwitchInst *cloneImpl() const;
3134 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3136 template <typename CaseHandleT> class CaseIteratorImpl;
3138 /// A handle to a particular switch case. It exposes a convenient interface
3139 /// to both the case value and the successor block.
3141 /// We define this as a template and instantiate it to form both a const and
3142 /// non-const handle.
3143 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3144 class CaseHandleImpl {
3145 // Directly befriend both const and non-const iterators.
3146 friend class SwitchInst::CaseIteratorImpl<
3147 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3150 // Expose the switch type we're parameterized with to the iterator.
3151 using SwitchInstType = SwitchInstT;
3156 CaseHandleImpl() = default;
3157 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3160 /// Resolves case value for current case.
3161 ConstantIntT *getCaseValue() const {
3162 assert((unsigned)Index < SI->getNumCases() &&
3163 "Index out the number of cases.");
3164 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3167 /// Resolves successor for current case.
3168 BasicBlockT *getCaseSuccessor() const {
3169 assert(((unsigned)Index < SI->getNumCases() ||
3170 (unsigned)Index == DefaultPseudoIndex) &&
3171 "Index out the number of cases.");
3172 return SI->getSuccessor(getSuccessorIndex());
3175 /// Returns number of current case.
3176 unsigned getCaseIndex() const { return Index; }
3178 /// Returns TerminatorInst's successor index for current case successor.
3179 unsigned getSuccessorIndex() const {
3180 assert(((unsigned)Index == DefaultPseudoIndex ||
3181 (unsigned)Index < SI->getNumCases()) &&
3182 "Index out the number of cases.");
3183 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3186 bool operator==(const CaseHandleImpl &RHS) const {
3187 assert(SI == RHS.SI && "Incompatible operators.");
3188 return Index == RHS.Index;
3192 using ConstCaseHandle =
3193 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3196 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3197 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3200 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3202 /// Sets the new value for current case.
3203 void setValue(ConstantInt *V) {
3204 assert((unsigned)Index < SI->getNumCases() &&
3205 "Index out the number of cases.");
3206 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3209 /// Sets the new successor for current case.
3210 void setSuccessor(BasicBlock *S) {
3211 SI->setSuccessor(getSuccessorIndex(), S);
3215 template <typename CaseHandleT>
3216 class CaseIteratorImpl
3217 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3218 std::random_access_iterator_tag,
3220 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3225 /// Default constructed iterator is in an invalid state until assigned to
3226 /// a case for a particular switch.
3227 CaseIteratorImpl() = default;
3229 /// Initializes case iterator for given SwitchInst and for given
3231 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3233 /// Initializes case iterator for given SwitchInst and for given
3234 /// TerminatorInst's successor index.
3235 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3236 unsigned SuccessorIndex) {
3237 assert(SuccessorIndex < SI->getNumSuccessors() &&
3238 "Successor index # out of range!");
3239 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3240 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3243 /// Support converting to the const variant. This will be a no-op for const
3245 operator CaseIteratorImpl<ConstCaseHandle>() const {
3246 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3249 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3250 // Check index correctness after addition.
3251 // Note: Index == getNumCases() means end().
3252 assert(Case.Index + N >= 0 &&
3253 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3254 "Case.Index out the number of cases.");
3258 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3259 // Check index correctness after subtraction.
3260 // Note: Case.Index == getNumCases() means end().
3261 assert(Case.Index - N >= 0 &&
3262 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3263 "Case.Index out the number of cases.");
3267 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3268 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3269 return Case.Index - RHS.Case.Index;
3271 bool operator==(const CaseIteratorImpl &RHS) const {
3272 return Case == RHS.Case;
3274 bool operator<(const CaseIteratorImpl &RHS) const {
3275 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3276 return Case.Index < RHS.Case.Index;
3278 CaseHandleT &operator*() { return Case; }
3279 const CaseHandleT &operator*() const { return Case; }
3282 using CaseIt = CaseIteratorImpl<CaseHandle>;
3283 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3285 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3287 Instruction *InsertBefore = nullptr) {
3288 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3291 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3292 unsigned NumCases, BasicBlock *InsertAtEnd) {
3293 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3296 /// Provide fast operand accessors
3297 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3299 // Accessor Methods for Switch stmt
3300 Value *getCondition() const { return getOperand(0); }
3301 void setCondition(Value *V) { setOperand(0, V); }
3303 BasicBlock *getDefaultDest() const {
3304 return cast<BasicBlock>(getOperand(1));
3307 void setDefaultDest(BasicBlock *DefaultCase) {
3308 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3311 /// Return the number of 'cases' in this switch instruction, excluding the
3313 unsigned getNumCases() const {
3314 return getNumOperands()/2 - 1;
3317 /// Returns a read/write iterator that points to the first case in the
3319 CaseIt case_begin() {
3320 return CaseIt(this, 0);
3323 /// Returns a read-only iterator that points to the first case in the
3325 ConstCaseIt case_begin() const {
3326 return ConstCaseIt(this, 0);
3329 /// Returns a read/write iterator that points one past the last in the
3332 return CaseIt(this, getNumCases());
3335 /// Returns a read-only iterator that points one past the last in the
3337 ConstCaseIt case_end() const {
3338 return ConstCaseIt(this, getNumCases());
3341 /// Iteration adapter for range-for loops.
3342 iterator_range<CaseIt> cases() {
3343 return make_range(case_begin(), case_end());
3346 /// Constant iteration adapter for range-for loops.
3347 iterator_range<ConstCaseIt> cases() const {
3348 return make_range(case_begin(), case_end());
3351 /// Returns an iterator that points to the default case.
3352 /// Note: this iterator allows to resolve successor only. Attempt
3353 /// to resolve case value causes an assertion.
3354 /// Also note, that increment and decrement also causes an assertion and
3355 /// makes iterator invalid.
3356 CaseIt case_default() {
3357 return CaseIt(this, DefaultPseudoIndex);
3359 ConstCaseIt case_default() const {
3360 return ConstCaseIt(this, DefaultPseudoIndex);
3363 /// Search all of the case values for the specified constant. If it is
3364 /// explicitly handled, return the case iterator of it, otherwise return
3365 /// default case iterator to indicate that it is handled by the default
3367 CaseIt findCaseValue(const ConstantInt *C) {
3368 CaseIt I = llvm::find_if(
3369 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3370 if (I != case_end())
3373 return case_default();
3375 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3376 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3377 return Case.getCaseValue() == C;
3379 if (I != case_end())
3382 return case_default();
3385 /// Finds the unique case value for a given successor. Returns null if the
3386 /// successor is not found, not unique, or is the default case.
3387 ConstantInt *findCaseDest(BasicBlock *BB) {
3388 if (BB == getDefaultDest())
3391 ConstantInt *CI = nullptr;
3392 for (auto Case : cases()) {
3393 if (Case.getCaseSuccessor() != BB)
3397 return nullptr; // Multiple cases lead to BB.
3399 CI = Case.getCaseValue();
3405 /// Add an entry to the switch instruction.
3407 /// This action invalidates case_end(). Old case_end() iterator will
3408 /// point to the added case.
3409 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3411 /// This method removes the specified case and its successor from the switch
3412 /// instruction. Note that this operation may reorder the remaining cases at
3413 /// index idx and above.
3415 /// This action invalidates iterators for all cases following the one removed,
3416 /// including the case_end() iterator. It returns an iterator for the next
3418 CaseIt removeCase(CaseIt I);
3420 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3421 BasicBlock *getSuccessor(unsigned idx) const {
3422 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3423 return cast<BasicBlock>(getOperand(idx*2+1));
3425 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3426 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3427 setOperand(idx * 2 + 1, NewSucc);
3430 // Methods for support type inquiry through isa, cast, and dyn_cast:
3431 static bool classof(const Instruction *I) {
3432 return I->getOpcode() == Instruction::Switch;
3434 static bool classof(const Value *V) {
3435 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3440 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3443 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3445 //===----------------------------------------------------------------------===//
3446 // IndirectBrInst Class
3447 //===----------------------------------------------------------------------===//
3449 //===---------------------------------------------------------------------------
3450 /// Indirect Branch Instruction.
3452 class IndirectBrInst : public TerminatorInst {
3453 unsigned ReservedSpace;
3455 // Operand[0] = Address to jump to
3456 // Operand[n+1] = n-th destination
3457 IndirectBrInst(const IndirectBrInst &IBI);
3459 /// Create a new indirectbr instruction, specifying an
3460 /// Address to jump to. The number of expected destinations can be specified
3461 /// here to make memory allocation more efficient. This constructor can also
3462 /// autoinsert before another instruction.
3463 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3465 /// Create a new indirectbr instruction, specifying an
3466 /// Address to jump to. The number of expected destinations can be specified
3467 /// here to make memory allocation more efficient. This constructor also
3468 /// autoinserts at the end of the specified BasicBlock.
3469 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3471 // allocate space for exactly zero operands
3472 void *operator new(size_t s) {
3473 return User::operator new(s);
3476 void init(Value *Address, unsigned NumDests);
3477 void growOperands();
3480 // Note: Instruction needs to be a friend here to call cloneImpl.
3481 friend class Instruction;
3483 IndirectBrInst *cloneImpl() const;
3486 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3487 Instruction *InsertBefore = nullptr) {
3488 return new IndirectBrInst(Address, NumDests, InsertBefore);
3491 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3492 BasicBlock *InsertAtEnd) {
3493 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3496 /// Provide fast operand accessors.
3497 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3499 // Accessor Methods for IndirectBrInst instruction.
3500 Value *getAddress() { return getOperand(0); }
3501 const Value *getAddress() const { return getOperand(0); }
3502 void setAddress(Value *V) { setOperand(0, V); }
3504 /// return the number of possible destinations in this
3505 /// indirectbr instruction.
3506 unsigned getNumDestinations() const { return getNumOperands()-1; }
3508 /// Return the specified destination.
3509 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3510 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3512 /// Add a destination.
3514 void addDestination(BasicBlock *Dest);
3516 /// This method removes the specified successor from the
3517 /// indirectbr instruction.
3518 void removeDestination(unsigned i);
3520 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3521 BasicBlock *getSuccessor(unsigned i) const {
3522 return cast<BasicBlock>(getOperand(i+1));
3524 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3525 setOperand(i + 1, NewSucc);
3528 // Methods for support type inquiry through isa, cast, and dyn_cast:
3529 static bool classof(const Instruction *I) {
3530 return I->getOpcode() == Instruction::IndirectBr;
3532 static bool classof(const Value *V) {
3533 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3538 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3541 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3543 //===----------------------------------------------------------------------===//
3545 //===----------------------------------------------------------------------===//
3547 /// Invoke instruction. The SubclassData field is used to hold the
3548 /// calling convention of the call.
3550 class InvokeInst : public TerminatorInst,
3551 public OperandBundleUser<InvokeInst, User::op_iterator> {
3552 friend class OperandBundleUser<InvokeInst, User::op_iterator>;
3554 AttributeList Attrs;
3557 InvokeInst(const InvokeInst &BI);
3559 /// Construct an InvokeInst given a range of arguments.
3561 /// Construct an InvokeInst from a range of arguments
3562 inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3563 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3564 unsigned Values, const Twine &NameStr,
3565 Instruction *InsertBefore)
3566 : InvokeInst(cast<FunctionType>(
3567 cast<PointerType>(Func->getType())->getElementType()),
3568 Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3571 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3572 BasicBlock *IfException, ArrayRef<Value *> Args,
3573 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3574 const Twine &NameStr, Instruction *InsertBefore);
3575 /// Construct an InvokeInst given a range of arguments.
3577 /// Construct an InvokeInst from a range of arguments
3578 inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3579 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3580 unsigned Values, const Twine &NameStr,
3581 BasicBlock *InsertAtEnd);
3583 bool hasDescriptor() const { return HasDescriptor; }
3585 void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3586 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3587 const Twine &NameStr) {
3588 init(cast<FunctionType>(
3589 cast<PointerType>(Func->getType())->getElementType()),
3590 Func, IfNormal, IfException, Args, Bundles, NameStr);
3593 void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3594 BasicBlock *IfException, ArrayRef<Value *> Args,
3595 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3598 // Note: Instruction needs to be a friend here to call cloneImpl.
3599 friend class Instruction;
3601 InvokeInst *cloneImpl() const;
3604 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3605 BasicBlock *IfException, ArrayRef<Value *> Args,
3606 const Twine &NameStr,
3607 Instruction *InsertBefore = nullptr) {
3608 return Create(cast<FunctionType>(
3609 cast<PointerType>(Func->getType())->getElementType()),
3610 Func, IfNormal, IfException, Args, None, NameStr,
3614 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3615 BasicBlock *IfException, ArrayRef<Value *> Args,
3616 ArrayRef<OperandBundleDef> Bundles = None,
3617 const Twine &NameStr = "",
3618 Instruction *InsertBefore = nullptr) {
3619 return Create(cast<FunctionType>(
3620 cast<PointerType>(Func->getType())->getElementType()),
3621 Func, IfNormal, IfException, Args, Bundles, NameStr,
3625 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3626 BasicBlock *IfException, ArrayRef<Value *> Args,
3627 const Twine &NameStr,
3628 Instruction *InsertBefore = nullptr) {
3629 unsigned Values = unsigned(Args.size()) + 3;
3630 return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3631 Values, NameStr, InsertBefore);
3634 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3635 BasicBlock *IfException, ArrayRef<Value *> Args,
3636 ArrayRef<OperandBundleDef> Bundles = None,
3637 const Twine &NameStr = "",
3638 Instruction *InsertBefore = nullptr) {
3639 unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3640 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3642 return new (Values, DescriptorBytes)
3643 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3644 NameStr, InsertBefore);
3647 static InvokeInst *Create(Value *Func,
3648 BasicBlock *IfNormal, BasicBlock *IfException,
3649 ArrayRef<Value *> Args, const Twine &NameStr,
3650 BasicBlock *InsertAtEnd) {
3651 unsigned Values = unsigned(Args.size()) + 3;
3652 return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3653 Values, NameStr, InsertAtEnd);
3656 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3657 BasicBlock *IfException, ArrayRef<Value *> Args,
3658 ArrayRef<OperandBundleDef> Bundles,
3659 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3660 unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3661 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3663 return new (Values, DescriptorBytes)
3664 InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3668 /// Create a clone of \p II with a different set of operand bundles and
3669 /// insert it before \p InsertPt.
3671 /// The returned invoke instruction is identical to \p II in every way except
3672 /// that the operand bundles for the new instruction are set to the operand
3673 /// bundles in \p Bundles.
3674 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3675 Instruction *InsertPt = nullptr);
3677 /// Provide fast operand accessors
3678 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3680 FunctionType *getFunctionType() const { return FTy; }
3682 void mutateFunctionType(FunctionType *FTy) {
3683 mutateType(FTy->getReturnType());
3687 /// Return the number of invoke arguments.
3689 unsigned getNumArgOperands() const {
3690 return getNumOperands() - getNumTotalBundleOperands() - 3;
3693 /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3695 Value *getArgOperand(unsigned i) const {
3696 assert(i < getNumArgOperands() && "Out of bounds!");
3697 return getOperand(i);
3699 void setArgOperand(unsigned i, Value *v) {
3700 assert(i < getNumArgOperands() && "Out of bounds!");
3704 /// Return the iterator pointing to the beginning of the argument list.
3705 op_iterator arg_begin() { return op_begin(); }
3707 /// Return the iterator pointing to the end of the argument list.
3708 op_iterator arg_end() {
3709 // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3710 return op_end() - getNumTotalBundleOperands() - 3;
3713 /// Iteration adapter for range-for loops.
3714 iterator_range<op_iterator> arg_operands() {
3715 return make_range(arg_begin(), arg_end());
3718 /// Return the iterator pointing to the beginning of the argument list.
3719 const_op_iterator arg_begin() const { return op_begin(); }
3721 /// Return the iterator pointing to the end of the argument list.
3722 const_op_iterator arg_end() const {
3723 // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3724 return op_end() - getNumTotalBundleOperands() - 3;
3727 /// Iteration adapter for range-for loops.
3728 iterator_range<const_op_iterator> arg_operands() const {
3729 return make_range(arg_begin(), arg_end());
3732 /// Wrappers for getting the \c Use of a invoke argument.
3733 const Use &getArgOperandUse(unsigned i) const {
3734 assert(i < getNumArgOperands() && "Out of bounds!");
3735 return getOperandUse(i);
3737 Use &getArgOperandUse(unsigned i) {
3738 assert(i < getNumArgOperands() && "Out of bounds!");
3739 return getOperandUse(i);
3742 /// If one of the arguments has the 'returned' attribute, return its
3743 /// operand value. Otherwise, return nullptr.
3744 Value *getReturnedArgOperand() const;
3746 /// getCallingConv/setCallingConv - Get or set the calling convention of this
3748 CallingConv::ID getCallingConv() const {
3749 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3751 void setCallingConv(CallingConv::ID CC) {
3752 auto ID = static_cast<unsigned>(CC);
3753 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
3754 setInstructionSubclassData(ID);
3757 /// Return the parameter attributes for this invoke.
3759 AttributeList getAttributes() const { return Attrs; }
3761 /// Set the parameter attributes for this invoke.
3763 void setAttributes(AttributeList A) { Attrs = A; }
3765 /// adds the attribute to the list of attributes.
3766 void addAttribute(unsigned i, Attribute::AttrKind Kind);
3768 /// adds the attribute to the list of attributes.
3769 void addAttribute(unsigned i, Attribute Attr);
3771 /// Adds the attribute to the indicated argument
3772 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3774 /// removes the attribute from the list of attributes.
3775 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
3777 /// removes the attribute from the list of attributes.
3778 void removeAttribute(unsigned i, StringRef Kind);
3780 /// Removes the attribute from the given argument
3781 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3783 /// adds the dereferenceable attribute to the list of attributes.
3784 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3786 /// adds the dereferenceable_or_null attribute to the list of
3788 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3790 /// Determine whether this call has the given attribute.
3791 bool hasFnAttr(Attribute::AttrKind Kind) const {
3792 assert(Kind != Attribute::NoBuiltin &&
3793 "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3794 return hasFnAttrImpl(Kind);
3797 /// Determine whether this call has the given attribute.
3798 bool hasFnAttr(StringRef Kind) const {
3799 return hasFnAttrImpl(Kind);
3802 /// Determine whether the return value has the given attribute.
3803 bool hasRetAttr(Attribute::AttrKind Kind) const;
3805 /// Determine whether the argument or parameter has the given attribute.
3806 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
3808 /// Get the attribute of a given kind at a position.
3809 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
3810 return getAttributes().getAttribute(i, Kind);
3813 /// Get the attribute of a given kind at a position.
3814 Attribute getAttribute(unsigned i, StringRef Kind) const {
3815 return getAttributes().getAttribute(i, Kind);
3818 /// Return true if the data operand at index \p i has the attribute \p
3821 /// Data operands include invoke arguments and values used in operand bundles,
3822 /// but does not include the invokee operand, or the two successor blocks.
3823 /// This routine dispatches to the underlying AttributeList or the
3824 /// OperandBundleUser as appropriate.
3826 /// The index \p i is interpreted as
3828 /// \p i == Attribute::ReturnIndex -> the return value
3829 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
3830 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
3831 /// (\p i - 1) in the operand list.
3832 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
3834 /// Extract the alignment of the return value.
3835 unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
3837 /// Extract the alignment for a call or parameter (0=unknown).
3838 unsigned getParamAlignment(unsigned ArgNo) const {
3839 return Attrs.getParamAlignment(ArgNo);
3842 /// Extract the number of dereferenceable bytes for a call or
3843 /// parameter (0=unknown).
3844 uint64_t getDereferenceableBytes(unsigned i) const {
3845 return Attrs.getDereferenceableBytes(i);
3848 /// Extract the number of dereferenceable_or_null bytes for a call or
3849 /// parameter (0=unknown).
3850 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
3851 return Attrs.getDereferenceableOrNullBytes(i);
3854 /// @brief Determine if the return value is marked with NoAlias attribute.
3855 bool returnDoesNotAlias() const {
3856 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
3859 /// Return true if the call should not be treated as a call to a
3861 bool isNoBuiltin() const {
3862 // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3863 // to check it by hand.
3864 return hasFnAttrImpl(Attribute::NoBuiltin) &&
3865 !hasFnAttrImpl(Attribute::Builtin);
3868 /// Determine if the call requires strict floating point semantics.
3869 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
3871 /// Return true if the call should not be inlined.
3872 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3873 void setIsNoInline() {
3874 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
3877 /// Determine if the call does not access memory.
3878 bool doesNotAccessMemory() const {
3879 return hasFnAttr(Attribute::ReadNone);
3881 void setDoesNotAccessMemory() {
3882 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
3885 /// Determine if the call does not access or only reads memory.
3886 bool onlyReadsMemory() const {
3887 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3889 void setOnlyReadsMemory() {
3890 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
3893 /// Determine if the call does not access or only writes memory.
3894 bool doesNotReadMemory() const {
3895 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
3897 void setDoesNotReadMemory() {
3898 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
3901 /// @brief Determine if the call access memmory only using it's pointer
3903 bool onlyAccessesArgMemory() const {
3904 return hasFnAttr(Attribute::ArgMemOnly);
3906 void setOnlyAccessesArgMemory() {
3907 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
3910 /// @brief Determine if the function may only access memory that is
3911 /// inaccessible from the IR.
3912 bool onlyAccessesInaccessibleMemory() const {
3913 return hasFnAttr(Attribute::InaccessibleMemOnly);
3915 void setOnlyAccessesInaccessibleMemory() {
3916 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOnly);
3919 /// @brief Determine if the function may only access memory that is
3920 /// either inaccessible from the IR or pointed to by its arguments.
3921 bool onlyAccessesInaccessibleMemOrArgMem() const {
3922 return hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
3924 void setOnlyAccessesInaccessibleMemOrArgMem() {
3925 addAttribute(AttributeList::FunctionIndex, Attribute::InaccessibleMemOrArgMemOnly);
3928 /// Determine if the call cannot return.
3929 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3930 void setDoesNotReturn() {
3931 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
3934 /// Determine if the call cannot unwind.
3935 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3936 void setDoesNotThrow() {
3937 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3940 /// Determine if the invoke cannot be duplicated.
3941 bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3942 void setCannotDuplicate() {
3943 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
3946 /// Determine if the invoke is convergent
3947 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
3948 void setConvergent() {
3949 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3951 void setNotConvergent() {
3952 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3955 /// Determine if the call returns a structure through first
3956 /// pointer argument.
3957 bool hasStructRetAttr() const {
3958 if (getNumArgOperands() == 0)
3961 // Be friendly and also check the callee.
3962 return paramHasAttr(0, Attribute::StructRet);
3965 /// Determine if any call argument is an aggregate passed by value.
3966 bool hasByValArgument() const {
3967 return Attrs.hasAttrSomewhere(Attribute::ByVal);
3970 /// Return the function called, or null if this is an
3971 /// indirect function invocation.
3973 Function *getCalledFunction() const {
3974 return dyn_cast<Function>(Op<-3>());
3977 /// Get a pointer to the function that is invoked by this
3979 const Value *getCalledValue() const { return Op<-3>(); }
3980 Value *getCalledValue() { return Op<-3>(); }
3982 /// Set the function called.
3983 void setCalledFunction(Value* Fn) {
3985 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
3988 void setCalledFunction(FunctionType *FTy, Value *Fn) {
3990 assert(FTy == cast<FunctionType>(
3991 cast<PointerType>(Fn->getType())->getElementType()));
3995 // get*Dest - Return the destination basic blocks...
3996 BasicBlock *getNormalDest() const {
3997 return cast<BasicBlock>(Op<-2>());
3999 BasicBlock *getUnwindDest() const {
4000 return cast<BasicBlock>(Op<-1>());
4002 void setNormalDest(BasicBlock *B) {
4003 Op<-2>() = reinterpret_cast<Value*>(B);
4005 void setUnwindDest(BasicBlock *B) {
4006 Op<-1>() = reinterpret_cast<Value*>(B);
4009 /// Get the landingpad instruction from the landing pad
4010 /// block (the unwind destination).
4011 LandingPadInst *getLandingPadInst() const;
4013 BasicBlock *getSuccessor(unsigned i) const {
4014 assert(i < 2 && "Successor # out of range for invoke!");
4015 return i == 0 ? getNormalDest() : getUnwindDest();
4018 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4019 assert(idx < 2 && "Successor # out of range for invoke!");
4020 *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
4023 unsigned getNumSuccessors() const { return 2; }
4025 // Methods for support type inquiry through isa, cast, and dyn_cast:
4026 static bool classof(const Instruction *I) {
4027 return (I->getOpcode() == Instruction::Invoke);
4029 static bool classof(const Value *V) {
4030 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4034 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
4035 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
4038 // Operand bundles override attributes on the called function, but don't
4039 // override attributes directly present on the invoke instruction.
4040 if (isFnAttrDisallowedByOpBundle(Kind))
4043 if (const Function *F = getCalledFunction())
4044 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
4049 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4050 // method so that subclasses cannot accidentally use it.
4051 void setInstructionSubclassData(unsigned short D) {
4052 Instruction::setInstructionSubclassData(D);
4057 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
4060 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4061 BasicBlock *IfException, ArrayRef<Value *> Args,
4062 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4063 const Twine &NameStr, Instruction *InsertBefore)
4064 : TerminatorInst(Ty->getReturnType(), Instruction::Invoke,
4065 OperandTraits<InvokeInst>::op_end(this) - Values, Values,
4067 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
4070 InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
4071 BasicBlock *IfException, ArrayRef<Value *> Args,
4072 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4073 const Twine &NameStr, BasicBlock *InsertAtEnd)
4075 cast<FunctionType>(cast<PointerType>(Func->getType())
4076 ->getElementType())->getReturnType(),
4077 Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - Values,
4078 Values, InsertAtEnd) {
4079 init(Func, IfNormal, IfException, Args, Bundles, NameStr);
4082 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
4084 //===----------------------------------------------------------------------===//
4086 //===----------------------------------------------------------------------===//
4088 //===---------------------------------------------------------------------------
4089 /// Resume the propagation of an exception.
4091 class ResumeInst : public TerminatorInst {
4092 ResumeInst(const ResumeInst &RI);
4094 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4095 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4098 // Note: Instruction needs to be a friend here to call cloneImpl.
4099 friend class Instruction;
4101 ResumeInst *cloneImpl() const;
4104 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4105 return new(1) ResumeInst(Exn, InsertBefore);
4108 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4109 return new(1) ResumeInst(Exn, InsertAtEnd);
4112 /// Provide fast operand accessors
4113 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4115 /// Convenience accessor.
4116 Value *getValue() const { return Op<0>(); }
4118 unsigned getNumSuccessors() const { return 0; }
4120 // Methods for support type inquiry through isa, cast, and dyn_cast:
4121 static bool classof(const Instruction *I) {
4122 return I->getOpcode() == Instruction::Resume;
4124 static bool classof(const Value *V) {
4125 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4129 friend TerminatorInst;
4131 BasicBlock *getSuccessor(unsigned idx) const {
4132 llvm_unreachable("ResumeInst has no successors!");
4135 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4136 llvm_unreachable("ResumeInst has no successors!");
4141 struct OperandTraits<ResumeInst> :
4142 public FixedNumOperandTraits<ResumeInst, 1> {
4145 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4147 //===----------------------------------------------------------------------===//
4148 // CatchSwitchInst Class
4149 //===----------------------------------------------------------------------===//
4150 class CatchSwitchInst : public TerminatorInst {
4151 /// The number of operands actually allocated. NumOperands is
4152 /// the number actually in use.
4153 unsigned ReservedSpace;
4155 // Operand[0] = Outer scope
4156 // Operand[1] = Unwind block destination
4157 // Operand[n] = BasicBlock to go to on match
4158 CatchSwitchInst(const CatchSwitchInst &CSI);
4160 /// Create a new switch instruction, specifying a
4161 /// default destination. The number of additional handlers can be specified
4162 /// here to make memory allocation more efficient.
4163 /// This constructor can also autoinsert before another instruction.
4164 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4165 unsigned NumHandlers, const Twine &NameStr,
4166 Instruction *InsertBefore);
4168 /// Create a new switch instruction, specifying a
4169 /// default destination. The number of additional handlers can be specified
4170 /// here to make memory allocation more efficient.
4171 /// This constructor also autoinserts at the end of the specified BasicBlock.
4172 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4173 unsigned NumHandlers, const Twine &NameStr,
4174 BasicBlock *InsertAtEnd);
4176 // allocate space for exactly zero operands
4177 void *operator new(size_t s) { return User::operator new(s); }
4179 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4180 void growOperands(unsigned Size);
4183 // Note: Instruction needs to be a friend here to call cloneImpl.
4184 friend class Instruction;
4186 CatchSwitchInst *cloneImpl() const;
4189 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4190 unsigned NumHandlers,
4191 const Twine &NameStr = "",
4192 Instruction *InsertBefore = nullptr) {
4193 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4197 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4198 unsigned NumHandlers, const Twine &NameStr,
4199 BasicBlock *InsertAtEnd) {
4200 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4204 /// Provide fast operand accessors
4205 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4207 // Accessor Methods for CatchSwitch stmt
4208 Value *getParentPad() const { return getOperand(0); }
4209 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4211 // Accessor Methods for CatchSwitch stmt
4212 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4213 bool unwindsToCaller() const { return !hasUnwindDest(); }
4214 BasicBlock *getUnwindDest() const {
4215 if (hasUnwindDest())
4216 return cast<BasicBlock>(getOperand(1));
4219 void setUnwindDest(BasicBlock *UnwindDest) {
4221 assert(hasUnwindDest());
4222 setOperand(1, UnwindDest);
4225 /// return the number of 'handlers' in this catchswitch
4226 /// instruction, except the default handler
4227 unsigned getNumHandlers() const {
4228 if (hasUnwindDest())
4229 return getNumOperands() - 2;
4230 return getNumOperands() - 1;
4234 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4235 static const BasicBlock *handler_helper(const Value *V) {
4236 return cast<BasicBlock>(V);
4240 using DerefFnTy = BasicBlock *(*)(Value *);
4241 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4242 using handler_range = iterator_range<handler_iterator>;
4243 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4244 using const_handler_iterator =
4245 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4246 using const_handler_range = iterator_range<const_handler_iterator>;
4248 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4249 handler_iterator handler_begin() {
4250 op_iterator It = op_begin() + 1;
4251 if (hasUnwindDest())
4253 return handler_iterator(It, DerefFnTy(handler_helper));
4256 /// Returns an iterator that points to the first handler in the
4257 /// CatchSwitchInst.
4258 const_handler_iterator handler_begin() const {
4259 const_op_iterator It = op_begin() + 1;
4260 if (hasUnwindDest())
4262 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4265 /// Returns a read-only iterator that points one past the last
4266 /// handler in the CatchSwitchInst.
4267 handler_iterator handler_end() {
4268 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4271 /// Returns an iterator that points one past the last handler in the
4272 /// CatchSwitchInst.
4273 const_handler_iterator handler_end() const {
4274 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4277 /// iteration adapter for range-for loops.
4278 handler_range handlers() {
4279 return make_range(handler_begin(), handler_end());
4282 /// iteration adapter for range-for loops.
4283 const_handler_range handlers() const {
4284 return make_range(handler_begin(), handler_end());
4287 /// Add an entry to the switch instruction...
4289 /// This action invalidates handler_end(). Old handler_end() iterator will
4290 /// point to the added handler.
4291 void addHandler(BasicBlock *Dest);
4293 void removeHandler(handler_iterator HI);
4295 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4296 BasicBlock *getSuccessor(unsigned Idx) const {
4297 assert(Idx < getNumSuccessors() &&
4298 "Successor # out of range for catchswitch!");
4299 return cast<BasicBlock>(getOperand(Idx + 1));
4301 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4302 assert(Idx < getNumSuccessors() &&
4303 "Successor # out of range for catchswitch!");
4304 setOperand(Idx + 1, NewSucc);
4307 // Methods for support type inquiry through isa, cast, and dyn_cast:
4308 static bool classof(const Instruction *I) {
4309 return I->getOpcode() == Instruction::CatchSwitch;
4311 static bool classof(const Value *V) {
4312 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4317 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4319 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4321 //===----------------------------------------------------------------------===//
4322 // CleanupPadInst Class
4323 //===----------------------------------------------------------------------===//
4324 class CleanupPadInst : public FuncletPadInst {
4326 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4327 unsigned Values, const Twine &NameStr,
4328 Instruction *InsertBefore)
4329 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4330 NameStr, InsertBefore) {}
4331 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4332 unsigned Values, const Twine &NameStr,
4333 BasicBlock *InsertAtEnd)
4334 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4335 NameStr, InsertAtEnd) {}
4338 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4339 const Twine &NameStr = "",
4340 Instruction *InsertBefore = nullptr) {
4341 unsigned Values = 1 + Args.size();
4343 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4346 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4347 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4348 unsigned Values = 1 + Args.size();
4350 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4353 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4354 static bool classof(const Instruction *I) {
4355 return I->getOpcode() == Instruction::CleanupPad;
4357 static bool classof(const Value *V) {
4358 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4362 //===----------------------------------------------------------------------===//
4363 // CatchPadInst Class
4364 //===----------------------------------------------------------------------===//
4365 class CatchPadInst : public FuncletPadInst {
4367 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4368 unsigned Values, const Twine &NameStr,
4369 Instruction *InsertBefore)
4370 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4371 NameStr, InsertBefore) {}
4372 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4373 unsigned Values, const Twine &NameStr,
4374 BasicBlock *InsertAtEnd)
4375 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4376 NameStr, InsertAtEnd) {}
4379 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4380 const Twine &NameStr = "",
4381 Instruction *InsertBefore = nullptr) {
4382 unsigned Values = 1 + Args.size();
4384 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4387 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4388 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4389 unsigned Values = 1 + Args.size();
4391 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4394 /// Convenience accessors
4395 CatchSwitchInst *getCatchSwitch() const {
4396 return cast<CatchSwitchInst>(Op<-1>());
4398 void setCatchSwitch(Value *CatchSwitch) {
4399 assert(CatchSwitch);
4400 Op<-1>() = CatchSwitch;
4403 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4404 static bool classof(const Instruction *I) {
4405 return I->getOpcode() == Instruction::CatchPad;
4407 static bool classof(const Value *V) {
4408 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4412 //===----------------------------------------------------------------------===//
4413 // CatchReturnInst Class
4414 //===----------------------------------------------------------------------===//
4416 class CatchReturnInst : public TerminatorInst {
4417 CatchReturnInst(const CatchReturnInst &RI);
4418 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4419 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4421 void init(Value *CatchPad, BasicBlock *BB);
4424 // Note: Instruction needs to be a friend here to call cloneImpl.
4425 friend class Instruction;
4427 CatchReturnInst *cloneImpl() const;
4430 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4431 Instruction *InsertBefore = nullptr) {
4434 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4437 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4438 BasicBlock *InsertAtEnd) {
4441 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4444 /// Provide fast operand accessors
4445 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4447 /// Convenience accessors.
4448 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4449 void setCatchPad(CatchPadInst *CatchPad) {
4454 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4455 void setSuccessor(BasicBlock *NewSucc) {
4459 unsigned getNumSuccessors() const { return 1; }
4461 /// Get the parentPad of this catchret's catchpad's catchswitch.
4462 /// The successor block is implicitly a member of this funclet.
4463 Value *getCatchSwitchParentPad() const {
4464 return getCatchPad()->getCatchSwitch()->getParentPad();
4467 // Methods for support type inquiry through isa, cast, and dyn_cast:
4468 static bool classof(const Instruction *I) {
4469 return (I->getOpcode() == Instruction::CatchRet);
4471 static bool classof(const Value *V) {
4472 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4476 friend TerminatorInst;
4478 BasicBlock *getSuccessor(unsigned Idx) const {
4479 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4480 return getSuccessor();
4483 void setSuccessor(unsigned Idx, BasicBlock *B) {
4484 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4490 struct OperandTraits<CatchReturnInst>
4491 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4493 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4495 //===----------------------------------------------------------------------===//
4496 // CleanupReturnInst Class
4497 //===----------------------------------------------------------------------===//
4499 class CleanupReturnInst : public TerminatorInst {
4501 CleanupReturnInst(const CleanupReturnInst &RI);
4502 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4503 Instruction *InsertBefore = nullptr);
4504 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4505 BasicBlock *InsertAtEnd);
4507 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4510 // Note: Instruction needs to be a friend here to call cloneImpl.
4511 friend class Instruction;
4513 CleanupReturnInst *cloneImpl() const;
4516 static CleanupReturnInst *Create(Value *CleanupPad,
4517 BasicBlock *UnwindBB = nullptr,
4518 Instruction *InsertBefore = nullptr) {
4520 unsigned Values = 1;
4524 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4527 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4528 BasicBlock *InsertAtEnd) {
4530 unsigned Values = 1;
4534 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4537 /// Provide fast operand accessors
4538 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4540 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4541 bool unwindsToCaller() const { return !hasUnwindDest(); }
4543 /// Convenience accessor.
4544 CleanupPadInst *getCleanupPad() const {
4545 return cast<CleanupPadInst>(Op<0>());
4547 void setCleanupPad(CleanupPadInst *CleanupPad) {
4549 Op<0>() = CleanupPad;
4552 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4554 BasicBlock *getUnwindDest() const {
4555 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4557 void setUnwindDest(BasicBlock *NewDest) {
4559 assert(hasUnwindDest());
4563 // Methods for support type inquiry through isa, cast, and dyn_cast:
4564 static bool classof(const Instruction *I) {
4565 return (I->getOpcode() == Instruction::CleanupRet);
4567 static bool classof(const Value *V) {
4568 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4572 friend TerminatorInst;
4574 BasicBlock *getSuccessor(unsigned Idx) const {
4576 return getUnwindDest();
4579 void setSuccessor(unsigned Idx, BasicBlock *B) {
4584 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4585 // method so that subclasses cannot accidentally use it.
4586 void setInstructionSubclassData(unsigned short D) {
4587 Instruction::setInstructionSubclassData(D);
4592 struct OperandTraits<CleanupReturnInst>
4593 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4595 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4597 //===----------------------------------------------------------------------===//
4598 // UnreachableInst Class
4599 //===----------------------------------------------------------------------===//
4601 //===---------------------------------------------------------------------------
4602 /// This function has undefined behavior. In particular, the
4603 /// presence of this instruction indicates some higher level knowledge that the
4604 /// end of the block cannot be reached.
4606 class UnreachableInst : public TerminatorInst {
4608 // Note: Instruction needs to be a friend here to call cloneImpl.
4609 friend class Instruction;
4611 UnreachableInst *cloneImpl() const;
4614 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4615 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4617 // allocate space for exactly zero operands
4618 void *operator new(size_t s) {
4619 return User::operator new(s, 0);
4622 unsigned getNumSuccessors() const { return 0; }
4624 // Methods for support type inquiry through isa, cast, and dyn_cast:
4625 static bool classof(const Instruction *I) {
4626 return I->getOpcode() == Instruction::Unreachable;
4628 static bool classof(const Value *V) {
4629 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4633 friend TerminatorInst;
4635 BasicBlock *getSuccessor(unsigned idx) const {
4636 llvm_unreachable("UnreachableInst has no successors!");
4639 void setSuccessor(unsigned idx, BasicBlock *B) {
4640 llvm_unreachable("UnreachableInst has no successors!");
4644 //===----------------------------------------------------------------------===//
4646 //===----------------------------------------------------------------------===//
4648 /// This class represents a truncation of integer types.
4649 class TruncInst : public CastInst {
4651 // Note: Instruction needs to be a friend here to call cloneImpl.
4652 friend class Instruction;
4654 /// Clone an identical TruncInst
4655 TruncInst *cloneImpl() const;
4658 /// Constructor with insert-before-instruction semantics
4660 Value *S, ///< The value to be truncated
4661 Type *Ty, ///< The (smaller) type to truncate to
4662 const Twine &NameStr = "", ///< A name for the new instruction
4663 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4666 /// Constructor with insert-at-end-of-block semantics
4668 Value *S, ///< The value to be truncated
4669 Type *Ty, ///< The (smaller) type to truncate to
4670 const Twine &NameStr, ///< A name for the new instruction
4671 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4674 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4675 static bool classof(const Instruction *I) {
4676 return I->getOpcode() == Trunc;
4678 static bool classof(const Value *V) {
4679 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4683 //===----------------------------------------------------------------------===//
4685 //===----------------------------------------------------------------------===//
4687 /// This class represents zero extension of integer types.
4688 class ZExtInst : public CastInst {
4690 // Note: Instruction needs to be a friend here to call cloneImpl.
4691 friend class Instruction;
4693 /// Clone an identical ZExtInst
4694 ZExtInst *cloneImpl() const;
4697 /// Constructor with insert-before-instruction semantics
4699 Value *S, ///< The value to be zero extended
4700 Type *Ty, ///< The type to zero extend to
4701 const Twine &NameStr = "", ///< A name for the new instruction
4702 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4705 /// Constructor with insert-at-end semantics.
4707 Value *S, ///< The value to be zero extended
4708 Type *Ty, ///< The type to zero extend to
4709 const Twine &NameStr, ///< A name for the new instruction
4710 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4713 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4714 static bool classof(const Instruction *I) {
4715 return I->getOpcode() == ZExt;
4717 static bool classof(const Value *V) {
4718 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4722 //===----------------------------------------------------------------------===//
4724 //===----------------------------------------------------------------------===//
4726 /// This class represents a sign extension of integer types.
4727 class SExtInst : public CastInst {
4729 // Note: Instruction needs to be a friend here to call cloneImpl.
4730 friend class Instruction;
4732 /// Clone an identical SExtInst
4733 SExtInst *cloneImpl() const;
4736 /// Constructor with insert-before-instruction semantics
4738 Value *S, ///< The value to be sign extended
4739 Type *Ty, ///< The type to sign extend to
4740 const Twine &NameStr = "", ///< A name for the new instruction
4741 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4744 /// Constructor with insert-at-end-of-block semantics
4746 Value *S, ///< The value to be sign extended
4747 Type *Ty, ///< The type to sign extend to
4748 const Twine &NameStr, ///< A name for the new instruction
4749 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4752 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4753 static bool classof(const Instruction *I) {
4754 return I->getOpcode() == SExt;
4756 static bool classof(const Value *V) {
4757 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4761 //===----------------------------------------------------------------------===//
4762 // FPTruncInst Class
4763 //===----------------------------------------------------------------------===//
4765 /// This class represents a truncation of floating point types.
4766 class FPTruncInst : public CastInst {
4768 // Note: Instruction needs to be a friend here to call cloneImpl.
4769 friend class Instruction;
4771 /// Clone an identical FPTruncInst
4772 FPTruncInst *cloneImpl() const;
4775 /// Constructor with insert-before-instruction semantics
4777 Value *S, ///< The value to be truncated
4778 Type *Ty, ///< The type to truncate to
4779 const Twine &NameStr = "", ///< A name for the new instruction
4780 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4783 /// Constructor with insert-before-instruction semantics
4785 Value *S, ///< The value to be truncated
4786 Type *Ty, ///< The type to truncate to
4787 const Twine &NameStr, ///< A name for the new instruction
4788 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4791 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4792 static bool classof(const Instruction *I) {
4793 return I->getOpcode() == FPTrunc;
4795 static bool classof(const Value *V) {
4796 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4800 //===----------------------------------------------------------------------===//
4802 //===----------------------------------------------------------------------===//
4804 /// This class represents an extension of floating point types.
4805 class FPExtInst : public CastInst {
4807 // Note: Instruction needs to be a friend here to call cloneImpl.
4808 friend class Instruction;
4810 /// Clone an identical FPExtInst
4811 FPExtInst *cloneImpl() const;
4814 /// Constructor with insert-before-instruction semantics
4816 Value *S, ///< The value to be extended
4817 Type *Ty, ///< The type to extend to
4818 const Twine &NameStr = "", ///< A name for the new instruction
4819 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4822 /// Constructor with insert-at-end-of-block semantics
4824 Value *S, ///< The value to be extended
4825 Type *Ty, ///< The type to extend to
4826 const Twine &NameStr, ///< A name for the new instruction
4827 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4830 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4831 static bool classof(const Instruction *I) {
4832 return I->getOpcode() == FPExt;
4834 static bool classof(const Value *V) {
4835 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4839 //===----------------------------------------------------------------------===//
4841 //===----------------------------------------------------------------------===//
4843 /// This class represents a cast unsigned integer to floating point.
4844 class UIToFPInst : public CastInst {
4846 // Note: Instruction needs to be a friend here to call cloneImpl.
4847 friend class Instruction;
4849 /// Clone an identical UIToFPInst
4850 UIToFPInst *cloneImpl() const;
4853 /// Constructor with insert-before-instruction semantics
4855 Value *S, ///< The value to be converted
4856 Type *Ty, ///< The type to convert to
4857 const Twine &NameStr = "", ///< A name for the new instruction
4858 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4861 /// Constructor with insert-at-end-of-block semantics
4863 Value *S, ///< The value to be converted
4864 Type *Ty, ///< The type to convert to
4865 const Twine &NameStr, ///< A name for the new instruction
4866 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4869 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4870 static bool classof(const Instruction *I) {
4871 return I->getOpcode() == UIToFP;
4873 static bool classof(const Value *V) {
4874 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4878 //===----------------------------------------------------------------------===//
4880 //===----------------------------------------------------------------------===//
4882 /// This class represents a cast from signed integer to floating point.
4883 class SIToFPInst : public CastInst {
4885 // Note: Instruction needs to be a friend here to call cloneImpl.
4886 friend class Instruction;
4888 /// Clone an identical SIToFPInst
4889 SIToFPInst *cloneImpl() const;
4892 /// Constructor with insert-before-instruction semantics
4894 Value *S, ///< The value to be converted
4895 Type *Ty, ///< The type to convert to
4896 const Twine &NameStr = "", ///< A name for the new instruction
4897 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4900 /// Constructor with insert-at-end-of-block semantics
4902 Value *S, ///< The value to be converted
4903 Type *Ty, ///< The type to convert to
4904 const Twine &NameStr, ///< A name for the new instruction
4905 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4908 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4909 static bool classof(const Instruction *I) {
4910 return I->getOpcode() == SIToFP;
4912 static bool classof(const Value *V) {
4913 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4917 //===----------------------------------------------------------------------===//
4919 //===----------------------------------------------------------------------===//
4921 /// This class represents a cast from floating point to unsigned integer
4922 class FPToUIInst : public CastInst {
4924 // Note: Instruction needs to be a friend here to call cloneImpl.
4925 friend class Instruction;
4927 /// Clone an identical FPToUIInst
4928 FPToUIInst *cloneImpl() const;
4931 /// Constructor with insert-before-instruction semantics
4933 Value *S, ///< The value to be converted
4934 Type *Ty, ///< The type to convert to
4935 const Twine &NameStr = "", ///< A name for the new instruction
4936 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4939 /// Constructor with insert-at-end-of-block semantics
4941 Value *S, ///< The value to be converted
4942 Type *Ty, ///< The type to convert to
4943 const Twine &NameStr, ///< A name for the new instruction
4944 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
4947 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4948 static bool classof(const Instruction *I) {
4949 return I->getOpcode() == FPToUI;
4951 static bool classof(const Value *V) {
4952 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4956 //===----------------------------------------------------------------------===//
4958 //===----------------------------------------------------------------------===//
4960 /// This class represents a cast from floating point to signed integer.
4961 class FPToSIInst : public CastInst {
4963 // Note: Instruction needs to be a friend here to call cloneImpl.
4964 friend class Instruction;
4966 /// Clone an identical FPToSIInst
4967 FPToSIInst *cloneImpl() const;
4970 /// Constructor with insert-before-instruction semantics
4972 Value *S, ///< The value to be converted
4973 Type *Ty, ///< The type to convert to
4974 const Twine &NameStr = "", ///< A name for the new instruction
4975 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4978 /// Constructor with insert-at-end-of-block semantics
4980 Value *S, ///< The value to be converted
4981 Type *Ty, ///< The type to convert to
4982 const Twine &NameStr, ///< A name for the new instruction
4983 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4986 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4987 static bool classof(const Instruction *I) {
4988 return I->getOpcode() == FPToSI;
4990 static bool classof(const Value *V) {
4991 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4995 //===----------------------------------------------------------------------===//
4996 // IntToPtrInst Class
4997 //===----------------------------------------------------------------------===//
4999 /// This class represents a cast from an integer to a pointer.
5000 class IntToPtrInst : public CastInst {
5002 // Note: Instruction needs to be a friend here to call cloneImpl.
5003 friend class Instruction;
5005 /// Constructor with insert-before-instruction semantics
5007 Value *S, ///< The value to be converted
5008 Type *Ty, ///< The type to convert to
5009 const Twine &NameStr = "", ///< A name for the new instruction
5010 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5013 /// Constructor with insert-at-end-of-block semantics
5015 Value *S, ///< The value to be converted
5016 Type *Ty, ///< The type to convert to
5017 const Twine &NameStr, ///< A name for the new instruction
5018 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5021 /// Clone an identical IntToPtrInst.
5022 IntToPtrInst *cloneImpl() const;
5024 /// Returns the address space of this instruction's pointer type.
5025 unsigned getAddressSpace() const {
5026 return getType()->getPointerAddressSpace();
5029 // Methods for support type inquiry through isa, cast, and dyn_cast:
5030 static bool classof(const Instruction *I) {
5031 return I->getOpcode() == IntToPtr;
5033 static bool classof(const Value *V) {
5034 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5038 //===----------------------------------------------------------------------===//
5039 // PtrToIntInst Class
5040 //===----------------------------------------------------------------------===//
5042 /// This class represents a cast from a pointer to an integer.
5043 class PtrToIntInst : public CastInst {
5045 // Note: Instruction needs to be a friend here to call cloneImpl.
5046 friend class Instruction;
5048 /// Clone an identical PtrToIntInst.
5049 PtrToIntInst *cloneImpl() const;
5052 /// Constructor with insert-before-instruction semantics
5054 Value *S, ///< The value to be converted
5055 Type *Ty, ///< The type to convert to
5056 const Twine &NameStr = "", ///< A name for the new instruction
5057 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5060 /// Constructor with insert-at-end-of-block semantics
5062 Value *S, ///< The value to be converted
5063 Type *Ty, ///< The type to convert to
5064 const Twine &NameStr, ///< A name for the new instruction
5065 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5068 /// Gets the pointer operand.
5069 Value *getPointerOperand() { return getOperand(0); }
5070 /// Gets the pointer operand.
5071 const Value *getPointerOperand() const { return getOperand(0); }
5072 /// Gets the operand index of the pointer operand.
5073 static unsigned getPointerOperandIndex() { return 0U; }
5075 /// Returns the address space of the pointer operand.
5076 unsigned getPointerAddressSpace() const {
5077 return getPointerOperand()->getType()->getPointerAddressSpace();
5080 // Methods for support type inquiry through isa, cast, and dyn_cast:
5081 static bool classof(const Instruction *I) {
5082 return I->getOpcode() == PtrToInt;
5084 static bool classof(const Value *V) {
5085 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5089 //===----------------------------------------------------------------------===//
5090 // BitCastInst Class
5091 //===----------------------------------------------------------------------===//
5093 /// This class represents a no-op cast from one type to another.
5094 class BitCastInst : public CastInst {
5096 // Note: Instruction needs to be a friend here to call cloneImpl.
5097 friend class Instruction;
5099 /// Clone an identical BitCastInst.
5100 BitCastInst *cloneImpl() const;
5103 /// Constructor with insert-before-instruction semantics
5105 Value *S, ///< The value to be casted
5106 Type *Ty, ///< The type to casted to
5107 const Twine &NameStr = "", ///< A name for the new instruction
5108 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5111 /// Constructor with insert-at-end-of-block semantics
5113 Value *S, ///< The value to be casted
5114 Type *Ty, ///< The type to casted to
5115 const Twine &NameStr, ///< A name for the new instruction
5116 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5119 // Methods for support type inquiry through isa, cast, and dyn_cast:
5120 static bool classof(const Instruction *I) {
5121 return I->getOpcode() == BitCast;
5123 static bool classof(const Value *V) {
5124 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5128 //===----------------------------------------------------------------------===//
5129 // AddrSpaceCastInst Class
5130 //===----------------------------------------------------------------------===//
5132 /// This class represents a conversion between pointers from one address space
5134 class AddrSpaceCastInst : public CastInst {
5136 // Note: Instruction needs to be a friend here to call cloneImpl.
5137 friend class Instruction;
5139 /// Clone an identical AddrSpaceCastInst.
5140 AddrSpaceCastInst *cloneImpl() const;
5143 /// Constructor with insert-before-instruction semantics
5145 Value *S, ///< The value to be casted
5146 Type *Ty, ///< The type to casted to
5147 const Twine &NameStr = "", ///< A name for the new instruction
5148 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5151 /// Constructor with insert-at-end-of-block semantics
5153 Value *S, ///< The value to be casted
5154 Type *Ty, ///< The type to casted to
5155 const Twine &NameStr, ///< A name for the new instruction
5156 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5159 // Methods for support type inquiry through isa, cast, and dyn_cast:
5160 static bool classof(const Instruction *I) {
5161 return I->getOpcode() == AddrSpaceCast;
5163 static bool classof(const Value *V) {
5164 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5167 /// Gets the pointer operand.
5168 Value *getPointerOperand() {
5169 return getOperand(0);
5172 /// Gets the pointer operand.
5173 const Value *getPointerOperand() const {
5174 return getOperand(0);
5177 /// Gets the operand index of the pointer operand.
5178 static unsigned getPointerOperandIndex() {
5182 /// Returns the address space of the pointer operand.
5183 unsigned getSrcAddressSpace() const {
5184 return getPointerOperand()->getType()->getPointerAddressSpace();
5187 /// Returns the address space of the result.
5188 unsigned getDestAddressSpace() const {
5189 return getType()->getPointerAddressSpace();
5193 } // end namespace llvm
5195 #endif // LLVM_IR_INSTRUCTIONS_H