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