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/iterator.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Twine.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 enum SynchronizationScope {
60 //===----------------------------------------------------------------------===//
62 //===----------------------------------------------------------------------===//
64 /// an instruction to allocate memory on the stack
65 class AllocaInst : public UnaryInstruction {
69 // Note: Instruction needs to be a friend here to call cloneImpl.
70 friend class Instruction;
72 AllocaInst *cloneImpl() const;
75 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
76 Value *ArraySize = nullptr,
77 const Twine &Name = "",
78 Instruction *InsertBefore = nullptr);
79 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
80 const Twine &Name, BasicBlock *InsertAtEnd);
82 AllocaInst(Type *Ty, unsigned AddrSpace,
83 const Twine &Name, Instruction *InsertBefore = nullptr);
84 AllocaInst(Type *Ty, unsigned AddrSpace,
85 const Twine &Name, BasicBlock *InsertAtEnd);
87 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
88 const Twine &Name = "", Instruction *InsertBefore = nullptr);
89 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
90 const Twine &Name, BasicBlock *InsertAtEnd);
92 /// Return true if there is an allocation size parameter to the allocation
93 /// instruction that is not 1.
94 bool isArrayAllocation() const;
96 /// Get the number of elements allocated. For a simple allocation of a single
97 /// element, this will return a constant 1 value.
98 const Value *getArraySize() const { return getOperand(0); }
99 Value *getArraySize() { return getOperand(0); }
101 /// Overload to return most specific pointer type.
102 PointerType *getType() const {
103 return cast<PointerType>(Instruction::getType());
106 /// Return the type that is being allocated by the instruction.
107 Type *getAllocatedType() const { return AllocatedType; }
108 /// for use only in special circumstances that need to generically
109 /// transform a whole instruction (eg: IR linking and vectorization).
110 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
112 /// Return the alignment of the memory that is being allocated by the
114 unsigned getAlignment() const {
115 return (1u << (getSubclassDataFromInstruction() & 31)) >> 1;
117 void setAlignment(unsigned Align);
119 /// Return true if this alloca is in the entry block of the function and is a
120 /// constant size. If so, the code generator will fold it into the
121 /// prolog/epilog code, so it is basically free.
122 bool isStaticAlloca() const;
124 /// Return true if this alloca is used as an inalloca argument to a call. Such
125 /// allocas are never considered static even if they are in the entry block.
126 bool isUsedWithInAlloca() const {
127 return getSubclassDataFromInstruction() & 32;
130 /// Specify whether this alloca is used to represent the arguments to a call.
131 void setUsedWithInAlloca(bool V) {
132 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
136 /// Return true if this alloca is used as a swifterror argument to a call.
137 bool isSwiftError() const {
138 return getSubclassDataFromInstruction() & 64;
141 /// Specify whether this alloca is used to represent a swifterror.
142 void setSwiftError(bool V) {
143 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
147 // Methods for support type inquiry through isa, cast, and dyn_cast:
148 static inline bool classof(const Instruction *I) {
149 return (I->getOpcode() == Instruction::Alloca);
151 static inline bool classof(const Value *V) {
152 return isa<Instruction>(V) && classof(cast<Instruction>(V));
156 // Shadow Instruction::setInstructionSubclassData with a private forwarding
157 // method so that subclasses cannot accidentally use it.
158 void setInstructionSubclassData(unsigned short D) {
159 Instruction::setInstructionSubclassData(D);
163 //===----------------------------------------------------------------------===//
165 //===----------------------------------------------------------------------===//
167 /// An instruction for reading from memory. This uses the SubclassData field in
168 /// Value to store whether or not the load is volatile.
169 class LoadInst : public UnaryInstruction {
173 // Note: Instruction needs to be a friend here to call cloneImpl.
174 friend class Instruction;
176 LoadInst *cloneImpl() const;
179 LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
180 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile = false,
182 Instruction *InsertBefore = nullptr);
183 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
184 Instruction *InsertBefore = nullptr)
185 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
186 NameStr, isVolatile, InsertBefore) {}
187 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
188 BasicBlock *InsertAtEnd);
189 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
190 Instruction *InsertBefore = nullptr)
191 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
192 NameStr, isVolatile, Align, InsertBefore) {}
193 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
194 unsigned Align, Instruction *InsertBefore = nullptr);
195 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
196 unsigned Align, BasicBlock *InsertAtEnd);
197 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
198 AtomicOrdering Order, SynchronizationScope SynchScope = CrossThread,
199 Instruction *InsertBefore = nullptr)
200 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
201 NameStr, isVolatile, Align, Order, SynchScope, InsertBefore) {}
202 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
203 unsigned Align, AtomicOrdering Order,
204 SynchronizationScope SynchScope = CrossThread,
205 Instruction *InsertBefore = nullptr);
206 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207 unsigned Align, AtomicOrdering Order,
208 SynchronizationScope SynchScope,
209 BasicBlock *InsertAtEnd);
210 LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
211 LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
212 LoadInst(Type *Ty, Value *Ptr, const char *NameStr = nullptr,
213 bool isVolatile = false, Instruction *InsertBefore = nullptr);
214 explicit LoadInst(Value *Ptr, const char *NameStr = nullptr,
215 bool isVolatile = false,
216 Instruction *InsertBefore = nullptr)
217 : LoadInst(cast<PointerType>(Ptr->getType())->getElementType(), Ptr,
218 NameStr, isVolatile, InsertBefore) {}
219 LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
220 BasicBlock *InsertAtEnd);
222 /// Return true if this is a load from a volatile memory location.
223 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
225 /// Specify whether this is a volatile load or not.
226 void setVolatile(bool V) {
227 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
231 /// Return the alignment of the access that is being performed.
232 unsigned getAlignment() const {
233 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
236 void setAlignment(unsigned Align);
238 /// Returns the ordering effect of this fence.
239 AtomicOrdering getOrdering() const {
240 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
243 /// Set the ordering constraint on this load. May not be Release or
245 void setOrdering(AtomicOrdering Ordering) {
246 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
247 ((unsigned)Ordering << 7));
250 SynchronizationScope getSynchScope() const {
251 return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
254 /// Specify whether this load is ordered with respect to all
255 /// concurrently executing threads, or only with respect to signal handlers
256 /// executing in the same thread.
257 void setSynchScope(SynchronizationScope xthread) {
258 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
262 void setAtomic(AtomicOrdering Ordering,
263 SynchronizationScope SynchScope = CrossThread) {
264 setOrdering(Ordering);
265 setSynchScope(SynchScope);
268 bool isSimple() const { return !isAtomic() && !isVolatile(); }
270 bool isUnordered() const {
271 return (getOrdering() == AtomicOrdering::NotAtomic ||
272 getOrdering() == AtomicOrdering::Unordered) &&
276 Value *getPointerOperand() { return getOperand(0); }
277 const Value *getPointerOperand() const { return getOperand(0); }
278 static unsigned getPointerOperandIndex() { return 0U; }
279 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
281 /// Returns the address space of the pointer operand.
282 unsigned getPointerAddressSpace() const {
283 return getPointerOperandType()->getPointerAddressSpace();
286 // Methods for support type inquiry through isa, cast, and dyn_cast:
287 static inline bool classof(const Instruction *I) {
288 return I->getOpcode() == Instruction::Load;
290 static inline bool classof(const Value *V) {
291 return isa<Instruction>(V) && classof(cast<Instruction>(V));
295 // Shadow Instruction::setInstructionSubclassData with a private forwarding
296 // method so that subclasses cannot accidentally use it.
297 void setInstructionSubclassData(unsigned short D) {
298 Instruction::setInstructionSubclassData(D);
302 //===----------------------------------------------------------------------===//
304 //===----------------------------------------------------------------------===//
306 /// An instruction for storing to memory.
307 class StoreInst : public Instruction {
311 // Note: Instruction needs to be a friend here to call cloneImpl.
312 friend class Instruction;
314 StoreInst *cloneImpl() const;
317 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
318 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
319 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
320 Instruction *InsertBefore = nullptr);
321 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
322 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
323 unsigned Align, Instruction *InsertBefore = nullptr);
324 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
325 unsigned Align, BasicBlock *InsertAtEnd);
326 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
327 unsigned Align, AtomicOrdering Order,
328 SynchronizationScope SynchScope = CrossThread,
329 Instruction *InsertBefore = nullptr);
330 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
331 unsigned Align, AtomicOrdering Order,
332 SynchronizationScope SynchScope,
333 BasicBlock *InsertAtEnd);
335 // allocate space for exactly two operands
336 void *operator new(size_t s) {
337 return User::operator new(s, 2);
340 void *operator new(size_t, unsigned) = delete;
342 /// Return true if this is a store to a volatile memory location.
343 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
345 /// Specify whether this is a volatile store or not.
346 void setVolatile(bool V) {
347 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
351 /// Transparently provide more efficient getOperand methods.
352 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
354 /// Return the alignment of the access that is being performed
355 unsigned getAlignment() const {
356 return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
359 void setAlignment(unsigned Align);
361 /// Returns the ordering effect of this store.
362 AtomicOrdering getOrdering() const {
363 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
366 /// Set the ordering constraint on this store. May not be Acquire or
368 void setOrdering(AtomicOrdering Ordering) {
369 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
370 ((unsigned)Ordering << 7));
373 SynchronizationScope getSynchScope() const {
374 return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
377 /// Specify whether this store instruction is ordered with respect to all
378 /// concurrently executing threads, or only with respect to signal handlers
379 /// executing in the same thread.
380 void setSynchScope(SynchronizationScope xthread) {
381 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
385 void setAtomic(AtomicOrdering Ordering,
386 SynchronizationScope SynchScope = CrossThread) {
387 setOrdering(Ordering);
388 setSynchScope(SynchScope);
391 bool isSimple() const { return !isAtomic() && !isVolatile(); }
393 bool isUnordered() const {
394 return (getOrdering() == AtomicOrdering::NotAtomic ||
395 getOrdering() == AtomicOrdering::Unordered) &&
399 Value *getValueOperand() { return getOperand(0); }
400 const Value *getValueOperand() const { return getOperand(0); }
402 Value *getPointerOperand() { return getOperand(1); }
403 const Value *getPointerOperand() const { return getOperand(1); }
404 static unsigned getPointerOperandIndex() { return 1U; }
405 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
407 /// Returns the address space of the pointer operand.
408 unsigned getPointerAddressSpace() const {
409 return getPointerOperandType()->getPointerAddressSpace();
412 // Methods for support type inquiry through isa, cast, and dyn_cast:
413 static inline bool classof(const Instruction *I) {
414 return I->getOpcode() == Instruction::Store;
416 static inline bool classof(const Value *V) {
417 return isa<Instruction>(V) && classof(cast<Instruction>(V));
421 // Shadow Instruction::setInstructionSubclassData with a private forwarding
422 // method so that subclasses cannot accidentally use it.
423 void setInstructionSubclassData(unsigned short D) {
424 Instruction::setInstructionSubclassData(D);
429 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
432 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
434 //===----------------------------------------------------------------------===//
436 //===----------------------------------------------------------------------===//
438 /// An instruction for ordering other memory operations.
439 class FenceInst : public Instruction {
440 void Init(AtomicOrdering Ordering, SynchronizationScope SynchScope);
443 // Note: Instruction needs to be a friend here to call cloneImpl.
444 friend class Instruction;
446 FenceInst *cloneImpl() const;
449 // Ordering may only be Acquire, Release, AcquireRelease, or
450 // SequentiallyConsistent.
451 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
452 SynchronizationScope SynchScope = CrossThread,
453 Instruction *InsertBefore = nullptr);
454 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
455 SynchronizationScope SynchScope,
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 void *operator new(size_t, unsigned) = delete;
465 /// Returns the ordering effect of this fence.
466 AtomicOrdering getOrdering() const {
467 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
470 /// Set the ordering constraint on this fence. May only be Acquire, Release,
471 /// AcquireRelease, or SequentiallyConsistent.
472 void setOrdering(AtomicOrdering Ordering) {
473 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
474 ((unsigned)Ordering << 1));
477 SynchronizationScope getSynchScope() const {
478 return SynchronizationScope(getSubclassDataFromInstruction() & 1);
481 /// Specify whether this fence orders other operations with respect to all
482 /// concurrently executing threads, or only with respect to signal handlers
483 /// executing in the same thread.
484 void setSynchScope(SynchronizationScope xthread) {
485 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
489 // Methods for support type inquiry through isa, cast, and dyn_cast:
490 static inline bool classof(const Instruction *I) {
491 return I->getOpcode() == Instruction::Fence;
493 static inline bool classof(const Value *V) {
494 return isa<Instruction>(V) && classof(cast<Instruction>(V));
498 // Shadow Instruction::setInstructionSubclassData with a private forwarding
499 // method so that subclasses cannot accidentally use it.
500 void setInstructionSubclassData(unsigned short D) {
501 Instruction::setInstructionSubclassData(D);
505 //===----------------------------------------------------------------------===//
506 // AtomicCmpXchgInst Class
507 //===----------------------------------------------------------------------===//
509 /// an instruction that atomically checks whether a
510 /// specified value is in a memory location, and, if it is, stores a new value
511 /// there. Returns the value that was loaded.
513 class AtomicCmpXchgInst : public Instruction {
514 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
515 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
516 SynchronizationScope SynchScope);
519 // Note: Instruction needs to be a friend here to call cloneImpl.
520 friend class Instruction;
522 AtomicCmpXchgInst *cloneImpl() const;
525 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
526 AtomicOrdering SuccessOrdering,
527 AtomicOrdering FailureOrdering,
528 SynchronizationScope SynchScope,
529 Instruction *InsertBefore = nullptr);
530 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
531 AtomicOrdering SuccessOrdering,
532 AtomicOrdering FailureOrdering,
533 SynchronizationScope SynchScope,
534 BasicBlock *InsertAtEnd);
536 // allocate space for exactly three operands
537 void *operator new(size_t s) {
538 return User::operator new(s, 3);
541 void *operator new(size_t, unsigned) = delete;
543 /// Return true if this is a cmpxchg from a volatile memory
546 bool isVolatile() const {
547 return getSubclassDataFromInstruction() & 1;
550 /// Specify whether this is a volatile cmpxchg.
552 void setVolatile(bool V) {
553 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
557 /// Return true if this cmpxchg may spuriously fail.
558 bool isWeak() const {
559 return getSubclassDataFromInstruction() & 0x100;
562 void setWeak(bool IsWeak) {
563 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
567 /// Transparently provide more efficient getOperand methods.
568 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
570 /// Set the ordering constraint on this cmpxchg.
571 void setSuccessOrdering(AtomicOrdering Ordering) {
572 assert(Ordering != AtomicOrdering::NotAtomic &&
573 "CmpXchg instructions can only be atomic.");
574 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
575 ((unsigned)Ordering << 2));
578 void setFailureOrdering(AtomicOrdering Ordering) {
579 assert(Ordering != AtomicOrdering::NotAtomic &&
580 "CmpXchg instructions can only be atomic.");
581 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
582 ((unsigned)Ordering << 5));
585 /// Specify whether this cmpxchg is atomic and orders other operations with
586 /// respect to all concurrently executing threads, or only with respect to
587 /// signal handlers executing in the same thread.
588 void setSynchScope(SynchronizationScope SynchScope) {
589 setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
593 /// Returns the ordering constraint on this cmpxchg.
594 AtomicOrdering getSuccessOrdering() const {
595 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
598 /// Returns the ordering constraint on this cmpxchg.
599 AtomicOrdering getFailureOrdering() const {
600 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
603 /// Returns whether this cmpxchg is atomic between threads or only within a
605 SynchronizationScope getSynchScope() const {
606 return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
609 Value *getPointerOperand() { return getOperand(0); }
610 const Value *getPointerOperand() const { return getOperand(0); }
611 static unsigned getPointerOperandIndex() { return 0U; }
613 Value *getCompareOperand() { return getOperand(1); }
614 const Value *getCompareOperand() const { return getOperand(1); }
616 Value *getNewValOperand() { return getOperand(2); }
617 const Value *getNewValOperand() const { return getOperand(2); }
619 /// Returns the address space of the pointer operand.
620 unsigned getPointerAddressSpace() const {
621 return getPointerOperand()->getType()->getPointerAddressSpace();
624 /// Returns the strongest permitted ordering on failure, given the
625 /// desired ordering on success.
627 /// If the comparison in a cmpxchg operation fails, there is no atomic store
628 /// so release semantics cannot be provided. So this function drops explicit
629 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
630 /// operation would remain SequentiallyConsistent.
631 static AtomicOrdering
632 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
633 switch (SuccessOrdering) {
635 llvm_unreachable("invalid cmpxchg success ordering");
636 case AtomicOrdering::Release:
637 case AtomicOrdering::Monotonic:
638 return AtomicOrdering::Monotonic;
639 case AtomicOrdering::AcquireRelease:
640 case AtomicOrdering::Acquire:
641 return AtomicOrdering::Acquire;
642 case AtomicOrdering::SequentiallyConsistent:
643 return AtomicOrdering::SequentiallyConsistent;
647 // Methods for support type inquiry through isa, cast, and dyn_cast:
648 static inline bool classof(const Instruction *I) {
649 return I->getOpcode() == Instruction::AtomicCmpXchg;
651 static inline bool classof(const Value *V) {
652 return isa<Instruction>(V) && classof(cast<Instruction>(V));
656 // Shadow Instruction::setInstructionSubclassData with a private forwarding
657 // method so that subclasses cannot accidentally use it.
658 void setInstructionSubclassData(unsigned short D) {
659 Instruction::setInstructionSubclassData(D);
664 struct OperandTraits<AtomicCmpXchgInst> :
665 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
668 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
670 //===----------------------------------------------------------------------===//
671 // AtomicRMWInst Class
672 //===----------------------------------------------------------------------===//
674 /// an instruction that atomically reads a memory location,
675 /// combines it with another value, and then stores the result back. Returns
678 class AtomicRMWInst : public Instruction {
680 // Note: Instruction needs to be a friend here to call cloneImpl.
681 friend class Instruction;
683 AtomicRMWInst *cloneImpl() const;
686 /// This enumeration lists the possible modifications atomicrmw can make. In
687 /// the descriptions, 'p' is the pointer to the instruction's memory location,
688 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
689 /// instruction. These instructions always return 'old'.
705 /// *p = old >signed v ? old : v
707 /// *p = old <signed v ? old : v
709 /// *p = old >unsigned v ? old : v
711 /// *p = old <unsigned v ? old : v
719 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
720 AtomicOrdering Ordering, SynchronizationScope SynchScope,
721 Instruction *InsertBefore = nullptr);
722 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
723 AtomicOrdering Ordering, SynchronizationScope SynchScope,
724 BasicBlock *InsertAtEnd);
726 // allocate space for exactly two operands
727 void *operator new(size_t s) {
728 return User::operator new(s, 2);
731 void *operator new(size_t, unsigned) = delete;
733 BinOp getOperation() const {
734 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
737 void setOperation(BinOp Operation) {
738 unsigned short SubclassData = getSubclassDataFromInstruction();
739 setInstructionSubclassData((SubclassData & 31) |
743 /// Return true if this is a RMW on a volatile memory location.
745 bool isVolatile() const {
746 return getSubclassDataFromInstruction() & 1;
749 /// Specify whether this is a volatile RMW or not.
751 void setVolatile(bool V) {
752 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
756 /// Transparently provide more efficient getOperand methods.
757 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
759 /// Set the ordering constraint on this RMW.
760 void setOrdering(AtomicOrdering Ordering) {
761 assert(Ordering != AtomicOrdering::NotAtomic &&
762 "atomicrmw instructions can only be atomic.");
763 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
764 ((unsigned)Ordering << 2));
767 /// Specify whether this RMW orders other operations with respect to all
768 /// concurrently executing threads, or only with respect to signal handlers
769 /// executing in the same thread.
770 void setSynchScope(SynchronizationScope SynchScope) {
771 setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
775 /// Returns the ordering constraint on this RMW.
776 AtomicOrdering getOrdering() const {
777 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
780 /// Returns whether this RMW is atomic between threads or only within a
782 SynchronizationScope getSynchScope() const {
783 return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
786 Value *getPointerOperand() { return getOperand(0); }
787 const Value *getPointerOperand() const { return getOperand(0); }
788 static unsigned getPointerOperandIndex() { return 0U; }
790 Value *getValOperand() { return getOperand(1); }
791 const Value *getValOperand() const { return getOperand(1); }
793 /// Returns the address space of the pointer operand.
794 unsigned getPointerAddressSpace() const {
795 return getPointerOperand()->getType()->getPointerAddressSpace();
798 // Methods for support type inquiry through isa, cast, and dyn_cast:
799 static inline bool classof(const Instruction *I) {
800 return I->getOpcode() == Instruction::AtomicRMW;
802 static inline bool classof(const Value *V) {
803 return isa<Instruction>(V) && classof(cast<Instruction>(V));
807 void Init(BinOp Operation, Value *Ptr, Value *Val,
808 AtomicOrdering Ordering, SynchronizationScope SynchScope);
810 // Shadow Instruction::setInstructionSubclassData with a private forwarding
811 // method so that subclasses cannot accidentally use it.
812 void setInstructionSubclassData(unsigned short D) {
813 Instruction::setInstructionSubclassData(D);
818 struct OperandTraits<AtomicRMWInst>
819 : public FixedNumOperandTraits<AtomicRMWInst,2> {
822 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
824 //===----------------------------------------------------------------------===//
825 // GetElementPtrInst Class
826 //===----------------------------------------------------------------------===//
828 // checkGEPType - Simple wrapper function to give a better assertion failure
829 // message on bad indexes for a gep instruction.
831 inline Type *checkGEPType(Type *Ty) {
832 assert(Ty && "Invalid GetElementPtrInst indices for type!");
836 /// an instruction for type-safe pointer arithmetic to
837 /// access elements of arrays and structs
839 class GetElementPtrInst : public Instruction {
840 Type *SourceElementType;
841 Type *ResultElementType;
843 GetElementPtrInst(const GetElementPtrInst &GEPI);
845 /// Constructors - Create a getelementptr instruction with a base pointer an
846 /// list of indices. The first ctor can optionally insert before an existing
847 /// instruction, the second appends the new instruction to the specified
849 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
850 ArrayRef<Value *> IdxList, unsigned Values,
851 const Twine &NameStr, Instruction *InsertBefore);
852 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
853 ArrayRef<Value *> IdxList, unsigned Values,
854 const Twine &NameStr, BasicBlock *InsertAtEnd);
856 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
859 // Note: Instruction needs to be a friend here to call cloneImpl.
860 friend class Instruction;
862 GetElementPtrInst *cloneImpl() const;
865 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
866 ArrayRef<Value *> IdxList,
867 const Twine &NameStr = "",
868 Instruction *InsertBefore = nullptr) {
869 unsigned Values = 1 + unsigned(IdxList.size());
872 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
876 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
877 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
878 NameStr, InsertBefore);
881 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
882 ArrayRef<Value *> IdxList,
883 const Twine &NameStr,
884 BasicBlock *InsertAtEnd) {
885 unsigned Values = 1 + unsigned(IdxList.size());
888 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
892 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
893 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
894 NameStr, InsertAtEnd);
897 /// Create an "inbounds" getelementptr. See the documentation for the
898 /// "inbounds" flag in LangRef.html for details.
899 static GetElementPtrInst *CreateInBounds(Value *Ptr,
900 ArrayRef<Value *> IdxList,
901 const Twine &NameStr = "",
902 Instruction *InsertBefore = nullptr){
903 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
906 static GetElementPtrInst *
907 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
908 const Twine &NameStr = "",
909 Instruction *InsertBefore = nullptr) {
910 GetElementPtrInst *GEP =
911 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
912 GEP->setIsInBounds(true);
916 static GetElementPtrInst *CreateInBounds(Value *Ptr,
917 ArrayRef<Value *> IdxList,
918 const Twine &NameStr,
919 BasicBlock *InsertAtEnd) {
920 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
923 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
924 ArrayRef<Value *> IdxList,
925 const Twine &NameStr,
926 BasicBlock *InsertAtEnd) {
927 GetElementPtrInst *GEP =
928 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
929 GEP->setIsInBounds(true);
933 /// Transparently provide more efficient getOperand methods.
934 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
936 Type *getSourceElementType() const { return SourceElementType; }
938 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
939 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
941 Type *getResultElementType() const {
942 assert(ResultElementType ==
943 cast<PointerType>(getType()->getScalarType())->getElementType());
944 return ResultElementType;
947 /// Returns the address space of this instruction's pointer type.
948 unsigned getAddressSpace() const {
949 // Note that this is always the same as the pointer operand's address space
950 // and that is cheaper to compute, so cheat here.
951 return getPointerAddressSpace();
954 /// Returns the type of the element that would be loaded with
955 /// a load instruction with the specified parameters.
957 /// Null is returned if the indices are invalid for the specified
960 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
961 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
962 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
964 inline op_iterator idx_begin() { return op_begin()+1; }
965 inline const_op_iterator idx_begin() const { return op_begin()+1; }
966 inline op_iterator idx_end() { return op_end(); }
967 inline const_op_iterator idx_end() const { return op_end(); }
969 inline iterator_range<op_iterator> indices() {
970 return make_range(idx_begin(), idx_end());
973 inline iterator_range<const_op_iterator> indices() const {
974 return make_range(idx_begin(), idx_end());
977 Value *getPointerOperand() {
978 return getOperand(0);
980 const Value *getPointerOperand() const {
981 return getOperand(0);
983 static unsigned getPointerOperandIndex() {
984 return 0U; // get index for modifying correct operand.
987 /// Method to return the pointer operand as a
989 Type *getPointerOperandType() const {
990 return getPointerOperand()->getType();
993 /// Returns the address space of the pointer operand.
994 unsigned getPointerAddressSpace() const {
995 return getPointerOperandType()->getPointerAddressSpace();
998 /// Returns the pointer type returned by the GEP
999 /// instruction, which may be a vector of pointers.
1000 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1001 return getGEPReturnType(
1002 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1005 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1006 ArrayRef<Value *> IdxList) {
1007 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1008 Ptr->getType()->getPointerAddressSpace());
1010 if (Ptr->getType()->isVectorTy()) {
1011 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1012 return VectorType::get(PtrTy, NumElem);
1014 for (Value *Index : IdxList)
1015 if (Index->getType()->isVectorTy()) {
1016 unsigned NumElem = Index->getType()->getVectorNumElements();
1017 return VectorType::get(PtrTy, NumElem);
1023 unsigned getNumIndices() const { // Note: always non-negative
1024 return getNumOperands() - 1;
1027 bool hasIndices() const {
1028 return getNumOperands() > 1;
1031 /// Return true if all of the indices of this GEP are
1032 /// zeros. If so, the result pointer and the first operand have the same
1033 /// value, just potentially different types.
1034 bool hasAllZeroIndices() const;
1036 /// Return true if all of the indices of this GEP are
1037 /// constant integers. If so, the result pointer and the first operand have
1038 /// a constant offset between them.
1039 bool hasAllConstantIndices() const;
1041 /// Set or clear the inbounds flag on this GEP instruction.
1042 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1043 void setIsInBounds(bool b = true);
1045 /// Determine whether the GEP has the inbounds flag.
1046 bool isInBounds() const;
1048 /// Accumulate the constant address offset of this GEP if possible.
1050 /// This routine accepts an APInt into which it will accumulate the constant
1051 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1052 /// all-constant, it returns false and the value of the offset APInt is
1053 /// undefined (it is *not* preserved!). The APInt passed into this routine
1054 /// must be at least as wide as the IntPtr type for the address space of
1055 /// the base GEP pointer.
1056 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1058 // Methods for support type inquiry through isa, cast, and dyn_cast:
1059 static inline bool classof(const Instruction *I) {
1060 return (I->getOpcode() == Instruction::GetElementPtr);
1062 static inline bool classof(const Value *V) {
1063 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1068 struct OperandTraits<GetElementPtrInst> :
1069 public VariadicOperandTraits<GetElementPtrInst, 1> {
1072 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1073 ArrayRef<Value *> IdxList, unsigned Values,
1074 const Twine &NameStr,
1075 Instruction *InsertBefore)
1076 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1077 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1078 Values, InsertBefore),
1079 SourceElementType(PointeeType),
1080 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1081 assert(ResultElementType ==
1082 cast<PointerType>(getType()->getScalarType())->getElementType());
1083 init(Ptr, IdxList, NameStr);
1086 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1087 ArrayRef<Value *> IdxList, unsigned Values,
1088 const Twine &NameStr,
1089 BasicBlock *InsertAtEnd)
1090 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1091 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1092 Values, InsertAtEnd),
1093 SourceElementType(PointeeType),
1094 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1095 assert(ResultElementType ==
1096 cast<PointerType>(getType()->getScalarType())->getElementType());
1097 init(Ptr, IdxList, NameStr);
1100 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1102 //===----------------------------------------------------------------------===//
1104 //===----------------------------------------------------------------------===//
1106 /// This instruction compares its operands according to the predicate given
1107 /// to the constructor. It only operates on integers or pointers. The operands
1108 /// must be identical types.
1109 /// Represent an integer comparison operator.
1110 class ICmpInst: public CmpInst {
1112 assert(getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1113 getPredicate() <= CmpInst::LAST_ICMP_PREDICATE &&
1114 "Invalid ICmp predicate value");
1115 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1116 "Both operands to ICmp instruction are not of the same type!");
1117 // Check that the operands are the right type
1118 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1119 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1120 "Invalid operand types for ICmp instruction");
1124 // Note: Instruction needs to be a friend here to call cloneImpl.
1125 friend class Instruction;
1127 /// Clone an identical ICmpInst
1128 ICmpInst *cloneImpl() const;
1131 /// Constructor with insert-before-instruction semantics.
1133 Instruction *InsertBefore, ///< Where to insert
1134 Predicate pred, ///< The predicate to use for the comparison
1135 Value *LHS, ///< The left-hand-side of the expression
1136 Value *RHS, ///< The right-hand-side of the expression
1137 const Twine &NameStr = "" ///< Name of the instruction
1138 ) : CmpInst(makeCmpResultType(LHS->getType()),
1139 Instruction::ICmp, pred, LHS, RHS, NameStr,
1146 /// Constructor with insert-at-end semantics.
1148 BasicBlock &InsertAtEnd, ///< Block to insert into.
1149 Predicate pred, ///< The predicate to use for the comparison
1150 Value *LHS, ///< The left-hand-side of the expression
1151 Value *RHS, ///< The right-hand-side of the expression
1152 const Twine &NameStr = "" ///< Name of the instruction
1153 ) : CmpInst(makeCmpResultType(LHS->getType()),
1154 Instruction::ICmp, pred, LHS, RHS, NameStr,
1161 /// Constructor with no-insertion semantics
1163 Predicate pred, ///< The predicate to use for the comparison
1164 Value *LHS, ///< The left-hand-side of the expression
1165 Value *RHS, ///< The right-hand-side of the expression
1166 const Twine &NameStr = "" ///< Name of the instruction
1167 ) : CmpInst(makeCmpResultType(LHS->getType()),
1168 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1174 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1175 /// @returns the predicate that would be the result if the operand were
1176 /// regarded as signed.
1177 /// Return the signed version of the predicate
1178 Predicate getSignedPredicate() const {
1179 return getSignedPredicate(getPredicate());
1182 /// This is a static version that you can use without an instruction.
1183 /// Return the signed version of the predicate.
1184 static Predicate getSignedPredicate(Predicate pred);
1186 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1187 /// @returns the predicate that would be the result if the operand were
1188 /// regarded as unsigned.
1189 /// Return the unsigned version of the predicate
1190 Predicate getUnsignedPredicate() const {
1191 return getUnsignedPredicate(getPredicate());
1194 /// This is a static version that you can use without an instruction.
1195 /// Return the unsigned version of the predicate.
1196 static Predicate getUnsignedPredicate(Predicate pred);
1198 /// Return true if this predicate is either EQ or NE. This also
1199 /// tests for commutativity.
1200 static bool isEquality(Predicate P) {
1201 return P == ICMP_EQ || P == ICMP_NE;
1204 /// Return true if this predicate is either EQ or NE. This also
1205 /// tests for commutativity.
1206 bool isEquality() const {
1207 return isEquality(getPredicate());
1210 /// @returns true if the predicate of this ICmpInst is commutative
1211 /// Determine if this relation is commutative.
1212 bool isCommutative() const { return isEquality(); }
1214 /// Return true if the predicate is relational (not EQ or NE).
1216 bool isRelational() const {
1217 return !isEquality();
1220 /// Return true if the predicate is relational (not EQ or NE).
1222 static bool isRelational(Predicate P) {
1223 return !isEquality(P);
1226 /// Exchange the two operands to this instruction in such a way that it does
1227 /// not modify the semantics of the instruction. The predicate value may be
1228 /// changed to retain the same result if the predicate is order dependent
1230 /// Swap operands and adjust predicate.
1231 void swapOperands() {
1232 setPredicate(getSwappedPredicate());
1233 Op<0>().swap(Op<1>());
1236 // Methods for support type inquiry through isa, cast, and dyn_cast:
1237 static inline bool classof(const Instruction *I) {
1238 return I->getOpcode() == Instruction::ICmp;
1240 static inline bool classof(const Value *V) {
1241 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1245 //===----------------------------------------------------------------------===//
1247 //===----------------------------------------------------------------------===//
1249 /// This instruction compares its operands according to the predicate given
1250 /// to the constructor. It only operates on floating point values or packed
1251 /// vectors of floating point values. The operands must be identical types.
1252 /// Represents a floating point comparison operator.
1253 class FCmpInst: public CmpInst {
1255 // Note: Instruction needs to be a friend here to call cloneImpl.
1256 friend class Instruction;
1258 /// Clone an identical FCmpInst
1259 FCmpInst *cloneImpl() const;
1262 /// Constructor with insert-before-instruction semantics.
1264 Instruction *InsertBefore, ///< Where to insert
1265 Predicate pred, ///< The predicate to use for the comparison
1266 Value *LHS, ///< The left-hand-side of the expression
1267 Value *RHS, ///< The right-hand-side of the expression
1268 const Twine &NameStr = "" ///< Name of the instruction
1269 ) : CmpInst(makeCmpResultType(LHS->getType()),
1270 Instruction::FCmp, pred, LHS, RHS, NameStr,
1272 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1273 "Invalid FCmp predicate value");
1274 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1275 "Both operands to FCmp instruction are not of the same type!");
1276 // Check that the operands are the right type
1277 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1278 "Invalid operand types for FCmp instruction");
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,
1291 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1292 "Invalid FCmp predicate value");
1293 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1294 "Both operands to FCmp instruction are not of the same type!");
1295 // Check that the operands are the right type
1296 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1297 "Invalid operand types for FCmp instruction");
1300 /// Constructor with no-insertion semantics
1302 Predicate pred, ///< The predicate to use for the comparison
1303 Value *LHS, ///< The left-hand-side of the expression
1304 Value *RHS, ///< The right-hand-side of the expression
1305 const Twine &NameStr = "" ///< Name of the instruction
1306 ) : CmpInst(makeCmpResultType(LHS->getType()),
1307 Instruction::FCmp, pred, LHS, RHS, NameStr) {
1308 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1309 "Invalid FCmp predicate value");
1310 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1311 "Both operands to FCmp instruction are not of the same type!");
1312 // Check that the operands are the right type
1313 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1314 "Invalid operand types for FCmp instruction");
1317 /// @returns true if the predicate of this instruction is EQ or NE.
1318 /// Determine if this is an equality predicate.
1319 static bool isEquality(Predicate Pred) {
1320 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1324 /// @returns true if the predicate of this instruction is EQ or NE.
1325 /// Determine if this is an equality predicate.
1326 bool isEquality() const { return isEquality(getPredicate()); }
1328 /// @returns true if the predicate of this instruction is commutative.
1329 /// Determine if this is a commutative predicate.
1330 bool isCommutative() const {
1331 return isEquality() ||
1332 getPredicate() == FCMP_FALSE ||
1333 getPredicate() == FCMP_TRUE ||
1334 getPredicate() == FCMP_ORD ||
1335 getPredicate() == FCMP_UNO;
1338 /// @returns true if the predicate is relational (not EQ or NE).
1339 /// Determine if this a relational predicate.
1340 bool isRelational() const { return !isEquality(); }
1342 /// Exchange the two operands to this instruction in such a way that it does
1343 /// not modify the semantics of the instruction. The predicate value may be
1344 /// changed to retain the same result if the predicate is order dependent
1346 /// Swap operands and adjust predicate.
1347 void swapOperands() {
1348 setPredicate(getSwappedPredicate());
1349 Op<0>().swap(Op<1>());
1352 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1353 static inline bool classof(const Instruction *I) {
1354 return I->getOpcode() == Instruction::FCmp;
1356 static inline bool classof(const Value *V) {
1357 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1361 //===----------------------------------------------------------------------===//
1362 /// This class represents a function call, abstracting a target
1363 /// machine's calling convention. This class uses low bit of the SubClassData
1364 /// field to indicate whether or not this is a tail call. The rest of the bits
1365 /// hold the calling convention of the call.
1367 class CallInst : public Instruction,
1368 public OperandBundleUser<CallInst, User::op_iterator> {
1369 friend class OperandBundleUser<CallInst, User::op_iterator>;
1371 AttributeList Attrs; ///< parameter attributes for call
1374 CallInst(const CallInst &CI);
1376 /// Construct a CallInst given a range of arguments.
1377 /// Construct a CallInst from a range of arguments
1378 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1379 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1380 Instruction *InsertBefore);
1382 inline CallInst(Value *Func, ArrayRef<Value *> Args,
1383 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1384 Instruction *InsertBefore)
1385 : CallInst(cast<FunctionType>(
1386 cast<PointerType>(Func->getType())->getElementType()),
1387 Func, Args, Bundles, NameStr, InsertBefore) {}
1389 inline CallInst(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr,
1390 Instruction *InsertBefore)
1391 : CallInst(Func, Args, None, NameStr, InsertBefore) {}
1393 /// Construct a CallInst given a range of arguments.
1394 /// Construct a CallInst from a range of arguments
1395 inline CallInst(Value *Func, ArrayRef<Value *> Args,
1396 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1397 BasicBlock *InsertAtEnd);
1399 explicit CallInst(Value *F, const Twine &NameStr,
1400 Instruction *InsertBefore);
1402 CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1404 void init(Value *Func, ArrayRef<Value *> Args,
1405 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
1406 init(cast<FunctionType>(
1407 cast<PointerType>(Func->getType())->getElementType()),
1408 Func, Args, Bundles, NameStr);
1410 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1411 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1412 void init(Value *Func, const Twine &NameStr);
1414 bool hasDescriptor() const { return HasDescriptor; }
1417 // Note: Instruction needs to be a friend here to call cloneImpl.
1418 friend class Instruction;
1420 CallInst *cloneImpl() const;
1423 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1424 ArrayRef<OperandBundleDef> Bundles = None,
1425 const Twine &NameStr = "",
1426 Instruction *InsertBefore = nullptr) {
1427 return Create(cast<FunctionType>(
1428 cast<PointerType>(Func->getType())->getElementType()),
1429 Func, Args, Bundles, NameStr, InsertBefore);
1432 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1433 const Twine &NameStr,
1434 Instruction *InsertBefore = nullptr) {
1435 return Create(cast<FunctionType>(
1436 cast<PointerType>(Func->getType())->getElementType()),
1437 Func, Args, None, NameStr, InsertBefore);
1440 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1441 const Twine &NameStr,
1442 Instruction *InsertBefore = nullptr) {
1443 return new (unsigned(Args.size() + 1))
1444 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1447 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1448 ArrayRef<OperandBundleDef> Bundles = None,
1449 const Twine &NameStr = "",
1450 Instruction *InsertBefore = nullptr) {
1451 const unsigned TotalOps =
1452 unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1453 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1455 return new (TotalOps, DescriptorBytes)
1456 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1459 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1460 ArrayRef<OperandBundleDef> Bundles,
1461 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1462 const unsigned TotalOps =
1463 unsigned(Args.size()) + CountBundleInputs(Bundles) + 1;
1464 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1466 return new (TotalOps, DescriptorBytes)
1467 CallInst(Func, Args, Bundles, NameStr, InsertAtEnd);
1470 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1471 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1472 return new (unsigned(Args.size() + 1))
1473 CallInst(Func, Args, None, NameStr, InsertAtEnd);
1476 static CallInst *Create(Value *F, const Twine &NameStr = "",
1477 Instruction *InsertBefore = nullptr) {
1478 return new(1) CallInst(F, NameStr, InsertBefore);
1481 static CallInst *Create(Value *F, const Twine &NameStr,
1482 BasicBlock *InsertAtEnd) {
1483 return new(1) CallInst(F, NameStr, InsertAtEnd);
1486 /// Create a clone of \p CI with a different set of operand bundles and
1487 /// insert it before \p InsertPt.
1489 /// The returned call instruction is identical \p CI in every way except that
1490 /// the operand bundles for the new instruction are set to the operand bundles
1492 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1493 Instruction *InsertPt = nullptr);
1495 /// Generate the IR for a call to malloc:
1496 /// 1. Compute the malloc call's argument as the specified type's size,
1497 /// possibly multiplied by the array size if the array size is not
1499 /// 2. Call malloc with that argument.
1500 /// 3. Bitcast the result of the malloc call to the specified type.
1501 static Instruction *CreateMalloc(Instruction *InsertBefore,
1502 Type *IntPtrTy, Type *AllocTy,
1503 Value *AllocSize, Value *ArraySize = nullptr,
1504 Function* MallocF = nullptr,
1505 const Twine &Name = "");
1506 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1507 Type *IntPtrTy, Type *AllocTy,
1508 Value *AllocSize, Value *ArraySize = nullptr,
1509 Function* MallocF = nullptr,
1510 const Twine &Name = "");
1511 static Instruction *CreateMalloc(Instruction *InsertBefore,
1512 Type *IntPtrTy, Type *AllocTy,
1513 Value *AllocSize, Value *ArraySize = nullptr,
1514 ArrayRef<OperandBundleDef> Bundles = None,
1515 Function* MallocF = nullptr,
1516 const Twine &Name = "");
1517 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1518 Type *IntPtrTy, Type *AllocTy,
1519 Value *AllocSize, Value *ArraySize = nullptr,
1520 ArrayRef<OperandBundleDef> Bundles = None,
1521 Function* MallocF = nullptr,
1522 const Twine &Name = "");
1523 /// Generate the IR for a call to the builtin free function.
1524 static Instruction *CreateFree(Value *Source,
1525 Instruction *InsertBefore);
1526 static Instruction *CreateFree(Value *Source,
1527 BasicBlock *InsertAtEnd);
1528 static Instruction *CreateFree(Value *Source,
1529 ArrayRef<OperandBundleDef> Bundles,
1530 Instruction *InsertBefore);
1531 static Instruction *CreateFree(Value *Source,
1532 ArrayRef<OperandBundleDef> Bundles,
1533 BasicBlock *InsertAtEnd);
1535 FunctionType *getFunctionType() const { return FTy; }
1537 void mutateFunctionType(FunctionType *FTy) {
1538 mutateType(FTy->getReturnType());
1542 // Note that 'musttail' implies 'tail'.
1543 enum TailCallKind { TCK_None = 0, TCK_Tail = 1, TCK_MustTail = 2,
1545 TailCallKind getTailCallKind() const {
1546 return TailCallKind(getSubclassDataFromInstruction() & 3);
1549 bool isTailCall() const {
1550 unsigned Kind = getSubclassDataFromInstruction() & 3;
1551 return Kind == TCK_Tail || Kind == TCK_MustTail;
1554 bool isMustTailCall() const {
1555 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1558 bool isNoTailCall() const {
1559 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1562 void setTailCall(bool isTC = true) {
1563 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1564 unsigned(isTC ? TCK_Tail : TCK_None));
1567 void setTailCallKind(TailCallKind TCK) {
1568 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1572 /// Provide fast operand accessors
1573 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1575 /// Return the number of call arguments.
1577 unsigned getNumArgOperands() const {
1578 return getNumOperands() - getNumTotalBundleOperands() - 1;
1581 /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1583 Value *getArgOperand(unsigned i) const {
1584 assert(i < getNumArgOperands() && "Out of bounds!");
1585 return getOperand(i);
1587 void setArgOperand(unsigned i, Value *v) {
1588 assert(i < getNumArgOperands() && "Out of bounds!");
1592 /// Return the iterator pointing to the beginning of the argument list.
1593 op_iterator arg_begin() { return op_begin(); }
1595 /// Return the iterator pointing to the end of the argument list.
1596 op_iterator arg_end() {
1597 // [ call args ], [ operand bundles ], callee
1598 return op_end() - getNumTotalBundleOperands() - 1;
1601 /// Iteration adapter for range-for loops.
1602 iterator_range<op_iterator> arg_operands() {
1603 return make_range(arg_begin(), arg_end());
1606 /// Return the iterator pointing to the beginning of the argument list.
1607 const_op_iterator arg_begin() const { return op_begin(); }
1609 /// Return the iterator pointing to the end of the argument list.
1610 const_op_iterator arg_end() const {
1611 // [ call args ], [ operand bundles ], callee
1612 return op_end() - getNumTotalBundleOperands() - 1;
1615 /// Iteration adapter for range-for loops.
1616 iterator_range<const_op_iterator> arg_operands() const {
1617 return make_range(arg_begin(), arg_end());
1620 /// Wrappers for getting the \c Use of a call argument.
1621 const Use &getArgOperandUse(unsigned i) const {
1622 assert(i < getNumArgOperands() && "Out of bounds!");
1623 return getOperandUse(i);
1625 Use &getArgOperandUse(unsigned i) {
1626 assert(i < getNumArgOperands() && "Out of bounds!");
1627 return getOperandUse(i);
1630 /// If one of the arguments has the 'returned' attribute, return its
1631 /// operand value. Otherwise, return nullptr.
1632 Value *getReturnedArgOperand() const;
1634 /// getCallingConv/setCallingConv - Get or set the calling convention of this
1636 CallingConv::ID getCallingConv() const {
1637 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 2);
1639 void setCallingConv(CallingConv::ID CC) {
1640 auto ID = static_cast<unsigned>(CC);
1641 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
1642 setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
1646 /// Return the parameter attributes for this call.
1648 AttributeList getAttributes() const { return Attrs; }
1650 /// Set the parameter attributes for this call.
1652 void setAttributes(AttributeList A) { Attrs = A; }
1654 /// adds the attribute to the list of attributes.
1655 void addAttribute(unsigned i, Attribute::AttrKind Kind);
1657 /// adds the attribute to the list of attributes.
1658 void addAttribute(unsigned i, Attribute Attr);
1660 /// Adds the attribute to the indicated argument
1661 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1663 /// Adds the attribute to the indicated argument
1664 void addParamAttr(unsigned ArgNo, Attribute Attr);
1666 /// removes the attribute from the list of attributes.
1667 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
1669 /// removes the attribute from the list of attributes.
1670 void removeAttribute(unsigned i, StringRef Kind);
1672 /// Removes the attribute from the given argument
1673 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
1675 /// Removes the attribute from the given argument
1676 void removeParamAttr(unsigned ArgNo, StringRef Kind);
1678 /// adds the dereferenceable attribute to the list of attributes.
1679 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
1681 /// adds the dereferenceable_or_null attribute to the list of
1683 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
1685 /// Determine whether this call has the given attribute.
1686 bool hasFnAttr(Attribute::AttrKind Kind) const {
1687 assert(Kind != Attribute::NoBuiltin &&
1688 "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
1689 return hasFnAttrImpl(Kind);
1692 /// Determine whether this call has the given attribute.
1693 bool hasFnAttr(StringRef Kind) const {
1694 return hasFnAttrImpl(Kind);
1697 /// Determine whether the return value has the given attribute.
1698 bool hasRetAttr(Attribute::AttrKind Kind) const;
1700 /// Determine whether the argument or parameter has the given attribute.
1701 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1703 /// Get the attribute of a given kind at a position.
1704 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
1705 return getAttributes().getAttribute(i, Kind);
1708 /// Get the attribute of a given kind at a position.
1709 Attribute getAttribute(unsigned i, StringRef Kind) const {
1710 return getAttributes().getAttribute(i, Kind);
1713 /// Get the attribute of a given kind from a given arg
1714 Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1715 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1716 return getAttributes().getParamAttr(ArgNo, Kind);
1719 /// Get the attribute of a given kind from a given arg
1720 Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1721 assert(ArgNo < getNumArgOperands() && "Out of bounds");
1722 return getAttributes().getParamAttr(ArgNo, Kind);
1725 /// Return true if the data operand at index \p i has the attribute \p
1728 /// Data operands include call arguments and values used in operand bundles,
1729 /// but does not include the callee operand. This routine dispatches to the
1730 /// underlying AttributeList or the OperandBundleUser as appropriate.
1732 /// The index \p i is interpreted as
1734 /// \p i == Attribute::ReturnIndex -> the return value
1735 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
1736 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
1737 /// (\p i - 1) in the operand list.
1738 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
1740 /// Extract the alignment of the return value.
1741 unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
1743 /// Extract the alignment for a call or parameter (0=unknown).
1744 unsigned getParamAlignment(unsigned ArgNo) const {
1745 return Attrs.getParamAlignment(ArgNo);
1748 /// Extract the number of dereferenceable bytes for a call or
1749 /// parameter (0=unknown).
1750 uint64_t getDereferenceableBytes(unsigned i) const {
1751 return Attrs.getDereferenceableBytes(i);
1754 /// Extract the number of dereferenceable_or_null bytes for a call or
1755 /// parameter (0=unknown).
1756 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
1757 return Attrs.getDereferenceableOrNullBytes(i);
1760 /// @brief Determine if the return value is marked with NoAlias attribute.
1761 bool returnDoesNotAlias() const {
1762 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1765 /// Return true if the call should not be treated as a call to a
1767 bool isNoBuiltin() const {
1768 return hasFnAttrImpl(Attribute::NoBuiltin) &&
1769 !hasFnAttrImpl(Attribute::Builtin);
1772 /// Return true if the call should not be inlined.
1773 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1774 void setIsNoInline() {
1775 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1778 /// Return true if the call can return twice
1779 bool canReturnTwice() const {
1780 return hasFnAttr(Attribute::ReturnsTwice);
1782 void setCanReturnTwice() {
1783 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1786 /// Determine if the call does not access memory.
1787 bool doesNotAccessMemory() const {
1788 return hasFnAttr(Attribute::ReadNone);
1790 void setDoesNotAccessMemory() {
1791 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
1794 /// Determine if the call does not access or only reads memory.
1795 bool onlyReadsMemory() const {
1796 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
1798 void setOnlyReadsMemory() {
1799 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
1802 /// Determine if the call does not access or only writes memory.
1803 bool doesNotReadMemory() const {
1804 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
1806 void setDoesNotReadMemory() {
1807 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
1810 /// @brief Determine if the call can access memmory only using pointers based
1811 /// on its arguments.
1812 bool onlyAccessesArgMemory() const {
1813 return hasFnAttr(Attribute::ArgMemOnly);
1815 void setOnlyAccessesArgMemory() {
1816 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
1819 /// Determine if the call cannot return.
1820 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1821 void setDoesNotReturn() {
1822 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
1825 /// Determine if the call cannot unwind.
1826 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1827 void setDoesNotThrow() {
1828 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
1831 /// Determine if the call cannot be duplicated.
1832 bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
1833 void setCannotDuplicate() {
1834 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
1837 /// Determine if the call is convergent
1838 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1839 void setConvergent() {
1840 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1842 void setNotConvergent() {
1843 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
1846 /// Determine if the call returns a structure through first
1847 /// pointer argument.
1848 bool hasStructRetAttr() const {
1849 if (getNumArgOperands() == 0)
1852 // Be friendly and also check the callee.
1853 return paramHasAttr(0, Attribute::StructRet);
1856 /// Determine if any call argument is an aggregate passed by value.
1857 bool hasByValArgument() const {
1858 return Attrs.hasAttrSomewhere(Attribute::ByVal);
1861 /// Return the function called, or null if this is an
1862 /// indirect function invocation.
1864 Function *getCalledFunction() const {
1865 return dyn_cast<Function>(Op<-1>());
1868 /// Get a pointer to the function that is invoked by this
1870 const Value *getCalledValue() const { return Op<-1>(); }
1871 Value *getCalledValue() { return Op<-1>(); }
1873 /// Set the function called.
1874 void setCalledFunction(Value* Fn) {
1876 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
1879 void setCalledFunction(FunctionType *FTy, Value *Fn) {
1881 assert(FTy == cast<FunctionType>(
1882 cast<PointerType>(Fn->getType())->getElementType()));
1886 /// Check if this call is an inline asm statement.
1887 bool isInlineAsm() const {
1888 return isa<InlineAsm>(Op<-1>());
1891 // Methods for support type inquiry through isa, cast, and dyn_cast:
1892 static inline bool classof(const Instruction *I) {
1893 return I->getOpcode() == Instruction::Call;
1895 static inline bool classof(const Value *V) {
1896 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1900 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
1901 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
1904 // Operand bundles override attributes on the called function, but don't
1905 // override attributes directly present on the call instruction.
1906 if (isFnAttrDisallowedByOpBundle(Kind))
1909 if (const Function *F = getCalledFunction())
1910 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
1915 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1916 // method so that subclasses cannot accidentally use it.
1917 void setInstructionSubclassData(unsigned short D) {
1918 Instruction::setInstructionSubclassData(D);
1923 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1926 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1927 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1928 BasicBlock *InsertAtEnd)
1930 cast<FunctionType>(cast<PointerType>(Func->getType())
1931 ->getElementType())->getReturnType(),
1932 Instruction::Call, OperandTraits<CallInst>::op_end(this) -
1933 (Args.size() + CountBundleInputs(Bundles) + 1),
1934 unsigned(Args.size() + CountBundleInputs(Bundles) + 1), InsertAtEnd) {
1935 init(Func, Args, Bundles, NameStr);
1938 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1939 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1940 Instruction *InsertBefore)
1941 : Instruction(Ty->getReturnType(), Instruction::Call,
1942 OperandTraits<CallInst>::op_end(this) -
1943 (Args.size() + CountBundleInputs(Bundles) + 1),
1944 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1946 init(Ty, Func, Args, Bundles, NameStr);
1949 // Note: if you get compile errors about private methods then
1950 // please update your code to use the high-level operand
1951 // interfaces. See line 943 above.
1952 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1954 //===----------------------------------------------------------------------===//
1956 //===----------------------------------------------------------------------===//
1958 /// This class represents the LLVM 'select' instruction.
1960 class SelectInst : public Instruction {
1961 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1962 Instruction *InsertBefore)
1963 : Instruction(S1->getType(), Instruction::Select,
1964 &Op<0>(), 3, InsertBefore) {
1969 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1970 BasicBlock *InsertAtEnd)
1971 : Instruction(S1->getType(), Instruction::Select,
1972 &Op<0>(), 3, InsertAtEnd) {
1977 void init(Value *C, Value *S1, Value *S2) {
1978 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1985 // Note: Instruction needs to be a friend here to call cloneImpl.
1986 friend class Instruction;
1988 SelectInst *cloneImpl() const;
1991 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1992 const Twine &NameStr = "",
1993 Instruction *InsertBefore = nullptr,
1994 Instruction *MDFrom = nullptr) {
1995 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1997 Sel->copyMetadata(*MDFrom);
2001 static SelectInst *Create(Value *C, Value *S1, Value *S2,
2002 const Twine &NameStr,
2003 BasicBlock *InsertAtEnd) {
2004 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
2007 const Value *getCondition() const { return Op<0>(); }
2008 const Value *getTrueValue() const { return Op<1>(); }
2009 const Value *getFalseValue() const { return Op<2>(); }
2010 Value *getCondition() { return Op<0>(); }
2011 Value *getTrueValue() { return Op<1>(); }
2012 Value *getFalseValue() { return Op<2>(); }
2014 void setCondition(Value *V) { Op<0>() = V; }
2015 void setTrueValue(Value *V) { Op<1>() = V; }
2016 void setFalseValue(Value *V) { Op<2>() = V; }
2018 /// Return a string if the specified operands are invalid
2019 /// for a select operation, otherwise return null.
2020 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
2022 /// Transparently provide more efficient getOperand methods.
2023 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2025 OtherOps getOpcode() const {
2026 return static_cast<OtherOps>(Instruction::getOpcode());
2029 // Methods for support type inquiry through isa, cast, and dyn_cast:
2030 static inline bool classof(const Instruction *I) {
2031 return I->getOpcode() == Instruction::Select;
2033 static inline bool classof(const Value *V) {
2034 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2039 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
2042 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
2044 //===----------------------------------------------------------------------===//
2046 //===----------------------------------------------------------------------===//
2048 /// This class represents the va_arg llvm instruction, which returns
2049 /// an argument of the specified type given a va_list and increments that list
2051 class VAArgInst : public UnaryInstruction {
2053 // Note: Instruction needs to be a friend here to call cloneImpl.
2054 friend class Instruction;
2056 VAArgInst *cloneImpl() const;
2059 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
2060 Instruction *InsertBefore = nullptr)
2061 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
2065 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
2066 BasicBlock *InsertAtEnd)
2067 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
2071 Value *getPointerOperand() { return getOperand(0); }
2072 const Value *getPointerOperand() const { return getOperand(0); }
2073 static unsigned getPointerOperandIndex() { return 0U; }
2075 // Methods for support type inquiry through isa, cast, and dyn_cast:
2076 static inline bool classof(const Instruction *I) {
2077 return I->getOpcode() == VAArg;
2079 static inline bool classof(const Value *V) {
2080 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2084 //===----------------------------------------------------------------------===//
2085 // ExtractElementInst Class
2086 //===----------------------------------------------------------------------===//
2088 /// This instruction extracts a single (scalar)
2089 /// element from a VectorType value
2091 class ExtractElementInst : public Instruction {
2092 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
2093 Instruction *InsertBefore = nullptr);
2094 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
2095 BasicBlock *InsertAtEnd);
2098 // Note: Instruction needs to be a friend here to call cloneImpl.
2099 friend class Instruction;
2101 ExtractElementInst *cloneImpl() const;
2104 static ExtractElementInst *Create(Value *Vec, Value *Idx,
2105 const Twine &NameStr = "",
2106 Instruction *InsertBefore = nullptr) {
2107 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
2110 static ExtractElementInst *Create(Value *Vec, Value *Idx,
2111 const Twine &NameStr,
2112 BasicBlock *InsertAtEnd) {
2113 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
2116 /// Return true if an extractelement instruction can be
2117 /// formed with the specified operands.
2118 static bool isValidOperands(const Value *Vec, const Value *Idx);
2120 Value *getVectorOperand() { return Op<0>(); }
2121 Value *getIndexOperand() { return Op<1>(); }
2122 const Value *getVectorOperand() const { return Op<0>(); }
2123 const Value *getIndexOperand() const { return Op<1>(); }
2125 VectorType *getVectorOperandType() const {
2126 return cast<VectorType>(getVectorOperand()->getType());
2129 /// Transparently provide more efficient getOperand methods.
2130 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2132 // Methods for support type inquiry through isa, cast, and dyn_cast:
2133 static inline bool classof(const Instruction *I) {
2134 return I->getOpcode() == Instruction::ExtractElement;
2136 static inline bool classof(const Value *V) {
2137 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2142 struct OperandTraits<ExtractElementInst> :
2143 public FixedNumOperandTraits<ExtractElementInst, 2> {
2146 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
2148 //===----------------------------------------------------------------------===//
2149 // InsertElementInst Class
2150 //===----------------------------------------------------------------------===//
2152 /// This instruction inserts a single (scalar)
2153 /// element into a VectorType value
2155 class InsertElementInst : public Instruction {
2156 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
2157 const Twine &NameStr = "",
2158 Instruction *InsertBefore = nullptr);
2159 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
2160 BasicBlock *InsertAtEnd);
2163 // Note: Instruction needs to be a friend here to call cloneImpl.
2164 friend class Instruction;
2166 InsertElementInst *cloneImpl() const;
2169 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2170 const Twine &NameStr = "",
2171 Instruction *InsertBefore = nullptr) {
2172 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
2175 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
2176 const Twine &NameStr,
2177 BasicBlock *InsertAtEnd) {
2178 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
2181 /// Return true if an insertelement instruction can be
2182 /// formed with the specified operands.
2183 static bool isValidOperands(const Value *Vec, const Value *NewElt,
2186 /// Overload to return most specific vector type.
2188 VectorType *getType() const {
2189 return cast<VectorType>(Instruction::getType());
2192 /// Transparently provide more efficient getOperand methods.
2193 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2195 // Methods for support type inquiry through isa, cast, and dyn_cast:
2196 static inline bool classof(const Instruction *I) {
2197 return I->getOpcode() == Instruction::InsertElement;
2199 static inline bool classof(const Value *V) {
2200 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2205 struct OperandTraits<InsertElementInst> :
2206 public FixedNumOperandTraits<InsertElementInst, 3> {
2209 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
2211 //===----------------------------------------------------------------------===//
2212 // ShuffleVectorInst Class
2213 //===----------------------------------------------------------------------===//
2215 /// This instruction constructs a fixed permutation of two
2218 class ShuffleVectorInst : public Instruction {
2220 // Note: Instruction needs to be a friend here to call cloneImpl.
2221 friend class Instruction;
2223 ShuffleVectorInst *cloneImpl() const;
2226 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2227 const Twine &NameStr = "",
2228 Instruction *InsertBefor = nullptr);
2229 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2230 const Twine &NameStr, BasicBlock *InsertAtEnd);
2232 // allocate space for exactly three operands
2233 void *operator new(size_t s) {
2234 return User::operator new(s, 3);
2237 /// Return true if a shufflevector instruction can be
2238 /// formed with the specified operands.
2239 static bool isValidOperands(const Value *V1, const Value *V2,
2242 /// Overload to return most specific vector type.
2244 VectorType *getType() const {
2245 return cast<VectorType>(Instruction::getType());
2248 /// Transparently provide more efficient getOperand methods.
2249 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2251 Constant *getMask() const {
2252 return cast<Constant>(getOperand(2));
2255 /// Return the shuffle mask value for the specified element of the mask.
2256 /// Return -1 if the element is undef.
2257 static int getMaskValue(Constant *Mask, unsigned Elt);
2259 /// Return the shuffle mask value of this instruction for the given element
2260 /// index. Return -1 if the element is undef.
2261 int getMaskValue(unsigned Elt) const {
2262 return getMaskValue(getMask(), Elt);
2265 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2266 /// elements of the mask are returned as -1.
2267 static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
2269 /// Return the mask for this instruction as a vector of integers. Undefined
2270 /// elements of the mask are returned as -1.
2271 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2272 return getShuffleMask(getMask(), Result);
2275 SmallVector<int, 16> getShuffleMask() const {
2276 SmallVector<int, 16> Mask;
2277 getShuffleMask(Mask);
2281 /// Change values in a shuffle permute mask assuming the two vector operands
2282 /// of length InVecNumElts have swapped position.
2283 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2284 unsigned InVecNumElts) {
2285 for (int &Idx : Mask) {
2288 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2289 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2290 "shufflevector mask index out of range");
2294 // Methods for support type inquiry through isa, cast, and dyn_cast:
2295 static inline bool classof(const Instruction *I) {
2296 return I->getOpcode() == Instruction::ShuffleVector;
2298 static inline bool classof(const Value *V) {
2299 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2304 struct OperandTraits<ShuffleVectorInst> :
2305 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2308 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2310 //===----------------------------------------------------------------------===//
2311 // ExtractValueInst Class
2312 //===----------------------------------------------------------------------===//
2314 /// This instruction extracts a struct member or array
2315 /// element value from an aggregate value.
2317 class ExtractValueInst : public UnaryInstruction {
2318 SmallVector<unsigned, 4> Indices;
2320 ExtractValueInst(const ExtractValueInst &EVI);
2322 /// Constructors - Create a extractvalue instruction with a base aggregate
2323 /// value and a list of indices. The first ctor can optionally insert before
2324 /// an existing instruction, the second appends the new instruction to the
2325 /// specified BasicBlock.
2326 inline ExtractValueInst(Value *Agg,
2327 ArrayRef<unsigned> Idxs,
2328 const Twine &NameStr,
2329 Instruction *InsertBefore);
2330 inline ExtractValueInst(Value *Agg,
2331 ArrayRef<unsigned> Idxs,
2332 const Twine &NameStr, BasicBlock *InsertAtEnd);
2334 // allocate space for exactly one operand
2335 void *operator new(size_t s) { return User::operator new(s, 1); }
2337 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2340 // Note: Instruction needs to be a friend here to call cloneImpl.
2341 friend class Instruction;
2343 ExtractValueInst *cloneImpl() const;
2346 static ExtractValueInst *Create(Value *Agg,
2347 ArrayRef<unsigned> Idxs,
2348 const Twine &NameStr = "",
2349 Instruction *InsertBefore = nullptr) {
2351 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2354 static ExtractValueInst *Create(Value *Agg,
2355 ArrayRef<unsigned> Idxs,
2356 const Twine &NameStr,
2357 BasicBlock *InsertAtEnd) {
2358 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2361 /// Returns the type of the element that would be extracted
2362 /// with an extractvalue instruction with the specified parameters.
2364 /// Null is returned if the indices are invalid for the specified type.
2365 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2367 using idx_iterator = const unsigned*;
2369 inline idx_iterator idx_begin() const { return Indices.begin(); }
2370 inline idx_iterator idx_end() const { return Indices.end(); }
2371 inline iterator_range<idx_iterator> indices() const {
2372 return make_range(idx_begin(), idx_end());
2375 Value *getAggregateOperand() {
2376 return getOperand(0);
2378 const Value *getAggregateOperand() const {
2379 return getOperand(0);
2381 static unsigned getAggregateOperandIndex() {
2382 return 0U; // get index for modifying correct operand
2385 ArrayRef<unsigned> getIndices() const {
2389 unsigned getNumIndices() const {
2390 return (unsigned)Indices.size();
2393 bool hasIndices() const {
2397 // Methods for support type inquiry through isa, cast, and dyn_cast:
2398 static inline bool classof(const Instruction *I) {
2399 return I->getOpcode() == Instruction::ExtractValue;
2401 static inline bool classof(const Value *V) {
2402 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2406 ExtractValueInst::ExtractValueInst(Value *Agg,
2407 ArrayRef<unsigned> Idxs,
2408 const Twine &NameStr,
2409 Instruction *InsertBefore)
2410 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2411 ExtractValue, Agg, InsertBefore) {
2412 init(Idxs, NameStr);
2415 ExtractValueInst::ExtractValueInst(Value *Agg,
2416 ArrayRef<unsigned> Idxs,
2417 const Twine &NameStr,
2418 BasicBlock *InsertAtEnd)
2419 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2420 ExtractValue, Agg, InsertAtEnd) {
2421 init(Idxs, NameStr);
2424 //===----------------------------------------------------------------------===//
2425 // InsertValueInst Class
2426 //===----------------------------------------------------------------------===//
2428 /// This instruction inserts a struct field of array element
2429 /// value into an aggregate value.
2431 class InsertValueInst : public Instruction {
2432 SmallVector<unsigned, 4> Indices;
2434 InsertValueInst(const InsertValueInst &IVI);
2436 /// Constructors - Create a insertvalue instruction with a base aggregate
2437 /// value, a value to insert, and a list of indices. The first ctor can
2438 /// optionally insert before an existing instruction, the second appends
2439 /// the new instruction to the specified BasicBlock.
2440 inline InsertValueInst(Value *Agg, Value *Val,
2441 ArrayRef<unsigned> Idxs,
2442 const Twine &NameStr,
2443 Instruction *InsertBefore);
2444 inline InsertValueInst(Value *Agg, Value *Val,
2445 ArrayRef<unsigned> Idxs,
2446 const Twine &NameStr, BasicBlock *InsertAtEnd);
2448 /// Constructors - These two constructors are convenience methods because one
2449 /// and two index insertvalue instructions are so common.
2450 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2451 const Twine &NameStr = "",
2452 Instruction *InsertBefore = nullptr);
2453 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2454 BasicBlock *InsertAtEnd);
2456 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2457 const Twine &NameStr);
2460 // Note: Instruction needs to be a friend here to call cloneImpl.
2461 friend class Instruction;
2463 InsertValueInst *cloneImpl() const;
2466 // allocate space for exactly two operands
2467 void *operator new(size_t s) {
2468 return User::operator new(s, 2);
2471 void *operator new(size_t, unsigned) = delete;
2473 static InsertValueInst *Create(Value *Agg, Value *Val,
2474 ArrayRef<unsigned> Idxs,
2475 const Twine &NameStr = "",
2476 Instruction *InsertBefore = nullptr) {
2477 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2480 static InsertValueInst *Create(Value *Agg, Value *Val,
2481 ArrayRef<unsigned> Idxs,
2482 const Twine &NameStr,
2483 BasicBlock *InsertAtEnd) {
2484 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2487 /// Transparently provide more efficient getOperand methods.
2488 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2490 using idx_iterator = const unsigned*;
2492 inline idx_iterator idx_begin() const { return Indices.begin(); }
2493 inline idx_iterator idx_end() const { return Indices.end(); }
2494 inline iterator_range<idx_iterator> indices() const {
2495 return make_range(idx_begin(), idx_end());
2498 Value *getAggregateOperand() {
2499 return getOperand(0);
2501 const Value *getAggregateOperand() const {
2502 return getOperand(0);
2504 static unsigned getAggregateOperandIndex() {
2505 return 0U; // get index for modifying correct operand
2508 Value *getInsertedValueOperand() {
2509 return getOperand(1);
2511 const Value *getInsertedValueOperand() const {
2512 return getOperand(1);
2514 static unsigned getInsertedValueOperandIndex() {
2515 return 1U; // get index for modifying correct operand
2518 ArrayRef<unsigned> getIndices() const {
2522 unsigned getNumIndices() const {
2523 return (unsigned)Indices.size();
2526 bool hasIndices() const {
2530 // Methods for support type inquiry through isa, cast, and dyn_cast:
2531 static inline bool classof(const Instruction *I) {
2532 return I->getOpcode() == Instruction::InsertValue;
2534 static inline bool classof(const Value *V) {
2535 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2540 struct OperandTraits<InsertValueInst> :
2541 public FixedNumOperandTraits<InsertValueInst, 2> {
2544 InsertValueInst::InsertValueInst(Value *Agg,
2546 ArrayRef<unsigned> Idxs,
2547 const Twine &NameStr,
2548 Instruction *InsertBefore)
2549 : Instruction(Agg->getType(), InsertValue,
2550 OperandTraits<InsertValueInst>::op_begin(this),
2552 init(Agg, Val, Idxs, NameStr);
2555 InsertValueInst::InsertValueInst(Value *Agg,
2557 ArrayRef<unsigned> Idxs,
2558 const Twine &NameStr,
2559 BasicBlock *InsertAtEnd)
2560 : Instruction(Agg->getType(), InsertValue,
2561 OperandTraits<InsertValueInst>::op_begin(this),
2563 init(Agg, Val, Idxs, NameStr);
2566 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2568 //===----------------------------------------------------------------------===//
2570 //===----------------------------------------------------------------------===//
2572 // PHINode - The PHINode class is used to represent the magical mystical PHI
2573 // node, that can not exist in nature, but can be synthesized in a computer
2574 // scientist's overactive imagination.
2576 class PHINode : public Instruction {
2577 /// The number of operands actually allocated. NumOperands is
2578 /// the number actually in use.
2579 unsigned ReservedSpace;
2581 PHINode(const PHINode &PN);
2582 // allocate space for exactly zero operands
2584 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2585 const Twine &NameStr = "",
2586 Instruction *InsertBefore = nullptr)
2587 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2588 ReservedSpace(NumReservedValues) {
2590 allocHungoffUses(ReservedSpace);
2593 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2594 BasicBlock *InsertAtEnd)
2595 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2596 ReservedSpace(NumReservedValues) {
2598 allocHungoffUses(ReservedSpace);
2601 void *operator new(size_t s) {
2602 return User::operator new(s);
2606 // Note: Instruction needs to be a friend here to call cloneImpl.
2607 friend class Instruction;
2609 PHINode *cloneImpl() const;
2611 // allocHungoffUses - this is more complicated than the generic
2612 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2613 // values and pointers to the incoming blocks, all in one allocation.
2614 void allocHungoffUses(unsigned N) {
2615 User::allocHungoffUses(N, /* IsPhi */ true);
2619 void *operator new(size_t, unsigned) = delete;
2621 /// Constructors - NumReservedValues is a hint for the number of incoming
2622 /// edges that this phi node will have (use 0 if you really have no idea).
2623 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2624 const Twine &NameStr = "",
2625 Instruction *InsertBefore = nullptr) {
2626 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2629 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2630 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2631 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2634 /// Provide fast operand accessors
2635 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2637 // Block iterator interface. This provides access to the list of incoming
2638 // basic blocks, which parallels the list of incoming values.
2640 using block_iterator = BasicBlock **;
2641 using const_block_iterator = BasicBlock * const *;
2643 block_iterator block_begin() {
2645 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2646 return reinterpret_cast<block_iterator>(ref + 1);
2649 const_block_iterator block_begin() const {
2650 const Use::UserRef *ref =
2651 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2652 return reinterpret_cast<const_block_iterator>(ref + 1);
2655 block_iterator block_end() {
2656 return block_begin() + getNumOperands();
2659 const_block_iterator block_end() const {
2660 return block_begin() + getNumOperands();
2663 iterator_range<block_iterator> blocks() {
2664 return make_range(block_begin(), block_end());
2667 iterator_range<const_block_iterator> blocks() const {
2668 return make_range(block_begin(), block_end());
2671 op_range incoming_values() { return operands(); }
2673 const_op_range incoming_values() const { return operands(); }
2675 /// Return the number of incoming edges
2677 unsigned getNumIncomingValues() const { return getNumOperands(); }
2679 /// Return incoming value number x
2681 Value *getIncomingValue(unsigned i) const {
2682 return getOperand(i);
2684 void setIncomingValue(unsigned i, Value *V) {
2685 assert(V && "PHI node got a null value!");
2686 assert(getType() == V->getType() &&
2687 "All operands to PHI node must be the same type as the PHI node!");
2691 static unsigned getOperandNumForIncomingValue(unsigned i) {
2695 static unsigned getIncomingValueNumForOperand(unsigned i) {
2699 /// Return incoming basic block number @p i.
2701 BasicBlock *getIncomingBlock(unsigned i) const {
2702 return block_begin()[i];
2705 /// Return incoming basic block corresponding
2706 /// to an operand of the PHI.
2708 BasicBlock *getIncomingBlock(const Use &U) const {
2709 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2710 return getIncomingBlock(unsigned(&U - op_begin()));
2713 /// Return incoming basic block corresponding
2714 /// to value use iterator.
2716 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2717 return getIncomingBlock(I.getUse());
2720 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2721 assert(BB && "PHI node got a null basic block!");
2722 block_begin()[i] = BB;
2725 /// Add an incoming value to the end of the PHI list
2727 void addIncoming(Value *V, BasicBlock *BB) {
2728 if (getNumOperands() == ReservedSpace)
2729 growOperands(); // Get more space!
2730 // Initialize some new operands.
2731 setNumHungOffUseOperands(getNumOperands() + 1);
2732 setIncomingValue(getNumOperands() - 1, V);
2733 setIncomingBlock(getNumOperands() - 1, BB);
2736 /// Remove an incoming value. This is useful if a
2737 /// predecessor basic block is deleted. The value removed is returned.
2739 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2740 /// is true), the PHI node is destroyed and any uses of it are replaced with
2741 /// dummy values. The only time there should be zero incoming values to a PHI
2742 /// node is when the block is dead, so this strategy is sound.
2744 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2746 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2747 int Idx = getBasicBlockIndex(BB);
2748 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2749 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2752 /// Return the first index of the specified basic
2753 /// block in the value list for this PHI. Returns -1 if no instance.
2755 int getBasicBlockIndex(const BasicBlock *BB) const {
2756 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2757 if (block_begin()[i] == BB)
2762 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2763 int Idx = getBasicBlockIndex(BB);
2764 assert(Idx >= 0 && "Invalid basic block argument!");
2765 return getIncomingValue(Idx);
2768 /// If the specified PHI node always merges together the
2769 /// same value, return the value, otherwise return null.
2770 Value *hasConstantValue() const;
2772 /// Whether the specified PHI node always merges
2773 /// together the same value, assuming undefs are equal to a unique
2774 /// non-undef value.
2775 bool hasConstantOrUndefValue() const;
2777 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2778 static inline bool classof(const Instruction *I) {
2779 return I->getOpcode() == Instruction::PHI;
2781 static inline bool classof(const Value *V) {
2782 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2786 void growOperands();
2790 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2793 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2795 //===----------------------------------------------------------------------===//
2796 // LandingPadInst Class
2797 //===----------------------------------------------------------------------===//
2799 //===---------------------------------------------------------------------------
2800 /// The landingpad instruction holds all of the information
2801 /// necessary to generate correct exception handling. The landingpad instruction
2802 /// cannot be moved from the top of a landing pad block, which itself is
2803 /// accessible only from the 'unwind' edge of an invoke. This uses the
2804 /// SubclassData field in Value to store whether or not the landingpad is a
2807 class LandingPadInst : public Instruction {
2808 /// The number of operands actually allocated. NumOperands is
2809 /// the number actually in use.
2810 unsigned ReservedSpace;
2812 LandingPadInst(const LandingPadInst &LP);
2815 enum ClauseType { Catch, Filter };
2818 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2819 const Twine &NameStr, Instruction *InsertBefore);
2820 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2821 const Twine &NameStr, BasicBlock *InsertAtEnd);
2823 // Allocate space for exactly zero operands.
2824 void *operator new(size_t s) {
2825 return User::operator new(s);
2828 void growOperands(unsigned Size);
2829 void init(unsigned NumReservedValues, const Twine &NameStr);
2832 // Note: Instruction needs to be a friend here to call cloneImpl.
2833 friend class Instruction;
2835 LandingPadInst *cloneImpl() const;
2838 void *operator new(size_t, unsigned) = delete;
2840 /// Constructors - NumReservedClauses is a hint for the number of incoming
2841 /// clauses that this landingpad will have (use 0 if you really have no idea).
2842 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2843 const Twine &NameStr = "",
2844 Instruction *InsertBefore = nullptr);
2845 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2846 const Twine &NameStr, BasicBlock *InsertAtEnd);
2848 /// Provide fast operand accessors
2849 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2851 /// Return 'true' if this landingpad instruction is a
2852 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2853 /// doesn't catch the exception.
2854 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2856 /// Indicate that this landingpad instruction is a cleanup.
2857 void setCleanup(bool V) {
2858 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2862 /// Add a catch or filter clause to the landing pad.
2863 void addClause(Constant *ClauseVal);
2865 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2866 /// determine what type of clause this is.
2867 Constant *getClause(unsigned Idx) const {
2868 return cast<Constant>(getOperandList()[Idx]);
2871 /// Return 'true' if the clause and index Idx is a catch clause.
2872 bool isCatch(unsigned Idx) const {
2873 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2876 /// Return 'true' if the clause and index Idx is a filter clause.
2877 bool isFilter(unsigned Idx) const {
2878 return isa<ArrayType>(getOperandList()[Idx]->getType());
2881 /// Get the number of clauses for this landing pad.
2882 unsigned getNumClauses() const { return getNumOperands(); }
2884 /// Grow the size of the operand list to accommodate the new
2885 /// number of clauses.
2886 void reserveClauses(unsigned Size) { growOperands(Size); }
2888 // Methods for support type inquiry through isa, cast, and dyn_cast:
2889 static inline bool classof(const Instruction *I) {
2890 return I->getOpcode() == Instruction::LandingPad;
2892 static inline bool classof(const Value *V) {
2893 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2898 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2901 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2903 //===----------------------------------------------------------------------===//
2905 //===----------------------------------------------------------------------===//
2907 //===---------------------------------------------------------------------------
2908 /// Return a value (possibly void), from a function. Execution
2909 /// does not continue in this function any longer.
2911 class ReturnInst : public TerminatorInst {
2912 ReturnInst(const ReturnInst &RI);
2915 // ReturnInst constructors:
2916 // ReturnInst() - 'ret void' instruction
2917 // ReturnInst( null) - 'ret void' instruction
2918 // ReturnInst(Value* X) - 'ret X' instruction
2919 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2920 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2921 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2922 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2924 // NOTE: If the Value* passed is of type void then the constructor behaves as
2925 // if it was passed NULL.
2926 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2927 Instruction *InsertBefore = nullptr);
2928 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2929 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2932 // Note: Instruction needs to be a friend here to call cloneImpl.
2933 friend class Instruction;
2935 ReturnInst *cloneImpl() const;
2938 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2939 Instruction *InsertBefore = nullptr) {
2940 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2943 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2944 BasicBlock *InsertAtEnd) {
2945 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2948 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2949 return new(0) ReturnInst(C, InsertAtEnd);
2952 /// Provide fast operand accessors
2953 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2955 /// Convenience accessor. Returns null if there is no return value.
2956 Value *getReturnValue() const {
2957 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2960 unsigned getNumSuccessors() const { return 0; }
2962 // Methods for support type inquiry through isa, cast, and dyn_cast:
2963 static inline bool classof(const Instruction *I) {
2964 return (I->getOpcode() == Instruction::Ret);
2966 static inline bool classof(const Value *V) {
2967 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2971 friend TerminatorInst;
2973 BasicBlock *getSuccessorV(unsigned idx) const;
2974 unsigned getNumSuccessorsV() const;
2975 void setSuccessorV(unsigned idx, BasicBlock *B);
2979 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2982 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2984 //===----------------------------------------------------------------------===//
2986 //===----------------------------------------------------------------------===//
2988 //===---------------------------------------------------------------------------
2989 /// Conditional or Unconditional Branch instruction.
2991 class BranchInst : public TerminatorInst {
2992 /// Ops list - Branches are strange. The operands are ordered:
2993 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2994 /// they don't have to check for cond/uncond branchness. These are mostly
2995 /// accessed relative from op_end().
2996 BranchInst(const BranchInst &BI);
2997 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2998 // BranchInst(BB *B) - 'br B'
2999 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
3000 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
3001 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3002 // BranchInst(BB* B, BB *I) - 'br B' insert at end
3003 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
3004 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3005 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3006 Instruction *InsertBefore = nullptr);
3007 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3008 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3009 BasicBlock *InsertAtEnd);
3014 // Note: Instruction needs to be a friend here to call cloneImpl.
3015 friend class Instruction;
3017 BranchInst *cloneImpl() const;
3020 static BranchInst *Create(BasicBlock *IfTrue,
3021 Instruction *InsertBefore = nullptr) {
3022 return new(1) BranchInst(IfTrue, InsertBefore);
3025 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3026 Value *Cond, Instruction *InsertBefore = nullptr) {
3027 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3030 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3031 return new(1) BranchInst(IfTrue, InsertAtEnd);
3034 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3035 Value *Cond, BasicBlock *InsertAtEnd) {
3036 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3039 /// Transparently provide more efficient getOperand methods.
3040 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3042 bool isUnconditional() const { return getNumOperands() == 1; }
3043 bool isConditional() const { return getNumOperands() == 3; }
3045 Value *getCondition() const {
3046 assert(isConditional() && "Cannot get condition of an uncond branch!");
3050 void setCondition(Value *V) {
3051 assert(isConditional() && "Cannot set condition of unconditional branch!");
3055 unsigned getNumSuccessors() const { return 1+isConditional(); }
3057 BasicBlock *getSuccessor(unsigned i) const {
3058 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3059 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3062 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3063 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3064 *(&Op<-1>() - idx) = NewSucc;
3067 /// Swap the successors of this branch instruction.
3069 /// Swaps the successors of the branch instruction. This also swaps any
3070 /// branch weight metadata associated with the instruction so that it
3071 /// continues to map correctly to each operand.
3072 void swapSuccessors();
3074 // Methods for support type inquiry through isa, cast, and dyn_cast:
3075 static inline bool classof(const Instruction *I) {
3076 return (I->getOpcode() == Instruction::Br);
3078 static inline bool classof(const Value *V) {
3079 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3083 friend TerminatorInst;
3085 BasicBlock *getSuccessorV(unsigned idx) const;
3086 unsigned getNumSuccessorsV() const;
3087 void setSuccessorV(unsigned idx, BasicBlock *B);
3091 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3094 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3096 //===----------------------------------------------------------------------===//
3098 //===----------------------------------------------------------------------===//
3100 //===---------------------------------------------------------------------------
3103 class SwitchInst : public TerminatorInst {
3104 unsigned ReservedSpace;
3106 // Operand[0] = Value to switch on
3107 // Operand[1] = Default basic block destination
3108 // Operand[2n ] = Value to match
3109 // Operand[2n+1] = BasicBlock to go to on match
3110 SwitchInst(const SwitchInst &SI);
3112 /// Create a new switch instruction, specifying a value to switch on and a
3113 /// default destination. The number of additional cases can be specified here
3114 /// to make memory allocation more efficient. This constructor can also
3115 /// auto-insert before another instruction.
3116 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3117 Instruction *InsertBefore);
3119 /// Create a new switch instruction, specifying a value to switch on and a
3120 /// default destination. The number of additional cases can be specified here
3121 /// to make memory allocation more efficient. This constructor also
3122 /// auto-inserts at the end of the specified BasicBlock.
3123 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3124 BasicBlock *InsertAtEnd);
3126 // allocate space for exactly zero operands
3127 void *operator new(size_t s) {
3128 return User::operator new(s);
3131 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3132 void growOperands();
3135 // Note: Instruction needs to be a friend here to call cloneImpl.
3136 friend class Instruction;
3138 SwitchInst *cloneImpl() const;
3141 void *operator new(size_t, unsigned) = delete;
3144 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3146 template <typename CaseHandleT> class CaseIteratorImpl;
3148 /// A handle to a particular switch case. It exposes a convenient interface
3149 /// to both the case value and the successor block.
3151 /// We define this as a template and instantiate it to form both a const and
3152 /// non-const handle.
3153 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3154 class CaseHandleImpl {
3155 // Directly befriend both const and non-const iterators.
3156 friend class SwitchInst::CaseIteratorImpl<
3157 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3160 // Expose the switch type we're parameterized with to the iterator.
3161 using SwitchInstType = SwitchInstT;
3166 CaseHandleImpl() = default;
3167 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3170 /// Resolves case value for current case.
3171 ConstantIntT *getCaseValue() const {
3172 assert((unsigned)Index < SI->getNumCases() &&
3173 "Index out the number of cases.");
3174 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3177 /// Resolves successor for current case.
3178 BasicBlockT *getCaseSuccessor() const {
3179 assert(((unsigned)Index < SI->getNumCases() ||
3180 (unsigned)Index == DefaultPseudoIndex) &&
3181 "Index out the number of cases.");
3182 return SI->getSuccessor(getSuccessorIndex());
3185 /// Returns number of current case.
3186 unsigned getCaseIndex() const { return Index; }
3188 /// Returns TerminatorInst's successor index for current case successor.
3189 unsigned getSuccessorIndex() const {
3190 assert(((unsigned)Index == DefaultPseudoIndex ||
3191 (unsigned)Index < SI->getNumCases()) &&
3192 "Index out the number of cases.");
3193 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3196 bool operator==(const CaseHandleImpl &RHS) const {
3197 assert(SI == RHS.SI && "Incompatible operators.");
3198 return Index == RHS.Index;
3202 using ConstCaseHandle =
3203 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3206 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3207 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3210 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3212 /// Sets the new value for current case.
3213 void setValue(ConstantInt *V) {
3214 assert((unsigned)Index < SI->getNumCases() &&
3215 "Index out the number of cases.");
3216 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3219 /// Sets the new successor for current case.
3220 void setSuccessor(BasicBlock *S) {
3221 SI->setSuccessor(getSuccessorIndex(), S);
3225 template <typename CaseHandleT>
3226 class CaseIteratorImpl
3227 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3228 std::random_access_iterator_tag,
3230 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3235 /// Default constructed iterator is in an invalid state until assigned to
3236 /// a case for a particular switch.
3237 CaseIteratorImpl() = default;
3239 /// Initializes case iterator for given SwitchInst and for given
3241 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3243 /// Initializes case iterator for given SwitchInst and for given
3244 /// TerminatorInst's successor index.
3245 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3246 unsigned SuccessorIndex) {
3247 assert(SuccessorIndex < SI->getNumSuccessors() &&
3248 "Successor index # out of range!");
3249 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3250 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3253 /// Support converting to the const variant. This will be a no-op for const
3255 operator CaseIteratorImpl<ConstCaseHandle>() const {
3256 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3259 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3260 // Check index correctness after addition.
3261 // Note: Index == getNumCases() means end().
3262 assert(Case.Index + N >= 0 &&
3263 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3264 "Case.Index out the number of cases.");
3268 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3269 // Check index correctness after subtraction.
3270 // Note: Case.Index == getNumCases() means end().
3271 assert(Case.Index - N >= 0 &&
3272 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3273 "Case.Index out the number of cases.");
3277 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3278 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3279 return Case.Index - RHS.Case.Index;
3281 bool operator==(const CaseIteratorImpl &RHS) const {
3282 return Case == RHS.Case;
3284 bool operator<(const CaseIteratorImpl &RHS) const {
3285 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3286 return Case.Index < RHS.Case.Index;
3288 CaseHandleT &operator*() { return Case; }
3289 const CaseHandleT &operator*() const { return Case; }
3292 using CaseIt = CaseIteratorImpl<CaseHandle>;
3293 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3295 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3297 Instruction *InsertBefore = nullptr) {
3298 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3301 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3302 unsigned NumCases, BasicBlock *InsertAtEnd) {
3303 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3306 /// Provide fast operand accessors
3307 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3309 // Accessor Methods for Switch stmt
3310 Value *getCondition() const { return getOperand(0); }
3311 void setCondition(Value *V) { setOperand(0, V); }
3313 BasicBlock *getDefaultDest() const {
3314 return cast<BasicBlock>(getOperand(1));
3317 void setDefaultDest(BasicBlock *DefaultCase) {
3318 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3321 /// Return the number of 'cases' in this switch instruction, excluding the
3323 unsigned getNumCases() const {
3324 return getNumOperands()/2 - 1;
3327 /// Returns a read/write iterator that points to the first case in the
3329 CaseIt case_begin() {
3330 return CaseIt(this, 0);
3333 /// Returns a read-only iterator that points to the first case in the
3335 ConstCaseIt case_begin() const {
3336 return ConstCaseIt(this, 0);
3339 /// Returns a read/write iterator that points one past the last in the
3342 return CaseIt(this, getNumCases());
3345 /// Returns a read-only iterator that points one past the last in the
3347 ConstCaseIt case_end() const {
3348 return ConstCaseIt(this, getNumCases());
3351 /// Iteration adapter for range-for loops.
3352 iterator_range<CaseIt> cases() {
3353 return make_range(case_begin(), case_end());
3356 /// Constant iteration adapter for range-for loops.
3357 iterator_range<ConstCaseIt> cases() const {
3358 return make_range(case_begin(), case_end());
3361 /// Returns an iterator that points to the default case.
3362 /// Note: this iterator allows to resolve successor only. Attempt
3363 /// to resolve case value causes an assertion.
3364 /// Also note, that increment and decrement also causes an assertion and
3365 /// makes iterator invalid.
3366 CaseIt case_default() {
3367 return CaseIt(this, DefaultPseudoIndex);
3369 ConstCaseIt case_default() const {
3370 return ConstCaseIt(this, DefaultPseudoIndex);
3373 /// Search all of the case values for the specified constant. If it is
3374 /// explicitly handled, return the case iterator of it, otherwise return
3375 /// default case iterator to indicate that it is handled by the default
3377 CaseIt findCaseValue(const ConstantInt *C) {
3378 CaseIt I = llvm::find_if(
3379 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3380 if (I != case_end())
3383 return case_default();
3385 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3386 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3387 return Case.getCaseValue() == C;
3389 if (I != case_end())
3392 return case_default();
3395 /// Finds the unique case value for a given successor. Returns null if the
3396 /// successor is not found, not unique, or is the default case.
3397 ConstantInt *findCaseDest(BasicBlock *BB) {
3398 if (BB == getDefaultDest())
3401 ConstantInt *CI = nullptr;
3402 for (auto Case : cases()) {
3403 if (Case.getCaseSuccessor() != BB)
3407 return nullptr; // Multiple cases lead to BB.
3409 CI = Case.getCaseValue();
3415 /// Add an entry to the switch instruction.
3417 /// This action invalidates case_end(). Old case_end() iterator will
3418 /// point to the added case.
3419 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3421 /// This method removes the specified case and its successor from the switch
3422 /// instruction. Note that this operation may reorder the remaining cases at
3423 /// index idx and above.
3425 /// This action invalidates iterators for all cases following the one removed,
3426 /// including the case_end() iterator. It returns an iterator for the next
3428 CaseIt removeCase(CaseIt I);
3430 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3431 BasicBlock *getSuccessor(unsigned idx) const {
3432 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3433 return cast<BasicBlock>(getOperand(idx*2+1));
3435 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3436 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3437 setOperand(idx * 2 + 1, NewSucc);
3440 // Methods for support type inquiry through isa, cast, and dyn_cast:
3441 static inline bool classof(const Instruction *I) {
3442 return I->getOpcode() == Instruction::Switch;
3444 static inline bool classof(const Value *V) {
3445 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3449 friend TerminatorInst;
3451 BasicBlock *getSuccessorV(unsigned idx) const;
3452 unsigned getNumSuccessorsV() const;
3453 void setSuccessorV(unsigned idx, BasicBlock *B);
3457 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3460 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3462 //===----------------------------------------------------------------------===//
3463 // IndirectBrInst Class
3464 //===----------------------------------------------------------------------===//
3466 //===---------------------------------------------------------------------------
3467 /// Indirect Branch Instruction.
3469 class IndirectBrInst : public TerminatorInst {
3470 unsigned ReservedSpace;
3472 // Operand[0] = Address to jump to
3473 // Operand[n+1] = n-th destination
3474 IndirectBrInst(const IndirectBrInst &IBI);
3476 /// Create a new indirectbr instruction, specifying an
3477 /// Address to jump to. The number of expected destinations can be specified
3478 /// here to make memory allocation more efficient. This constructor can also
3479 /// autoinsert before another instruction.
3480 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3482 /// Create a new indirectbr instruction, specifying an
3483 /// Address to jump to. The number of expected destinations can be specified
3484 /// here to make memory allocation more efficient. This constructor also
3485 /// autoinserts at the end of the specified BasicBlock.
3486 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3488 // allocate space for exactly zero operands
3489 void *operator new(size_t s) {
3490 return User::operator new(s);
3493 void init(Value *Address, unsigned NumDests);
3494 void growOperands();
3497 // Note: Instruction needs to be a friend here to call cloneImpl.
3498 friend class Instruction;
3500 IndirectBrInst *cloneImpl() const;
3503 void *operator new(size_t, unsigned) = delete;
3505 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3506 Instruction *InsertBefore = nullptr) {
3507 return new IndirectBrInst(Address, NumDests, InsertBefore);
3510 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3511 BasicBlock *InsertAtEnd) {
3512 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3515 /// Provide fast operand accessors.
3516 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3518 // Accessor Methods for IndirectBrInst instruction.
3519 Value *getAddress() { return getOperand(0); }
3520 const Value *getAddress() const { return getOperand(0); }
3521 void setAddress(Value *V) { setOperand(0, V); }
3523 /// return the number of possible destinations in this
3524 /// indirectbr instruction.
3525 unsigned getNumDestinations() const { return getNumOperands()-1; }
3527 /// Return the specified destination.
3528 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3529 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3531 /// Add a destination.
3533 void addDestination(BasicBlock *Dest);
3535 /// This method removes the specified successor from the
3536 /// indirectbr instruction.
3537 void removeDestination(unsigned i);
3539 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3540 BasicBlock *getSuccessor(unsigned i) const {
3541 return cast<BasicBlock>(getOperand(i+1));
3543 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3544 setOperand(i + 1, NewSucc);
3547 // Methods for support type inquiry through isa, cast, and dyn_cast:
3548 static inline bool classof(const Instruction *I) {
3549 return I->getOpcode() == Instruction::IndirectBr;
3551 static inline bool classof(const Value *V) {
3552 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3556 friend TerminatorInst;
3558 BasicBlock *getSuccessorV(unsigned idx) const;
3559 unsigned getNumSuccessorsV() const;
3560 void setSuccessorV(unsigned idx, BasicBlock *B);
3564 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3567 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3569 //===----------------------------------------------------------------------===//
3571 //===----------------------------------------------------------------------===//
3573 /// Invoke instruction. The SubclassData field is used to hold the
3574 /// calling convention of the call.
3576 class InvokeInst : public TerminatorInst,
3577 public OperandBundleUser<InvokeInst, User::op_iterator> {
3578 friend class OperandBundleUser<InvokeInst, User::op_iterator>;
3580 AttributeList Attrs;
3583 InvokeInst(const InvokeInst &BI);
3585 /// Construct an InvokeInst given a range of arguments.
3587 /// Construct an InvokeInst from a range of arguments
3588 inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3589 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3590 unsigned Values, const Twine &NameStr,
3591 Instruction *InsertBefore)
3592 : InvokeInst(cast<FunctionType>(
3593 cast<PointerType>(Func->getType())->getElementType()),
3594 Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3597 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3598 BasicBlock *IfException, ArrayRef<Value *> Args,
3599 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
3600 const Twine &NameStr, Instruction *InsertBefore);
3601 /// Construct an InvokeInst given a range of arguments.
3603 /// Construct an InvokeInst from a range of arguments
3604 inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3605 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3606 unsigned Values, const Twine &NameStr,
3607 BasicBlock *InsertAtEnd);
3609 bool hasDescriptor() const { return HasDescriptor; }
3611 void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
3612 ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles,
3613 const Twine &NameStr) {
3614 init(cast<FunctionType>(
3615 cast<PointerType>(Func->getType())->getElementType()),
3616 Func, IfNormal, IfException, Args, Bundles, NameStr);
3619 void init(FunctionType *FTy, Value *Func, BasicBlock *IfNormal,
3620 BasicBlock *IfException, ArrayRef<Value *> Args,
3621 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3624 // Note: Instruction needs to be a friend here to call cloneImpl.
3625 friend class Instruction;
3627 InvokeInst *cloneImpl() const;
3630 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3631 BasicBlock *IfException, ArrayRef<Value *> Args,
3632 const Twine &NameStr,
3633 Instruction *InsertBefore = nullptr) {
3634 return Create(cast<FunctionType>(
3635 cast<PointerType>(Func->getType())->getElementType()),
3636 Func, IfNormal, IfException, Args, None, NameStr,
3640 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3641 BasicBlock *IfException, ArrayRef<Value *> Args,
3642 ArrayRef<OperandBundleDef> Bundles = None,
3643 const Twine &NameStr = "",
3644 Instruction *InsertBefore = nullptr) {
3645 return Create(cast<FunctionType>(
3646 cast<PointerType>(Func->getType())->getElementType()),
3647 Func, IfNormal, IfException, Args, Bundles, NameStr,
3651 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3652 BasicBlock *IfException, ArrayRef<Value *> Args,
3653 const Twine &NameStr,
3654 Instruction *InsertBefore = nullptr) {
3655 unsigned Values = unsigned(Args.size()) + 3;
3656 return new (Values) InvokeInst(Ty, Func, IfNormal, IfException, Args, None,
3657 Values, NameStr, InsertBefore);
3660 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3661 BasicBlock *IfException, ArrayRef<Value *> Args,
3662 ArrayRef<OperandBundleDef> Bundles = None,
3663 const Twine &NameStr = "",
3664 Instruction *InsertBefore = nullptr) {
3665 unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3666 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3668 return new (Values, DescriptorBytes)
3669 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, Values,
3670 NameStr, InsertBefore);
3673 static InvokeInst *Create(Value *Func,
3674 BasicBlock *IfNormal, BasicBlock *IfException,
3675 ArrayRef<Value *> Args, const Twine &NameStr,
3676 BasicBlock *InsertAtEnd) {
3677 unsigned Values = unsigned(Args.size()) + 3;
3678 return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None,
3679 Values, NameStr, InsertAtEnd);
3682 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3683 BasicBlock *IfException, ArrayRef<Value *> Args,
3684 ArrayRef<OperandBundleDef> Bundles,
3685 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3686 unsigned Values = unsigned(Args.size()) + CountBundleInputs(Bundles) + 3;
3687 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3689 return new (Values, DescriptorBytes)
3690 InvokeInst(Func, IfNormal, IfException, Args, Bundles, Values, NameStr,
3694 /// Create a clone of \p II with a different set of operand bundles and
3695 /// insert it before \p InsertPt.
3697 /// The returned invoke instruction is identical to \p II in every way except
3698 /// that the operand bundles for the new instruction are set to the operand
3699 /// bundles in \p Bundles.
3700 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3701 Instruction *InsertPt = nullptr);
3703 /// Provide fast operand accessors
3704 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3706 FunctionType *getFunctionType() const { return FTy; }
3708 void mutateFunctionType(FunctionType *FTy) {
3709 mutateType(FTy->getReturnType());
3713 /// Return the number of invoke arguments.
3715 unsigned getNumArgOperands() const {
3716 return getNumOperands() - getNumTotalBundleOperands() - 3;
3719 /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3721 Value *getArgOperand(unsigned i) const {
3722 assert(i < getNumArgOperands() && "Out of bounds!");
3723 return getOperand(i);
3725 void setArgOperand(unsigned i, Value *v) {
3726 assert(i < getNumArgOperands() && "Out of bounds!");
3730 /// Return the iterator pointing to the beginning of the argument list.
3731 op_iterator arg_begin() { return op_begin(); }
3733 /// Return the iterator pointing to the end of the argument list.
3734 op_iterator arg_end() {
3735 // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3736 return op_end() - getNumTotalBundleOperands() - 3;
3739 /// Iteration adapter for range-for loops.
3740 iterator_range<op_iterator> arg_operands() {
3741 return make_range(arg_begin(), arg_end());
3744 /// Return the iterator pointing to the beginning of the argument list.
3745 const_op_iterator arg_begin() const { return op_begin(); }
3747 /// Return the iterator pointing to the end of the argument list.
3748 const_op_iterator arg_end() const {
3749 // [ invoke args ], [ operand bundles ], normal dest, unwind dest, callee
3750 return op_end() - getNumTotalBundleOperands() - 3;
3753 /// Iteration adapter for range-for loops.
3754 iterator_range<const_op_iterator> arg_operands() const {
3755 return make_range(arg_begin(), arg_end());
3758 /// Wrappers for getting the \c Use of a invoke argument.
3759 const Use &getArgOperandUse(unsigned i) const {
3760 assert(i < getNumArgOperands() && "Out of bounds!");
3761 return getOperandUse(i);
3763 Use &getArgOperandUse(unsigned i) {
3764 assert(i < getNumArgOperands() && "Out of bounds!");
3765 return getOperandUse(i);
3768 /// If one of the arguments has the 'returned' attribute, return its
3769 /// operand value. Otherwise, return nullptr.
3770 Value *getReturnedArgOperand() const;
3772 /// getCallingConv/setCallingConv - Get or set the calling convention of this
3774 CallingConv::ID getCallingConv() const {
3775 return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3777 void setCallingConv(CallingConv::ID CC) {
3778 auto ID = static_cast<unsigned>(CC);
3779 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
3780 setInstructionSubclassData(ID);
3783 /// Return the parameter attributes for this invoke.
3785 AttributeList getAttributes() const { return Attrs; }
3787 /// Set the parameter attributes for this invoke.
3789 void setAttributes(AttributeList A) { Attrs = A; }
3791 /// adds the attribute to the list of attributes.
3792 void addAttribute(unsigned i, Attribute::AttrKind Kind);
3794 /// adds the attribute to the list of attributes.
3795 void addAttribute(unsigned i, Attribute Attr);
3797 /// Adds the attribute to the indicated argument
3798 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3800 /// removes the attribute from the list of attributes.
3801 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
3803 /// removes the attribute from the list of attributes.
3804 void removeAttribute(unsigned i, StringRef Kind);
3806 /// Removes the attribute from the given argument
3807 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
3809 /// adds the dereferenceable attribute to the list of attributes.
3810 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
3812 /// adds the dereferenceable_or_null attribute to the list of
3814 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
3816 /// Determine whether this call has the given attribute.
3817 bool hasFnAttr(Attribute::AttrKind Kind) const {
3818 assert(Kind != Attribute::NoBuiltin &&
3819 "Use CallInst::isNoBuiltin() to check for Attribute::NoBuiltin");
3820 return hasFnAttrImpl(Kind);
3823 /// Determine whether this call has the given attribute.
3824 bool hasFnAttr(StringRef Kind) const {
3825 return hasFnAttrImpl(Kind);
3828 /// Determine whether the return value has the given attribute.
3829 bool hasRetAttr(Attribute::AttrKind Kind) const;
3831 /// Determine whether the argument or parameter has the given attribute.
3832 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
3834 /// Get the attribute of a given kind at a position.
3835 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
3836 return getAttributes().getAttribute(i, Kind);
3839 /// Get the attribute of a given kind at a position.
3840 Attribute getAttribute(unsigned i, StringRef Kind) const {
3841 return getAttributes().getAttribute(i, Kind);
3844 /// Return true if the data operand at index \p i has the attribute \p
3847 /// Data operands include invoke arguments and values used in operand bundles,
3848 /// but does not include the invokee operand, or the two successor blocks.
3849 /// This routine dispatches to the underlying AttributeList or the
3850 /// OperandBundleUser as appropriate.
3852 /// The index \p i is interpreted as
3854 /// \p i == Attribute::ReturnIndex -> the return value
3855 /// \p i in [1, arg_size + 1) -> argument number (\p i - 1)
3856 /// \p i in [arg_size + 1, data_operand_size + 1) -> bundle operand at index
3857 /// (\p i - 1) in the operand list.
3858 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const;
3860 /// Extract the alignment of the return value.
3861 unsigned getRetAlignment() const { return Attrs.getRetAlignment(); }
3863 /// Extract the alignment for a call or parameter (0=unknown).
3864 unsigned getParamAlignment(unsigned ArgNo) const {
3865 return Attrs.getParamAlignment(ArgNo);
3868 /// Extract the number of dereferenceable bytes for a call or
3869 /// parameter (0=unknown).
3870 uint64_t getDereferenceableBytes(unsigned i) const {
3871 return Attrs.getDereferenceableBytes(i);
3874 /// Extract the number of dereferenceable_or_null bytes for a call or
3875 /// parameter (0=unknown).
3876 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
3877 return Attrs.getDereferenceableOrNullBytes(i);
3880 /// @brief Determine if the return value is marked with NoAlias attribute.
3881 bool returnDoesNotAlias() const {
3882 return Attrs.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
3885 /// Return true if the call should not be treated as a call to a
3887 bool isNoBuiltin() const {
3888 // We assert in hasFnAttr if one passes in Attribute::NoBuiltin, so we have
3889 // to check it by hand.
3890 return hasFnAttrImpl(Attribute::NoBuiltin) &&
3891 !hasFnAttrImpl(Attribute::Builtin);
3894 /// Return true if the call should not be inlined.
3895 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
3896 void setIsNoInline() {
3897 addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
3900 /// Determine if the call does not access memory.
3901 bool doesNotAccessMemory() const {
3902 return hasFnAttr(Attribute::ReadNone);
3904 void setDoesNotAccessMemory() {
3905 addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
3908 /// Determine if the call does not access or only reads memory.
3909 bool onlyReadsMemory() const {
3910 return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
3912 void setOnlyReadsMemory() {
3913 addAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);
3916 /// Determine if the call does not access or only writes memory.
3917 bool doesNotReadMemory() const {
3918 return doesNotAccessMemory() || hasFnAttr(Attribute::WriteOnly);
3920 void setDoesNotReadMemory() {
3921 addAttribute(AttributeList::FunctionIndex, Attribute::WriteOnly);
3924 /// @brief Determine if the call access memmory only using it's pointer
3926 bool onlyAccessesArgMemory() const {
3927 return hasFnAttr(Attribute::ArgMemOnly);
3929 void setOnlyAccessesArgMemory() {
3930 addAttribute(AttributeList::FunctionIndex, Attribute::ArgMemOnly);
3933 /// Determine if the call cannot return.
3934 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
3935 void setDoesNotReturn() {
3936 addAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
3939 /// Determine if the call cannot unwind.
3940 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3941 void setDoesNotThrow() {
3942 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3945 /// Determine if the invoke cannot be duplicated.
3946 bool cannotDuplicate() const {return hasFnAttr(Attribute::NoDuplicate); }
3947 void setCannotDuplicate() {
3948 addAttribute(AttributeList::FunctionIndex, Attribute::NoDuplicate);
3951 /// Determine if the invoke is convergent
3952 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
3953 void setConvergent() {
3954 addAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3956 void setNotConvergent() {
3957 removeAttribute(AttributeList::FunctionIndex, Attribute::Convergent);
3960 /// Determine if the call returns a structure through first
3961 /// pointer argument.
3962 bool hasStructRetAttr() const {
3963 if (getNumArgOperands() == 0)
3966 // Be friendly and also check the callee.
3967 return paramHasAttr(0, Attribute::StructRet);
3970 /// Determine if any call argument is an aggregate passed by value.
3971 bool hasByValArgument() const {
3972 return Attrs.hasAttrSomewhere(Attribute::ByVal);
3975 /// Return the function called, or null if this is an
3976 /// indirect function invocation.
3978 Function *getCalledFunction() const {
3979 return dyn_cast<Function>(Op<-3>());
3982 /// Get a pointer to the function that is invoked by this
3984 const Value *getCalledValue() const { return Op<-3>(); }
3985 Value *getCalledValue() { return Op<-3>(); }
3987 /// Set the function called.
3988 void setCalledFunction(Value* Fn) {
3990 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()),
3993 void setCalledFunction(FunctionType *FTy, Value *Fn) {
3995 assert(FTy == cast<FunctionType>(
3996 cast<PointerType>(Fn->getType())->getElementType()));
4000 // get*Dest - Return the destination basic blocks...
4001 BasicBlock *getNormalDest() const {
4002 return cast<BasicBlock>(Op<-2>());
4004 BasicBlock *getUnwindDest() const {
4005 return cast<BasicBlock>(Op<-1>());
4007 void setNormalDest(BasicBlock *B) {
4008 Op<-2>() = reinterpret_cast<Value*>(B);
4010 void setUnwindDest(BasicBlock *B) {
4011 Op<-1>() = reinterpret_cast<Value*>(B);
4014 /// Get the landingpad instruction from the landing pad
4015 /// block (the unwind destination).
4016 LandingPadInst *getLandingPadInst() const;
4018 BasicBlock *getSuccessor(unsigned i) const {
4019 assert(i < 2 && "Successor # out of range for invoke!");
4020 return i == 0 ? getNormalDest() : getUnwindDest();
4023 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4024 assert(idx < 2 && "Successor # out of range for invoke!");
4025 *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
4028 unsigned getNumSuccessors() const { return 2; }
4030 // Methods for support type inquiry through isa, cast, and dyn_cast:
4031 static inline bool classof(const Instruction *I) {
4032 return (I->getOpcode() == Instruction::Invoke);
4034 static inline bool classof(const Value *V) {
4035 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4039 friend TerminatorInst;
4041 BasicBlock *getSuccessorV(unsigned idx) const;
4042 unsigned getNumSuccessorsV() const;
4043 void setSuccessorV(unsigned idx, BasicBlock *B);
4045 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
4046 if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind))
4049 // Operand bundles override attributes on the called function, but don't
4050 // override attributes directly present on the invoke instruction.
4051 if (isFnAttrDisallowedByOpBundle(Kind))
4054 if (const Function *F = getCalledFunction())
4055 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex,
4060 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4061 // method so that subclasses cannot accidentally use it.
4062 void setInstructionSubclassData(unsigned short D) {
4063 Instruction::setInstructionSubclassData(D);
4068 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
4071 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
4072 BasicBlock *IfException, ArrayRef<Value *> Args,
4073 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4074 const Twine &NameStr, Instruction *InsertBefore)
4075 : TerminatorInst(Ty->getReturnType(), Instruction::Invoke,
4076 OperandTraits<InvokeInst>::op_end(this) - Values, Values,
4078 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
4081 InvokeInst::InvokeInst(Value *Func, BasicBlock *IfNormal,
4082 BasicBlock *IfException, ArrayRef<Value *> Args,
4083 ArrayRef<OperandBundleDef> Bundles, unsigned Values,
4084 const Twine &NameStr, BasicBlock *InsertAtEnd)
4086 cast<FunctionType>(cast<PointerType>(Func->getType())
4087 ->getElementType())->getReturnType(),
4088 Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - Values,
4089 Values, InsertAtEnd) {
4090 init(Func, IfNormal, IfException, Args, Bundles, NameStr);
4093 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
4095 //===----------------------------------------------------------------------===//
4097 //===----------------------------------------------------------------------===//
4099 //===---------------------------------------------------------------------------
4100 /// Resume the propagation of an exception.
4102 class ResumeInst : public TerminatorInst {
4103 ResumeInst(const ResumeInst &RI);
4105 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4106 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4109 // Note: Instruction needs to be a friend here to call cloneImpl.
4110 friend class Instruction;
4112 ResumeInst *cloneImpl() const;
4115 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4116 return new(1) ResumeInst(Exn, InsertBefore);
4119 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4120 return new(1) ResumeInst(Exn, InsertAtEnd);
4123 /// Provide fast operand accessors
4124 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4126 /// Convenience accessor.
4127 Value *getValue() const { return Op<0>(); }
4129 unsigned getNumSuccessors() const { return 0; }
4131 // Methods for support type inquiry through isa, cast, and dyn_cast:
4132 static inline bool classof(const Instruction *I) {
4133 return I->getOpcode() == Instruction::Resume;
4135 static inline bool classof(const Value *V) {
4136 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4140 friend TerminatorInst;
4142 BasicBlock *getSuccessorV(unsigned idx) const;
4143 unsigned getNumSuccessorsV() const;
4144 void setSuccessorV(unsigned idx, BasicBlock *B);
4148 struct OperandTraits<ResumeInst> :
4149 public FixedNumOperandTraits<ResumeInst, 1> {
4152 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4154 //===----------------------------------------------------------------------===//
4155 // CatchSwitchInst Class
4156 //===----------------------------------------------------------------------===//
4157 class CatchSwitchInst : public TerminatorInst {
4158 /// The number of operands actually allocated. NumOperands is
4159 /// the number actually in use.
4160 unsigned ReservedSpace;
4162 // Operand[0] = Outer scope
4163 // Operand[1] = Unwind block destination
4164 // Operand[n] = BasicBlock to go to on match
4165 CatchSwitchInst(const CatchSwitchInst &CSI);
4167 /// Create a new switch instruction, specifying a
4168 /// default destination. The number of additional handlers can be specified
4169 /// here to make memory allocation more efficient.
4170 /// This constructor can also autoinsert before another instruction.
4171 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4172 unsigned NumHandlers, const Twine &NameStr,
4173 Instruction *InsertBefore);
4175 /// Create a new switch instruction, specifying a
4176 /// default destination. The number of additional handlers can be specified
4177 /// here to make memory allocation more efficient.
4178 /// This constructor also autoinserts at the end of the specified BasicBlock.
4179 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4180 unsigned NumHandlers, const Twine &NameStr,
4181 BasicBlock *InsertAtEnd);
4183 // allocate space for exactly zero operands
4184 void *operator new(size_t s) { return User::operator new(s); }
4186 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4187 void growOperands(unsigned Size);
4190 // Note: Instruction needs to be a friend here to call cloneImpl.
4191 friend class Instruction;
4193 CatchSwitchInst *cloneImpl() const;
4196 void *operator new(size_t, unsigned) = delete;
4198 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4199 unsigned NumHandlers,
4200 const Twine &NameStr = "",
4201 Instruction *InsertBefore = nullptr) {
4202 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4206 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4207 unsigned NumHandlers, const Twine &NameStr,
4208 BasicBlock *InsertAtEnd) {
4209 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4213 /// Provide fast operand accessors
4214 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4216 // Accessor Methods for CatchSwitch stmt
4217 Value *getParentPad() const { return getOperand(0); }
4218 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4220 // Accessor Methods for CatchSwitch stmt
4221 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4222 bool unwindsToCaller() const { return !hasUnwindDest(); }
4223 BasicBlock *getUnwindDest() const {
4224 if (hasUnwindDest())
4225 return cast<BasicBlock>(getOperand(1));
4228 void setUnwindDest(BasicBlock *UnwindDest) {
4230 assert(hasUnwindDest());
4231 setOperand(1, UnwindDest);
4234 /// return the number of 'handlers' in this catchswitch
4235 /// instruction, except the default handler
4236 unsigned getNumHandlers() const {
4237 if (hasUnwindDest())
4238 return getNumOperands() - 2;
4239 return getNumOperands() - 1;
4243 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4244 static const BasicBlock *handler_helper(const Value *V) {
4245 return cast<BasicBlock>(V);
4249 using DerefFnTy = std::pointer_to_unary_function<Value *, BasicBlock *>;
4250 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4251 using handler_range = iterator_range<handler_iterator>;
4252 using ConstDerefFnTy =
4253 std::pointer_to_unary_function<const Value *, const BasicBlock *>;
4254 using const_handler_iterator =
4255 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4256 using const_handler_range = iterator_range<const_handler_iterator>;
4258 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4259 handler_iterator handler_begin() {
4260 op_iterator It = op_begin() + 1;
4261 if (hasUnwindDest())
4263 return handler_iterator(It, DerefFnTy(handler_helper));
4266 /// Returns an iterator that points to the first handler in the
4267 /// CatchSwitchInst.
4268 const_handler_iterator handler_begin() const {
4269 const_op_iterator It = op_begin() + 1;
4270 if (hasUnwindDest())
4272 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4275 /// Returns a read-only iterator that points one past the last
4276 /// handler in the CatchSwitchInst.
4277 handler_iterator handler_end() {
4278 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4281 /// Returns an iterator that points one past the last handler in the
4282 /// CatchSwitchInst.
4283 const_handler_iterator handler_end() const {
4284 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4287 /// iteration adapter for range-for loops.
4288 handler_range handlers() {
4289 return make_range(handler_begin(), handler_end());
4292 /// iteration adapter for range-for loops.
4293 const_handler_range handlers() const {
4294 return make_range(handler_begin(), handler_end());
4297 /// Add an entry to the switch instruction...
4299 /// This action invalidates handler_end(). Old handler_end() iterator will
4300 /// point to the added handler.
4301 void addHandler(BasicBlock *Dest);
4303 void removeHandler(handler_iterator HI);
4305 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4306 BasicBlock *getSuccessor(unsigned Idx) const {
4307 assert(Idx < getNumSuccessors() &&
4308 "Successor # out of range for catchswitch!");
4309 return cast<BasicBlock>(getOperand(Idx + 1));
4311 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4312 assert(Idx < getNumSuccessors() &&
4313 "Successor # out of range for catchswitch!");
4314 setOperand(Idx + 1, NewSucc);
4317 // Methods for support type inquiry through isa, cast, and dyn_cast:
4318 static inline bool classof(const Instruction *I) {
4319 return I->getOpcode() == Instruction::CatchSwitch;
4321 static inline bool classof(const Value *V) {
4322 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4326 friend TerminatorInst;
4328 BasicBlock *getSuccessorV(unsigned Idx) const;
4329 unsigned getNumSuccessorsV() const;
4330 void setSuccessorV(unsigned Idx, BasicBlock *B);
4334 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4336 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4338 //===----------------------------------------------------------------------===//
4339 // CleanupPadInst Class
4340 //===----------------------------------------------------------------------===//
4341 class CleanupPadInst : public FuncletPadInst {
4343 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4344 unsigned Values, const Twine &NameStr,
4345 Instruction *InsertBefore)
4346 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4347 NameStr, InsertBefore) {}
4348 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4349 unsigned Values, const Twine &NameStr,
4350 BasicBlock *InsertAtEnd)
4351 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4352 NameStr, InsertAtEnd) {}
4355 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4356 const Twine &NameStr = "",
4357 Instruction *InsertBefore = nullptr) {
4358 unsigned Values = 1 + Args.size();
4360 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4363 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4364 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4365 unsigned Values = 1 + Args.size();
4367 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4370 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4371 static inline bool classof(const Instruction *I) {
4372 return I->getOpcode() == Instruction::CleanupPad;
4374 static inline bool classof(const Value *V) {
4375 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4379 //===----------------------------------------------------------------------===//
4380 // CatchPadInst Class
4381 //===----------------------------------------------------------------------===//
4382 class CatchPadInst : public FuncletPadInst {
4384 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4385 unsigned Values, const Twine &NameStr,
4386 Instruction *InsertBefore)
4387 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4388 NameStr, InsertBefore) {}
4389 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4390 unsigned Values, const Twine &NameStr,
4391 BasicBlock *InsertAtEnd)
4392 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4393 NameStr, InsertAtEnd) {}
4396 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4397 const Twine &NameStr = "",
4398 Instruction *InsertBefore = nullptr) {
4399 unsigned Values = 1 + Args.size();
4401 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4404 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4405 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4406 unsigned Values = 1 + Args.size();
4408 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4411 /// Convenience accessors
4412 CatchSwitchInst *getCatchSwitch() const {
4413 return cast<CatchSwitchInst>(Op<-1>());
4415 void setCatchSwitch(Value *CatchSwitch) {
4416 assert(CatchSwitch);
4417 Op<-1>() = CatchSwitch;
4420 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4421 static inline bool classof(const Instruction *I) {
4422 return I->getOpcode() == Instruction::CatchPad;
4424 static inline bool classof(const Value *V) {
4425 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4429 //===----------------------------------------------------------------------===//
4430 // CatchReturnInst Class
4431 //===----------------------------------------------------------------------===//
4433 class CatchReturnInst : public TerminatorInst {
4434 CatchReturnInst(const CatchReturnInst &RI);
4435 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4436 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4438 void init(Value *CatchPad, BasicBlock *BB);
4441 // Note: Instruction needs to be a friend here to call cloneImpl.
4442 friend class Instruction;
4444 CatchReturnInst *cloneImpl() const;
4447 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4448 Instruction *InsertBefore = nullptr) {
4451 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4454 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4455 BasicBlock *InsertAtEnd) {
4458 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4461 /// Provide fast operand accessors
4462 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4464 /// Convenience accessors.
4465 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4466 void setCatchPad(CatchPadInst *CatchPad) {
4471 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4472 void setSuccessor(BasicBlock *NewSucc) {
4476 unsigned getNumSuccessors() const { return 1; }
4478 /// Get the parentPad of this catchret's catchpad's catchswitch.
4479 /// The successor block is implicitly a member of this funclet.
4480 Value *getCatchSwitchParentPad() const {
4481 return getCatchPad()->getCatchSwitch()->getParentPad();
4484 // Methods for support type inquiry through isa, cast, and dyn_cast:
4485 static inline bool classof(const Instruction *I) {
4486 return (I->getOpcode() == Instruction::CatchRet);
4488 static inline bool classof(const Value *V) {
4489 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4493 friend TerminatorInst;
4495 BasicBlock *getSuccessorV(unsigned Idx) const;
4496 unsigned getNumSuccessorsV() const;
4497 void setSuccessorV(unsigned Idx, BasicBlock *B);
4501 struct OperandTraits<CatchReturnInst>
4502 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4504 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4506 //===----------------------------------------------------------------------===//
4507 // CleanupReturnInst Class
4508 //===----------------------------------------------------------------------===//
4510 class CleanupReturnInst : public TerminatorInst {
4512 CleanupReturnInst(const CleanupReturnInst &RI);
4513 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4514 Instruction *InsertBefore = nullptr);
4515 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4516 BasicBlock *InsertAtEnd);
4518 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4521 // Note: Instruction needs to be a friend here to call cloneImpl.
4522 friend class Instruction;
4524 CleanupReturnInst *cloneImpl() const;
4527 static CleanupReturnInst *Create(Value *CleanupPad,
4528 BasicBlock *UnwindBB = nullptr,
4529 Instruction *InsertBefore = nullptr) {
4531 unsigned Values = 1;
4535 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4538 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4539 BasicBlock *InsertAtEnd) {
4541 unsigned Values = 1;
4545 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4548 /// Provide fast operand accessors
4549 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4551 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4552 bool unwindsToCaller() const { return !hasUnwindDest(); }
4554 /// Convenience accessor.
4555 CleanupPadInst *getCleanupPad() const {
4556 return cast<CleanupPadInst>(Op<0>());
4558 void setCleanupPad(CleanupPadInst *CleanupPad) {
4560 Op<0>() = CleanupPad;
4563 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4565 BasicBlock *getUnwindDest() const {
4566 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4568 void setUnwindDest(BasicBlock *NewDest) {
4570 assert(hasUnwindDest());
4574 // Methods for support type inquiry through isa, cast, and dyn_cast:
4575 static inline bool classof(const Instruction *I) {
4576 return (I->getOpcode() == Instruction::CleanupRet);
4578 static inline bool classof(const Value *V) {
4579 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4583 friend TerminatorInst;
4585 BasicBlock *getSuccessorV(unsigned Idx) const;
4586 unsigned getNumSuccessorsV() const;
4587 void setSuccessorV(unsigned Idx, BasicBlock *B);
4589 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4590 // method so that subclasses cannot accidentally use it.
4591 void setInstructionSubclassData(unsigned short D) {
4592 Instruction::setInstructionSubclassData(D);
4597 struct OperandTraits<CleanupReturnInst>
4598 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4600 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4602 //===----------------------------------------------------------------------===//
4603 // UnreachableInst Class
4604 //===----------------------------------------------------------------------===//
4606 //===---------------------------------------------------------------------------
4607 /// This function has undefined behavior. In particular, the
4608 /// presence of this instruction indicates some higher level knowledge that the
4609 /// end of the block cannot be reached.
4611 class UnreachableInst : public TerminatorInst {
4613 // Note: Instruction needs to be a friend here to call cloneImpl.
4614 friend class Instruction;
4616 UnreachableInst *cloneImpl() const;
4619 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4620 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4622 // allocate space for exactly zero operands
4623 void *operator new(size_t s) {
4624 return User::operator new(s, 0);
4627 void *operator new(size_t, unsigned) = delete;
4629 unsigned getNumSuccessors() const { return 0; }
4631 // Methods for support type inquiry through isa, cast, and dyn_cast:
4632 static inline bool classof(const Instruction *I) {
4633 return I->getOpcode() == Instruction::Unreachable;
4635 static inline bool classof(const Value *V) {
4636 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4640 friend TerminatorInst;
4642 BasicBlock *getSuccessorV(unsigned idx) const;
4643 unsigned getNumSuccessorsV() const;
4644 void setSuccessorV(unsigned idx, BasicBlock *B);
4647 //===----------------------------------------------------------------------===//
4649 //===----------------------------------------------------------------------===//
4651 /// This class represents a truncation of integer types.
4652 class TruncInst : public CastInst {
4654 // Note: Instruction needs to be a friend here to call cloneImpl.
4655 friend class Instruction;
4657 /// Clone an identical TruncInst
4658 TruncInst *cloneImpl() const;
4661 /// Constructor with insert-before-instruction semantics
4663 Value *S, ///< The value to be truncated
4664 Type *Ty, ///< The (smaller) type to truncate to
4665 const Twine &NameStr = "", ///< A name for the new instruction
4666 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4669 /// Constructor with insert-at-end-of-block semantics
4671 Value *S, ///< The value to be truncated
4672 Type *Ty, ///< The (smaller) type to truncate to
4673 const Twine &NameStr, ///< A name for the new instruction
4674 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4677 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4678 static inline bool classof(const Instruction *I) {
4679 return I->getOpcode() == Trunc;
4681 static inline bool classof(const Value *V) {
4682 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4686 //===----------------------------------------------------------------------===//
4688 //===----------------------------------------------------------------------===//
4690 /// This class represents zero extension of integer types.
4691 class ZExtInst : public CastInst {
4693 // Note: Instruction needs to be a friend here to call cloneImpl.
4694 friend class Instruction;
4696 /// Clone an identical ZExtInst
4697 ZExtInst *cloneImpl() const;
4700 /// Constructor with insert-before-instruction semantics
4702 Value *S, ///< The value to be zero extended
4703 Type *Ty, ///< The type to zero extend to
4704 const Twine &NameStr = "", ///< A name for the new instruction
4705 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4708 /// Constructor with insert-at-end semantics.
4710 Value *S, ///< The value to be zero extended
4711 Type *Ty, ///< The type to zero extend to
4712 const Twine &NameStr, ///< A name for the new instruction
4713 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4716 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4717 static inline bool classof(const Instruction *I) {
4718 return I->getOpcode() == ZExt;
4720 static inline bool classof(const Value *V) {
4721 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4725 //===----------------------------------------------------------------------===//
4727 //===----------------------------------------------------------------------===//
4729 /// This class represents a sign extension of integer types.
4730 class SExtInst : public CastInst {
4732 // Note: Instruction needs to be a friend here to call cloneImpl.
4733 friend class Instruction;
4735 /// Clone an identical SExtInst
4736 SExtInst *cloneImpl() const;
4739 /// Constructor with insert-before-instruction semantics
4741 Value *S, ///< The value to be sign extended
4742 Type *Ty, ///< The type to sign extend to
4743 const Twine &NameStr = "", ///< A name for the new instruction
4744 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4747 /// Constructor with insert-at-end-of-block semantics
4749 Value *S, ///< The value to be sign extended
4750 Type *Ty, ///< The type to sign extend to
4751 const Twine &NameStr, ///< A name for the new instruction
4752 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4755 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4756 static inline bool classof(const Instruction *I) {
4757 return I->getOpcode() == SExt;
4759 static inline bool classof(const Value *V) {
4760 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4764 //===----------------------------------------------------------------------===//
4765 // FPTruncInst Class
4766 //===----------------------------------------------------------------------===//
4768 /// This class represents a truncation of floating point types.
4769 class FPTruncInst : public CastInst {
4771 // Note: Instruction needs to be a friend here to call cloneImpl.
4772 friend class Instruction;
4774 /// Clone an identical FPTruncInst
4775 FPTruncInst *cloneImpl() const;
4778 /// Constructor with insert-before-instruction semantics
4780 Value *S, ///< The value to be truncated
4781 Type *Ty, ///< The type to truncate to
4782 const Twine &NameStr = "", ///< A name for the new instruction
4783 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4786 /// Constructor with insert-before-instruction semantics
4788 Value *S, ///< The value to be truncated
4789 Type *Ty, ///< The type to truncate to
4790 const Twine &NameStr, ///< A name for the new instruction
4791 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4794 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4795 static inline bool classof(const Instruction *I) {
4796 return I->getOpcode() == FPTrunc;
4798 static inline bool classof(const Value *V) {
4799 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4803 //===----------------------------------------------------------------------===//
4805 //===----------------------------------------------------------------------===//
4807 /// This class represents an extension of floating point types.
4808 class FPExtInst : public CastInst {
4810 // Note: Instruction needs to be a friend here to call cloneImpl.
4811 friend class Instruction;
4813 /// Clone an identical FPExtInst
4814 FPExtInst *cloneImpl() const;
4817 /// Constructor with insert-before-instruction semantics
4819 Value *S, ///< The value to be extended
4820 Type *Ty, ///< The type to extend to
4821 const Twine &NameStr = "", ///< A name for the new instruction
4822 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4825 /// Constructor with insert-at-end-of-block semantics
4827 Value *S, ///< The value to be extended
4828 Type *Ty, ///< The type to extend to
4829 const Twine &NameStr, ///< A name for the new instruction
4830 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4833 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4834 static inline bool classof(const Instruction *I) {
4835 return I->getOpcode() == FPExt;
4837 static inline bool classof(const Value *V) {
4838 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4842 //===----------------------------------------------------------------------===//
4844 //===----------------------------------------------------------------------===//
4846 /// This class represents a cast unsigned integer to floating point.
4847 class UIToFPInst : public CastInst {
4849 // Note: Instruction needs to be a friend here to call cloneImpl.
4850 friend class Instruction;
4852 /// Clone an identical UIToFPInst
4853 UIToFPInst *cloneImpl() const;
4856 /// Constructor with insert-before-instruction semantics
4858 Value *S, ///< The value to be converted
4859 Type *Ty, ///< The type to convert to
4860 const Twine &NameStr = "", ///< A name for the new instruction
4861 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4864 /// Constructor with insert-at-end-of-block semantics
4866 Value *S, ///< The value to be converted
4867 Type *Ty, ///< The type to convert to
4868 const Twine &NameStr, ///< A name for the new instruction
4869 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4872 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4873 static inline bool classof(const Instruction *I) {
4874 return I->getOpcode() == UIToFP;
4876 static inline bool classof(const Value *V) {
4877 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4881 //===----------------------------------------------------------------------===//
4883 //===----------------------------------------------------------------------===//
4885 /// This class represents a cast from signed integer to floating point.
4886 class SIToFPInst : public CastInst {
4888 // Note: Instruction needs to be a friend here to call cloneImpl.
4889 friend class Instruction;
4891 /// Clone an identical SIToFPInst
4892 SIToFPInst *cloneImpl() const;
4895 /// Constructor with insert-before-instruction semantics
4897 Value *S, ///< The value to be converted
4898 Type *Ty, ///< The type to convert to
4899 const Twine &NameStr = "", ///< A name for the new instruction
4900 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4903 /// Constructor with insert-at-end-of-block semantics
4905 Value *S, ///< The value to be converted
4906 Type *Ty, ///< The type to convert to
4907 const Twine &NameStr, ///< A name for the new instruction
4908 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4911 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4912 static inline bool classof(const Instruction *I) {
4913 return I->getOpcode() == SIToFP;
4915 static inline bool classof(const Value *V) {
4916 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4920 //===----------------------------------------------------------------------===//
4922 //===----------------------------------------------------------------------===//
4924 /// This class represents a cast from floating point to unsigned integer
4925 class FPToUIInst : public CastInst {
4927 // Note: Instruction needs to be a friend here to call cloneImpl.
4928 friend class Instruction;
4930 /// Clone an identical FPToUIInst
4931 FPToUIInst *cloneImpl() const;
4934 /// Constructor with insert-before-instruction semantics
4936 Value *S, ///< The value to be converted
4937 Type *Ty, ///< The type to convert to
4938 const Twine &NameStr = "", ///< A name for the new instruction
4939 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4942 /// Constructor with insert-at-end-of-block semantics
4944 Value *S, ///< The value to be converted
4945 Type *Ty, ///< The type to convert to
4946 const Twine &NameStr, ///< A name for the new instruction
4947 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
4950 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4951 static inline bool classof(const Instruction *I) {
4952 return I->getOpcode() == FPToUI;
4954 static inline bool classof(const Value *V) {
4955 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4959 //===----------------------------------------------------------------------===//
4961 //===----------------------------------------------------------------------===//
4963 /// This class represents a cast from floating point to signed integer.
4964 class FPToSIInst : public CastInst {
4966 // Note: Instruction needs to be a friend here to call cloneImpl.
4967 friend class Instruction;
4969 /// Clone an identical FPToSIInst
4970 FPToSIInst *cloneImpl() const;
4973 /// Constructor with insert-before-instruction semantics
4975 Value *S, ///< The value to be converted
4976 Type *Ty, ///< The type to convert to
4977 const Twine &NameStr = "", ///< A name for the new instruction
4978 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4981 /// Constructor with insert-at-end-of-block semantics
4983 Value *S, ///< The value to be converted
4984 Type *Ty, ///< The type to convert to
4985 const Twine &NameStr, ///< A name for the new instruction
4986 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4989 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4990 static inline bool classof(const Instruction *I) {
4991 return I->getOpcode() == FPToSI;
4993 static inline bool classof(const Value *V) {
4994 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4998 //===----------------------------------------------------------------------===//
4999 // IntToPtrInst Class
5000 //===----------------------------------------------------------------------===//
5002 /// This class represents a cast from an integer to a pointer.
5003 class IntToPtrInst : public CastInst {
5005 // Note: Instruction needs to be a friend here to call cloneImpl.
5006 friend class Instruction;
5008 /// Constructor with insert-before-instruction semantics
5010 Value *S, ///< The value to be converted
5011 Type *Ty, ///< The type to convert to
5012 const Twine &NameStr = "", ///< A name for the new instruction
5013 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5016 /// Constructor with insert-at-end-of-block semantics
5018 Value *S, ///< The value to be converted
5019 Type *Ty, ///< The type to convert to
5020 const Twine &NameStr, ///< A name for the new instruction
5021 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5024 /// Clone an identical IntToPtrInst.
5025 IntToPtrInst *cloneImpl() const;
5027 /// Returns the address space of this instruction's pointer type.
5028 unsigned getAddressSpace() const {
5029 return getType()->getPointerAddressSpace();
5032 // Methods for support type inquiry through isa, cast, and dyn_cast:
5033 static inline bool classof(const Instruction *I) {
5034 return I->getOpcode() == IntToPtr;
5036 static inline bool classof(const Value *V) {
5037 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5041 //===----------------------------------------------------------------------===//
5042 // PtrToIntInst Class
5043 //===----------------------------------------------------------------------===//
5045 /// This class represents a cast from a pointer to an integer.
5046 class PtrToIntInst : public CastInst {
5048 // Note: Instruction needs to be a friend here to call cloneImpl.
5049 friend class Instruction;
5051 /// Clone an identical PtrToIntInst.
5052 PtrToIntInst *cloneImpl() const;
5055 /// Constructor with insert-before-instruction semantics
5057 Value *S, ///< The value to be converted
5058 Type *Ty, ///< The type to convert to
5059 const Twine &NameStr = "", ///< A name for the new instruction
5060 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5063 /// Constructor with insert-at-end-of-block semantics
5065 Value *S, ///< The value to be converted
5066 Type *Ty, ///< The type to convert to
5067 const Twine &NameStr, ///< A name for the new instruction
5068 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5071 /// Gets the pointer operand.
5072 Value *getPointerOperand() { return getOperand(0); }
5073 /// Gets the pointer operand.
5074 const Value *getPointerOperand() const { return getOperand(0); }
5075 /// Gets the operand index of the pointer operand.
5076 static unsigned getPointerOperandIndex() { return 0U; }
5078 /// Returns the address space of the pointer operand.
5079 unsigned getPointerAddressSpace() const {
5080 return getPointerOperand()->getType()->getPointerAddressSpace();
5083 // Methods for support type inquiry through isa, cast, and dyn_cast:
5084 static inline bool classof(const Instruction *I) {
5085 return I->getOpcode() == PtrToInt;
5087 static inline bool classof(const Value *V) {
5088 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5092 //===----------------------------------------------------------------------===//
5093 // BitCastInst Class
5094 //===----------------------------------------------------------------------===//
5096 /// This class represents a no-op cast from one type to another.
5097 class BitCastInst : public CastInst {
5099 // Note: Instruction needs to be a friend here to call cloneImpl.
5100 friend class Instruction;
5102 /// Clone an identical BitCastInst.
5103 BitCastInst *cloneImpl() const;
5106 /// Constructor with insert-before-instruction semantics
5108 Value *S, ///< The value to be casted
5109 Type *Ty, ///< The type to casted to
5110 const Twine &NameStr = "", ///< A name for the new instruction
5111 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5114 /// Constructor with insert-at-end-of-block semantics
5116 Value *S, ///< The value to be casted
5117 Type *Ty, ///< The type to casted to
5118 const Twine &NameStr, ///< A name for the new instruction
5119 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5122 // Methods for support type inquiry through isa, cast, and dyn_cast:
5123 static inline bool classof(const Instruction *I) {
5124 return I->getOpcode() == BitCast;
5126 static inline bool classof(const Value *V) {
5127 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5131 //===----------------------------------------------------------------------===//
5132 // AddrSpaceCastInst Class
5133 //===----------------------------------------------------------------------===//
5135 /// This class represents a conversion between pointers from one address space
5137 class AddrSpaceCastInst : public CastInst {
5139 // Note: Instruction needs to be a friend here to call cloneImpl.
5140 friend class Instruction;
5142 /// Clone an identical AddrSpaceCastInst.
5143 AddrSpaceCastInst *cloneImpl() const;
5146 /// Constructor with insert-before-instruction semantics
5148 Value *S, ///< The value to be casted
5149 Type *Ty, ///< The type to casted to
5150 const Twine &NameStr = "", ///< A name for the new instruction
5151 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5154 /// Constructor with insert-at-end-of-block semantics
5156 Value *S, ///< The value to be casted
5157 Type *Ty, ///< The type to casted to
5158 const Twine &NameStr, ///< A name for the new instruction
5159 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5162 // Methods for support type inquiry through isa, cast, and dyn_cast:
5163 static inline bool classof(const Instruction *I) {
5164 return I->getOpcode() == AddrSpaceCast;
5166 static inline bool classof(const Value *V) {
5167 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5170 /// Gets the pointer operand.
5171 Value *getPointerOperand() {
5172 return getOperand(0);
5175 /// Gets the pointer operand.
5176 const Value *getPointerOperand() const {
5177 return getOperand(0);
5180 /// Gets the operand index of the pointer operand.
5181 static unsigned getPointerOperandIndex() {
5185 /// Returns the address space of the pointer operand.
5186 unsigned getSrcAddressSpace() const {
5187 return getPointerOperand()->getType()->getPointerAddressSpace();
5190 /// Returns the address space of the result.
5191 unsigned getDestAddressSpace() const {
5192 return getType()->getPointerAddressSpace();
5196 } // end namespace llvm
5198 #endif // LLVM_IR_INSTRUCTIONS_H