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