[Alignment][NFC] Convert StoreInst to MaybeAlign
[llvm-core.git] / include / llvm / IR / Instructions.h
blobfa980df03ef0c2a02c69c116eb3bdc7dce2b238e
1 //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file exposes the class definitions of all of the subclasses of the
10 // Instruction class. This is meant to be an easy way to get access to all
11 // instruction subclasses.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_INSTRUCTIONS_H
16 #define LLVM_IR_INSTRUCTIONS_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/ADT/iterator.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/InstrTypes.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/OperandTraits.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/Use.h"
37 #include "llvm/IR/User.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Support/AtomicOrdering.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include <cassert>
43 #include <cstddef>
44 #include <cstdint>
45 #include <iterator>
47 namespace llvm {
49 class APInt;
50 class ConstantInt;
51 class DataLayout;
52 class LLVMContext;
54 //===----------------------------------------------------------------------===//
55 // AllocaInst Class
56 //===----------------------------------------------------------------------===//
58 /// an instruction to allocate memory on the stack
59 class AllocaInst : public UnaryInstruction {
60 Type *AllocatedType;
62 protected:
63 // Note: Instruction needs to be a friend here to call cloneImpl.
64 friend class Instruction;
66 AllocaInst *cloneImpl() const;
68 public:
69 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
70 Value *ArraySize = nullptr,
71 const Twine &Name = "",
72 Instruction *InsertBefore = nullptr);
73 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
74 const Twine &Name, BasicBlock *InsertAtEnd);
76 AllocaInst(Type *Ty, unsigned AddrSpace,
77 const Twine &Name, Instruction *InsertBefore = nullptr);
78 AllocaInst(Type *Ty, unsigned AddrSpace,
79 const Twine &Name, BasicBlock *InsertAtEnd);
81 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
82 const Twine &Name = "", Instruction *InsertBefore = nullptr);
83 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
84 const Twine &Name, BasicBlock *InsertAtEnd);
86 /// Return true if there is an allocation size parameter to the allocation
87 /// instruction that is not 1.
88 bool isArrayAllocation() const;
90 /// Get the number of elements allocated. For a simple allocation of a single
91 /// element, this will return a constant 1 value.
92 const Value *getArraySize() const { return getOperand(0); }
93 Value *getArraySize() { return getOperand(0); }
95 /// Overload to return most specific pointer type.
96 PointerType *getType() const {
97 return cast<PointerType>(Instruction::getType());
100 /// Get allocation size in bits. Returns None if size can't be determined,
101 /// e.g. in case of a VLA.
102 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
104 /// Return the type that is being allocated by the instruction.
105 Type *getAllocatedType() const { return AllocatedType; }
106 /// for use only in special circumstances that need to generically
107 /// transform a whole instruction (eg: IR linking and vectorization).
108 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
110 /// Return the alignment of the memory that is being allocated by the
111 /// instruction.
112 unsigned getAlignment() const {
113 if (const auto MA = decodeMaybeAlign(getSubclassDataFromInstruction() & 31))
114 return MA->value();
115 return 0;
117 void setAlignment(MaybeAlign 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) |
133 (V ? 32 : 0));
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) |
144 (V ? 64 : 0));
147 // Methods for support type inquiry through isa, cast, and dyn_cast:
148 static bool classof(const Instruction *I) {
149 return (I->getOpcode() == Instruction::Alloca);
151 static bool classof(const Value *V) {
152 return isa<Instruction>(V) && classof(cast<Instruction>(V));
155 private:
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 //===----------------------------------------------------------------------===//
164 // LoadInst Class
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 {
170 void AssertOK();
172 protected:
173 // Note: Instruction needs to be a friend here to call cloneImpl.
174 friend class Instruction;
176 LoadInst *cloneImpl() const;
178 public:
179 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
180 Instruction *InsertBefore = nullptr);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
182 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183 Instruction *InsertBefore = nullptr);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 BasicBlock *InsertAtEnd);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 MaybeAlign Align, Instruction *InsertBefore = nullptr);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 MaybeAlign Align, BasicBlock *InsertAtEnd);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 MaybeAlign Align, AtomicOrdering Order,
192 SyncScope::ID SSID = SyncScope::System,
193 Instruction *InsertBefore = nullptr);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
196 BasicBlock *InsertAtEnd);
198 // Deprecated [opaque pointer types]
199 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
200 Instruction *InsertBefore = nullptr)
201 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
202 InsertBefore) {}
203 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
204 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
205 InsertAtEnd) {}
206 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Instruction *InsertBefore = nullptr)
208 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
209 isVolatile, InsertBefore) {}
210 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
211 BasicBlock *InsertAtEnd)
212 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
213 isVolatile, InsertAtEnd) {}
214 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
215 Instruction *InsertBefore = nullptr)
216 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
217 isVolatile, Align, InsertBefore) {}
218 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
219 BasicBlock *InsertAtEnd)
220 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
221 isVolatile, Align, InsertAtEnd) {}
222 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
223 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
224 Instruction *InsertBefore = nullptr)
225 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
226 isVolatile, Align, Order, SSID, InsertBefore) {}
227 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
228 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
229 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
230 isVolatile, Align, Order, SSID, InsertAtEnd) {}
232 /// Return true if this is a load from a volatile memory location.
233 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
235 /// Specify whether this is a volatile load or not.
236 void setVolatile(bool V) {
237 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
238 (V ? 1 : 0));
241 /// Return the alignment of the access that is being performed.
242 unsigned getAlignment() const {
243 if (const auto MA =
244 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
245 return MA->value();
246 return 0;
249 void setAlignment(MaybeAlign Align);
251 /// Returns the ordering constraint of this load instruction.
252 AtomicOrdering getOrdering() const {
253 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
256 /// Sets the ordering constraint of this load instruction. May not be Release
257 /// or AcquireRelease.
258 void setOrdering(AtomicOrdering Ordering) {
259 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
260 ((unsigned)Ordering << 7));
263 /// Returns the synchronization scope ID of this load instruction.
264 SyncScope::ID getSyncScopeID() const {
265 return SSID;
268 /// Sets the synchronization scope ID of this load instruction.
269 void setSyncScopeID(SyncScope::ID SSID) {
270 this->SSID = SSID;
273 /// Sets the ordering constraint and the synchronization scope ID of this load
274 /// instruction.
275 void setAtomic(AtomicOrdering Ordering,
276 SyncScope::ID SSID = SyncScope::System) {
277 setOrdering(Ordering);
278 setSyncScopeID(SSID);
281 bool isSimple() const { return !isAtomic() && !isVolatile(); }
283 bool isUnordered() const {
284 return (getOrdering() == AtomicOrdering::NotAtomic ||
285 getOrdering() == AtomicOrdering::Unordered) &&
286 !isVolatile();
289 Value *getPointerOperand() { return getOperand(0); }
290 const Value *getPointerOperand() const { return getOperand(0); }
291 static unsigned getPointerOperandIndex() { return 0U; }
292 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
294 /// Returns the address space of the pointer operand.
295 unsigned getPointerAddressSpace() const {
296 return getPointerOperandType()->getPointerAddressSpace();
299 // Methods for support type inquiry through isa, cast, and dyn_cast:
300 static bool classof(const Instruction *I) {
301 return I->getOpcode() == Instruction::Load;
303 static bool classof(const Value *V) {
304 return isa<Instruction>(V) && classof(cast<Instruction>(V));
307 private:
308 // Shadow Instruction::setInstructionSubclassData with a private forwarding
309 // method so that subclasses cannot accidentally use it.
310 void setInstructionSubclassData(unsigned short D) {
311 Instruction::setInstructionSubclassData(D);
314 /// The synchronization scope ID of this load instruction. Not quite enough
315 /// room in SubClassData for everything, so synchronization scope ID gets its
316 /// own field.
317 SyncScope::ID SSID;
320 //===----------------------------------------------------------------------===//
321 // StoreInst Class
322 //===----------------------------------------------------------------------===//
324 /// An instruction for storing to memory.
325 class StoreInst : public Instruction {
326 void AssertOK();
328 protected:
329 // Note: Instruction needs to be a friend here to call cloneImpl.
330 friend class Instruction;
332 StoreInst *cloneImpl() const;
334 public:
335 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
336 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
337 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
338 Instruction *InsertBefore = nullptr);
339 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
340 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
341 Instruction *InsertBefore = nullptr);
342 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
343 BasicBlock *InsertAtEnd);
344 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
345 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
346 Instruction *InsertBefore = nullptr);
347 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
348 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
350 // allocate space for exactly two operands
351 void *operator new(size_t s) {
352 return User::operator new(s, 2);
355 /// Return true if this is a store to a volatile memory location.
356 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
358 /// Specify whether this is a volatile store or not.
359 void setVolatile(bool V) {
360 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
361 (V ? 1 : 0));
364 /// Transparently provide more efficient getOperand methods.
365 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
367 /// Return the alignment of the access that is being performed
368 unsigned getAlignment() const {
369 if (const auto MA =
370 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
371 return MA->value();
372 return 0;
375 void setAlignment(MaybeAlign Align);
377 /// Returns the ordering constraint of this store instruction.
378 AtomicOrdering getOrdering() const {
379 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
382 /// Sets the ordering constraint of this store instruction. May not be
383 /// Acquire or AcquireRelease.
384 void setOrdering(AtomicOrdering Ordering) {
385 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
386 ((unsigned)Ordering << 7));
389 /// Returns the synchronization scope ID of this store instruction.
390 SyncScope::ID getSyncScopeID() const {
391 return SSID;
394 /// Sets the synchronization scope ID of this store instruction.
395 void setSyncScopeID(SyncScope::ID SSID) {
396 this->SSID = SSID;
399 /// Sets the ordering constraint and the synchronization scope ID of this
400 /// store instruction.
401 void setAtomic(AtomicOrdering Ordering,
402 SyncScope::ID SSID = SyncScope::System) {
403 setOrdering(Ordering);
404 setSyncScopeID(SSID);
407 bool isSimple() const { return !isAtomic() && !isVolatile(); }
409 bool isUnordered() const {
410 return (getOrdering() == AtomicOrdering::NotAtomic ||
411 getOrdering() == AtomicOrdering::Unordered) &&
412 !isVolatile();
415 Value *getValueOperand() { return getOperand(0); }
416 const Value *getValueOperand() const { return getOperand(0); }
418 Value *getPointerOperand() { return getOperand(1); }
419 const Value *getPointerOperand() const { return getOperand(1); }
420 static unsigned getPointerOperandIndex() { return 1U; }
421 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
423 /// Returns the address space of the pointer operand.
424 unsigned getPointerAddressSpace() const {
425 return getPointerOperandType()->getPointerAddressSpace();
428 // Methods for support type inquiry through isa, cast, and dyn_cast:
429 static bool classof(const Instruction *I) {
430 return I->getOpcode() == Instruction::Store;
432 static bool classof(const Value *V) {
433 return isa<Instruction>(V) && classof(cast<Instruction>(V));
436 private:
437 // Shadow Instruction::setInstructionSubclassData with a private forwarding
438 // method so that subclasses cannot accidentally use it.
439 void setInstructionSubclassData(unsigned short D) {
440 Instruction::setInstructionSubclassData(D);
443 /// The synchronization scope ID of this store instruction. Not quite enough
444 /// room in SubClassData for everything, so synchronization scope ID gets its
445 /// own field.
446 SyncScope::ID SSID;
449 template <>
450 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
453 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
455 //===----------------------------------------------------------------------===//
456 // FenceInst Class
457 //===----------------------------------------------------------------------===//
459 /// An instruction for ordering other memory operations.
460 class FenceInst : public Instruction {
461 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
463 protected:
464 // Note: Instruction needs to be a friend here to call cloneImpl.
465 friend class Instruction;
467 FenceInst *cloneImpl() const;
469 public:
470 // Ordering may only be Acquire, Release, AcquireRelease, or
471 // SequentiallyConsistent.
472 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
473 SyncScope::ID SSID = SyncScope::System,
474 Instruction *InsertBefore = nullptr);
475 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
476 BasicBlock *InsertAtEnd);
478 // allocate space for exactly zero operands
479 void *operator new(size_t s) {
480 return User::operator new(s, 0);
483 /// Returns the ordering constraint of this fence instruction.
484 AtomicOrdering getOrdering() const {
485 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
488 /// Sets the ordering constraint of this fence instruction. May only be
489 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
490 void setOrdering(AtomicOrdering Ordering) {
491 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
492 ((unsigned)Ordering << 1));
495 /// Returns the synchronization scope ID of this fence instruction.
496 SyncScope::ID getSyncScopeID() const {
497 return SSID;
500 /// Sets the synchronization scope ID of this fence instruction.
501 void setSyncScopeID(SyncScope::ID SSID) {
502 this->SSID = SSID;
505 // Methods for support type inquiry through isa, cast, and dyn_cast:
506 static bool classof(const Instruction *I) {
507 return I->getOpcode() == Instruction::Fence;
509 static bool classof(const Value *V) {
510 return isa<Instruction>(V) && classof(cast<Instruction>(V));
513 private:
514 // Shadow Instruction::setInstructionSubclassData with a private forwarding
515 // method so that subclasses cannot accidentally use it.
516 void setInstructionSubclassData(unsigned short D) {
517 Instruction::setInstructionSubclassData(D);
520 /// The synchronization scope ID of this fence instruction. Not quite enough
521 /// room in SubClassData for everything, so synchronization scope ID gets its
522 /// own field.
523 SyncScope::ID SSID;
526 //===----------------------------------------------------------------------===//
527 // AtomicCmpXchgInst Class
528 //===----------------------------------------------------------------------===//
530 /// An instruction that atomically checks whether a
531 /// specified value is in a memory location, and, if it is, stores a new value
532 /// there. The value returned by this instruction is a pair containing the
533 /// original value as first element, and an i1 indicating success (true) or
534 /// failure (false) as second element.
536 class AtomicCmpXchgInst : public Instruction {
537 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
538 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
539 SyncScope::ID SSID);
541 protected:
542 // Note: Instruction needs to be a friend here to call cloneImpl.
543 friend class Instruction;
545 AtomicCmpXchgInst *cloneImpl() const;
547 public:
548 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
549 AtomicOrdering SuccessOrdering,
550 AtomicOrdering FailureOrdering,
551 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
552 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
553 AtomicOrdering SuccessOrdering,
554 AtomicOrdering FailureOrdering,
555 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
557 // allocate space for exactly three operands
558 void *operator new(size_t s) {
559 return User::operator new(s, 3);
562 /// Return true if this is a cmpxchg from a volatile memory
563 /// location.
565 bool isVolatile() const {
566 return getSubclassDataFromInstruction() & 1;
569 /// Specify whether this is a volatile cmpxchg.
571 void setVolatile(bool V) {
572 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
573 (unsigned)V);
576 /// Return true if this cmpxchg may spuriously fail.
577 bool isWeak() const {
578 return getSubclassDataFromInstruction() & 0x100;
581 void setWeak(bool IsWeak) {
582 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
583 (IsWeak << 8));
586 /// Transparently provide more efficient getOperand methods.
587 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
589 /// Returns the success ordering constraint of this cmpxchg instruction.
590 AtomicOrdering getSuccessOrdering() const {
591 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
594 /// Sets the success ordering constraint of this cmpxchg instruction.
595 void setSuccessOrdering(AtomicOrdering Ordering) {
596 assert(Ordering != AtomicOrdering::NotAtomic &&
597 "CmpXchg instructions can only be atomic.");
598 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
599 ((unsigned)Ordering << 2));
602 /// Returns the failure ordering constraint of this cmpxchg instruction.
603 AtomicOrdering getFailureOrdering() const {
604 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
607 /// Sets the failure ordering constraint of this cmpxchg instruction.
608 void setFailureOrdering(AtomicOrdering Ordering) {
609 assert(Ordering != AtomicOrdering::NotAtomic &&
610 "CmpXchg instructions can only be atomic.");
611 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
612 ((unsigned)Ordering << 5));
615 /// Returns the synchronization scope ID of this cmpxchg instruction.
616 SyncScope::ID getSyncScopeID() const {
617 return SSID;
620 /// Sets the synchronization scope ID of this cmpxchg instruction.
621 void setSyncScopeID(SyncScope::ID SSID) {
622 this->SSID = SSID;
625 Value *getPointerOperand() { return getOperand(0); }
626 const Value *getPointerOperand() const { return getOperand(0); }
627 static unsigned getPointerOperandIndex() { return 0U; }
629 Value *getCompareOperand() { return getOperand(1); }
630 const Value *getCompareOperand() const { return getOperand(1); }
632 Value *getNewValOperand() { return getOperand(2); }
633 const Value *getNewValOperand() const { return getOperand(2); }
635 /// Returns the address space of the pointer operand.
636 unsigned getPointerAddressSpace() const {
637 return getPointerOperand()->getType()->getPointerAddressSpace();
640 /// Returns the strongest permitted ordering on failure, given the
641 /// desired ordering on success.
643 /// If the comparison in a cmpxchg operation fails, there is no atomic store
644 /// so release semantics cannot be provided. So this function drops explicit
645 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
646 /// operation would remain SequentiallyConsistent.
647 static AtomicOrdering
648 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
649 switch (SuccessOrdering) {
650 default:
651 llvm_unreachable("invalid cmpxchg success ordering");
652 case AtomicOrdering::Release:
653 case AtomicOrdering::Monotonic:
654 return AtomicOrdering::Monotonic;
655 case AtomicOrdering::AcquireRelease:
656 case AtomicOrdering::Acquire:
657 return AtomicOrdering::Acquire;
658 case AtomicOrdering::SequentiallyConsistent:
659 return AtomicOrdering::SequentiallyConsistent;
663 // Methods for support type inquiry through isa, cast, and dyn_cast:
664 static bool classof(const Instruction *I) {
665 return I->getOpcode() == Instruction::AtomicCmpXchg;
667 static bool classof(const Value *V) {
668 return isa<Instruction>(V) && classof(cast<Instruction>(V));
671 private:
672 // Shadow Instruction::setInstructionSubclassData with a private forwarding
673 // method so that subclasses cannot accidentally use it.
674 void setInstructionSubclassData(unsigned short D) {
675 Instruction::setInstructionSubclassData(D);
678 /// The synchronization scope ID of this cmpxchg instruction. Not quite
679 /// enough room in SubClassData for everything, so synchronization scope ID
680 /// gets its own field.
681 SyncScope::ID SSID;
684 template <>
685 struct OperandTraits<AtomicCmpXchgInst> :
686 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
689 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
691 //===----------------------------------------------------------------------===//
692 // AtomicRMWInst Class
693 //===----------------------------------------------------------------------===//
695 /// an instruction that atomically reads a memory location,
696 /// combines it with another value, and then stores the result back. Returns
697 /// the old value.
699 class AtomicRMWInst : public Instruction {
700 protected:
701 // Note: Instruction needs to be a friend here to call cloneImpl.
702 friend class Instruction;
704 AtomicRMWInst *cloneImpl() const;
706 public:
707 /// This enumeration lists the possible modifications atomicrmw can make. In
708 /// the descriptions, 'p' is the pointer to the instruction's memory location,
709 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
710 /// instruction. These instructions always return 'old'.
711 enum BinOp {
712 /// *p = v
713 Xchg,
714 /// *p = old + v
715 Add,
716 /// *p = old - v
717 Sub,
718 /// *p = old & v
719 And,
720 /// *p = ~(old & v)
721 Nand,
722 /// *p = old | v
724 /// *p = old ^ v
725 Xor,
726 /// *p = old >signed v ? old : v
727 Max,
728 /// *p = old <signed v ? old : v
729 Min,
730 /// *p = old >unsigned v ? old : v
731 UMax,
732 /// *p = old <unsigned v ? old : v
733 UMin,
735 /// *p = old + v
736 FAdd,
738 /// *p = old - v
739 FSub,
741 FIRST_BINOP = Xchg,
742 LAST_BINOP = FSub,
743 BAD_BINOP
746 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
747 AtomicOrdering Ordering, SyncScope::ID SSID,
748 Instruction *InsertBefore = nullptr);
749 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
750 AtomicOrdering Ordering, SyncScope::ID SSID,
751 BasicBlock *InsertAtEnd);
753 // allocate space for exactly two operands
754 void *operator new(size_t s) {
755 return User::operator new(s, 2);
758 BinOp getOperation() const {
759 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
762 static StringRef getOperationName(BinOp Op);
764 static bool isFPOperation(BinOp Op) {
765 switch (Op) {
766 case AtomicRMWInst::FAdd:
767 case AtomicRMWInst::FSub:
768 return true;
769 default:
770 return false;
774 void setOperation(BinOp Operation) {
775 unsigned short SubclassData = getSubclassDataFromInstruction();
776 setInstructionSubclassData((SubclassData & 31) |
777 (Operation << 5));
780 /// Return true if this is a RMW on a volatile memory location.
782 bool isVolatile() const {
783 return getSubclassDataFromInstruction() & 1;
786 /// Specify whether this is a volatile RMW or not.
788 void setVolatile(bool V) {
789 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
790 (unsigned)V);
793 /// Transparently provide more efficient getOperand methods.
794 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
796 /// Returns the ordering constraint of this rmw instruction.
797 AtomicOrdering getOrdering() const {
798 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
801 /// Sets the ordering constraint of this rmw instruction.
802 void setOrdering(AtomicOrdering Ordering) {
803 assert(Ordering != AtomicOrdering::NotAtomic &&
804 "atomicrmw instructions can only be atomic.");
805 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
806 ((unsigned)Ordering << 2));
809 /// Returns the synchronization scope ID of this rmw instruction.
810 SyncScope::ID getSyncScopeID() const {
811 return SSID;
814 /// Sets the synchronization scope ID of this rmw instruction.
815 void setSyncScopeID(SyncScope::ID SSID) {
816 this->SSID = SSID;
819 Value *getPointerOperand() { return getOperand(0); }
820 const Value *getPointerOperand() const { return getOperand(0); }
821 static unsigned getPointerOperandIndex() { return 0U; }
823 Value *getValOperand() { return getOperand(1); }
824 const Value *getValOperand() const { return getOperand(1); }
826 /// Returns the address space of the pointer operand.
827 unsigned getPointerAddressSpace() const {
828 return getPointerOperand()->getType()->getPointerAddressSpace();
831 bool isFloatingPointOperation() const {
832 return isFPOperation(getOperation());
835 // Methods for support type inquiry through isa, cast, and dyn_cast:
836 static bool classof(const Instruction *I) {
837 return I->getOpcode() == Instruction::AtomicRMW;
839 static bool classof(const Value *V) {
840 return isa<Instruction>(V) && classof(cast<Instruction>(V));
843 private:
844 void Init(BinOp Operation, Value *Ptr, Value *Val,
845 AtomicOrdering Ordering, SyncScope::ID SSID);
847 // Shadow Instruction::setInstructionSubclassData with a private forwarding
848 // method so that subclasses cannot accidentally use it.
849 void setInstructionSubclassData(unsigned short D) {
850 Instruction::setInstructionSubclassData(D);
853 /// The synchronization scope ID of this rmw instruction. Not quite enough
854 /// room in SubClassData for everything, so synchronization scope ID gets its
855 /// own field.
856 SyncScope::ID SSID;
859 template <>
860 struct OperandTraits<AtomicRMWInst>
861 : public FixedNumOperandTraits<AtomicRMWInst,2> {
864 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
866 //===----------------------------------------------------------------------===//
867 // GetElementPtrInst Class
868 //===----------------------------------------------------------------------===//
870 // checkGEPType - Simple wrapper function to give a better assertion failure
871 // message on bad indexes for a gep instruction.
873 inline Type *checkGEPType(Type *Ty) {
874 assert(Ty && "Invalid GetElementPtrInst indices for type!");
875 return Ty;
878 /// an instruction for type-safe pointer arithmetic to
879 /// access elements of arrays and structs
881 class GetElementPtrInst : public Instruction {
882 Type *SourceElementType;
883 Type *ResultElementType;
885 GetElementPtrInst(const GetElementPtrInst &GEPI);
887 /// Constructors - Create a getelementptr instruction with a base pointer an
888 /// list of indices. The first ctor can optionally insert before an existing
889 /// instruction, the second appends the new instruction to the specified
890 /// BasicBlock.
891 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
892 ArrayRef<Value *> IdxList, unsigned Values,
893 const Twine &NameStr, Instruction *InsertBefore);
894 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
895 ArrayRef<Value *> IdxList, unsigned Values,
896 const Twine &NameStr, BasicBlock *InsertAtEnd);
898 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
900 protected:
901 // Note: Instruction needs to be a friend here to call cloneImpl.
902 friend class Instruction;
904 GetElementPtrInst *cloneImpl() const;
906 public:
907 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
908 ArrayRef<Value *> IdxList,
909 const Twine &NameStr = "",
910 Instruction *InsertBefore = nullptr) {
911 unsigned Values = 1 + unsigned(IdxList.size());
912 if (!PointeeType)
913 PointeeType =
914 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
915 else
916 assert(
917 PointeeType ==
918 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
919 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
920 NameStr, InsertBefore);
923 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
924 ArrayRef<Value *> IdxList,
925 const Twine &NameStr,
926 BasicBlock *InsertAtEnd) {
927 unsigned Values = 1 + unsigned(IdxList.size());
928 if (!PointeeType)
929 PointeeType =
930 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
931 else
932 assert(
933 PointeeType ==
934 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
935 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
936 NameStr, InsertAtEnd);
939 /// Create an "inbounds" getelementptr. See the documentation for the
940 /// "inbounds" flag in LangRef.html for details.
941 static GetElementPtrInst *CreateInBounds(Value *Ptr,
942 ArrayRef<Value *> IdxList,
943 const Twine &NameStr = "",
944 Instruction *InsertBefore = nullptr){
945 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
948 static GetElementPtrInst *
949 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
950 const Twine &NameStr = "",
951 Instruction *InsertBefore = nullptr) {
952 GetElementPtrInst *GEP =
953 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
954 GEP->setIsInBounds(true);
955 return GEP;
958 static GetElementPtrInst *CreateInBounds(Value *Ptr,
959 ArrayRef<Value *> IdxList,
960 const Twine &NameStr,
961 BasicBlock *InsertAtEnd) {
962 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
965 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
966 ArrayRef<Value *> IdxList,
967 const Twine &NameStr,
968 BasicBlock *InsertAtEnd) {
969 GetElementPtrInst *GEP =
970 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
971 GEP->setIsInBounds(true);
972 return GEP;
975 /// Transparently provide more efficient getOperand methods.
976 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
978 Type *getSourceElementType() const { return SourceElementType; }
980 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
981 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
983 Type *getResultElementType() const {
984 assert(ResultElementType ==
985 cast<PointerType>(getType()->getScalarType())->getElementType());
986 return ResultElementType;
989 /// Returns the address space of this instruction's pointer type.
990 unsigned getAddressSpace() const {
991 // Note that this is always the same as the pointer operand's address space
992 // and that is cheaper to compute, so cheat here.
993 return getPointerAddressSpace();
996 /// Returns the type of the element that would be loaded with
997 /// a load instruction with the specified parameters.
999 /// Null is returned if the indices are invalid for the specified
1000 /// pointer type.
1002 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1003 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1004 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1006 inline op_iterator idx_begin() { return op_begin()+1; }
1007 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1008 inline op_iterator idx_end() { return op_end(); }
1009 inline const_op_iterator idx_end() const { return op_end(); }
1011 inline iterator_range<op_iterator> indices() {
1012 return make_range(idx_begin(), idx_end());
1015 inline iterator_range<const_op_iterator> indices() const {
1016 return make_range(idx_begin(), idx_end());
1019 Value *getPointerOperand() {
1020 return getOperand(0);
1022 const Value *getPointerOperand() const {
1023 return getOperand(0);
1025 static unsigned getPointerOperandIndex() {
1026 return 0U; // get index for modifying correct operand.
1029 /// Method to return the pointer operand as a
1030 /// PointerType.
1031 Type *getPointerOperandType() const {
1032 return getPointerOperand()->getType();
1035 /// Returns the address space of the pointer operand.
1036 unsigned getPointerAddressSpace() const {
1037 return getPointerOperandType()->getPointerAddressSpace();
1040 /// Returns the pointer type returned by the GEP
1041 /// instruction, which may be a vector of pointers.
1042 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1043 return getGEPReturnType(
1044 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1045 Ptr, IdxList);
1047 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1048 ArrayRef<Value *> IdxList) {
1049 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1050 Ptr->getType()->getPointerAddressSpace());
1051 // Vector GEP
1052 if (Ptr->getType()->isVectorTy()) {
1053 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1054 return VectorType::get(PtrTy, NumElem);
1056 for (Value *Index : IdxList)
1057 if (Index->getType()->isVectorTy()) {
1058 unsigned NumElem = Index->getType()->getVectorNumElements();
1059 return VectorType::get(PtrTy, NumElem);
1061 // Scalar GEP
1062 return PtrTy;
1065 unsigned getNumIndices() const { // Note: always non-negative
1066 return getNumOperands() - 1;
1069 bool hasIndices() const {
1070 return getNumOperands() > 1;
1073 /// Return true if all of the indices of this GEP are
1074 /// zeros. If so, the result pointer and the first operand have the same
1075 /// value, just potentially different types.
1076 bool hasAllZeroIndices() const;
1078 /// Return true if all of the indices of this GEP are
1079 /// constant integers. If so, the result pointer and the first operand have
1080 /// a constant offset between them.
1081 bool hasAllConstantIndices() const;
1083 /// Set or clear the inbounds flag on this GEP instruction.
1084 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1085 void setIsInBounds(bool b = true);
1087 /// Determine whether the GEP has the inbounds flag.
1088 bool isInBounds() const;
1090 /// Accumulate the constant address offset of this GEP if possible.
1092 /// This routine accepts an APInt into which it will accumulate the constant
1093 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1094 /// all-constant, it returns false and the value of the offset APInt is
1095 /// undefined (it is *not* preserved!). The APInt passed into this routine
1096 /// must be at least as wide as the IntPtr type for the address space of
1097 /// the base GEP pointer.
1098 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1100 // Methods for support type inquiry through isa, cast, and dyn_cast:
1101 static bool classof(const Instruction *I) {
1102 return (I->getOpcode() == Instruction::GetElementPtr);
1104 static bool classof(const Value *V) {
1105 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1109 template <>
1110 struct OperandTraits<GetElementPtrInst> :
1111 public VariadicOperandTraits<GetElementPtrInst, 1> {
1114 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1115 ArrayRef<Value *> IdxList, unsigned Values,
1116 const Twine &NameStr,
1117 Instruction *InsertBefore)
1118 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1119 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1120 Values, InsertBefore),
1121 SourceElementType(PointeeType),
1122 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1123 assert(ResultElementType ==
1124 cast<PointerType>(getType()->getScalarType())->getElementType());
1125 init(Ptr, IdxList, NameStr);
1128 GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1129 ArrayRef<Value *> IdxList, unsigned Values,
1130 const Twine &NameStr,
1131 BasicBlock *InsertAtEnd)
1132 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1133 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1134 Values, InsertAtEnd),
1135 SourceElementType(PointeeType),
1136 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1137 assert(ResultElementType ==
1138 cast<PointerType>(getType()->getScalarType())->getElementType());
1139 init(Ptr, IdxList, NameStr);
1142 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
1144 //===----------------------------------------------------------------------===//
1145 // ICmpInst Class
1146 //===----------------------------------------------------------------------===//
1148 /// This instruction compares its operands according to the predicate given
1149 /// to the constructor. It only operates on integers or pointers. The operands
1150 /// must be identical types.
1151 /// Represent an integer comparison operator.
1152 class ICmpInst: public CmpInst {
1153 void AssertOK() {
1154 assert(isIntPredicate() &&
1155 "Invalid ICmp predicate value");
1156 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1157 "Both operands to ICmp instruction are not of the same type!");
1158 // Check that the operands are the right type
1159 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
1160 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
1161 "Invalid operand types for ICmp instruction");
1164 protected:
1165 // Note: Instruction needs to be a friend here to call cloneImpl.
1166 friend class Instruction;
1168 /// Clone an identical ICmpInst
1169 ICmpInst *cloneImpl() const;
1171 public:
1172 /// Constructor with insert-before-instruction semantics.
1173 ICmpInst(
1174 Instruction *InsertBefore, ///< Where to insert
1175 Predicate pred, ///< The predicate to use for the comparison
1176 Value *LHS, ///< The left-hand-side of the expression
1177 Value *RHS, ///< The right-hand-side of the expression
1178 const Twine &NameStr = "" ///< Name of the instruction
1179 ) : CmpInst(makeCmpResultType(LHS->getType()),
1180 Instruction::ICmp, pred, LHS, RHS, NameStr,
1181 InsertBefore) {
1182 #ifndef NDEBUG
1183 AssertOK();
1184 #endif
1187 /// Constructor with insert-at-end semantics.
1188 ICmpInst(
1189 BasicBlock &InsertAtEnd, ///< Block to insert into.
1190 Predicate pred, ///< The predicate to use for the comparison
1191 Value *LHS, ///< The left-hand-side of the expression
1192 Value *RHS, ///< The right-hand-side of the expression
1193 const Twine &NameStr = "" ///< Name of the instruction
1194 ) : CmpInst(makeCmpResultType(LHS->getType()),
1195 Instruction::ICmp, pred, LHS, RHS, NameStr,
1196 &InsertAtEnd) {
1197 #ifndef NDEBUG
1198 AssertOK();
1199 #endif
1202 /// Constructor with no-insertion semantics
1203 ICmpInst(
1204 Predicate pred, ///< The predicate to use for the comparison
1205 Value *LHS, ///< The left-hand-side of the expression
1206 Value *RHS, ///< The right-hand-side of the expression
1207 const Twine &NameStr = "" ///< Name of the instruction
1208 ) : CmpInst(makeCmpResultType(LHS->getType()),
1209 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1210 #ifndef NDEBUG
1211 AssertOK();
1212 #endif
1215 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1216 /// @returns the predicate that would be the result if the operand were
1217 /// regarded as signed.
1218 /// Return the signed version of the predicate
1219 Predicate getSignedPredicate() const {
1220 return getSignedPredicate(getPredicate());
1223 /// This is a static version that you can use without an instruction.
1224 /// Return the signed version of the predicate.
1225 static Predicate getSignedPredicate(Predicate pred);
1227 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1228 /// @returns the predicate that would be the result if the operand were
1229 /// regarded as unsigned.
1230 /// Return the unsigned version of the predicate
1231 Predicate getUnsignedPredicate() const {
1232 return getUnsignedPredicate(getPredicate());
1235 /// This is a static version that you can use without an instruction.
1236 /// Return the unsigned version of the predicate.
1237 static Predicate getUnsignedPredicate(Predicate pred);
1239 /// Return true if this predicate is either EQ or NE. This also
1240 /// tests for commutativity.
1241 static bool isEquality(Predicate P) {
1242 return P == ICMP_EQ || P == ICMP_NE;
1245 /// Return true if this predicate is either EQ or NE. This also
1246 /// tests for commutativity.
1247 bool isEquality() const {
1248 return isEquality(getPredicate());
1251 /// @returns true if the predicate of this ICmpInst is commutative
1252 /// Determine if this relation is commutative.
1253 bool isCommutative() const { return isEquality(); }
1255 /// Return true if the predicate is relational (not EQ or NE).
1257 bool isRelational() const {
1258 return !isEquality();
1261 /// Return true if the predicate is relational (not EQ or NE).
1263 static bool isRelational(Predicate P) {
1264 return !isEquality(P);
1267 /// Exchange the two operands to this instruction in such a way that it does
1268 /// not modify the semantics of the instruction. The predicate value may be
1269 /// changed to retain the same result if the predicate is order dependent
1270 /// (e.g. ult).
1271 /// Swap operands and adjust predicate.
1272 void swapOperands() {
1273 setPredicate(getSwappedPredicate());
1274 Op<0>().swap(Op<1>());
1277 // Methods for support type inquiry through isa, cast, and dyn_cast:
1278 static bool classof(const Instruction *I) {
1279 return I->getOpcode() == Instruction::ICmp;
1281 static bool classof(const Value *V) {
1282 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1286 //===----------------------------------------------------------------------===//
1287 // FCmpInst Class
1288 //===----------------------------------------------------------------------===//
1290 /// This instruction compares its operands according to the predicate given
1291 /// to the constructor. It only operates on floating point values or packed
1292 /// vectors of floating point values. The operands must be identical types.
1293 /// Represents a floating point comparison operator.
1294 class FCmpInst: public CmpInst {
1295 void AssertOK() {
1296 assert(isFPPredicate() && "Invalid FCmp predicate value");
1297 assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1298 "Both operands to FCmp instruction are not of the same type!");
1299 // Check that the operands are the right type
1300 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1301 "Invalid operand types for FCmp instruction");
1304 protected:
1305 // Note: Instruction needs to be a friend here to call cloneImpl.
1306 friend class Instruction;
1308 /// Clone an identical FCmpInst
1309 FCmpInst *cloneImpl() const;
1311 public:
1312 /// Constructor with insert-before-instruction semantics.
1313 FCmpInst(
1314 Instruction *InsertBefore, ///< Where to insert
1315 Predicate pred, ///< The predicate to use for the comparison
1316 Value *LHS, ///< The left-hand-side of the expression
1317 Value *RHS, ///< The right-hand-side of the expression
1318 const Twine &NameStr = "" ///< Name of the instruction
1319 ) : CmpInst(makeCmpResultType(LHS->getType()),
1320 Instruction::FCmp, pred, LHS, RHS, NameStr,
1321 InsertBefore) {
1322 AssertOK();
1325 /// Constructor with insert-at-end semantics.
1326 FCmpInst(
1327 BasicBlock &InsertAtEnd, ///< Block to insert into.
1328 Predicate pred, ///< The predicate to use for the comparison
1329 Value *LHS, ///< The left-hand-side of the expression
1330 Value *RHS, ///< The right-hand-side of the expression
1331 const Twine &NameStr = "" ///< Name of the instruction
1332 ) : CmpInst(makeCmpResultType(LHS->getType()),
1333 Instruction::FCmp, pred, LHS, RHS, NameStr,
1334 &InsertAtEnd) {
1335 AssertOK();
1338 /// Constructor with no-insertion semantics
1339 FCmpInst(
1340 Predicate Pred, ///< The predicate to use for the comparison
1341 Value *LHS, ///< The left-hand-side of the expression
1342 Value *RHS, ///< The right-hand-side of the expression
1343 const Twine &NameStr = "", ///< Name of the instruction
1344 Instruction *FlagsSource = nullptr
1345 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1346 RHS, NameStr, nullptr, FlagsSource) {
1347 AssertOK();
1350 /// @returns true if the predicate of this instruction is EQ or NE.
1351 /// Determine if this is an equality predicate.
1352 static bool isEquality(Predicate Pred) {
1353 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1354 Pred == FCMP_UNE;
1357 /// @returns true if the predicate of this instruction is EQ or NE.
1358 /// Determine if this is an equality predicate.
1359 bool isEquality() const { return isEquality(getPredicate()); }
1361 /// @returns true if the predicate of this instruction is commutative.
1362 /// Determine if this is a commutative predicate.
1363 bool isCommutative() const {
1364 return isEquality() ||
1365 getPredicate() == FCMP_FALSE ||
1366 getPredicate() == FCMP_TRUE ||
1367 getPredicate() == FCMP_ORD ||
1368 getPredicate() == FCMP_UNO;
1371 /// @returns true if the predicate is relational (not EQ or NE).
1372 /// Determine if this a relational predicate.
1373 bool isRelational() const { return !isEquality(); }
1375 /// Exchange the two operands to this instruction in such a way that it does
1376 /// not modify the semantics of the instruction. The predicate value may be
1377 /// changed to retain the same result if the predicate is order dependent
1378 /// (e.g. ult).
1379 /// Swap operands and adjust predicate.
1380 void swapOperands() {
1381 setPredicate(getSwappedPredicate());
1382 Op<0>().swap(Op<1>());
1385 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1386 static bool classof(const Instruction *I) {
1387 return I->getOpcode() == Instruction::FCmp;
1389 static bool classof(const Value *V) {
1390 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1394 //===----------------------------------------------------------------------===//
1395 /// This class represents a function call, abstracting a target
1396 /// machine's calling convention. This class uses low bit of the SubClassData
1397 /// field to indicate whether or not this is a tail call. The rest of the bits
1398 /// hold the calling convention of the call.
1400 class CallInst : public CallBase {
1401 CallInst(const CallInst &CI);
1403 /// Construct a CallInst given a range of arguments.
1404 /// Construct a CallInst from a range of arguments
1405 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1406 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1407 Instruction *InsertBefore);
1409 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1410 const Twine &NameStr, Instruction *InsertBefore)
1411 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1413 /// Construct a CallInst given a range of arguments.
1414 /// Construct a CallInst from a range of arguments
1415 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1416 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1417 BasicBlock *InsertAtEnd);
1419 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1420 Instruction *InsertBefore);
1422 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1423 BasicBlock *InsertAtEnd);
1425 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1426 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1427 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1429 /// Compute the number of operands to allocate.
1430 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1431 // We need one operand for the called function, plus the input operand
1432 // counts provided.
1433 return 1 + NumArgs + NumBundleInputs;
1436 protected:
1437 // Note: Instruction needs to be a friend here to call cloneImpl.
1438 friend class Instruction;
1440 CallInst *cloneImpl() const;
1442 public:
1443 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1444 Instruction *InsertBefore = nullptr) {
1445 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1448 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1449 const Twine &NameStr,
1450 Instruction *InsertBefore = nullptr) {
1451 return new (ComputeNumOperands(Args.size()))
1452 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1455 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1456 ArrayRef<OperandBundleDef> Bundles = None,
1457 const Twine &NameStr = "",
1458 Instruction *InsertBefore = nullptr) {
1459 const int NumOperands =
1460 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1461 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1463 return new (NumOperands, DescriptorBytes)
1464 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1467 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1468 BasicBlock *InsertAtEnd) {
1469 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1472 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1473 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1474 return new (ComputeNumOperands(Args.size()))
1475 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1478 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1479 ArrayRef<OperandBundleDef> Bundles,
1480 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1481 const int NumOperands =
1482 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1483 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1485 return new (NumOperands, DescriptorBytes)
1486 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1489 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1490 Instruction *InsertBefore = nullptr) {
1491 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1492 InsertBefore);
1495 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1496 ArrayRef<OperandBundleDef> Bundles = None,
1497 const Twine &NameStr = "",
1498 Instruction *InsertBefore = nullptr) {
1499 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1500 NameStr, InsertBefore);
1503 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1504 const Twine &NameStr,
1505 Instruction *InsertBefore = nullptr) {
1506 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1507 InsertBefore);
1510 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1511 BasicBlock *InsertAtEnd) {
1512 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1513 InsertAtEnd);
1516 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1517 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1518 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1519 InsertAtEnd);
1522 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1523 ArrayRef<OperandBundleDef> Bundles,
1524 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1525 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1526 NameStr, InsertAtEnd);
1529 // Deprecated [opaque pointer types]
1530 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1531 Instruction *InsertBefore = nullptr) {
1532 return Create(cast<FunctionType>(
1533 cast<PointerType>(Func->getType())->getElementType()),
1534 Func, NameStr, InsertBefore);
1537 // Deprecated [opaque pointer types]
1538 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1539 const Twine &NameStr,
1540 Instruction *InsertBefore = nullptr) {
1541 return Create(cast<FunctionType>(
1542 cast<PointerType>(Func->getType())->getElementType()),
1543 Func, Args, NameStr, InsertBefore);
1546 // Deprecated [opaque pointer types]
1547 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1548 ArrayRef<OperandBundleDef> Bundles = None,
1549 const Twine &NameStr = "",
1550 Instruction *InsertBefore = nullptr) {
1551 return Create(cast<FunctionType>(
1552 cast<PointerType>(Func->getType())->getElementType()),
1553 Func, Args, Bundles, NameStr, InsertBefore);
1556 // Deprecated [opaque pointer types]
1557 static CallInst *Create(Value *Func, const Twine &NameStr,
1558 BasicBlock *InsertAtEnd) {
1559 return Create(cast<FunctionType>(
1560 cast<PointerType>(Func->getType())->getElementType()),
1561 Func, NameStr, InsertAtEnd);
1564 // Deprecated [opaque pointer types]
1565 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1566 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1567 return Create(cast<FunctionType>(
1568 cast<PointerType>(Func->getType())->getElementType()),
1569 Func, Args, NameStr, InsertAtEnd);
1572 // Deprecated [opaque pointer types]
1573 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1574 ArrayRef<OperandBundleDef> Bundles,
1575 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1576 return Create(cast<FunctionType>(
1577 cast<PointerType>(Func->getType())->getElementType()),
1578 Func, Args, Bundles, NameStr, InsertAtEnd);
1581 /// Create a clone of \p CI with a different set of operand bundles and
1582 /// insert it before \p InsertPt.
1584 /// The returned call instruction is identical \p CI in every way except that
1585 /// the operand bundles for the new instruction are set to the operand bundles
1586 /// in \p Bundles.
1587 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1588 Instruction *InsertPt = nullptr);
1590 /// Generate the IR for a call to malloc:
1591 /// 1. Compute the malloc call's argument as the specified type's size,
1592 /// possibly multiplied by the array size if the array size is not
1593 /// constant 1.
1594 /// 2. Call malloc with that argument.
1595 /// 3. Bitcast the result of the malloc call to the specified type.
1596 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1597 Type *AllocTy, Value *AllocSize,
1598 Value *ArraySize = nullptr,
1599 Function *MallocF = nullptr,
1600 const Twine &Name = "");
1601 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1602 Type *AllocTy, Value *AllocSize,
1603 Value *ArraySize = nullptr,
1604 Function *MallocF = nullptr,
1605 const Twine &Name = "");
1606 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1607 Type *AllocTy, Value *AllocSize,
1608 Value *ArraySize = nullptr,
1609 ArrayRef<OperandBundleDef> Bundles = None,
1610 Function *MallocF = nullptr,
1611 const Twine &Name = "");
1612 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1613 Type *AllocTy, Value *AllocSize,
1614 Value *ArraySize = nullptr,
1615 ArrayRef<OperandBundleDef> Bundles = None,
1616 Function *MallocF = nullptr,
1617 const Twine &Name = "");
1618 /// Generate the IR for a call to the builtin free function.
1619 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1620 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1621 static Instruction *CreateFree(Value *Source,
1622 ArrayRef<OperandBundleDef> Bundles,
1623 Instruction *InsertBefore);
1624 static Instruction *CreateFree(Value *Source,
1625 ArrayRef<OperandBundleDef> Bundles,
1626 BasicBlock *InsertAtEnd);
1628 // Note that 'musttail' implies 'tail'.
1629 enum TailCallKind {
1630 TCK_None = 0,
1631 TCK_Tail = 1,
1632 TCK_MustTail = 2,
1633 TCK_NoTail = 3
1635 TailCallKind getTailCallKind() const {
1636 return TailCallKind(getSubclassDataFromInstruction() & 3);
1639 bool isTailCall() const {
1640 unsigned Kind = getSubclassDataFromInstruction() & 3;
1641 return Kind == TCK_Tail || Kind == TCK_MustTail;
1644 bool isMustTailCall() const {
1645 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1648 bool isNoTailCall() const {
1649 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1652 void setTailCall(bool isTC = true) {
1653 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1654 unsigned(isTC ? TCK_Tail : TCK_None));
1657 void setTailCallKind(TailCallKind TCK) {
1658 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1659 unsigned(TCK));
1662 /// Return true if the call can return twice
1663 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1664 void setCanReturnTwice() {
1665 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1668 // Methods for support type inquiry through isa, cast, and dyn_cast:
1669 static bool classof(const Instruction *I) {
1670 return I->getOpcode() == Instruction::Call;
1672 static bool classof(const Value *V) {
1673 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1676 /// Updates profile metadata by scaling it by \p S / \p T.
1677 void updateProfWeight(uint64_t S, uint64_t T);
1679 private:
1680 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1681 // method so that subclasses cannot accidentally use it.
1682 void setInstructionSubclassData(unsigned short D) {
1683 Instruction::setInstructionSubclassData(D);
1687 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1688 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1689 BasicBlock *InsertAtEnd)
1690 : CallBase(Ty->getReturnType(), Instruction::Call,
1691 OperandTraits<CallBase>::op_end(this) -
1692 (Args.size() + CountBundleInputs(Bundles) + 1),
1693 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1694 InsertAtEnd) {
1695 init(Ty, Func, Args, Bundles, NameStr);
1698 CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1699 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1700 Instruction *InsertBefore)
1701 : CallBase(Ty->getReturnType(), Instruction::Call,
1702 OperandTraits<CallBase>::op_end(this) -
1703 (Args.size() + CountBundleInputs(Bundles) + 1),
1704 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1705 InsertBefore) {
1706 init(Ty, Func, Args, Bundles, NameStr);
1709 //===----------------------------------------------------------------------===//
1710 // SelectInst Class
1711 //===----------------------------------------------------------------------===//
1713 /// This class represents the LLVM 'select' instruction.
1715 class SelectInst : public Instruction {
1716 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1717 Instruction *InsertBefore)
1718 : Instruction(S1->getType(), Instruction::Select,
1719 &Op<0>(), 3, InsertBefore) {
1720 init(C, S1, S2);
1721 setName(NameStr);
1724 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1725 BasicBlock *InsertAtEnd)
1726 : Instruction(S1->getType(), Instruction::Select,
1727 &Op<0>(), 3, InsertAtEnd) {
1728 init(C, S1, S2);
1729 setName(NameStr);
1732 void init(Value *C, Value *S1, Value *S2) {
1733 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1734 Op<0>() = C;
1735 Op<1>() = S1;
1736 Op<2>() = S2;
1739 protected:
1740 // Note: Instruction needs to be a friend here to call cloneImpl.
1741 friend class Instruction;
1743 SelectInst *cloneImpl() const;
1745 public:
1746 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1747 const Twine &NameStr = "",
1748 Instruction *InsertBefore = nullptr,
1749 Instruction *MDFrom = nullptr) {
1750 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1751 if (MDFrom)
1752 Sel->copyMetadata(*MDFrom);
1753 return Sel;
1756 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1757 const Twine &NameStr,
1758 BasicBlock *InsertAtEnd) {
1759 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1762 const Value *getCondition() const { return Op<0>(); }
1763 const Value *getTrueValue() const { return Op<1>(); }
1764 const Value *getFalseValue() const { return Op<2>(); }
1765 Value *getCondition() { return Op<0>(); }
1766 Value *getTrueValue() { return Op<1>(); }
1767 Value *getFalseValue() { return Op<2>(); }
1769 void setCondition(Value *V) { Op<0>() = V; }
1770 void setTrueValue(Value *V) { Op<1>() = V; }
1771 void setFalseValue(Value *V) { Op<2>() = V; }
1773 /// Swap the true and false values of the select instruction.
1774 /// This doesn't swap prof metadata.
1775 void swapValues() { Op<1>().swap(Op<2>()); }
1777 /// Return a string if the specified operands are invalid
1778 /// for a select operation, otherwise return null.
1779 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1781 /// Transparently provide more efficient getOperand methods.
1782 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1784 OtherOps getOpcode() const {
1785 return static_cast<OtherOps>(Instruction::getOpcode());
1788 // Methods for support type inquiry through isa, cast, and dyn_cast:
1789 static bool classof(const Instruction *I) {
1790 return I->getOpcode() == Instruction::Select;
1792 static bool classof(const Value *V) {
1793 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1797 template <>
1798 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1801 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1803 //===----------------------------------------------------------------------===//
1804 // VAArgInst Class
1805 //===----------------------------------------------------------------------===//
1807 /// This class represents the va_arg llvm instruction, which returns
1808 /// an argument of the specified type given a va_list and increments that list
1810 class VAArgInst : public UnaryInstruction {
1811 protected:
1812 // Note: Instruction needs to be a friend here to call cloneImpl.
1813 friend class Instruction;
1815 VAArgInst *cloneImpl() const;
1817 public:
1818 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1819 Instruction *InsertBefore = nullptr)
1820 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1821 setName(NameStr);
1824 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1825 BasicBlock *InsertAtEnd)
1826 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1827 setName(NameStr);
1830 Value *getPointerOperand() { return getOperand(0); }
1831 const Value *getPointerOperand() const { return getOperand(0); }
1832 static unsigned getPointerOperandIndex() { return 0U; }
1834 // Methods for support type inquiry through isa, cast, and dyn_cast:
1835 static bool classof(const Instruction *I) {
1836 return I->getOpcode() == VAArg;
1838 static bool classof(const Value *V) {
1839 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1843 //===----------------------------------------------------------------------===//
1844 // ExtractElementInst Class
1845 //===----------------------------------------------------------------------===//
1847 /// This instruction extracts a single (scalar)
1848 /// element from a VectorType value
1850 class ExtractElementInst : public Instruction {
1851 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1852 Instruction *InsertBefore = nullptr);
1853 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1854 BasicBlock *InsertAtEnd);
1856 protected:
1857 // Note: Instruction needs to be a friend here to call cloneImpl.
1858 friend class Instruction;
1860 ExtractElementInst *cloneImpl() const;
1862 public:
1863 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1864 const Twine &NameStr = "",
1865 Instruction *InsertBefore = nullptr) {
1866 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1869 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1870 const Twine &NameStr,
1871 BasicBlock *InsertAtEnd) {
1872 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1875 /// Return true if an extractelement instruction can be
1876 /// formed with the specified operands.
1877 static bool isValidOperands(const Value *Vec, const Value *Idx);
1879 Value *getVectorOperand() { return Op<0>(); }
1880 Value *getIndexOperand() { return Op<1>(); }
1881 const Value *getVectorOperand() const { return Op<0>(); }
1882 const Value *getIndexOperand() const { return Op<1>(); }
1884 VectorType *getVectorOperandType() const {
1885 return cast<VectorType>(getVectorOperand()->getType());
1888 /// Transparently provide more efficient getOperand methods.
1889 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1891 // Methods for support type inquiry through isa, cast, and dyn_cast:
1892 static bool classof(const Instruction *I) {
1893 return I->getOpcode() == Instruction::ExtractElement;
1895 static bool classof(const Value *V) {
1896 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1900 template <>
1901 struct OperandTraits<ExtractElementInst> :
1902 public FixedNumOperandTraits<ExtractElementInst, 2> {
1905 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1907 //===----------------------------------------------------------------------===//
1908 // InsertElementInst Class
1909 //===----------------------------------------------------------------------===//
1911 /// This instruction inserts a single (scalar)
1912 /// element into a VectorType value
1914 class InsertElementInst : public Instruction {
1915 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1916 const Twine &NameStr = "",
1917 Instruction *InsertBefore = nullptr);
1918 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1919 BasicBlock *InsertAtEnd);
1921 protected:
1922 // Note: Instruction needs to be a friend here to call cloneImpl.
1923 friend class Instruction;
1925 InsertElementInst *cloneImpl() const;
1927 public:
1928 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1929 const Twine &NameStr = "",
1930 Instruction *InsertBefore = nullptr) {
1931 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1934 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1935 const Twine &NameStr,
1936 BasicBlock *InsertAtEnd) {
1937 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1940 /// Return true if an insertelement instruction can be
1941 /// formed with the specified operands.
1942 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1943 const Value *Idx);
1945 /// Overload to return most specific vector type.
1947 VectorType *getType() const {
1948 return cast<VectorType>(Instruction::getType());
1951 /// Transparently provide more efficient getOperand methods.
1952 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1954 // Methods for support type inquiry through isa, cast, and dyn_cast:
1955 static bool classof(const Instruction *I) {
1956 return I->getOpcode() == Instruction::InsertElement;
1958 static bool classof(const Value *V) {
1959 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1963 template <>
1964 struct OperandTraits<InsertElementInst> :
1965 public FixedNumOperandTraits<InsertElementInst, 3> {
1968 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1970 //===----------------------------------------------------------------------===//
1971 // ShuffleVectorInst Class
1972 //===----------------------------------------------------------------------===//
1974 /// This instruction constructs a fixed permutation of two
1975 /// input vectors.
1977 class ShuffleVectorInst : public Instruction {
1978 protected:
1979 // Note: Instruction needs to be a friend here to call cloneImpl.
1980 friend class Instruction;
1982 ShuffleVectorInst *cloneImpl() const;
1984 public:
1985 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1986 const Twine &NameStr = "",
1987 Instruction *InsertBefor = nullptr);
1988 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1989 const Twine &NameStr, BasicBlock *InsertAtEnd);
1991 // allocate space for exactly three operands
1992 void *operator new(size_t s) {
1993 return User::operator new(s, 3);
1996 /// Swap the first 2 operands and adjust the mask to preserve the semantics
1997 /// of the instruction.
1998 void commute();
2000 /// Return true if a shufflevector instruction can be
2001 /// formed with the specified operands.
2002 static bool isValidOperands(const Value *V1, const Value *V2,
2003 const Value *Mask);
2005 /// Overload to return most specific vector type.
2007 VectorType *getType() const {
2008 return cast<VectorType>(Instruction::getType());
2011 /// Transparently provide more efficient getOperand methods.
2012 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2014 Constant *getMask() const {
2015 return cast<Constant>(getOperand(2));
2018 /// Return the shuffle mask value for the specified element of the mask.
2019 /// Return -1 if the element is undef.
2020 static int getMaskValue(const Constant *Mask, unsigned Elt);
2022 /// Return the shuffle mask value of this instruction for the given element
2023 /// index. Return -1 if the element is undef.
2024 int getMaskValue(unsigned Elt) const {
2025 return getMaskValue(getMask(), Elt);
2028 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2029 /// elements of the mask are returned as -1.
2030 static void getShuffleMask(const Constant *Mask,
2031 SmallVectorImpl<int> &Result);
2033 /// Return the mask for this instruction as a vector of integers. Undefined
2034 /// elements of the mask are returned as -1.
2035 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2036 return getShuffleMask(getMask(), Result);
2039 SmallVector<int, 16> getShuffleMask() const {
2040 SmallVector<int, 16> Mask;
2041 getShuffleMask(Mask);
2042 return Mask;
2045 /// Return true if this shuffle returns a vector with a different number of
2046 /// elements than its source vectors.
2047 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2048 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2049 bool changesLength() const {
2050 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2051 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2052 return NumSourceElts != NumMaskElts;
2055 /// Return true if this shuffle returns a vector with a greater number of
2056 /// elements than its source vectors.
2057 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2058 bool increasesLength() const {
2059 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2060 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2061 return NumSourceElts < NumMaskElts;
2064 /// Return true if this shuffle mask chooses elements from exactly one source
2065 /// vector.
2066 /// Example: <7,5,undef,7>
2067 /// This assumes that vector operands are the same length as the mask.
2068 static bool isSingleSourceMask(ArrayRef<int> Mask);
2069 static bool isSingleSourceMask(const Constant *Mask) {
2070 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2071 SmallVector<int, 16> MaskAsInts;
2072 getShuffleMask(Mask, MaskAsInts);
2073 return isSingleSourceMask(MaskAsInts);
2076 /// Return true if this shuffle chooses elements from exactly one source
2077 /// vector without changing the length of that vector.
2078 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2079 /// TODO: Optionally allow length-changing shuffles.
2080 bool isSingleSource() const {
2081 return !changesLength() && isSingleSourceMask(getMask());
2084 /// Return true if this shuffle mask chooses elements from exactly one source
2085 /// vector without lane crossings. A shuffle using this mask is not
2086 /// necessarily a no-op because it may change the number of elements from its
2087 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2088 /// Example: <undef,undef,2,3>
2089 static bool isIdentityMask(ArrayRef<int> Mask);
2090 static bool isIdentityMask(const Constant *Mask) {
2091 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2092 SmallVector<int, 16> MaskAsInts;
2093 getShuffleMask(Mask, MaskAsInts);
2094 return isIdentityMask(MaskAsInts);
2097 /// Return true if this shuffle chooses elements from exactly one source
2098 /// vector without lane crossings and does not change the number of elements
2099 /// from its input vectors.
2100 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2101 bool isIdentity() const {
2102 return !changesLength() && isIdentityMask(getShuffleMask());
2105 /// Return true if this shuffle lengthens exactly one source vector with
2106 /// undefs in the high elements.
2107 bool isIdentityWithPadding() const;
2109 /// Return true if this shuffle extracts the first N elements of exactly one
2110 /// source vector.
2111 bool isIdentityWithExtract() const;
2113 /// Return true if this shuffle concatenates its 2 source vectors. This
2114 /// returns false if either input is undefined. In that case, the shuffle is
2115 /// is better classified as an identity with padding operation.
2116 bool isConcat() const;
2118 /// Return true if this shuffle mask chooses elements from its source vectors
2119 /// without lane crossings. A shuffle using this mask would be
2120 /// equivalent to a vector select with a constant condition operand.
2121 /// Example: <4,1,6,undef>
2122 /// This returns false if the mask does not choose from both input vectors.
2123 /// In that case, the shuffle is better classified as an identity shuffle.
2124 /// This assumes that vector operands are the same length as the mask
2125 /// (a length-changing shuffle can never be equivalent to a vector select).
2126 static bool isSelectMask(ArrayRef<int> Mask);
2127 static bool isSelectMask(const Constant *Mask) {
2128 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2129 SmallVector<int, 16> MaskAsInts;
2130 getShuffleMask(Mask, MaskAsInts);
2131 return isSelectMask(MaskAsInts);
2134 /// Return true if this shuffle chooses elements from its source vectors
2135 /// without lane crossings and all operands have the same number of elements.
2136 /// In other words, this shuffle is equivalent to a vector select with a
2137 /// constant condition operand.
2138 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2139 /// This returns false if the mask does not choose from both input vectors.
2140 /// In that case, the shuffle is better classified as an identity shuffle.
2141 /// TODO: Optionally allow length-changing shuffles.
2142 bool isSelect() const {
2143 return !changesLength() && isSelectMask(getMask());
2146 /// Return true if this shuffle mask swaps the order of elements from exactly
2147 /// one source vector.
2148 /// Example: <7,6,undef,4>
2149 /// This assumes that vector operands are the same length as the mask.
2150 static bool isReverseMask(ArrayRef<int> Mask);
2151 static bool isReverseMask(const Constant *Mask) {
2152 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2153 SmallVector<int, 16> MaskAsInts;
2154 getShuffleMask(Mask, MaskAsInts);
2155 return isReverseMask(MaskAsInts);
2158 /// Return true if this shuffle swaps the order of elements from exactly
2159 /// one source vector.
2160 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2161 /// TODO: Optionally allow length-changing shuffles.
2162 bool isReverse() const {
2163 return !changesLength() && isReverseMask(getMask());
2166 /// Return true if this shuffle mask chooses all elements with the same value
2167 /// as the first element of exactly one source vector.
2168 /// Example: <4,undef,undef,4>
2169 /// This assumes that vector operands are the same length as the mask.
2170 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2171 static bool isZeroEltSplatMask(const Constant *Mask) {
2172 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2173 SmallVector<int, 16> MaskAsInts;
2174 getShuffleMask(Mask, MaskAsInts);
2175 return isZeroEltSplatMask(MaskAsInts);
2178 /// Return true if all elements of this shuffle are the same value as the
2179 /// first element of exactly one source vector without changing the length
2180 /// of that vector.
2181 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2182 /// TODO: Optionally allow length-changing shuffles.
2183 /// TODO: Optionally allow splats from other elements.
2184 bool isZeroEltSplat() const {
2185 return !changesLength() && isZeroEltSplatMask(getMask());
2188 /// Return true if this shuffle mask is a transpose mask.
2189 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2190 /// even- or odd-numbered vector elements from two n-dimensional source
2191 /// vectors and write each result into consecutive elements of an
2192 /// n-dimensional destination vector. Two shuffles are necessary to complete
2193 /// the transpose, one for the even elements and another for the odd elements.
2194 /// This description closely follows how the TRN1 and TRN2 AArch64
2195 /// instructions operate.
2197 /// For example, a simple 2x2 matrix can be transposed with:
2199 /// ; Original matrix
2200 /// m0 = < a, b >
2201 /// m1 = < c, d >
2203 /// ; Transposed matrix
2204 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2205 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2207 /// For matrices having greater than n columns, the resulting nx2 transposed
2208 /// matrix is stored in two result vectors such that one vector contains
2209 /// interleaved elements from all the even-numbered rows and the other vector
2210 /// contains interleaved elements from all the odd-numbered rows. For example,
2211 /// a 2x4 matrix can be transposed with:
2213 /// ; Original matrix
2214 /// m0 = < a, b, c, d >
2215 /// m1 = < e, f, g, h >
2217 /// ; Transposed matrix
2218 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2219 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2220 static bool isTransposeMask(ArrayRef<int> Mask);
2221 static bool isTransposeMask(const Constant *Mask) {
2222 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2223 SmallVector<int, 16> MaskAsInts;
2224 getShuffleMask(Mask, MaskAsInts);
2225 return isTransposeMask(MaskAsInts);
2228 /// Return true if this shuffle transposes the elements of its inputs without
2229 /// changing the length of the vectors. This operation may also be known as a
2230 /// merge or interleave. See the description for isTransposeMask() for the
2231 /// exact specification.
2232 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2233 bool isTranspose() const {
2234 return !changesLength() && isTransposeMask(getMask());
2237 /// Return true if this shuffle mask is an extract subvector mask.
2238 /// A valid extract subvector mask returns a smaller vector from a single
2239 /// source operand. The base extraction index is returned as well.
2240 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2241 int &Index);
2242 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2243 int &Index) {
2244 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
2245 SmallVector<int, 16> MaskAsInts;
2246 getShuffleMask(Mask, MaskAsInts);
2247 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2250 /// Return true if this shuffle mask is an extract subvector mask.
2251 bool isExtractSubvectorMask(int &Index) const {
2252 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2253 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2256 /// Change values in a shuffle permute mask assuming the two vector operands
2257 /// of length InVecNumElts have swapped position.
2258 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2259 unsigned InVecNumElts) {
2260 for (int &Idx : Mask) {
2261 if (Idx == -1)
2262 continue;
2263 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2264 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
2265 "shufflevector mask index out of range");
2269 // Methods for support type inquiry through isa, cast, and dyn_cast:
2270 static bool classof(const Instruction *I) {
2271 return I->getOpcode() == Instruction::ShuffleVector;
2273 static bool classof(const Value *V) {
2274 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2278 template <>
2279 struct OperandTraits<ShuffleVectorInst> :
2280 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2283 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
2285 //===----------------------------------------------------------------------===//
2286 // ExtractValueInst Class
2287 //===----------------------------------------------------------------------===//
2289 /// This instruction extracts a struct member or array
2290 /// element value from an aggregate value.
2292 class ExtractValueInst : public UnaryInstruction {
2293 SmallVector<unsigned, 4> Indices;
2295 ExtractValueInst(const ExtractValueInst &EVI);
2297 /// Constructors - Create a extractvalue instruction with a base aggregate
2298 /// value and a list of indices. The first ctor can optionally insert before
2299 /// an existing instruction, the second appends the new instruction to the
2300 /// specified BasicBlock.
2301 inline ExtractValueInst(Value *Agg,
2302 ArrayRef<unsigned> Idxs,
2303 const Twine &NameStr,
2304 Instruction *InsertBefore);
2305 inline ExtractValueInst(Value *Agg,
2306 ArrayRef<unsigned> Idxs,
2307 const Twine &NameStr, BasicBlock *InsertAtEnd);
2309 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2311 protected:
2312 // Note: Instruction needs to be a friend here to call cloneImpl.
2313 friend class Instruction;
2315 ExtractValueInst *cloneImpl() const;
2317 public:
2318 static ExtractValueInst *Create(Value *Agg,
2319 ArrayRef<unsigned> Idxs,
2320 const Twine &NameStr = "",
2321 Instruction *InsertBefore = nullptr) {
2322 return new
2323 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2326 static ExtractValueInst *Create(Value *Agg,
2327 ArrayRef<unsigned> Idxs,
2328 const Twine &NameStr,
2329 BasicBlock *InsertAtEnd) {
2330 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2333 /// Returns the type of the element that would be extracted
2334 /// with an extractvalue instruction with the specified parameters.
2336 /// Null is returned if the indices are invalid for the specified type.
2337 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2339 using idx_iterator = const unsigned*;
2341 inline idx_iterator idx_begin() const { return Indices.begin(); }
2342 inline idx_iterator idx_end() const { return Indices.end(); }
2343 inline iterator_range<idx_iterator> indices() const {
2344 return make_range(idx_begin(), idx_end());
2347 Value *getAggregateOperand() {
2348 return getOperand(0);
2350 const Value *getAggregateOperand() const {
2351 return getOperand(0);
2353 static unsigned getAggregateOperandIndex() {
2354 return 0U; // get index for modifying correct operand
2357 ArrayRef<unsigned> getIndices() const {
2358 return Indices;
2361 unsigned getNumIndices() const {
2362 return (unsigned)Indices.size();
2365 bool hasIndices() const {
2366 return true;
2369 // Methods for support type inquiry through isa, cast, and dyn_cast:
2370 static bool classof(const Instruction *I) {
2371 return I->getOpcode() == Instruction::ExtractValue;
2373 static bool classof(const Value *V) {
2374 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2378 ExtractValueInst::ExtractValueInst(Value *Agg,
2379 ArrayRef<unsigned> Idxs,
2380 const Twine &NameStr,
2381 Instruction *InsertBefore)
2382 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2383 ExtractValue, Agg, InsertBefore) {
2384 init(Idxs, NameStr);
2387 ExtractValueInst::ExtractValueInst(Value *Agg,
2388 ArrayRef<unsigned> Idxs,
2389 const Twine &NameStr,
2390 BasicBlock *InsertAtEnd)
2391 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2392 ExtractValue, Agg, InsertAtEnd) {
2393 init(Idxs, NameStr);
2396 //===----------------------------------------------------------------------===//
2397 // InsertValueInst Class
2398 //===----------------------------------------------------------------------===//
2400 /// This instruction inserts a struct field of array element
2401 /// value into an aggregate value.
2403 class InsertValueInst : public Instruction {
2404 SmallVector<unsigned, 4> Indices;
2406 InsertValueInst(const InsertValueInst &IVI);
2408 /// Constructors - Create a insertvalue instruction with a base aggregate
2409 /// value, a value to insert, and a list of indices. The first ctor can
2410 /// optionally insert before an existing instruction, the second appends
2411 /// the new instruction to the specified BasicBlock.
2412 inline InsertValueInst(Value *Agg, Value *Val,
2413 ArrayRef<unsigned> Idxs,
2414 const Twine &NameStr,
2415 Instruction *InsertBefore);
2416 inline InsertValueInst(Value *Agg, Value *Val,
2417 ArrayRef<unsigned> Idxs,
2418 const Twine &NameStr, BasicBlock *InsertAtEnd);
2420 /// Constructors - These two constructors are convenience methods because one
2421 /// and two index insertvalue instructions are so common.
2422 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2423 const Twine &NameStr = "",
2424 Instruction *InsertBefore = nullptr);
2425 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2426 BasicBlock *InsertAtEnd);
2428 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2429 const Twine &NameStr);
2431 protected:
2432 // Note: Instruction needs to be a friend here to call cloneImpl.
2433 friend class Instruction;
2435 InsertValueInst *cloneImpl() const;
2437 public:
2438 // allocate space for exactly two operands
2439 void *operator new(size_t s) {
2440 return User::operator new(s, 2);
2443 static InsertValueInst *Create(Value *Agg, Value *Val,
2444 ArrayRef<unsigned> Idxs,
2445 const Twine &NameStr = "",
2446 Instruction *InsertBefore = nullptr) {
2447 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2450 static InsertValueInst *Create(Value *Agg, Value *Val,
2451 ArrayRef<unsigned> Idxs,
2452 const Twine &NameStr,
2453 BasicBlock *InsertAtEnd) {
2454 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2457 /// Transparently provide more efficient getOperand methods.
2458 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2460 using idx_iterator = const unsigned*;
2462 inline idx_iterator idx_begin() const { return Indices.begin(); }
2463 inline idx_iterator idx_end() const { return Indices.end(); }
2464 inline iterator_range<idx_iterator> indices() const {
2465 return make_range(idx_begin(), idx_end());
2468 Value *getAggregateOperand() {
2469 return getOperand(0);
2471 const Value *getAggregateOperand() const {
2472 return getOperand(0);
2474 static unsigned getAggregateOperandIndex() {
2475 return 0U; // get index for modifying correct operand
2478 Value *getInsertedValueOperand() {
2479 return getOperand(1);
2481 const Value *getInsertedValueOperand() const {
2482 return getOperand(1);
2484 static unsigned getInsertedValueOperandIndex() {
2485 return 1U; // get index for modifying correct operand
2488 ArrayRef<unsigned> getIndices() const {
2489 return Indices;
2492 unsigned getNumIndices() const {
2493 return (unsigned)Indices.size();
2496 bool hasIndices() const {
2497 return true;
2500 // Methods for support type inquiry through isa, cast, and dyn_cast:
2501 static bool classof(const Instruction *I) {
2502 return I->getOpcode() == Instruction::InsertValue;
2504 static bool classof(const Value *V) {
2505 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2509 template <>
2510 struct OperandTraits<InsertValueInst> :
2511 public FixedNumOperandTraits<InsertValueInst, 2> {
2514 InsertValueInst::InsertValueInst(Value *Agg,
2515 Value *Val,
2516 ArrayRef<unsigned> Idxs,
2517 const Twine &NameStr,
2518 Instruction *InsertBefore)
2519 : Instruction(Agg->getType(), InsertValue,
2520 OperandTraits<InsertValueInst>::op_begin(this),
2521 2, InsertBefore) {
2522 init(Agg, Val, Idxs, NameStr);
2525 InsertValueInst::InsertValueInst(Value *Agg,
2526 Value *Val,
2527 ArrayRef<unsigned> Idxs,
2528 const Twine &NameStr,
2529 BasicBlock *InsertAtEnd)
2530 : Instruction(Agg->getType(), InsertValue,
2531 OperandTraits<InsertValueInst>::op_begin(this),
2532 2, InsertAtEnd) {
2533 init(Agg, Val, Idxs, NameStr);
2536 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
2538 //===----------------------------------------------------------------------===//
2539 // PHINode Class
2540 //===----------------------------------------------------------------------===//
2542 // PHINode - The PHINode class is used to represent the magical mystical PHI
2543 // node, that can not exist in nature, but can be synthesized in a computer
2544 // scientist's overactive imagination.
2546 class PHINode : public Instruction {
2547 /// The number of operands actually allocated. NumOperands is
2548 /// the number actually in use.
2549 unsigned ReservedSpace;
2551 PHINode(const PHINode &PN);
2553 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2554 const Twine &NameStr = "",
2555 Instruction *InsertBefore = nullptr)
2556 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2557 ReservedSpace(NumReservedValues) {
2558 setName(NameStr);
2559 allocHungoffUses(ReservedSpace);
2562 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2563 BasicBlock *InsertAtEnd)
2564 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2565 ReservedSpace(NumReservedValues) {
2566 setName(NameStr);
2567 allocHungoffUses(ReservedSpace);
2570 protected:
2571 // Note: Instruction needs to be a friend here to call cloneImpl.
2572 friend class Instruction;
2574 PHINode *cloneImpl() const;
2576 // allocHungoffUses - this is more complicated than the generic
2577 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2578 // values and pointers to the incoming blocks, all in one allocation.
2579 void allocHungoffUses(unsigned N) {
2580 User::allocHungoffUses(N, /* IsPhi */ true);
2583 public:
2584 /// Constructors - NumReservedValues is a hint for the number of incoming
2585 /// edges that this phi node will have (use 0 if you really have no idea).
2586 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2587 const Twine &NameStr = "",
2588 Instruction *InsertBefore = nullptr) {
2589 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2592 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2593 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2594 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2597 /// Provide fast operand accessors
2598 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2600 // Block iterator interface. This provides access to the list of incoming
2601 // basic blocks, which parallels the list of incoming values.
2603 using block_iterator = BasicBlock **;
2604 using const_block_iterator = BasicBlock * const *;
2606 block_iterator block_begin() {
2607 Use::UserRef *ref =
2608 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2609 return reinterpret_cast<block_iterator>(ref + 1);
2612 const_block_iterator block_begin() const {
2613 const Use::UserRef *ref =
2614 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2615 return reinterpret_cast<const_block_iterator>(ref + 1);
2618 block_iterator block_end() {
2619 return block_begin() + getNumOperands();
2622 const_block_iterator block_end() const {
2623 return block_begin() + getNumOperands();
2626 iterator_range<block_iterator> blocks() {
2627 return make_range(block_begin(), block_end());
2630 iterator_range<const_block_iterator> blocks() const {
2631 return make_range(block_begin(), block_end());
2634 op_range incoming_values() { return operands(); }
2636 const_op_range incoming_values() const { return operands(); }
2638 /// Return the number of incoming edges
2640 unsigned getNumIncomingValues() const { return getNumOperands(); }
2642 /// Return incoming value number x
2644 Value *getIncomingValue(unsigned i) const {
2645 return getOperand(i);
2647 void setIncomingValue(unsigned i, Value *V) {
2648 assert(V && "PHI node got a null value!");
2649 assert(getType() == V->getType() &&
2650 "All operands to PHI node must be the same type as the PHI node!");
2651 setOperand(i, V);
2654 static unsigned getOperandNumForIncomingValue(unsigned i) {
2655 return i;
2658 static unsigned getIncomingValueNumForOperand(unsigned i) {
2659 return i;
2662 /// Return incoming basic block number @p i.
2664 BasicBlock *getIncomingBlock(unsigned i) const {
2665 return block_begin()[i];
2668 /// Return incoming basic block corresponding
2669 /// to an operand of the PHI.
2671 BasicBlock *getIncomingBlock(const Use &U) const {
2672 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2673 return getIncomingBlock(unsigned(&U - op_begin()));
2676 /// Return incoming basic block corresponding
2677 /// to value use iterator.
2679 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2680 return getIncomingBlock(I.getUse());
2683 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2684 assert(BB && "PHI node got a null basic block!");
2685 block_begin()[i] = BB;
2688 /// Replace every incoming basic block \p Old to basic block \p New.
2689 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2690 assert(New && Old && "PHI node got a null basic block!");
2691 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2692 if (getIncomingBlock(Op) == Old)
2693 setIncomingBlock(Op, New);
2696 /// Add an incoming value to the end of the PHI list
2698 void addIncoming(Value *V, BasicBlock *BB) {
2699 if (getNumOperands() == ReservedSpace)
2700 growOperands(); // Get more space!
2701 // Initialize some new operands.
2702 setNumHungOffUseOperands(getNumOperands() + 1);
2703 setIncomingValue(getNumOperands() - 1, V);
2704 setIncomingBlock(getNumOperands() - 1, BB);
2707 /// Remove an incoming value. This is useful if a
2708 /// predecessor basic block is deleted. The value removed is returned.
2710 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2711 /// is true), the PHI node is destroyed and any uses of it are replaced with
2712 /// dummy values. The only time there should be zero incoming values to a PHI
2713 /// node is when the block is dead, so this strategy is sound.
2715 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2717 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2718 int Idx = getBasicBlockIndex(BB);
2719 assert(Idx >= 0 && "Invalid basic block argument to remove!");
2720 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2723 /// Return the first index of the specified basic
2724 /// block in the value list for this PHI. Returns -1 if no instance.
2726 int getBasicBlockIndex(const BasicBlock *BB) const {
2727 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2728 if (block_begin()[i] == BB)
2729 return i;
2730 return -1;
2733 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2734 int Idx = getBasicBlockIndex(BB);
2735 assert(Idx >= 0 && "Invalid basic block argument!");
2736 return getIncomingValue(Idx);
2739 /// Set every incoming value(s) for block \p BB to \p V.
2740 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2741 assert(BB && "PHI node got a null basic block!");
2742 bool Found = false;
2743 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2744 if (getIncomingBlock(Op) == BB) {
2745 Found = true;
2746 setIncomingValue(Op, V);
2748 (void)Found;
2749 assert(Found && "Invalid basic block argument to set!");
2752 /// If the specified PHI node always merges together the
2753 /// same value, return the value, otherwise return null.
2754 Value *hasConstantValue() const;
2756 /// Whether the specified PHI node always merges
2757 /// together the same value, assuming undefs are equal to a unique
2758 /// non-undef value.
2759 bool hasConstantOrUndefValue() const;
2761 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2762 static bool classof(const Instruction *I) {
2763 return I->getOpcode() == Instruction::PHI;
2765 static bool classof(const Value *V) {
2766 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2769 private:
2770 void growOperands();
2773 template <>
2774 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2777 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2779 //===----------------------------------------------------------------------===//
2780 // LandingPadInst Class
2781 //===----------------------------------------------------------------------===//
2783 //===---------------------------------------------------------------------------
2784 /// The landingpad instruction holds all of the information
2785 /// necessary to generate correct exception handling. The landingpad instruction
2786 /// cannot be moved from the top of a landing pad block, which itself is
2787 /// accessible only from the 'unwind' edge of an invoke. This uses the
2788 /// SubclassData field in Value to store whether or not the landingpad is a
2789 /// cleanup.
2791 class LandingPadInst : public Instruction {
2792 /// The number of operands actually allocated. NumOperands is
2793 /// the number actually in use.
2794 unsigned ReservedSpace;
2796 LandingPadInst(const LandingPadInst &LP);
2798 public:
2799 enum ClauseType { Catch, Filter };
2801 private:
2802 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2803 const Twine &NameStr, Instruction *InsertBefore);
2804 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2805 const Twine &NameStr, BasicBlock *InsertAtEnd);
2807 // Allocate space for exactly zero operands.
2808 void *operator new(size_t s) {
2809 return User::operator new(s);
2812 void growOperands(unsigned Size);
2813 void init(unsigned NumReservedValues, const Twine &NameStr);
2815 protected:
2816 // Note: Instruction needs to be a friend here to call cloneImpl.
2817 friend class Instruction;
2819 LandingPadInst *cloneImpl() const;
2821 public:
2822 /// Constructors - NumReservedClauses is a hint for the number of incoming
2823 /// clauses that this landingpad will have (use 0 if you really have no idea).
2824 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2825 const Twine &NameStr = "",
2826 Instruction *InsertBefore = nullptr);
2827 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2828 const Twine &NameStr, BasicBlock *InsertAtEnd);
2830 /// Provide fast operand accessors
2831 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2833 /// Return 'true' if this landingpad instruction is a
2834 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2835 /// doesn't catch the exception.
2836 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2838 /// Indicate that this landingpad instruction is a cleanup.
2839 void setCleanup(bool V) {
2840 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2841 (V ? 1 : 0));
2844 /// Add a catch or filter clause to the landing pad.
2845 void addClause(Constant *ClauseVal);
2847 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2848 /// determine what type of clause this is.
2849 Constant *getClause(unsigned Idx) const {
2850 return cast<Constant>(getOperandList()[Idx]);
2853 /// Return 'true' if the clause and index Idx is a catch clause.
2854 bool isCatch(unsigned Idx) const {
2855 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2858 /// Return 'true' if the clause and index Idx is a filter clause.
2859 bool isFilter(unsigned Idx) const {
2860 return isa<ArrayType>(getOperandList()[Idx]->getType());
2863 /// Get the number of clauses for this landing pad.
2864 unsigned getNumClauses() const { return getNumOperands(); }
2866 /// Grow the size of the operand list to accommodate the new
2867 /// number of clauses.
2868 void reserveClauses(unsigned Size) { growOperands(Size); }
2870 // Methods for support type inquiry through isa, cast, and dyn_cast:
2871 static bool classof(const Instruction *I) {
2872 return I->getOpcode() == Instruction::LandingPad;
2874 static bool classof(const Value *V) {
2875 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2879 template <>
2880 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2883 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2885 //===----------------------------------------------------------------------===//
2886 // ReturnInst Class
2887 //===----------------------------------------------------------------------===//
2889 //===---------------------------------------------------------------------------
2890 /// Return a value (possibly void), from a function. Execution
2891 /// does not continue in this function any longer.
2893 class ReturnInst : public Instruction {
2894 ReturnInst(const ReturnInst &RI);
2896 private:
2897 // ReturnInst constructors:
2898 // ReturnInst() - 'ret void' instruction
2899 // ReturnInst( null) - 'ret void' instruction
2900 // ReturnInst(Value* X) - 'ret X' instruction
2901 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2902 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2903 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2904 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2906 // NOTE: If the Value* passed is of type void then the constructor behaves as
2907 // if it was passed NULL.
2908 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2909 Instruction *InsertBefore = nullptr);
2910 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2911 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2913 protected:
2914 // Note: Instruction needs to be a friend here to call cloneImpl.
2915 friend class Instruction;
2917 ReturnInst *cloneImpl() const;
2919 public:
2920 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2921 Instruction *InsertBefore = nullptr) {
2922 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2925 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2926 BasicBlock *InsertAtEnd) {
2927 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2930 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2931 return new(0) ReturnInst(C, InsertAtEnd);
2934 /// Provide fast operand accessors
2935 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2937 /// Convenience accessor. Returns null if there is no return value.
2938 Value *getReturnValue() const {
2939 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2942 unsigned getNumSuccessors() const { return 0; }
2944 // Methods for support type inquiry through isa, cast, and dyn_cast:
2945 static bool classof(const Instruction *I) {
2946 return (I->getOpcode() == Instruction::Ret);
2948 static bool classof(const Value *V) {
2949 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2952 private:
2953 BasicBlock *getSuccessor(unsigned idx) const {
2954 llvm_unreachable("ReturnInst has no successors!");
2957 void setSuccessor(unsigned idx, BasicBlock *B) {
2958 llvm_unreachable("ReturnInst has no successors!");
2962 template <>
2963 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2966 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2968 //===----------------------------------------------------------------------===//
2969 // BranchInst Class
2970 //===----------------------------------------------------------------------===//
2972 //===---------------------------------------------------------------------------
2973 /// Conditional or Unconditional Branch instruction.
2975 class BranchInst : public Instruction {
2976 /// Ops list - Branches are strange. The operands are ordered:
2977 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2978 /// they don't have to check for cond/uncond branchness. These are mostly
2979 /// accessed relative from op_end().
2980 BranchInst(const BranchInst &BI);
2981 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2982 // BranchInst(BB *B) - 'br B'
2983 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2984 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2985 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2986 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2987 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2988 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2989 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2990 Instruction *InsertBefore = nullptr);
2991 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2992 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2993 BasicBlock *InsertAtEnd);
2995 void AssertOK();
2997 protected:
2998 // Note: Instruction needs to be a friend here to call cloneImpl.
2999 friend class Instruction;
3001 BranchInst *cloneImpl() const;
3003 public:
3004 /// Iterator type that casts an operand to a basic block.
3006 /// This only makes sense because the successors are stored as adjacent
3007 /// operands for branch instructions.
3008 struct succ_op_iterator
3009 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3010 std::random_access_iterator_tag, BasicBlock *,
3011 ptrdiff_t, BasicBlock *, BasicBlock *> {
3012 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3014 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3015 BasicBlock *operator->() const { return operator*(); }
3018 /// The const version of `succ_op_iterator`.
3019 struct const_succ_op_iterator
3020 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3021 std::random_access_iterator_tag,
3022 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3023 const BasicBlock *> {
3024 explicit const_succ_op_iterator(const_value_op_iterator I)
3025 : iterator_adaptor_base(I) {}
3027 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3028 const BasicBlock *operator->() const { return operator*(); }
3031 static BranchInst *Create(BasicBlock *IfTrue,
3032 Instruction *InsertBefore = nullptr) {
3033 return new(1) BranchInst(IfTrue, InsertBefore);
3036 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3037 Value *Cond, Instruction *InsertBefore = nullptr) {
3038 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3041 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3042 return new(1) BranchInst(IfTrue, InsertAtEnd);
3045 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3046 Value *Cond, BasicBlock *InsertAtEnd) {
3047 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3050 /// Transparently provide more efficient getOperand methods.
3051 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3053 bool isUnconditional() const { return getNumOperands() == 1; }
3054 bool isConditional() const { return getNumOperands() == 3; }
3056 Value *getCondition() const {
3057 assert(isConditional() && "Cannot get condition of an uncond branch!");
3058 return Op<-3>();
3061 void setCondition(Value *V) {
3062 assert(isConditional() && "Cannot set condition of unconditional branch!");
3063 Op<-3>() = V;
3066 unsigned getNumSuccessors() const { return 1+isConditional(); }
3068 BasicBlock *getSuccessor(unsigned i) const {
3069 assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
3070 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3073 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3074 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
3075 *(&Op<-1>() - idx) = NewSucc;
3078 /// Swap the successors of this branch instruction.
3080 /// Swaps the successors of the branch instruction. This also swaps any
3081 /// branch weight metadata associated with the instruction so that it
3082 /// continues to map correctly to each operand.
3083 void swapSuccessors();
3085 iterator_range<succ_op_iterator> successors() {
3086 return make_range(
3087 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3088 succ_op_iterator(value_op_end()));
3091 iterator_range<const_succ_op_iterator> successors() const {
3092 return make_range(const_succ_op_iterator(
3093 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3094 const_succ_op_iterator(value_op_end()));
3097 // Methods for support type inquiry through isa, cast, and dyn_cast:
3098 static bool classof(const Instruction *I) {
3099 return (I->getOpcode() == Instruction::Br);
3101 static bool classof(const Value *V) {
3102 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3106 template <>
3107 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3110 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
3112 //===----------------------------------------------------------------------===//
3113 // SwitchInst Class
3114 //===----------------------------------------------------------------------===//
3116 //===---------------------------------------------------------------------------
3117 /// Multiway switch
3119 class SwitchInst : public Instruction {
3120 unsigned ReservedSpace;
3122 // Operand[0] = Value to switch on
3123 // Operand[1] = Default basic block destination
3124 // Operand[2n ] = Value to match
3125 // Operand[2n+1] = BasicBlock to go to on match
3126 SwitchInst(const SwitchInst &SI);
3128 /// Create a new switch instruction, specifying a value to switch on and a
3129 /// default destination. The number of additional cases can be specified here
3130 /// to make memory allocation more efficient. This constructor can also
3131 /// auto-insert before another instruction.
3132 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3133 Instruction *InsertBefore);
3135 /// Create a new switch instruction, specifying a value to switch on and a
3136 /// default destination. The number of additional cases can be specified here
3137 /// to make memory allocation more efficient. This constructor also
3138 /// auto-inserts at the end of the specified BasicBlock.
3139 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3140 BasicBlock *InsertAtEnd);
3142 // allocate space for exactly zero operands
3143 void *operator new(size_t s) {
3144 return User::operator new(s);
3147 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3148 void growOperands();
3150 protected:
3151 // Note: Instruction needs to be a friend here to call cloneImpl.
3152 friend class Instruction;
3154 SwitchInst *cloneImpl() const;
3156 public:
3157 // -2
3158 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3160 template <typename CaseHandleT> class CaseIteratorImpl;
3162 /// A handle to a particular switch case. It exposes a convenient interface
3163 /// to both the case value and the successor block.
3165 /// We define this as a template and instantiate it to form both a const and
3166 /// non-const handle.
3167 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3168 class CaseHandleImpl {
3169 // Directly befriend both const and non-const iterators.
3170 friend class SwitchInst::CaseIteratorImpl<
3171 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3173 protected:
3174 // Expose the switch type we're parameterized with to the iterator.
3175 using SwitchInstType = SwitchInstT;
3177 SwitchInstT *SI;
3178 ptrdiff_t Index;
3180 CaseHandleImpl() = default;
3181 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3183 public:
3184 /// Resolves case value for current case.
3185 ConstantIntT *getCaseValue() const {
3186 assert((unsigned)Index < SI->getNumCases() &&
3187 "Index out the number of cases.");
3188 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3191 /// Resolves successor for current case.
3192 BasicBlockT *getCaseSuccessor() const {
3193 assert(((unsigned)Index < SI->getNumCases() ||
3194 (unsigned)Index == DefaultPseudoIndex) &&
3195 "Index out the number of cases.");
3196 return SI->getSuccessor(getSuccessorIndex());
3199 /// Returns number of current case.
3200 unsigned getCaseIndex() const { return Index; }
3202 /// Returns successor index for current case successor.
3203 unsigned getSuccessorIndex() const {
3204 assert(((unsigned)Index == DefaultPseudoIndex ||
3205 (unsigned)Index < SI->getNumCases()) &&
3206 "Index out the number of cases.");
3207 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3210 bool operator==(const CaseHandleImpl &RHS) const {
3211 assert(SI == RHS.SI && "Incompatible operators.");
3212 return Index == RHS.Index;
3216 using ConstCaseHandle =
3217 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3219 class CaseHandle
3220 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3221 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3223 public:
3224 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3226 /// Sets the new value for current case.
3227 void setValue(ConstantInt *V) {
3228 assert((unsigned)Index < SI->getNumCases() &&
3229 "Index out the number of cases.");
3230 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3233 /// Sets the new successor for current case.
3234 void setSuccessor(BasicBlock *S) {
3235 SI->setSuccessor(getSuccessorIndex(), S);
3239 template <typename CaseHandleT>
3240 class CaseIteratorImpl
3241 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3242 std::random_access_iterator_tag,
3243 CaseHandleT> {
3244 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3246 CaseHandleT Case;
3248 public:
3249 /// Default constructed iterator is in an invalid state until assigned to
3250 /// a case for a particular switch.
3251 CaseIteratorImpl() = default;
3253 /// Initializes case iterator for given SwitchInst and for given
3254 /// case number.
3255 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3257 /// Initializes case iterator for given SwitchInst and for given
3258 /// successor index.
3259 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3260 unsigned SuccessorIndex) {
3261 assert(SuccessorIndex < SI->getNumSuccessors() &&
3262 "Successor index # out of range!");
3263 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3264 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3267 /// Support converting to the const variant. This will be a no-op for const
3268 /// variant.
3269 operator CaseIteratorImpl<ConstCaseHandle>() const {
3270 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3273 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3274 // Check index correctness after addition.
3275 // Note: Index == getNumCases() means end().
3276 assert(Case.Index + N >= 0 &&
3277 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
3278 "Case.Index out the number of cases.");
3279 Case.Index += N;
3280 return *this;
3282 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3283 // Check index correctness after subtraction.
3284 // Note: Case.Index == getNumCases() means end().
3285 assert(Case.Index - N >= 0 &&
3286 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
3287 "Case.Index out the number of cases.");
3288 Case.Index -= N;
3289 return *this;
3291 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3292 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3293 return Case.Index - RHS.Case.Index;
3295 bool operator==(const CaseIteratorImpl &RHS) const {
3296 return Case == RHS.Case;
3298 bool operator<(const CaseIteratorImpl &RHS) const {
3299 assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
3300 return Case.Index < RHS.Case.Index;
3302 CaseHandleT &operator*() { return Case; }
3303 const CaseHandleT &operator*() const { return Case; }
3306 using CaseIt = CaseIteratorImpl<CaseHandle>;
3307 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3309 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3310 unsigned NumCases,
3311 Instruction *InsertBefore = nullptr) {
3312 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3315 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3316 unsigned NumCases, BasicBlock *InsertAtEnd) {
3317 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3320 /// Provide fast operand accessors
3321 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3323 // Accessor Methods for Switch stmt
3324 Value *getCondition() const { return getOperand(0); }
3325 void setCondition(Value *V) { setOperand(0, V); }
3327 BasicBlock *getDefaultDest() const {
3328 return cast<BasicBlock>(getOperand(1));
3331 void setDefaultDest(BasicBlock *DefaultCase) {
3332 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3335 /// Return the number of 'cases' in this switch instruction, excluding the
3336 /// default case.
3337 unsigned getNumCases() const {
3338 return getNumOperands()/2 - 1;
3341 /// Returns a read/write iterator that points to the first case in the
3342 /// SwitchInst.
3343 CaseIt case_begin() {
3344 return CaseIt(this, 0);
3347 /// Returns a read-only iterator that points to the first case in the
3348 /// SwitchInst.
3349 ConstCaseIt case_begin() const {
3350 return ConstCaseIt(this, 0);
3353 /// Returns a read/write iterator that points one past the last in the
3354 /// SwitchInst.
3355 CaseIt case_end() {
3356 return CaseIt(this, getNumCases());
3359 /// Returns a read-only iterator that points one past the last in the
3360 /// SwitchInst.
3361 ConstCaseIt case_end() const {
3362 return ConstCaseIt(this, getNumCases());
3365 /// Iteration adapter for range-for loops.
3366 iterator_range<CaseIt> cases() {
3367 return make_range(case_begin(), case_end());
3370 /// Constant iteration adapter for range-for loops.
3371 iterator_range<ConstCaseIt> cases() const {
3372 return make_range(case_begin(), case_end());
3375 /// Returns an iterator that points to the default case.
3376 /// Note: this iterator allows to resolve successor only. Attempt
3377 /// to resolve case value causes an assertion.
3378 /// Also note, that increment and decrement also causes an assertion and
3379 /// makes iterator invalid.
3380 CaseIt case_default() {
3381 return CaseIt(this, DefaultPseudoIndex);
3383 ConstCaseIt case_default() const {
3384 return ConstCaseIt(this, DefaultPseudoIndex);
3387 /// Search all of the case values for the specified constant. If it is
3388 /// explicitly handled, return the case iterator of it, otherwise return
3389 /// default case iterator to indicate that it is handled by the default
3390 /// handler.
3391 CaseIt findCaseValue(const ConstantInt *C) {
3392 CaseIt I = llvm::find_if(
3393 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3394 if (I != case_end())
3395 return I;
3397 return case_default();
3399 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3400 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3401 return Case.getCaseValue() == C;
3403 if (I != case_end())
3404 return I;
3406 return case_default();
3409 /// Finds the unique case value for a given successor. Returns null if the
3410 /// successor is not found, not unique, or is the default case.
3411 ConstantInt *findCaseDest(BasicBlock *BB) {
3412 if (BB == getDefaultDest())
3413 return nullptr;
3415 ConstantInt *CI = nullptr;
3416 for (auto Case : cases()) {
3417 if (Case.getCaseSuccessor() != BB)
3418 continue;
3420 if (CI)
3421 return nullptr; // Multiple cases lead to BB.
3423 CI = Case.getCaseValue();
3426 return CI;
3429 /// Add an entry to the switch instruction.
3430 /// Note:
3431 /// This action invalidates case_end(). Old case_end() iterator will
3432 /// point to the added case.
3433 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3435 /// This method removes the specified case and its successor from the switch
3436 /// instruction. Note that this operation may reorder the remaining cases at
3437 /// index idx and above.
3438 /// Note:
3439 /// This action invalidates iterators for all cases following the one removed,
3440 /// including the case_end() iterator. It returns an iterator for the next
3441 /// case.
3442 CaseIt removeCase(CaseIt I);
3444 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3445 BasicBlock *getSuccessor(unsigned idx) const {
3446 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
3447 return cast<BasicBlock>(getOperand(idx*2+1));
3449 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3450 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
3451 setOperand(idx * 2 + 1, NewSucc);
3454 // Methods for support type inquiry through isa, cast, and dyn_cast:
3455 static bool classof(const Instruction *I) {
3456 return I->getOpcode() == Instruction::Switch;
3458 static bool classof(const Value *V) {
3459 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3463 /// A wrapper class to simplify modification of SwitchInst cases along with
3464 /// their prof branch_weights metadata.
3465 class SwitchInstProfUpdateWrapper {
3466 SwitchInst &SI;
3467 Optional<SmallVector<uint32_t, 8> > Weights = None;
3468 bool Changed = false;
3470 protected:
3471 static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3473 MDNode *buildProfBranchWeightsMD();
3475 void init();
3477 public:
3478 using CaseWeightOpt = Optional<uint32_t>;
3479 SwitchInst *operator->() { return &SI; }
3480 SwitchInst &operator*() { return SI; }
3481 operator SwitchInst *() { return &SI; }
3483 SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
3485 ~SwitchInstProfUpdateWrapper() {
3486 if (Changed)
3487 SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3490 /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3491 /// correspondent branch weight.
3492 SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3494 /// Delegate the call to the underlying SwitchInst::addCase() and set the
3495 /// specified branch weight for the added case.
3496 void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3498 /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3499 /// this object to not touch the underlying SwitchInst in destructor.
3500 SymbolTableList<Instruction>::iterator eraseFromParent();
3502 void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3503 CaseWeightOpt getSuccessorWeight(unsigned idx);
3505 static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3508 template <>
3509 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3512 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
3514 //===----------------------------------------------------------------------===//
3515 // IndirectBrInst Class
3516 //===----------------------------------------------------------------------===//
3518 //===---------------------------------------------------------------------------
3519 /// Indirect Branch Instruction.
3521 class IndirectBrInst : public Instruction {
3522 unsigned ReservedSpace;
3524 // Operand[0] = Address to jump to
3525 // Operand[n+1] = n-th destination
3526 IndirectBrInst(const IndirectBrInst &IBI);
3528 /// Create a new indirectbr instruction, specifying an
3529 /// Address to jump to. The number of expected destinations can be specified
3530 /// here to make memory allocation more efficient. This constructor can also
3531 /// autoinsert before another instruction.
3532 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3534 /// Create a new indirectbr instruction, specifying an
3535 /// Address to jump to. The number of expected destinations can be specified
3536 /// here to make memory allocation more efficient. This constructor also
3537 /// autoinserts at the end of the specified BasicBlock.
3538 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3540 // allocate space for exactly zero operands
3541 void *operator new(size_t s) {
3542 return User::operator new(s);
3545 void init(Value *Address, unsigned NumDests);
3546 void growOperands();
3548 protected:
3549 // Note: Instruction needs to be a friend here to call cloneImpl.
3550 friend class Instruction;
3552 IndirectBrInst *cloneImpl() const;
3554 public:
3555 /// Iterator type that casts an operand to a basic block.
3557 /// This only makes sense because the successors are stored as adjacent
3558 /// operands for indirectbr instructions.
3559 struct succ_op_iterator
3560 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3561 std::random_access_iterator_tag, BasicBlock *,
3562 ptrdiff_t, BasicBlock *, BasicBlock *> {
3563 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3565 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3566 BasicBlock *operator->() const { return operator*(); }
3569 /// The const version of `succ_op_iterator`.
3570 struct const_succ_op_iterator
3571 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3572 std::random_access_iterator_tag,
3573 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3574 const BasicBlock *> {
3575 explicit const_succ_op_iterator(const_value_op_iterator I)
3576 : iterator_adaptor_base(I) {}
3578 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3579 const BasicBlock *operator->() const { return operator*(); }
3582 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3583 Instruction *InsertBefore = nullptr) {
3584 return new IndirectBrInst(Address, NumDests, InsertBefore);
3587 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3588 BasicBlock *InsertAtEnd) {
3589 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3592 /// Provide fast operand accessors.
3593 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3595 // Accessor Methods for IndirectBrInst instruction.
3596 Value *getAddress() { return getOperand(0); }
3597 const Value *getAddress() const { return getOperand(0); }
3598 void setAddress(Value *V) { setOperand(0, V); }
3600 /// return the number of possible destinations in this
3601 /// indirectbr instruction.
3602 unsigned getNumDestinations() const { return getNumOperands()-1; }
3604 /// Return the specified destination.
3605 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3606 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3608 /// Add a destination.
3610 void addDestination(BasicBlock *Dest);
3612 /// This method removes the specified successor from the
3613 /// indirectbr instruction.
3614 void removeDestination(unsigned i);
3616 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3617 BasicBlock *getSuccessor(unsigned i) const {
3618 return cast<BasicBlock>(getOperand(i+1));
3620 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3621 setOperand(i + 1, NewSucc);
3624 iterator_range<succ_op_iterator> successors() {
3625 return make_range(succ_op_iterator(std::next(value_op_begin())),
3626 succ_op_iterator(value_op_end()));
3629 iterator_range<const_succ_op_iterator> successors() const {
3630 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3631 const_succ_op_iterator(value_op_end()));
3634 // Methods for support type inquiry through isa, cast, and dyn_cast:
3635 static bool classof(const Instruction *I) {
3636 return I->getOpcode() == Instruction::IndirectBr;
3638 static bool classof(const Value *V) {
3639 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3643 template <>
3644 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3647 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
3649 //===----------------------------------------------------------------------===//
3650 // InvokeInst Class
3651 //===----------------------------------------------------------------------===//
3653 /// Invoke instruction. The SubclassData field is used to hold the
3654 /// calling convention of the call.
3656 class InvokeInst : public CallBase {
3657 /// The number of operands for this call beyond the called function,
3658 /// arguments, and operand bundles.
3659 static constexpr int NumExtraOperands = 2;
3661 /// The index from the end of the operand array to the normal destination.
3662 static constexpr int NormalDestOpEndIdx = -3;
3664 /// The index from the end of the operand array to the unwind destination.
3665 static constexpr int UnwindDestOpEndIdx = -2;
3667 InvokeInst(const InvokeInst &BI);
3669 /// Construct an InvokeInst given a range of arguments.
3671 /// Construct an InvokeInst from a range of arguments
3672 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3673 BasicBlock *IfException, ArrayRef<Value *> Args,
3674 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3675 const Twine &NameStr, Instruction *InsertBefore);
3677 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3678 BasicBlock *IfException, ArrayRef<Value *> Args,
3679 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3680 const Twine &NameStr, BasicBlock *InsertAtEnd);
3682 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3683 BasicBlock *IfException, ArrayRef<Value *> Args,
3684 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3686 /// Compute the number of operands to allocate.
3687 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3688 // We need one operand for the called function, plus our extra operands and
3689 // the input operand counts provided.
3690 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3693 protected:
3694 // Note: Instruction needs to be a friend here to call cloneImpl.
3695 friend class Instruction;
3697 InvokeInst *cloneImpl() const;
3699 public:
3700 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3701 BasicBlock *IfException, ArrayRef<Value *> Args,
3702 const Twine &NameStr,
3703 Instruction *InsertBefore = nullptr) {
3704 int NumOperands = ComputeNumOperands(Args.size());
3705 return new (NumOperands)
3706 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3707 NameStr, InsertBefore);
3710 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3711 BasicBlock *IfException, ArrayRef<Value *> Args,
3712 ArrayRef<OperandBundleDef> Bundles = None,
3713 const Twine &NameStr = "",
3714 Instruction *InsertBefore = nullptr) {
3715 int NumOperands =
3716 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3717 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3719 return new (NumOperands, DescriptorBytes)
3720 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3721 NameStr, InsertBefore);
3724 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3725 BasicBlock *IfException, ArrayRef<Value *> Args,
3726 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3727 int NumOperands = ComputeNumOperands(Args.size());
3728 return new (NumOperands)
3729 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3730 NameStr, InsertAtEnd);
3733 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3734 BasicBlock *IfException, ArrayRef<Value *> Args,
3735 ArrayRef<OperandBundleDef> Bundles,
3736 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3737 int NumOperands =
3738 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3739 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3741 return new (NumOperands, DescriptorBytes)
3742 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3743 NameStr, InsertAtEnd);
3746 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3747 BasicBlock *IfException, ArrayRef<Value *> Args,
3748 const Twine &NameStr,
3749 Instruction *InsertBefore = nullptr) {
3750 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3751 IfException, Args, None, NameStr, InsertBefore);
3754 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3755 BasicBlock *IfException, ArrayRef<Value *> Args,
3756 ArrayRef<OperandBundleDef> Bundles = None,
3757 const Twine &NameStr = "",
3758 Instruction *InsertBefore = nullptr) {
3759 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3760 IfException, Args, Bundles, NameStr, InsertBefore);
3763 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3764 BasicBlock *IfException, ArrayRef<Value *> Args,
3765 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3766 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3767 IfException, Args, NameStr, InsertAtEnd);
3770 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3771 BasicBlock *IfException, ArrayRef<Value *> Args,
3772 ArrayRef<OperandBundleDef> Bundles,
3773 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3774 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3775 IfException, Args, Bundles, NameStr, InsertAtEnd);
3778 // Deprecated [opaque pointer types]
3779 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3780 BasicBlock *IfException, ArrayRef<Value *> Args,
3781 const Twine &NameStr,
3782 Instruction *InsertBefore = nullptr) {
3783 return Create(cast<FunctionType>(
3784 cast<PointerType>(Func->getType())->getElementType()),
3785 Func, IfNormal, IfException, Args, None, NameStr,
3786 InsertBefore);
3789 // Deprecated [opaque pointer types]
3790 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3791 BasicBlock *IfException, ArrayRef<Value *> Args,
3792 ArrayRef<OperandBundleDef> Bundles = None,
3793 const Twine &NameStr = "",
3794 Instruction *InsertBefore = nullptr) {
3795 return Create(cast<FunctionType>(
3796 cast<PointerType>(Func->getType())->getElementType()),
3797 Func, IfNormal, IfException, Args, Bundles, NameStr,
3798 InsertBefore);
3801 // Deprecated [opaque pointer types]
3802 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3803 BasicBlock *IfException, ArrayRef<Value *> Args,
3804 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3805 return Create(cast<FunctionType>(
3806 cast<PointerType>(Func->getType())->getElementType()),
3807 Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3810 // Deprecated [opaque pointer types]
3811 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3812 BasicBlock *IfException, ArrayRef<Value *> Args,
3813 ArrayRef<OperandBundleDef> Bundles,
3814 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3815 return Create(cast<FunctionType>(
3816 cast<PointerType>(Func->getType())->getElementType()),
3817 Func, IfNormal, IfException, Args, Bundles, NameStr,
3818 InsertAtEnd);
3821 /// Create a clone of \p II with a different set of operand bundles and
3822 /// insert it before \p InsertPt.
3824 /// The returned invoke instruction is identical to \p II in every way except
3825 /// that the operand bundles for the new instruction are set to the operand
3826 /// bundles in \p Bundles.
3827 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3828 Instruction *InsertPt = nullptr);
3830 /// Determine if the call should not perform indirect branch tracking.
3831 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3833 /// Determine if the call cannot unwind.
3834 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3835 void setDoesNotThrow() {
3836 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3839 // get*Dest - Return the destination basic blocks...
3840 BasicBlock *getNormalDest() const {
3841 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3843 BasicBlock *getUnwindDest() const {
3844 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3846 void setNormalDest(BasicBlock *B) {
3847 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3849 void setUnwindDest(BasicBlock *B) {
3850 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3853 /// Get the landingpad instruction from the landing pad
3854 /// block (the unwind destination).
3855 LandingPadInst *getLandingPadInst() const;
3857 BasicBlock *getSuccessor(unsigned i) const {
3858 assert(i < 2 && "Successor # out of range for invoke!");
3859 return i == 0 ? getNormalDest() : getUnwindDest();
3862 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3863 assert(i < 2 && "Successor # out of range for invoke!");
3864 if (i == 0)
3865 setNormalDest(NewSucc);
3866 else
3867 setUnwindDest(NewSucc);
3870 unsigned getNumSuccessors() const { return 2; }
3872 // Methods for support type inquiry through isa, cast, and dyn_cast:
3873 static bool classof(const Instruction *I) {
3874 return (I->getOpcode() == Instruction::Invoke);
3876 static bool classof(const Value *V) {
3877 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3880 private:
3882 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3883 // method so that subclasses cannot accidentally use it.
3884 void setInstructionSubclassData(unsigned short D) {
3885 Instruction::setInstructionSubclassData(D);
3889 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3890 BasicBlock *IfException, ArrayRef<Value *> Args,
3891 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3892 const Twine &NameStr, Instruction *InsertBefore)
3893 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3894 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3895 InsertBefore) {
3896 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3899 InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3900 BasicBlock *IfException, ArrayRef<Value *> Args,
3901 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3902 const Twine &NameStr, BasicBlock *InsertAtEnd)
3903 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3904 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3905 InsertAtEnd) {
3906 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3909 //===----------------------------------------------------------------------===//
3910 // CallBrInst Class
3911 //===----------------------------------------------------------------------===//
3913 /// CallBr instruction, tracking function calls that may not return control but
3914 /// instead transfer it to a third location. The SubclassData field is used to
3915 /// hold the calling convention of the call.
3917 class CallBrInst : public CallBase {
3919 unsigned NumIndirectDests;
3921 CallBrInst(const CallBrInst &BI);
3923 /// Construct a CallBrInst given a range of arguments.
3925 /// Construct a CallBrInst from a range of arguments
3926 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3927 ArrayRef<BasicBlock *> IndirectDests,
3928 ArrayRef<Value *> Args,
3929 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3930 const Twine &NameStr, Instruction *InsertBefore);
3932 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3933 ArrayRef<BasicBlock *> IndirectDests,
3934 ArrayRef<Value *> Args,
3935 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3936 const Twine &NameStr, BasicBlock *InsertAtEnd);
3938 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3939 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3940 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3942 /// Should the Indirect Destinations change, scan + update the Arg list.
3943 void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3945 /// Compute the number of operands to allocate.
3946 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3947 int NumBundleInputs = 0) {
3948 // We need one operand for the called function, plus our extra operands and
3949 // the input operand counts provided.
3950 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3953 protected:
3954 // Note: Instruction needs to be a friend here to call cloneImpl.
3955 friend class Instruction;
3957 CallBrInst *cloneImpl() const;
3959 public:
3960 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3961 BasicBlock *DefaultDest,
3962 ArrayRef<BasicBlock *> IndirectDests,
3963 ArrayRef<Value *> Args, const Twine &NameStr,
3964 Instruction *InsertBefore = nullptr) {
3965 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3966 return new (NumOperands)
3967 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3968 NumOperands, NameStr, InsertBefore);
3971 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3972 BasicBlock *DefaultDest,
3973 ArrayRef<BasicBlock *> IndirectDests,
3974 ArrayRef<Value *> Args,
3975 ArrayRef<OperandBundleDef> Bundles = None,
3976 const Twine &NameStr = "",
3977 Instruction *InsertBefore = nullptr) {
3978 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3979 CountBundleInputs(Bundles));
3980 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3982 return new (NumOperands, DescriptorBytes)
3983 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3984 NumOperands, NameStr, InsertBefore);
3987 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3988 BasicBlock *DefaultDest,
3989 ArrayRef<BasicBlock *> IndirectDests,
3990 ArrayRef<Value *> Args, const Twine &NameStr,
3991 BasicBlock *InsertAtEnd) {
3992 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3993 return new (NumOperands)
3994 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3995 NumOperands, NameStr, InsertAtEnd);
3998 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3999 BasicBlock *DefaultDest,
4000 ArrayRef<BasicBlock *> IndirectDests,
4001 ArrayRef<Value *> Args,
4002 ArrayRef<OperandBundleDef> Bundles,
4003 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4004 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
4005 CountBundleInputs(Bundles));
4006 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4008 return new (NumOperands, DescriptorBytes)
4009 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
4010 NumOperands, NameStr, InsertAtEnd);
4013 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4014 ArrayRef<BasicBlock *> IndirectDests,
4015 ArrayRef<Value *> Args, const Twine &NameStr,
4016 Instruction *InsertBefore = nullptr) {
4017 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4018 IndirectDests, Args, NameStr, InsertBefore);
4021 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4022 ArrayRef<BasicBlock *> IndirectDests,
4023 ArrayRef<Value *> Args,
4024 ArrayRef<OperandBundleDef> Bundles = None,
4025 const Twine &NameStr = "",
4026 Instruction *InsertBefore = nullptr) {
4027 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4028 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4031 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4032 ArrayRef<BasicBlock *> IndirectDests,
4033 ArrayRef<Value *> Args, const Twine &NameStr,
4034 BasicBlock *InsertAtEnd) {
4035 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4036 IndirectDests, Args, NameStr, InsertAtEnd);
4039 static CallBrInst *Create(FunctionCallee Func,
4040 BasicBlock *DefaultDest,
4041 ArrayRef<BasicBlock *> IndirectDests,
4042 ArrayRef<Value *> Args,
4043 ArrayRef<OperandBundleDef> Bundles,
4044 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4045 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4046 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4049 /// Create a clone of \p CBI with a different set of operand bundles and
4050 /// insert it before \p InsertPt.
4052 /// The returned callbr instruction is identical to \p CBI in every way
4053 /// except that the operand bundles for the new instruction are set to the
4054 /// operand bundles in \p Bundles.
4055 static CallBrInst *Create(CallBrInst *CBI,
4056 ArrayRef<OperandBundleDef> Bundles,
4057 Instruction *InsertPt = nullptr);
4059 /// Return the number of callbr indirect dest labels.
4061 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4063 /// getIndirectDestLabel - Return the i-th indirect dest label.
4065 Value *getIndirectDestLabel(unsigned i) const {
4066 assert(i < getNumIndirectDests() && "Out of bounds!");
4067 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4071 Value *getIndirectDestLabelUse(unsigned i) const {
4072 assert(i < getNumIndirectDests() && "Out of bounds!");
4073 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4077 // Return the destination basic blocks...
4078 BasicBlock *getDefaultDest() const {
4079 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4081 BasicBlock *getIndirectDest(unsigned i) const {
4082 return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4084 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4085 SmallVector<BasicBlock *, 16> IndirectDests;
4086 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4087 IndirectDests.push_back(getIndirectDest(i));
4088 return IndirectDests;
4090 void setDefaultDest(BasicBlock *B) {
4091 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4093 void setIndirectDest(unsigned i, BasicBlock *B) {
4094 updateArgBlockAddresses(i, B);
4095 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4098 BasicBlock *getSuccessor(unsigned i) const {
4099 assert(i < getNumSuccessors() + 1 &&
4100 "Successor # out of range for callbr!");
4101 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4104 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4105 assert(i < getNumIndirectDests() + 1 &&
4106 "Successor # out of range for callbr!");
4107 return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4110 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4112 // Methods for support type inquiry through isa, cast, and dyn_cast:
4113 static bool classof(const Instruction *I) {
4114 return (I->getOpcode() == Instruction::CallBr);
4116 static bool classof(const Value *V) {
4117 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4120 private:
4122 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4123 // method so that subclasses cannot accidentally use it.
4124 void setInstructionSubclassData(unsigned short D) {
4125 Instruction::setInstructionSubclassData(D);
4129 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4130 ArrayRef<BasicBlock *> IndirectDests,
4131 ArrayRef<Value *> Args,
4132 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4133 const Twine &NameStr, Instruction *InsertBefore)
4134 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4135 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4136 InsertBefore) {
4137 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4140 CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4141 ArrayRef<BasicBlock *> IndirectDests,
4142 ArrayRef<Value *> Args,
4143 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4144 const Twine &NameStr, BasicBlock *InsertAtEnd)
4145 : CallBase(
4146 cast<FunctionType>(
4147 cast<PointerType>(Func->getType())->getElementType())
4148 ->getReturnType(),
4149 Instruction::CallBr,
4150 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4151 InsertAtEnd) {
4152 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4155 //===----------------------------------------------------------------------===//
4156 // ResumeInst Class
4157 //===----------------------------------------------------------------------===//
4159 //===---------------------------------------------------------------------------
4160 /// Resume the propagation of an exception.
4162 class ResumeInst : public Instruction {
4163 ResumeInst(const ResumeInst &RI);
4165 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4166 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4168 protected:
4169 // Note: Instruction needs to be a friend here to call cloneImpl.
4170 friend class Instruction;
4172 ResumeInst *cloneImpl() const;
4174 public:
4175 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4176 return new(1) ResumeInst(Exn, InsertBefore);
4179 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4180 return new(1) ResumeInst(Exn, InsertAtEnd);
4183 /// Provide fast operand accessors
4184 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4186 /// Convenience accessor.
4187 Value *getValue() const { return Op<0>(); }
4189 unsigned getNumSuccessors() const { return 0; }
4191 // Methods for support type inquiry through isa, cast, and dyn_cast:
4192 static bool classof(const Instruction *I) {
4193 return I->getOpcode() == Instruction::Resume;
4195 static bool classof(const Value *V) {
4196 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4199 private:
4200 BasicBlock *getSuccessor(unsigned idx) const {
4201 llvm_unreachable("ResumeInst has no successors!");
4204 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4205 llvm_unreachable("ResumeInst has no successors!");
4209 template <>
4210 struct OperandTraits<ResumeInst> :
4211 public FixedNumOperandTraits<ResumeInst, 1> {
4214 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
4216 //===----------------------------------------------------------------------===//
4217 // CatchSwitchInst Class
4218 //===----------------------------------------------------------------------===//
4219 class CatchSwitchInst : public Instruction {
4220 /// The number of operands actually allocated. NumOperands is
4221 /// the number actually in use.
4222 unsigned ReservedSpace;
4224 // Operand[0] = Outer scope
4225 // Operand[1] = Unwind block destination
4226 // Operand[n] = BasicBlock to go to on match
4227 CatchSwitchInst(const CatchSwitchInst &CSI);
4229 /// Create a new switch instruction, specifying a
4230 /// default destination. The number of additional handlers can be specified
4231 /// here to make memory allocation more efficient.
4232 /// This constructor can also autoinsert before another instruction.
4233 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4234 unsigned NumHandlers, const Twine &NameStr,
4235 Instruction *InsertBefore);
4237 /// Create a new switch instruction, specifying a
4238 /// default destination. The number of additional handlers can be specified
4239 /// here to make memory allocation more efficient.
4240 /// This constructor also autoinserts at the end of the specified BasicBlock.
4241 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4242 unsigned NumHandlers, const Twine &NameStr,
4243 BasicBlock *InsertAtEnd);
4245 // allocate space for exactly zero operands
4246 void *operator new(size_t s) { return User::operator new(s); }
4248 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4249 void growOperands(unsigned Size);
4251 protected:
4252 // Note: Instruction needs to be a friend here to call cloneImpl.
4253 friend class Instruction;
4255 CatchSwitchInst *cloneImpl() const;
4257 public:
4258 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4259 unsigned NumHandlers,
4260 const Twine &NameStr = "",
4261 Instruction *InsertBefore = nullptr) {
4262 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4263 InsertBefore);
4266 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4267 unsigned NumHandlers, const Twine &NameStr,
4268 BasicBlock *InsertAtEnd) {
4269 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4270 InsertAtEnd);
4273 /// Provide fast operand accessors
4274 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4276 // Accessor Methods for CatchSwitch stmt
4277 Value *getParentPad() const { return getOperand(0); }
4278 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4280 // Accessor Methods for CatchSwitch stmt
4281 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4282 bool unwindsToCaller() const { return !hasUnwindDest(); }
4283 BasicBlock *getUnwindDest() const {
4284 if (hasUnwindDest())
4285 return cast<BasicBlock>(getOperand(1));
4286 return nullptr;
4288 void setUnwindDest(BasicBlock *UnwindDest) {
4289 assert(UnwindDest);
4290 assert(hasUnwindDest());
4291 setOperand(1, UnwindDest);
4294 /// return the number of 'handlers' in this catchswitch
4295 /// instruction, except the default handler
4296 unsigned getNumHandlers() const {
4297 if (hasUnwindDest())
4298 return getNumOperands() - 2;
4299 return getNumOperands() - 1;
4302 private:
4303 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4304 static const BasicBlock *handler_helper(const Value *V) {
4305 return cast<BasicBlock>(V);
4308 public:
4309 using DerefFnTy = BasicBlock *(*)(Value *);
4310 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4311 using handler_range = iterator_range<handler_iterator>;
4312 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4313 using const_handler_iterator =
4314 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4315 using const_handler_range = iterator_range<const_handler_iterator>;
4317 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4318 handler_iterator handler_begin() {
4319 op_iterator It = op_begin() + 1;
4320 if (hasUnwindDest())
4321 ++It;
4322 return handler_iterator(It, DerefFnTy(handler_helper));
4325 /// Returns an iterator that points to the first handler in the
4326 /// CatchSwitchInst.
4327 const_handler_iterator handler_begin() const {
4328 const_op_iterator It = op_begin() + 1;
4329 if (hasUnwindDest())
4330 ++It;
4331 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4334 /// Returns a read-only iterator that points one past the last
4335 /// handler in the CatchSwitchInst.
4336 handler_iterator handler_end() {
4337 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4340 /// Returns an iterator that points one past the last handler in the
4341 /// CatchSwitchInst.
4342 const_handler_iterator handler_end() const {
4343 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4346 /// iteration adapter for range-for loops.
4347 handler_range handlers() {
4348 return make_range(handler_begin(), handler_end());
4351 /// iteration adapter for range-for loops.
4352 const_handler_range handlers() const {
4353 return make_range(handler_begin(), handler_end());
4356 /// Add an entry to the switch instruction...
4357 /// Note:
4358 /// This action invalidates handler_end(). Old handler_end() iterator will
4359 /// point to the added handler.
4360 void addHandler(BasicBlock *Dest);
4362 void removeHandler(handler_iterator HI);
4364 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4365 BasicBlock *getSuccessor(unsigned Idx) const {
4366 assert(Idx < getNumSuccessors() &&
4367 "Successor # out of range for catchswitch!");
4368 return cast<BasicBlock>(getOperand(Idx + 1));
4370 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4371 assert(Idx < getNumSuccessors() &&
4372 "Successor # out of range for catchswitch!");
4373 setOperand(Idx + 1, NewSucc);
4376 // Methods for support type inquiry through isa, cast, and dyn_cast:
4377 static bool classof(const Instruction *I) {
4378 return I->getOpcode() == Instruction::CatchSwitch;
4380 static bool classof(const Value *V) {
4381 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4385 template <>
4386 struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4388 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
4390 //===----------------------------------------------------------------------===//
4391 // CleanupPadInst Class
4392 //===----------------------------------------------------------------------===//
4393 class CleanupPadInst : public FuncletPadInst {
4394 private:
4395 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4396 unsigned Values, const Twine &NameStr,
4397 Instruction *InsertBefore)
4398 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4399 NameStr, InsertBefore) {}
4400 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4401 unsigned Values, const Twine &NameStr,
4402 BasicBlock *InsertAtEnd)
4403 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4404 NameStr, InsertAtEnd) {}
4406 public:
4407 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4408 const Twine &NameStr = "",
4409 Instruction *InsertBefore = nullptr) {
4410 unsigned Values = 1 + Args.size();
4411 return new (Values)
4412 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4415 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4416 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4417 unsigned Values = 1 + Args.size();
4418 return new (Values)
4419 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4422 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4423 static bool classof(const Instruction *I) {
4424 return I->getOpcode() == Instruction::CleanupPad;
4426 static bool classof(const Value *V) {
4427 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4431 //===----------------------------------------------------------------------===//
4432 // CatchPadInst Class
4433 //===----------------------------------------------------------------------===//
4434 class CatchPadInst : public FuncletPadInst {
4435 private:
4436 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4437 unsigned Values, const Twine &NameStr,
4438 Instruction *InsertBefore)
4439 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4440 NameStr, InsertBefore) {}
4441 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4442 unsigned Values, const Twine &NameStr,
4443 BasicBlock *InsertAtEnd)
4444 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4445 NameStr, InsertAtEnd) {}
4447 public:
4448 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4449 const Twine &NameStr = "",
4450 Instruction *InsertBefore = nullptr) {
4451 unsigned Values = 1 + Args.size();
4452 return new (Values)
4453 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4456 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4457 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4458 unsigned Values = 1 + Args.size();
4459 return new (Values)
4460 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4463 /// Convenience accessors
4464 CatchSwitchInst *getCatchSwitch() const {
4465 return cast<CatchSwitchInst>(Op<-1>());
4467 void setCatchSwitch(Value *CatchSwitch) {
4468 assert(CatchSwitch);
4469 Op<-1>() = CatchSwitch;
4472 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4473 static bool classof(const Instruction *I) {
4474 return I->getOpcode() == Instruction::CatchPad;
4476 static bool classof(const Value *V) {
4477 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4481 //===----------------------------------------------------------------------===//
4482 // CatchReturnInst Class
4483 //===----------------------------------------------------------------------===//
4485 class CatchReturnInst : public Instruction {
4486 CatchReturnInst(const CatchReturnInst &RI);
4487 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4488 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4490 void init(Value *CatchPad, BasicBlock *BB);
4492 protected:
4493 // Note: Instruction needs to be a friend here to call cloneImpl.
4494 friend class Instruction;
4496 CatchReturnInst *cloneImpl() const;
4498 public:
4499 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4500 Instruction *InsertBefore = nullptr) {
4501 assert(CatchPad);
4502 assert(BB);
4503 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4506 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4507 BasicBlock *InsertAtEnd) {
4508 assert(CatchPad);
4509 assert(BB);
4510 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4513 /// Provide fast operand accessors
4514 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4516 /// Convenience accessors.
4517 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4518 void setCatchPad(CatchPadInst *CatchPad) {
4519 assert(CatchPad);
4520 Op<0>() = CatchPad;
4523 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4524 void setSuccessor(BasicBlock *NewSucc) {
4525 assert(NewSucc);
4526 Op<1>() = NewSucc;
4528 unsigned getNumSuccessors() const { return 1; }
4530 /// Get the parentPad of this catchret's catchpad's catchswitch.
4531 /// The successor block is implicitly a member of this funclet.
4532 Value *getCatchSwitchParentPad() const {
4533 return getCatchPad()->getCatchSwitch()->getParentPad();
4536 // Methods for support type inquiry through isa, cast, and dyn_cast:
4537 static bool classof(const Instruction *I) {
4538 return (I->getOpcode() == Instruction::CatchRet);
4540 static bool classof(const Value *V) {
4541 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4544 private:
4545 BasicBlock *getSuccessor(unsigned Idx) const {
4546 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4547 return getSuccessor();
4550 void setSuccessor(unsigned Idx, BasicBlock *B) {
4551 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
4552 setSuccessor(B);
4556 template <>
4557 struct OperandTraits<CatchReturnInst>
4558 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4560 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
4562 //===----------------------------------------------------------------------===//
4563 // CleanupReturnInst Class
4564 //===----------------------------------------------------------------------===//
4566 class CleanupReturnInst : public Instruction {
4567 private:
4568 CleanupReturnInst(const CleanupReturnInst &RI);
4569 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4570 Instruction *InsertBefore = nullptr);
4571 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4572 BasicBlock *InsertAtEnd);
4574 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4576 protected:
4577 // Note: Instruction needs to be a friend here to call cloneImpl.
4578 friend class Instruction;
4580 CleanupReturnInst *cloneImpl() const;
4582 public:
4583 static CleanupReturnInst *Create(Value *CleanupPad,
4584 BasicBlock *UnwindBB = nullptr,
4585 Instruction *InsertBefore = nullptr) {
4586 assert(CleanupPad);
4587 unsigned Values = 1;
4588 if (UnwindBB)
4589 ++Values;
4590 return new (Values)
4591 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4594 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4595 BasicBlock *InsertAtEnd) {
4596 assert(CleanupPad);
4597 unsigned Values = 1;
4598 if (UnwindBB)
4599 ++Values;
4600 return new (Values)
4601 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4604 /// Provide fast operand accessors
4605 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
4607 bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; }
4608 bool unwindsToCaller() const { return !hasUnwindDest(); }
4610 /// Convenience accessor.
4611 CleanupPadInst *getCleanupPad() const {
4612 return cast<CleanupPadInst>(Op<0>());
4614 void setCleanupPad(CleanupPadInst *CleanupPad) {
4615 assert(CleanupPad);
4616 Op<0>() = CleanupPad;
4619 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4621 BasicBlock *getUnwindDest() const {
4622 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4624 void setUnwindDest(BasicBlock *NewDest) {
4625 assert(NewDest);
4626 assert(hasUnwindDest());
4627 Op<1>() = NewDest;
4630 // Methods for support type inquiry through isa, cast, and dyn_cast:
4631 static bool classof(const Instruction *I) {
4632 return (I->getOpcode() == Instruction::CleanupRet);
4634 static bool classof(const Value *V) {
4635 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4638 private:
4639 BasicBlock *getSuccessor(unsigned Idx) const {
4640 assert(Idx == 0);
4641 return getUnwindDest();
4644 void setSuccessor(unsigned Idx, BasicBlock *B) {
4645 assert(Idx == 0);
4646 setUnwindDest(B);
4649 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4650 // method so that subclasses cannot accidentally use it.
4651 void setInstructionSubclassData(unsigned short D) {
4652 Instruction::setInstructionSubclassData(D);
4656 template <>
4657 struct OperandTraits<CleanupReturnInst>
4658 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4660 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
4662 //===----------------------------------------------------------------------===//
4663 // UnreachableInst Class
4664 //===----------------------------------------------------------------------===//
4666 //===---------------------------------------------------------------------------
4667 /// This function has undefined behavior. In particular, the
4668 /// presence of this instruction indicates some higher level knowledge that the
4669 /// end of the block cannot be reached.
4671 class UnreachableInst : public Instruction {
4672 protected:
4673 // Note: Instruction needs to be a friend here to call cloneImpl.
4674 friend class Instruction;
4676 UnreachableInst *cloneImpl() const;
4678 public:
4679 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4680 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4682 // allocate space for exactly zero operands
4683 void *operator new(size_t s) {
4684 return User::operator new(s, 0);
4687 unsigned getNumSuccessors() const { return 0; }
4689 // Methods for support type inquiry through isa, cast, and dyn_cast:
4690 static bool classof(const Instruction *I) {
4691 return I->getOpcode() == Instruction::Unreachable;
4693 static bool classof(const Value *V) {
4694 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4697 private:
4698 BasicBlock *getSuccessor(unsigned idx) const {
4699 llvm_unreachable("UnreachableInst has no successors!");
4702 void setSuccessor(unsigned idx, BasicBlock *B) {
4703 llvm_unreachable("UnreachableInst has no successors!");
4707 //===----------------------------------------------------------------------===//
4708 // TruncInst Class
4709 //===----------------------------------------------------------------------===//
4711 /// This class represents a truncation of integer types.
4712 class TruncInst : public CastInst {
4713 protected:
4714 // Note: Instruction needs to be a friend here to call cloneImpl.
4715 friend class Instruction;
4717 /// Clone an identical TruncInst
4718 TruncInst *cloneImpl() const;
4720 public:
4721 /// Constructor with insert-before-instruction semantics
4722 TruncInst(
4723 Value *S, ///< The value to be truncated
4724 Type *Ty, ///< The (smaller) type to truncate to
4725 const Twine &NameStr = "", ///< A name for the new instruction
4726 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4729 /// Constructor with insert-at-end-of-block semantics
4730 TruncInst(
4731 Value *S, ///< The value to be truncated
4732 Type *Ty, ///< The (smaller) type to truncate to
4733 const Twine &NameStr, ///< A name for the new instruction
4734 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4737 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4738 static bool classof(const Instruction *I) {
4739 return I->getOpcode() == Trunc;
4741 static bool classof(const Value *V) {
4742 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4746 //===----------------------------------------------------------------------===//
4747 // ZExtInst Class
4748 //===----------------------------------------------------------------------===//
4750 /// This class represents zero extension of integer types.
4751 class ZExtInst : public CastInst {
4752 protected:
4753 // Note: Instruction needs to be a friend here to call cloneImpl.
4754 friend class Instruction;
4756 /// Clone an identical ZExtInst
4757 ZExtInst *cloneImpl() const;
4759 public:
4760 /// Constructor with insert-before-instruction semantics
4761 ZExtInst(
4762 Value *S, ///< The value to be zero extended
4763 Type *Ty, ///< The type to zero extend to
4764 const Twine &NameStr = "", ///< A name for the new instruction
4765 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4768 /// Constructor with insert-at-end semantics.
4769 ZExtInst(
4770 Value *S, ///< The value to be zero extended
4771 Type *Ty, ///< The type to zero extend to
4772 const Twine &NameStr, ///< A name for the new instruction
4773 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4776 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4777 static bool classof(const Instruction *I) {
4778 return I->getOpcode() == ZExt;
4780 static bool classof(const Value *V) {
4781 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4785 //===----------------------------------------------------------------------===//
4786 // SExtInst Class
4787 //===----------------------------------------------------------------------===//
4789 /// This class represents a sign extension of integer types.
4790 class SExtInst : public CastInst {
4791 protected:
4792 // Note: Instruction needs to be a friend here to call cloneImpl.
4793 friend class Instruction;
4795 /// Clone an identical SExtInst
4796 SExtInst *cloneImpl() const;
4798 public:
4799 /// Constructor with insert-before-instruction semantics
4800 SExtInst(
4801 Value *S, ///< The value to be sign extended
4802 Type *Ty, ///< The type to sign extend to
4803 const Twine &NameStr = "", ///< A name for the new instruction
4804 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4807 /// Constructor with insert-at-end-of-block semantics
4808 SExtInst(
4809 Value *S, ///< The value to be sign extended
4810 Type *Ty, ///< The type to sign extend to
4811 const Twine &NameStr, ///< A name for the new instruction
4812 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4815 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4816 static bool classof(const Instruction *I) {
4817 return I->getOpcode() == SExt;
4819 static bool classof(const Value *V) {
4820 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4824 //===----------------------------------------------------------------------===//
4825 // FPTruncInst Class
4826 //===----------------------------------------------------------------------===//
4828 /// This class represents a truncation of floating point types.
4829 class FPTruncInst : public CastInst {
4830 protected:
4831 // Note: Instruction needs to be a friend here to call cloneImpl.
4832 friend class Instruction;
4834 /// Clone an identical FPTruncInst
4835 FPTruncInst *cloneImpl() const;
4837 public:
4838 /// Constructor with insert-before-instruction semantics
4839 FPTruncInst(
4840 Value *S, ///< The value to be truncated
4841 Type *Ty, ///< The type to truncate to
4842 const Twine &NameStr = "", ///< A name for the new instruction
4843 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4846 /// Constructor with insert-before-instruction semantics
4847 FPTruncInst(
4848 Value *S, ///< The value to be truncated
4849 Type *Ty, ///< The type to truncate to
4850 const Twine &NameStr, ///< A name for the new instruction
4851 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4854 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4855 static bool classof(const Instruction *I) {
4856 return I->getOpcode() == FPTrunc;
4858 static bool classof(const Value *V) {
4859 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4863 //===----------------------------------------------------------------------===//
4864 // FPExtInst Class
4865 //===----------------------------------------------------------------------===//
4867 /// This class represents an extension of floating point types.
4868 class FPExtInst : public CastInst {
4869 protected:
4870 // Note: Instruction needs to be a friend here to call cloneImpl.
4871 friend class Instruction;
4873 /// Clone an identical FPExtInst
4874 FPExtInst *cloneImpl() const;
4876 public:
4877 /// Constructor with insert-before-instruction semantics
4878 FPExtInst(
4879 Value *S, ///< The value to be extended
4880 Type *Ty, ///< The type to extend to
4881 const Twine &NameStr = "", ///< A name for the new instruction
4882 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4885 /// Constructor with insert-at-end-of-block semantics
4886 FPExtInst(
4887 Value *S, ///< The value to be extended
4888 Type *Ty, ///< The type to extend to
4889 const Twine &NameStr, ///< A name for the new instruction
4890 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4893 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4894 static bool classof(const Instruction *I) {
4895 return I->getOpcode() == FPExt;
4897 static bool classof(const Value *V) {
4898 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4902 //===----------------------------------------------------------------------===//
4903 // UIToFPInst Class
4904 //===----------------------------------------------------------------------===//
4906 /// This class represents a cast unsigned integer to floating point.
4907 class UIToFPInst : public CastInst {
4908 protected:
4909 // Note: Instruction needs to be a friend here to call cloneImpl.
4910 friend class Instruction;
4912 /// Clone an identical UIToFPInst
4913 UIToFPInst *cloneImpl() const;
4915 public:
4916 /// Constructor with insert-before-instruction semantics
4917 UIToFPInst(
4918 Value *S, ///< The value to be converted
4919 Type *Ty, ///< The type to convert to
4920 const Twine &NameStr = "", ///< A name for the new instruction
4921 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4924 /// Constructor with insert-at-end-of-block semantics
4925 UIToFPInst(
4926 Value *S, ///< The value to be converted
4927 Type *Ty, ///< The type to convert to
4928 const Twine &NameStr, ///< A name for the new instruction
4929 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4932 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4933 static bool classof(const Instruction *I) {
4934 return I->getOpcode() == UIToFP;
4936 static bool classof(const Value *V) {
4937 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4941 //===----------------------------------------------------------------------===//
4942 // SIToFPInst Class
4943 //===----------------------------------------------------------------------===//
4945 /// This class represents a cast from signed integer to floating point.
4946 class SIToFPInst : public CastInst {
4947 protected:
4948 // Note: Instruction needs to be a friend here to call cloneImpl.
4949 friend class Instruction;
4951 /// Clone an identical SIToFPInst
4952 SIToFPInst *cloneImpl() const;
4954 public:
4955 /// Constructor with insert-before-instruction semantics
4956 SIToFPInst(
4957 Value *S, ///< The value to be converted
4958 Type *Ty, ///< The type to convert to
4959 const Twine &NameStr = "", ///< A name for the new instruction
4960 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4963 /// Constructor with insert-at-end-of-block semantics
4964 SIToFPInst(
4965 Value *S, ///< The value to be converted
4966 Type *Ty, ///< The type to convert to
4967 const Twine &NameStr, ///< A name for the new instruction
4968 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4971 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4972 static bool classof(const Instruction *I) {
4973 return I->getOpcode() == SIToFP;
4975 static bool classof(const Value *V) {
4976 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4980 //===----------------------------------------------------------------------===//
4981 // FPToUIInst Class
4982 //===----------------------------------------------------------------------===//
4984 /// This class represents a cast from floating point to unsigned integer
4985 class FPToUIInst : public CastInst {
4986 protected:
4987 // Note: Instruction needs to be a friend here to call cloneImpl.
4988 friend class Instruction;
4990 /// Clone an identical FPToUIInst
4991 FPToUIInst *cloneImpl() const;
4993 public:
4994 /// Constructor with insert-before-instruction semantics
4995 FPToUIInst(
4996 Value *S, ///< The value to be converted
4997 Type *Ty, ///< The type to convert to
4998 const Twine &NameStr = "", ///< A name for the new instruction
4999 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5002 /// Constructor with insert-at-end-of-block semantics
5003 FPToUIInst(
5004 Value *S, ///< The value to be converted
5005 Type *Ty, ///< The type to convert to
5006 const Twine &NameStr, ///< A name for the new instruction
5007 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
5010 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5011 static bool classof(const Instruction *I) {
5012 return I->getOpcode() == FPToUI;
5014 static bool classof(const Value *V) {
5015 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5019 //===----------------------------------------------------------------------===//
5020 // FPToSIInst Class
5021 //===----------------------------------------------------------------------===//
5023 /// This class represents a cast from floating point to signed integer.
5024 class FPToSIInst : public CastInst {
5025 protected:
5026 // Note: Instruction needs to be a friend here to call cloneImpl.
5027 friend class Instruction;
5029 /// Clone an identical FPToSIInst
5030 FPToSIInst *cloneImpl() const;
5032 public:
5033 /// Constructor with insert-before-instruction semantics
5034 FPToSIInst(
5035 Value *S, ///< The value to be converted
5036 Type *Ty, ///< The type to convert to
5037 const Twine &NameStr = "", ///< A name for the new instruction
5038 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5041 /// Constructor with insert-at-end-of-block semantics
5042 FPToSIInst(
5043 Value *S, ///< The value to be converted
5044 Type *Ty, ///< The type to convert to
5045 const Twine &NameStr, ///< A name for the new instruction
5046 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5049 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5050 static bool classof(const Instruction *I) {
5051 return I->getOpcode() == FPToSI;
5053 static bool classof(const Value *V) {
5054 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5058 //===----------------------------------------------------------------------===//
5059 // IntToPtrInst Class
5060 //===----------------------------------------------------------------------===//
5062 /// This class represents a cast from an integer to a pointer.
5063 class IntToPtrInst : public CastInst {
5064 public:
5065 // Note: Instruction needs to be a friend here to call cloneImpl.
5066 friend class Instruction;
5068 /// Constructor with insert-before-instruction semantics
5069 IntToPtrInst(
5070 Value *S, ///< The value to be converted
5071 Type *Ty, ///< The type to convert to
5072 const Twine &NameStr = "", ///< A name for the new instruction
5073 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5076 /// Constructor with insert-at-end-of-block semantics
5077 IntToPtrInst(
5078 Value *S, ///< The value to be converted
5079 Type *Ty, ///< The type to convert to
5080 const Twine &NameStr, ///< A name for the new instruction
5081 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5084 /// Clone an identical IntToPtrInst.
5085 IntToPtrInst *cloneImpl() const;
5087 /// Returns the address space of this instruction's pointer type.
5088 unsigned getAddressSpace() const {
5089 return getType()->getPointerAddressSpace();
5092 // Methods for support type inquiry through isa, cast, and dyn_cast:
5093 static bool classof(const Instruction *I) {
5094 return I->getOpcode() == IntToPtr;
5096 static bool classof(const Value *V) {
5097 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5101 //===----------------------------------------------------------------------===//
5102 // PtrToIntInst Class
5103 //===----------------------------------------------------------------------===//
5105 /// This class represents a cast from a pointer to an integer.
5106 class PtrToIntInst : public CastInst {
5107 protected:
5108 // Note: Instruction needs to be a friend here to call cloneImpl.
5109 friend class Instruction;
5111 /// Clone an identical PtrToIntInst.
5112 PtrToIntInst *cloneImpl() const;
5114 public:
5115 /// Constructor with insert-before-instruction semantics
5116 PtrToIntInst(
5117 Value *S, ///< The value to be converted
5118 Type *Ty, ///< The type to convert to
5119 const Twine &NameStr = "", ///< A name for the new instruction
5120 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5123 /// Constructor with insert-at-end-of-block semantics
5124 PtrToIntInst(
5125 Value *S, ///< The value to be converted
5126 Type *Ty, ///< The type to convert to
5127 const Twine &NameStr, ///< A name for the new instruction
5128 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5131 /// Gets the pointer operand.
5132 Value *getPointerOperand() { return getOperand(0); }
5133 /// Gets the pointer operand.
5134 const Value *getPointerOperand() const { return getOperand(0); }
5135 /// Gets the operand index of the pointer operand.
5136 static unsigned getPointerOperandIndex() { return 0U; }
5138 /// Returns the address space of the pointer operand.
5139 unsigned getPointerAddressSpace() const {
5140 return getPointerOperand()->getType()->getPointerAddressSpace();
5143 // Methods for support type inquiry through isa, cast, and dyn_cast:
5144 static bool classof(const Instruction *I) {
5145 return I->getOpcode() == PtrToInt;
5147 static bool classof(const Value *V) {
5148 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5152 //===----------------------------------------------------------------------===//
5153 // BitCastInst Class
5154 //===----------------------------------------------------------------------===//
5156 /// This class represents a no-op cast from one type to another.
5157 class BitCastInst : public CastInst {
5158 protected:
5159 // Note: Instruction needs to be a friend here to call cloneImpl.
5160 friend class Instruction;
5162 /// Clone an identical BitCastInst.
5163 BitCastInst *cloneImpl() const;
5165 public:
5166 /// Constructor with insert-before-instruction semantics
5167 BitCastInst(
5168 Value *S, ///< The value to be casted
5169 Type *Ty, ///< The type to casted to
5170 const Twine &NameStr = "", ///< A name for the new instruction
5171 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5174 /// Constructor with insert-at-end-of-block semantics
5175 BitCastInst(
5176 Value *S, ///< The value to be casted
5177 Type *Ty, ///< The type to casted to
5178 const Twine &NameStr, ///< A name for the new instruction
5179 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5182 // Methods for support type inquiry through isa, cast, and dyn_cast:
5183 static bool classof(const Instruction *I) {
5184 return I->getOpcode() == BitCast;
5186 static bool classof(const Value *V) {
5187 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5191 //===----------------------------------------------------------------------===//
5192 // AddrSpaceCastInst Class
5193 //===----------------------------------------------------------------------===//
5195 /// This class represents a conversion between pointers from one address space
5196 /// to another.
5197 class AddrSpaceCastInst : public CastInst {
5198 protected:
5199 // Note: Instruction needs to be a friend here to call cloneImpl.
5200 friend class Instruction;
5202 /// Clone an identical AddrSpaceCastInst.
5203 AddrSpaceCastInst *cloneImpl() const;
5205 public:
5206 /// Constructor with insert-before-instruction semantics
5207 AddrSpaceCastInst(
5208 Value *S, ///< The value to be casted
5209 Type *Ty, ///< The type to casted to
5210 const Twine &NameStr = "", ///< A name for the new instruction
5211 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5214 /// Constructor with insert-at-end-of-block semantics
5215 AddrSpaceCastInst(
5216 Value *S, ///< The value to be casted
5217 Type *Ty, ///< The type to casted to
5218 const Twine &NameStr, ///< A name for the new instruction
5219 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5222 // Methods for support type inquiry through isa, cast, and dyn_cast:
5223 static bool classof(const Instruction *I) {
5224 return I->getOpcode() == AddrSpaceCast;
5226 static bool classof(const Value *V) {
5227 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5230 /// Gets the pointer operand.
5231 Value *getPointerOperand() {
5232 return getOperand(0);
5235 /// Gets the pointer operand.
5236 const Value *getPointerOperand() const {
5237 return getOperand(0);
5240 /// Gets the operand index of the pointer operand.
5241 static unsigned getPointerOperandIndex() {
5242 return 0U;
5245 /// Returns the address space of the pointer operand.
5246 unsigned getSrcAddressSpace() const {
5247 return getPointerOperand()->getType()->getPointerAddressSpace();
5250 /// Returns the address space of the result.
5251 unsigned getDestAddressSpace() const {
5252 return getType()->getPointerAddressSpace();
5256 /// A helper function that returns the pointer operand of a load or store
5257 /// instruction. Returns nullptr if not load or store.
5258 inline const Value *getLoadStorePointerOperand(const Value *V) {
5259 if (auto *Load = dyn_cast<LoadInst>(V))
5260 return Load->getPointerOperand();
5261 if (auto *Store = dyn_cast<StoreInst>(V))
5262 return Store->getPointerOperand();
5263 return nullptr;
5265 inline Value *getLoadStorePointerOperand(Value *V) {
5266 return const_cast<Value *>(
5267 getLoadStorePointerOperand(static_cast<const Value *>(V)));
5270 /// A helper function that returns the pointer operand of a load, store
5271 /// or GEP instruction. Returns nullptr if not load, store, or GEP.
5272 inline const Value *getPointerOperand(const Value *V) {
5273 if (auto *Ptr = getLoadStorePointerOperand(V))
5274 return Ptr;
5275 if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
5276 return Gep->getPointerOperand();
5277 return nullptr;
5279 inline Value *getPointerOperand(Value *V) {
5280 return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V)));
5283 /// A helper function that returns the alignment of load or store instruction.
5284 inline MaybeAlign getLoadStoreAlignment(Value *I) {
5285 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5286 "Expected Load or Store instruction");
5287 if (auto *LI = dyn_cast<LoadInst>(I))
5288 return MaybeAlign(LI->getAlignment());
5289 return MaybeAlign(cast<StoreInst>(I)->getAlignment());
5292 /// A helper function that returns the address space of the pointer operand of
5293 /// load or store instruction.
5294 inline unsigned getLoadStoreAddressSpace(Value *I) {
5295 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5296 "Expected Load or Store instruction");
5297 if (auto *LI = dyn_cast<LoadInst>(I))
5298 return LI->getPointerAddressSpace();
5299 return cast<StoreInst>(I)->getPointerAddressSpace();
5302 } // end namespace llvm
5304 #endif // LLVM_IR_INSTRUCTIONS_H