1 //===- llvm/InstrTypes.h - Important Instruction subclasses -----*- 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 defines various meta classes of instructions that exist in the VM 10 // representation. Specific concrete subclasses of these may be found in the 11 // i*.h files... 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_IR_INSTRTYPES_H 16 #define LLVM_IR_INSTRTYPES_H 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/Sequence.h" 21 #include "llvm/ADT/StringMap.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/ADT/iterator_range.h" 24 #include "llvm/IR/Attributes.h" 25 #include "llvm/IR/CallingConv.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/Instruction.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/OperandTraits.h" 31 #include "llvm/IR/User.h" 32 #include <algorithm> 33 #include <cassert> 34 #include <cstddef> 35 #include <cstdint> 36 #include <iterator> 37 #include <optional> 38 #include <string> 39 #include <vector> 40 41 namespace llvm { 42 43 class StringRef; 44 class Type; 45 class Value; 46 47 namespace Intrinsic { 48 typedef unsigned ID; 49 } 50 51 //===----------------------------------------------------------------------===// 52 // UnaryInstruction Class 53 //===----------------------------------------------------------------------===// 54 55 class UnaryInstruction : public Instruction { 56 protected: 57 UnaryInstruction(Type *Ty, unsigned iType, Value *V, 58 Instruction *IB = nullptr) 59 : Instruction(Ty, iType, &Op<0>(), 1, IB) { 60 Op<0>() = V; 61 } 62 UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE) 63 : Instruction(Ty, iType, &Op<0>(), 1, IAE) { 64 Op<0>() = V; 65 } 66 67 public: 68 // allocate space for exactly one operand 69 void *operator new(size_t S) { return User::operator new(S, 1); } 70 void operator delete(void *Ptr) { User::operator delete(Ptr); } 71 72 /// Transparently provide more efficient getOperand methods. 73 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 74 75 // Methods for support type inquiry through isa, cast, and dyn_cast: 76 static bool classof(const Instruction *I) { 77 return I->isUnaryOp() || 78 I->getOpcode() == Instruction::Alloca || 79 I->getOpcode() == Instruction::Load || 80 I->getOpcode() == Instruction::VAArg || 81 I->getOpcode() == Instruction::ExtractValue || 82 (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd); 83 } 84 static bool classof(const Value *V) { 85 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 86 } 87 }; 88 89 template <> 90 struct OperandTraits<UnaryInstruction> : 91 public FixedNumOperandTraits<UnaryInstruction, 1> { 92 }; 93 94 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value) 95 96 //===----------------------------------------------------------------------===// 97 // UnaryOperator Class 98 //===----------------------------------------------------------------------===// 99 100 class UnaryOperator : public UnaryInstruction { 101 void AssertOK(); 102 103 protected: 104 UnaryOperator(UnaryOps iType, Value *S, Type *Ty, 105 const Twine &Name, Instruction *InsertBefore); 106 UnaryOperator(UnaryOps iType, Value *S, Type *Ty, 107 const Twine &Name, BasicBlock *InsertAtEnd); 108 109 // Note: Instruction needs to be a friend here to call cloneImpl. 110 friend class Instruction; 111 112 UnaryOperator *cloneImpl() const; 113 114 public: 115 116 /// Construct a unary instruction, given the opcode and an operand. 117 /// Optionally (if InstBefore is specified) insert the instruction 118 /// into a BasicBlock right before the specified instruction. The specified 119 /// Instruction is allowed to be a dereferenced end iterator. 120 /// 121 static UnaryOperator *Create(UnaryOps Op, Value *S, 122 const Twine &Name = Twine(), 123 Instruction *InsertBefore = nullptr); 124 125 /// Construct a unary instruction, given the opcode and an operand. 126 /// Also automatically insert this instruction to the end of the 127 /// BasicBlock specified. 128 /// 129 static UnaryOperator *Create(UnaryOps Op, Value *S, 130 const Twine &Name, 131 BasicBlock *InsertAtEnd); 132 133 /// These methods just forward to Create, and are useful when you 134 /// statically know what type of instruction you're going to create. These 135 /// helpers just save some typing. 136 #define HANDLE_UNARY_INST(N, OPC, CLASS) \ 137 static UnaryOperator *Create##OPC(Value *V, const Twine &Name = "") {\ 138 return Create(Instruction::OPC, V, Name);\ 139 } 140 #include "llvm/IR/Instruction.def" 141 #define HANDLE_UNARY_INST(N, OPC, CLASS) \ 142 static UnaryOperator *Create##OPC(Value *V, const Twine &Name, \ 143 BasicBlock *BB) {\ 144 return Create(Instruction::OPC, V, Name, BB);\ 145 } 146 #include "llvm/IR/Instruction.def" 147 #define HANDLE_UNARY_INST(N, OPC, CLASS) \ 148 static UnaryOperator *Create##OPC(Value *V, const Twine &Name, \ 149 Instruction *I) {\ 150 return Create(Instruction::OPC, V, Name, I);\ 151 } 152 #include "llvm/IR/Instruction.def" 153 154 static UnaryOperator * 155 CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO, 156 const Twine &Name = "", 157 Instruction *InsertBefore = nullptr) { 158 UnaryOperator *UO = Create(Opc, V, Name, InsertBefore); 159 UO->copyIRFlags(CopyO); 160 return UO; 161 } 162 163 static UnaryOperator *CreateFNegFMF(Value *Op, Instruction *FMFSource, 164 const Twine &Name = "", 165 Instruction *InsertBefore = nullptr) { 166 return CreateWithCopiedFlags(Instruction::FNeg, Op, FMFSource, Name, 167 InsertBefore); 168 } 169 170 UnaryOps getOpcode() const { 171 return static_cast<UnaryOps>(Instruction::getOpcode()); 172 } 173 174 // Methods for support type inquiry through isa, cast, and dyn_cast: 175 static bool classof(const Instruction *I) { 176 return I->isUnaryOp(); 177 } 178 static bool classof(const Value *V) { 179 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 180 } 181 }; 182 183 //===----------------------------------------------------------------------===// 184 // BinaryOperator Class 185 //===----------------------------------------------------------------------===// 186 187 class BinaryOperator : public Instruction { 188 void AssertOK(); 189 190 protected: 191 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, 192 const Twine &Name, Instruction *InsertBefore); 193 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, 194 const Twine &Name, BasicBlock *InsertAtEnd); 195 196 // Note: Instruction needs to be a friend here to call cloneImpl. 197 friend class Instruction; 198 199 BinaryOperator *cloneImpl() const; 200 201 public: 202 // allocate space for exactly two operands 203 void *operator new(size_t S) { return User::operator new(S, 2); } 204 void operator delete(void *Ptr) { User::operator delete(Ptr); } 205 206 /// Transparently provide more efficient getOperand methods. 207 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 208 209 /// Construct a binary instruction, given the opcode and the two 210 /// operands. Optionally (if InstBefore is specified) insert the instruction 211 /// into a BasicBlock right before the specified instruction. The specified 212 /// Instruction is allowed to be a dereferenced end iterator. 213 /// 214 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2, 215 const Twine &Name = Twine(), 216 Instruction *InsertBefore = nullptr); 217 218 /// Construct a binary instruction, given the opcode and the two 219 /// operands. Also automatically insert this instruction to the end of the 220 /// BasicBlock specified. 221 /// 222 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2, 223 const Twine &Name, BasicBlock *InsertAtEnd); 224 225 /// These methods just forward to Create, and are useful when you 226 /// statically know what type of instruction you're going to create. These 227 /// helpers just save some typing. 228 #define HANDLE_BINARY_INST(N, OPC, CLASS) \ 229 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \ 230 const Twine &Name = "") {\ 231 return Create(Instruction::OPC, V1, V2, Name);\ 232 } 233 #include "llvm/IR/Instruction.def" 234 #define HANDLE_BINARY_INST(N, OPC, CLASS) \ 235 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \ 236 const Twine &Name, BasicBlock *BB) {\ 237 return Create(Instruction::OPC, V1, V2, Name, BB);\ 238 } 239 #include "llvm/IR/Instruction.def" 240 #define HANDLE_BINARY_INST(N, OPC, CLASS) \ 241 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \ 242 const Twine &Name, Instruction *I) {\ 243 return Create(Instruction::OPC, V1, V2, Name, I);\ 244 } 245 #include "llvm/IR/Instruction.def" 246 247 static BinaryOperator * 248 CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, 249 const Twine &Name = "", 250 Instruction *InsertBefore = nullptr) { 251 BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore); 252 BO->copyIRFlags(CopyO); 253 return BO; 254 } 255 256 static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2, 257 Instruction *FMFSource, 258 const Twine &Name = "") { 259 return CreateWithCopiedFlags(Instruction::FAdd, V1, V2, FMFSource, Name); 260 } 261 static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2, 262 Instruction *FMFSource, 263 const Twine &Name = "") { 264 return CreateWithCopiedFlags(Instruction::FSub, V1, V2, FMFSource, Name); 265 } 266 static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2, 267 Instruction *FMFSource, 268 const Twine &Name = "") { 269 return CreateWithCopiedFlags(Instruction::FMul, V1, V2, FMFSource, Name); 270 } 271 static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2, 272 Instruction *FMFSource, 273 const Twine &Name = "") { 274 return CreateWithCopiedFlags(Instruction::FDiv, V1, V2, FMFSource, Name); 275 } 276 static BinaryOperator *CreateFRemFMF(Value *V1, Value *V2, 277 Instruction *FMFSource, 278 const Twine &Name = "") { 279 return CreateWithCopiedFlags(Instruction::FRem, V1, V2, FMFSource, Name); 280 } 281 282 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2, 283 const Twine &Name = "") { 284 BinaryOperator *BO = Create(Opc, V1, V2, Name); 285 BO->setHasNoSignedWrap(true); 286 return BO; 287 } 288 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2, 289 const Twine &Name, BasicBlock *BB) { 290 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB); 291 BO->setHasNoSignedWrap(true); 292 return BO; 293 } 294 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2, 295 const Twine &Name, Instruction *I) { 296 BinaryOperator *BO = Create(Opc, V1, V2, Name, I); 297 BO->setHasNoSignedWrap(true); 298 return BO; 299 } 300 301 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2, 302 const Twine &Name = "") { 303 BinaryOperator *BO = Create(Opc, V1, V2, Name); 304 BO->setHasNoUnsignedWrap(true); 305 return BO; 306 } 307 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2, 308 const Twine &Name, BasicBlock *BB) { 309 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB); 310 BO->setHasNoUnsignedWrap(true); 311 return BO; 312 } 313 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2, 314 const Twine &Name, Instruction *I) { 315 BinaryOperator *BO = Create(Opc, V1, V2, Name, I); 316 BO->setHasNoUnsignedWrap(true); 317 return BO; 318 } 319 320 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2, 321 const Twine &Name = "") { 322 BinaryOperator *BO = Create(Opc, V1, V2, Name); 323 BO->setIsExact(true); 324 return BO; 325 } 326 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2, 327 const Twine &Name, BasicBlock *BB) { 328 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB); 329 BO->setIsExact(true); 330 return BO; 331 } 332 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2, 333 const Twine &Name, Instruction *I) { 334 BinaryOperator *BO = Create(Opc, V1, V2, Name, I); 335 BO->setIsExact(true); 336 return BO; 337 } 338 339 #define DEFINE_HELPERS(OPC, NUWNSWEXACT) \ 340 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \ 341 const Twine &Name = "") { \ 342 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \ 343 } \ 344 static BinaryOperator *Create##NUWNSWEXACT##OPC( \ 345 Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \ 346 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \ 347 } \ 348 static BinaryOperator *Create##NUWNSWEXACT##OPC( \ 349 Value *V1, Value *V2, const Twine &Name, Instruction *I) { \ 350 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \ 351 } 352 353 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd 354 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd 355 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub 356 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub 357 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul 358 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul 359 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl 360 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl 361 362 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv 363 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv 364 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr 365 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr 366 367 #undef DEFINE_HELPERS 368 369 /// Helper functions to construct and inspect unary operations (NEG and NOT) 370 /// via binary operators SUB and XOR: 371 /// 372 /// Create the NEG and NOT instructions out of SUB and XOR instructions. 373 /// 374 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "", 375 Instruction *InsertBefore = nullptr); 376 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name, 377 BasicBlock *InsertAtEnd); 378 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "", 379 Instruction *InsertBefore = nullptr); 380 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name, 381 BasicBlock *InsertAtEnd); 382 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "", 383 Instruction *InsertBefore = nullptr); 384 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name, 385 BasicBlock *InsertAtEnd); 386 static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "", 387 Instruction *InsertBefore = nullptr); 388 static BinaryOperator *CreateNot(Value *Op, const Twine &Name, 389 BasicBlock *InsertAtEnd); 390 391 BinaryOps getOpcode() const { 392 return static_cast<BinaryOps>(Instruction::getOpcode()); 393 } 394 395 /// Exchange the two operands to this instruction. 396 /// This instruction is safe to use on any binary instruction and 397 /// does not modify the semantics of the instruction. If the instruction 398 /// cannot be reversed (ie, it's a Div), then return true. 399 /// 400 bool swapOperands(); 401 402 // Methods for support type inquiry through isa, cast, and dyn_cast: 403 static bool classof(const Instruction *I) { 404 return I->isBinaryOp(); 405 } 406 static bool classof(const Value *V) { 407 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 408 } 409 }; 410 411 template <> 412 struct OperandTraits<BinaryOperator> : 413 public FixedNumOperandTraits<BinaryOperator, 2> { 414 }; 415 416 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value) 417 418 //===----------------------------------------------------------------------===// 419 // CastInst Class 420 //===----------------------------------------------------------------------===// 421 422 /// This is the base class for all instructions that perform data 423 /// casts. It is simply provided so that instruction category testing 424 /// can be performed with code like: 425 /// 426 /// if (isa<CastInst>(Instr)) { ... } 427 /// Base class of casting instructions. 428 class CastInst : public UnaryInstruction { 429 protected: 430 /// Constructor with insert-before-instruction semantics for subclasses 431 CastInst(Type *Ty, unsigned iType, Value *S, 432 const Twine &NameStr = "", Instruction *InsertBefore = nullptr) 433 : UnaryInstruction(Ty, iType, S, InsertBefore) { 434 setName(NameStr); 435 } 436 /// Constructor with insert-at-end-of-block semantics for subclasses 437 CastInst(Type *Ty, unsigned iType, Value *S, 438 const Twine &NameStr, BasicBlock *InsertAtEnd) 439 : UnaryInstruction(Ty, iType, S, InsertAtEnd) { 440 setName(NameStr); 441 } 442 443 public: 444 /// Provides a way to construct any of the CastInst subclasses using an 445 /// opcode instead of the subclass's constructor. The opcode must be in the 446 /// CastOps category (Instruction::isCast(opcode) returns true). This 447 /// constructor has insert-before-instruction semantics to automatically 448 /// insert the new CastInst before InsertBefore (if it is non-null). 449 /// Construct any of the CastInst subclasses 450 static CastInst *Create( 451 Instruction::CastOps, ///< The opcode of the cast instruction 452 Value *S, ///< The value to be casted (operand 0) 453 Type *Ty, ///< The type to which cast should be made 454 const Twine &Name = "", ///< Name for the instruction 455 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 456 ); 457 /// Provides a way to construct any of the CastInst subclasses using an 458 /// opcode instead of the subclass's constructor. The opcode must be in the 459 /// CastOps category. This constructor has insert-at-end-of-block semantics 460 /// to automatically insert the new CastInst at the end of InsertAtEnd (if 461 /// its non-null). 462 /// Construct any of the CastInst subclasses 463 static CastInst *Create( 464 Instruction::CastOps, ///< The opcode for the cast instruction 465 Value *S, ///< The value to be casted (operand 0) 466 Type *Ty, ///< The type to which operand is casted 467 const Twine &Name, ///< The name for the instruction 468 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 469 ); 470 471 /// Create a ZExt or BitCast cast instruction 472 static CastInst *CreateZExtOrBitCast( 473 Value *S, ///< The value to be casted (operand 0) 474 Type *Ty, ///< The type to which cast should be made 475 const Twine &Name = "", ///< Name for the instruction 476 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 477 ); 478 479 /// Create a ZExt or BitCast cast instruction 480 static CastInst *CreateZExtOrBitCast( 481 Value *S, ///< The value to be casted (operand 0) 482 Type *Ty, ///< The type to which operand is casted 483 const Twine &Name, ///< The name for the instruction 484 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 485 ); 486 487 /// Create a SExt or BitCast cast instruction 488 static CastInst *CreateSExtOrBitCast( 489 Value *S, ///< The value to be casted (operand 0) 490 Type *Ty, ///< The type to which cast should be made 491 const Twine &Name = "", ///< Name for the instruction 492 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 493 ); 494 495 /// Create a SExt or BitCast cast instruction 496 static CastInst *CreateSExtOrBitCast( 497 Value *S, ///< The value to be casted (operand 0) 498 Type *Ty, ///< The type to which operand is casted 499 const Twine &Name, ///< The name for the instruction 500 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 501 ); 502 503 /// Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction. 504 static CastInst *CreatePointerCast( 505 Value *S, ///< The pointer value to be casted (operand 0) 506 Type *Ty, ///< The type to which operand is casted 507 const Twine &Name, ///< The name for the instruction 508 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 509 ); 510 511 /// Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction. 512 static CastInst *CreatePointerCast( 513 Value *S, ///< The pointer value to be casted (operand 0) 514 Type *Ty, ///< The type to which cast should be made 515 const Twine &Name = "", ///< Name for the instruction 516 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 517 ); 518 519 /// Create a BitCast or an AddrSpaceCast cast instruction. 520 static CastInst *CreatePointerBitCastOrAddrSpaceCast( 521 Value *S, ///< The pointer value to be casted (operand 0) 522 Type *Ty, ///< The type to which operand is casted 523 const Twine &Name, ///< The name for the instruction 524 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 525 ); 526 527 /// Create a BitCast or an AddrSpaceCast cast instruction. 528 static CastInst *CreatePointerBitCastOrAddrSpaceCast( 529 Value *S, ///< The pointer value to be casted (operand 0) 530 Type *Ty, ///< The type to which cast should be made 531 const Twine &Name = "", ///< Name for the instruction 532 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 533 ); 534 535 /// Create a BitCast, a PtrToInt, or an IntToPTr cast instruction. 536 /// 537 /// If the value is a pointer type and the destination an integer type, 538 /// creates a PtrToInt cast. If the value is an integer type and the 539 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates 540 /// a bitcast. 541 static CastInst *CreateBitOrPointerCast( 542 Value *S, ///< The pointer value to be casted (operand 0) 543 Type *Ty, ///< The type to which cast should be made 544 const Twine &Name = "", ///< Name for the instruction 545 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 546 ); 547 548 /// Create a ZExt, BitCast, or Trunc for int -> int casts. 549 static CastInst *CreateIntegerCast( 550 Value *S, ///< The pointer value to be casted (operand 0) 551 Type *Ty, ///< The type to which cast should be made 552 bool isSigned, ///< Whether to regard S as signed or not 553 const Twine &Name = "", ///< Name for the instruction 554 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 555 ); 556 557 /// Create a ZExt, BitCast, or Trunc for int -> int casts. 558 static CastInst *CreateIntegerCast( 559 Value *S, ///< The integer value to be casted (operand 0) 560 Type *Ty, ///< The integer type to which operand is casted 561 bool isSigned, ///< Whether to regard S as signed or not 562 const Twine &Name, ///< The name for the instruction 563 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 564 ); 565 566 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts 567 static CastInst *CreateFPCast( 568 Value *S, ///< The floating point value to be casted 569 Type *Ty, ///< The floating point type to cast to 570 const Twine &Name = "", ///< Name for the instruction 571 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 572 ); 573 574 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts 575 static CastInst *CreateFPCast( 576 Value *S, ///< The floating point value to be casted 577 Type *Ty, ///< The floating point type to cast to 578 const Twine &Name, ///< The name for the instruction 579 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 580 ); 581 582 /// Create a Trunc or BitCast cast instruction 583 static CastInst *CreateTruncOrBitCast( 584 Value *S, ///< The value to be casted (operand 0) 585 Type *Ty, ///< The type to which cast should be made 586 const Twine &Name = "", ///< Name for the instruction 587 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 588 ); 589 590 /// Create a Trunc or BitCast cast instruction 591 static CastInst *CreateTruncOrBitCast( 592 Value *S, ///< The value to be casted (operand 0) 593 Type *Ty, ///< The type to which operand is casted 594 const Twine &Name, ///< The name for the instruction 595 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 596 ); 597 598 /// Check whether a bitcast between these types is valid 599 static bool isBitCastable( 600 Type *SrcTy, ///< The Type from which the value should be cast. 601 Type *DestTy ///< The Type to which the value should be cast. 602 ); 603 604 /// Check whether a bitcast, inttoptr, or ptrtoint cast between these 605 /// types is valid and a no-op. 606 /// 607 /// This ensures that any pointer<->integer cast has enough bits in the 608 /// integer and any other cast is a bitcast. 609 static bool isBitOrNoopPointerCastable( 610 Type *SrcTy, ///< The Type from which the value should be cast. 611 Type *DestTy, ///< The Type to which the value should be cast. 612 const DataLayout &DL); 613 614 /// Returns the opcode necessary to cast Val into Ty using usual casting 615 /// rules. 616 /// Infer the opcode for cast operand and type 617 static Instruction::CastOps getCastOpcode( 618 const Value *Val, ///< The value to cast 619 bool SrcIsSigned, ///< Whether to treat the source as signed 620 Type *Ty, ///< The Type to which the value should be casted 621 bool DstIsSigned ///< Whether to treate the dest. as signed 622 ); 623 624 /// There are several places where we need to know if a cast instruction 625 /// only deals with integer source and destination types. To simplify that 626 /// logic, this method is provided. 627 /// @returns true iff the cast has only integral typed operand and dest type. 628 /// Determine if this is an integer-only cast. 629 bool isIntegerCast() const; 630 631 /// A no-op cast is one that can be effected without changing any bits. 632 /// It implies that the source and destination types are the same size. The 633 /// DataLayout argument is to determine the pointer size when examining casts 634 /// involving Integer and Pointer types. They are no-op casts if the integer 635 /// is the same size as the pointer. However, pointer size varies with 636 /// platform. Note that a precondition of this method is that the cast is 637 /// legal - i.e. the instruction formed with these operands would verify. 638 static bool isNoopCast( 639 Instruction::CastOps Opcode, ///< Opcode of cast 640 Type *SrcTy, ///< SrcTy of cast 641 Type *DstTy, ///< DstTy of cast 642 const DataLayout &DL ///< DataLayout to get the Int Ptr type from. 643 ); 644 645 /// Determine if this cast is a no-op cast. 646 /// 647 /// \param DL is the DataLayout to determine pointer size. 648 bool isNoopCast(const DataLayout &DL) const; 649 650 /// Determine how a pair of casts can be eliminated, if they can be at all. 651 /// This is a helper function for both CastInst and ConstantExpr. 652 /// @returns 0 if the CastInst pair can't be eliminated, otherwise 653 /// returns Instruction::CastOps value for a cast that can replace 654 /// the pair, casting SrcTy to DstTy. 655 /// Determine if a cast pair is eliminable 656 static unsigned isEliminableCastPair( 657 Instruction::CastOps firstOpcode, ///< Opcode of first cast 658 Instruction::CastOps secondOpcode, ///< Opcode of second cast 659 Type *SrcTy, ///< SrcTy of 1st cast 660 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast 661 Type *DstTy, ///< DstTy of 2nd cast 662 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null 663 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null 664 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null 665 ); 666 667 /// Return the opcode of this CastInst 668 Instruction::CastOps getOpcode() const { 669 return Instruction::CastOps(Instruction::getOpcode()); 670 } 671 672 /// Return the source type, as a convenience 673 Type* getSrcTy() const { return getOperand(0)->getType(); } 674 /// Return the destination type, as a convenience 675 Type* getDestTy() const { return getType(); } 676 677 /// This method can be used to determine if a cast from SrcTy to DstTy using 678 /// Opcode op is valid or not. 679 /// @returns true iff the proposed cast is valid. 680 /// Determine if a cast is valid without creating one. 681 static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy); 682 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { 683 return castIsValid(op, S->getType(), DstTy); 684 } 685 686 /// Methods for support type inquiry through isa, cast, and dyn_cast: 687 static bool classof(const Instruction *I) { 688 return I->isCast(); 689 } 690 static bool classof(const Value *V) { 691 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 692 } 693 }; 694 695 //===----------------------------------------------------------------------===// 696 // CmpInst Class 697 //===----------------------------------------------------------------------===// 698 699 /// This class is the base class for the comparison instructions. 700 /// Abstract base class of comparison instructions. 701 class CmpInst : public Instruction { 702 public: 703 /// This enumeration lists the possible predicates for CmpInst subclasses. 704 /// Values in the range 0-31 are reserved for FCmpInst, while values in the 705 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the 706 /// predicate values are not overlapping between the classes. 707 /// 708 /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of 709 /// FCMP_* values. Changing the bit patterns requires a potential change to 710 /// those passes. 711 enum Predicate : unsigned { 712 // Opcode U L G E Intuitive operation 713 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded) 714 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal 715 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than 716 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal 717 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than 718 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal 719 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal 720 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans) 721 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y) 722 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal 723 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than 724 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal 725 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than 726 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal 727 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal 728 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded) 729 FIRST_FCMP_PREDICATE = FCMP_FALSE, 730 LAST_FCMP_PREDICATE = FCMP_TRUE, 731 BAD_FCMP_PREDICATE = FCMP_TRUE + 1, 732 ICMP_EQ = 32, ///< equal 733 ICMP_NE = 33, ///< not equal 734 ICMP_UGT = 34, ///< unsigned greater than 735 ICMP_UGE = 35, ///< unsigned greater or equal 736 ICMP_ULT = 36, ///< unsigned less than 737 ICMP_ULE = 37, ///< unsigned less or equal 738 ICMP_SGT = 38, ///< signed greater than 739 ICMP_SGE = 39, ///< signed greater or equal 740 ICMP_SLT = 40, ///< signed less than 741 ICMP_SLE = 41, ///< signed less or equal 742 FIRST_ICMP_PREDICATE = ICMP_EQ, 743 LAST_ICMP_PREDICATE = ICMP_SLE, 744 BAD_ICMP_PREDICATE = ICMP_SLE + 1 745 }; 746 using PredicateField = 747 Bitfield::Element<Predicate, 0, 6, LAST_ICMP_PREDICATE>; 748 749 /// Returns the sequence of all FCmp predicates. 750 static auto FCmpPredicates() { 751 return enum_seq_inclusive(Predicate::FIRST_FCMP_PREDICATE, 752 Predicate::LAST_FCMP_PREDICATE, 753 force_iteration_on_noniterable_enum); 754 } 755 756 /// Returns the sequence of all ICmp predicates. 757 static auto ICmpPredicates() { 758 return enum_seq_inclusive(Predicate::FIRST_ICMP_PREDICATE, 759 Predicate::LAST_ICMP_PREDICATE, 760 force_iteration_on_noniterable_enum); 761 } 762 763 protected: 764 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, 765 Value *LHS, Value *RHS, const Twine &Name = "", 766 Instruction *InsertBefore = nullptr, 767 Instruction *FlagsSource = nullptr); 768 769 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, 770 Value *LHS, Value *RHS, const Twine &Name, 771 BasicBlock *InsertAtEnd); 772 773 public: 774 // allocate space for exactly two operands 775 void *operator new(size_t S) { return User::operator new(S, 2); } 776 void operator delete(void *Ptr) { User::operator delete(Ptr); } 777 778 /// Construct a compare instruction, given the opcode, the predicate and 779 /// the two operands. Optionally (if InstBefore is specified) insert the 780 /// instruction into a BasicBlock right before the specified instruction. 781 /// The specified Instruction is allowed to be a dereferenced end iterator. 782 /// Create a CmpInst 783 static CmpInst *Create(OtherOps Op, 784 Predicate predicate, Value *S1, 785 Value *S2, const Twine &Name = "", 786 Instruction *InsertBefore = nullptr); 787 788 /// Construct a compare instruction, given the opcode, the predicate and the 789 /// two operands. Also automatically insert this instruction to the end of 790 /// the BasicBlock specified. 791 /// Create a CmpInst 792 static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1, 793 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd); 794 795 /// Get the opcode casted to the right type 796 OtherOps getOpcode() const { 797 return static_cast<OtherOps>(Instruction::getOpcode()); 798 } 799 800 /// Return the predicate for this instruction. 801 Predicate getPredicate() const { return getSubclassData<PredicateField>(); } 802 803 /// Set the predicate for this instruction to the specified value. 804 void setPredicate(Predicate P) { setSubclassData<PredicateField>(P); } 805 806 static bool isFPPredicate(Predicate P) { 807 static_assert(FIRST_FCMP_PREDICATE == 0, 808 "FIRST_FCMP_PREDICATE is required to be 0"); 809 return P <= LAST_FCMP_PREDICATE; 810 } 811 812 static bool isIntPredicate(Predicate P) { 813 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE; 814 } 815 816 static StringRef getPredicateName(Predicate P); 817 818 bool isFPPredicate() const { return isFPPredicate(getPredicate()); } 819 bool isIntPredicate() const { return isIntPredicate(getPredicate()); } 820 821 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE, 822 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc. 823 /// @returns the inverse predicate for the instruction's current predicate. 824 /// Return the inverse of the instruction's predicate. 825 Predicate getInversePredicate() const { 826 return getInversePredicate(getPredicate()); 827 } 828 829 /// Returns the ordered variant of a floating point compare. 830 /// 831 /// For example, UEQ -> OEQ, ULT -> OLT, OEQ -> OEQ 832 static Predicate getOrderedPredicate(Predicate Pred) { 833 return static_cast<Predicate>(Pred & FCMP_ORD); 834 } 835 836 Predicate getOrderedPredicate() const { 837 return getOrderedPredicate(getPredicate()); 838 } 839 840 /// Returns the unordered variant of a floating point compare. 841 /// 842 /// For example, OEQ -> UEQ, OLT -> ULT, OEQ -> UEQ 843 static Predicate getUnorderedPredicate(Predicate Pred) { 844 return static_cast<Predicate>(Pred | FCMP_UNO); 845 } 846 847 Predicate getUnorderedPredicate() const { 848 return getUnorderedPredicate(getPredicate()); 849 } 850 851 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE, 852 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc. 853 /// @returns the inverse predicate for predicate provided in \p pred. 854 /// Return the inverse of a given predicate 855 static Predicate getInversePredicate(Predicate pred); 856 857 /// For example, EQ->EQ, SLE->SGE, ULT->UGT, 858 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc. 859 /// @returns the predicate that would be the result of exchanging the two 860 /// operands of the CmpInst instruction without changing the result 861 /// produced. 862 /// Return the predicate as if the operands were swapped 863 Predicate getSwappedPredicate() const { 864 return getSwappedPredicate(getPredicate()); 865 } 866 867 /// This is a static version that you can use without an instruction 868 /// available. 869 /// Return the predicate as if the operands were swapped. 870 static Predicate getSwappedPredicate(Predicate pred); 871 872 /// This is a static version that you can use without an instruction 873 /// available. 874 /// @returns true if the comparison predicate is strict, false otherwise. 875 static bool isStrictPredicate(Predicate predicate); 876 877 /// @returns true if the comparison predicate is strict, false otherwise. 878 /// Determine if this instruction is using an strict comparison predicate. 879 bool isStrictPredicate() const { return isStrictPredicate(getPredicate()); } 880 881 /// This is a static version that you can use without an instruction 882 /// available. 883 /// @returns true if the comparison predicate is non-strict, false otherwise. 884 static bool isNonStrictPredicate(Predicate predicate); 885 886 /// @returns true if the comparison predicate is non-strict, false otherwise. 887 /// Determine if this instruction is using an non-strict comparison predicate. 888 bool isNonStrictPredicate() const { 889 return isNonStrictPredicate(getPredicate()); 890 } 891 892 /// For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT. 893 /// Returns the strict version of non-strict comparisons. 894 Predicate getStrictPredicate() const { 895 return getStrictPredicate(getPredicate()); 896 } 897 898 /// This is a static version that you can use without an instruction 899 /// available. 900 /// @returns the strict version of comparison provided in \p pred. 901 /// If \p pred is not a strict comparison predicate, returns \p pred. 902 /// Returns the strict version of non-strict comparisons. 903 static Predicate getStrictPredicate(Predicate pred); 904 905 /// For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE. 906 /// Returns the non-strict version of strict comparisons. 907 Predicate getNonStrictPredicate() const { 908 return getNonStrictPredicate(getPredicate()); 909 } 910 911 /// This is a static version that you can use without an instruction 912 /// available. 913 /// @returns the non-strict version of comparison provided in \p pred. 914 /// If \p pred is not a strict comparison predicate, returns \p pred. 915 /// Returns the non-strict version of strict comparisons. 916 static Predicate getNonStrictPredicate(Predicate pred); 917 918 /// This is a static version that you can use without an instruction 919 /// available. 920 /// Return the flipped strictness of predicate 921 static Predicate getFlippedStrictnessPredicate(Predicate pred); 922 923 /// For predicate of kind "is X or equal to 0" returns the predicate "is X". 924 /// For predicate of kind "is X" returns the predicate "is X or equal to 0". 925 /// does not support other kind of predicates. 926 /// @returns the predicate that does not contains is equal to zero if 927 /// it had and vice versa. 928 /// Return the flipped strictness of predicate 929 Predicate getFlippedStrictnessPredicate() const { 930 return getFlippedStrictnessPredicate(getPredicate()); 931 } 932 933 /// Provide more efficient getOperand methods. 934 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 935 936 /// This is just a convenience that dispatches to the subclasses. 937 /// Swap the operands and adjust predicate accordingly to retain 938 /// the same comparison. 939 void swapOperands(); 940 941 /// This is just a convenience that dispatches to the subclasses. 942 /// Determine if this CmpInst is commutative. 943 bool isCommutative() const; 944 945 /// Determine if this is an equals/not equals predicate. 946 /// This is a static version that you can use without an instruction 947 /// available. 948 static bool isEquality(Predicate pred); 949 950 /// Determine if this is an equals/not equals predicate. 951 bool isEquality() const { return isEquality(getPredicate()); } 952 953 /// Return true if the predicate is relational (not EQ or NE). 954 static bool isRelational(Predicate P) { return !isEquality(P); } 955 956 /// Return true if the predicate is relational (not EQ or NE). 957 bool isRelational() const { return !isEquality(); } 958 959 /// @returns true if the comparison is signed, false otherwise. 960 /// Determine if this instruction is using a signed comparison. 961 bool isSigned() const { 962 return isSigned(getPredicate()); 963 } 964 965 /// @returns true if the comparison is unsigned, false otherwise. 966 /// Determine if this instruction is using an unsigned comparison. 967 bool isUnsigned() const { 968 return isUnsigned(getPredicate()); 969 } 970 971 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert 972 /// @returns the signed version of the unsigned predicate pred. 973 /// return the signed version of a predicate 974 static Predicate getSignedPredicate(Predicate pred); 975 976 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert 977 /// @returns the signed version of the predicate for this instruction (which 978 /// has to be an unsigned predicate). 979 /// return the signed version of a predicate 980 Predicate getSignedPredicate() { 981 return getSignedPredicate(getPredicate()); 982 } 983 984 /// For example, SLT->ULT, SLE->ULE, SGT->UGT, SGE->UGE, ULT->Failed assert 985 /// @returns the unsigned version of the signed predicate pred. 986 static Predicate getUnsignedPredicate(Predicate pred); 987 988 /// For example, SLT->ULT, SLE->ULE, SGT->UGT, SGE->UGE, ULT->Failed assert 989 /// @returns the unsigned version of the predicate for this instruction (which 990 /// has to be an signed predicate). 991 /// return the unsigned version of a predicate 992 Predicate getUnsignedPredicate() { 993 return getUnsignedPredicate(getPredicate()); 994 } 995 996 /// For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->Failed assert 997 /// @returns the unsigned version of the signed predicate pred or 998 /// the signed version of the signed predicate pred. 999 static Predicate getFlippedSignednessPredicate(Predicate pred); 1000 1001 /// For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->Failed assert 1002 /// @returns the unsigned version of the signed predicate pred or 1003 /// the signed version of the signed predicate pred. 1004 Predicate getFlippedSignednessPredicate() { 1005 return getFlippedSignednessPredicate(getPredicate()); 1006 } 1007 1008 /// This is just a convenience. 1009 /// Determine if this is true when both operands are the same. 1010 bool isTrueWhenEqual() const { 1011 return isTrueWhenEqual(getPredicate()); 1012 } 1013 1014 /// This is just a convenience. 1015 /// Determine if this is false when both operands are the same. 1016 bool isFalseWhenEqual() const { 1017 return isFalseWhenEqual(getPredicate()); 1018 } 1019 1020 /// @returns true if the predicate is unsigned, false otherwise. 1021 /// Determine if the predicate is an unsigned operation. 1022 static bool isUnsigned(Predicate predicate); 1023 1024 /// @returns true if the predicate is signed, false otherwise. 1025 /// Determine if the predicate is an signed operation. 1026 static bool isSigned(Predicate predicate); 1027 1028 /// Determine if the predicate is an ordered operation. 1029 static bool isOrdered(Predicate predicate); 1030 1031 /// Determine if the predicate is an unordered operation. 1032 static bool isUnordered(Predicate predicate); 1033 1034 /// Determine if the predicate is true when comparing a value with itself. 1035 static bool isTrueWhenEqual(Predicate predicate); 1036 1037 /// Determine if the predicate is false when comparing a value with itself. 1038 static bool isFalseWhenEqual(Predicate predicate); 1039 1040 /// Determine if Pred1 implies Pred2 is true when two compares have matching 1041 /// operands. 1042 static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2); 1043 1044 /// Determine if Pred1 implies Pred2 is false when two compares have matching 1045 /// operands. 1046 static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2); 1047 1048 /// Methods for support type inquiry through isa, cast, and dyn_cast: 1049 static bool classof(const Instruction *I) { 1050 return I->getOpcode() == Instruction::ICmp || 1051 I->getOpcode() == Instruction::FCmp; 1052 } 1053 static bool classof(const Value *V) { 1054 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 1055 } 1056 1057 /// Create a result type for fcmp/icmp 1058 static Type* makeCmpResultType(Type* opnd_type) { 1059 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) { 1060 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()), 1061 vt->getElementCount()); 1062 } 1063 return Type::getInt1Ty(opnd_type->getContext()); 1064 } 1065 1066 private: 1067 // Shadow Value::setValueSubclassData with a private forwarding method so that 1068 // subclasses cannot accidentally use it. 1069 void setValueSubclassData(unsigned short D) { 1070 Value::setValueSubclassData(D); 1071 } 1072 }; 1073 1074 // FIXME: these are redundant if CmpInst < BinaryOperator 1075 template <> 1076 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> { 1077 }; 1078 1079 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value) 1080 1081 raw_ostream &operator<<(raw_ostream &OS, CmpInst::Predicate Pred); 1082 1083 /// A lightweight accessor for an operand bundle meant to be passed 1084 /// around by value. 1085 struct OperandBundleUse { 1086 ArrayRef<Use> Inputs; 1087 1088 OperandBundleUse() = default; 1089 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs) 1090 : Inputs(Inputs), Tag(Tag) {} 1091 1092 /// Return true if the operand at index \p Idx in this operand bundle 1093 /// has the attribute A. 1094 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const { 1095 if (isDeoptOperandBundle()) 1096 if (A == Attribute::ReadOnly || A == Attribute::NoCapture) 1097 return Inputs[Idx]->getType()->isPointerTy(); 1098 1099 // Conservative answer: no operands have any attributes. 1100 return false; 1101 } 1102 1103 /// Return the tag of this operand bundle as a string. 1104 StringRef getTagName() const { 1105 return Tag->getKey(); 1106 } 1107 1108 /// Return the tag of this operand bundle as an integer. 1109 /// 1110 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag, 1111 /// and this function returns the unique integer getOrInsertBundleTag 1112 /// associated the tag of this operand bundle to. 1113 uint32_t getTagID() const { 1114 return Tag->getValue(); 1115 } 1116 1117 /// Return true if this is a "deopt" operand bundle. 1118 bool isDeoptOperandBundle() const { 1119 return getTagID() == LLVMContext::OB_deopt; 1120 } 1121 1122 /// Return true if this is a "funclet" operand bundle. 1123 bool isFuncletOperandBundle() const { 1124 return getTagID() == LLVMContext::OB_funclet; 1125 } 1126 1127 /// Return true if this is a "cfguardtarget" operand bundle. 1128 bool isCFGuardTargetOperandBundle() const { 1129 return getTagID() == LLVMContext::OB_cfguardtarget; 1130 } 1131 1132 private: 1133 /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag. 1134 StringMapEntry<uint32_t> *Tag; 1135 }; 1136 1137 /// A container for an operand bundle being viewed as a set of values 1138 /// rather than a set of uses. 1139 /// 1140 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and 1141 /// so it is possible to create and pass around "self-contained" instances of 1142 /// OperandBundleDef and ConstOperandBundleDef. 1143 template <typename InputTy> class OperandBundleDefT { 1144 std::string Tag; 1145 std::vector<InputTy> Inputs; 1146 1147 public: 1148 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs) 1149 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {} 1150 explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs) 1151 : Tag(std::move(Tag)), Inputs(Inputs) {} 1152 1153 explicit OperandBundleDefT(const OperandBundleUse &OBU) { 1154 Tag = std::string(OBU.getTagName()); 1155 llvm::append_range(Inputs, OBU.Inputs); 1156 } 1157 1158 ArrayRef<InputTy> inputs() const { return Inputs; } 1159 1160 using input_iterator = typename std::vector<InputTy>::const_iterator; 1161 1162 size_t input_size() const { return Inputs.size(); } 1163 input_iterator input_begin() const { return Inputs.begin(); } 1164 input_iterator input_end() const { return Inputs.end(); } 1165 1166 StringRef getTag() const { return Tag; } 1167 }; 1168 1169 using OperandBundleDef = OperandBundleDefT<Value *>; 1170 using ConstOperandBundleDef = OperandBundleDefT<const Value *>; 1171 1172 //===----------------------------------------------------------------------===// 1173 // CallBase Class 1174 //===----------------------------------------------------------------------===// 1175 1176 /// Base class for all callable instructions (InvokeInst and CallInst) 1177 /// Holds everything related to calling a function. 1178 /// 1179 /// All call-like instructions are required to use a common operand layout: 1180 /// - Zero or more arguments to the call, 1181 /// - Zero or more operand bundles with zero or more operand inputs each 1182 /// bundle, 1183 /// - Zero or more subclass controlled operands 1184 /// - The called function. 1185 /// 1186 /// This allows this base class to easily access the called function and the 1187 /// start of the arguments without knowing how many other operands a particular 1188 /// subclass requires. Note that accessing the end of the argument list isn't 1189 /// as cheap as most other operations on the base class. 1190 class CallBase : public Instruction { 1191 protected: 1192 // The first two bits are reserved by CallInst for fast retrieval, 1193 using CallInstReservedField = Bitfield::Element<unsigned, 0, 2>; 1194 using CallingConvField = 1195 Bitfield::Element<CallingConv::ID, CallInstReservedField::NextBit, 10, 1196 CallingConv::MaxID>; 1197 static_assert( 1198 Bitfield::areContiguous<CallInstReservedField, CallingConvField>(), 1199 "Bitfields must be contiguous"); 1200 1201 /// The last operand is the called operand. 1202 static constexpr int CalledOperandOpEndIdx = -1; 1203 1204 AttributeList Attrs; ///< parameter attributes for callable 1205 FunctionType *FTy; 1206 1207 template <class... ArgsTy> 1208 CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args) 1209 : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {} 1210 1211 using Instruction::Instruction; 1212 1213 bool hasDescriptor() const { return Value::HasDescriptor; } 1214 1215 unsigned getNumSubclassExtraOperands() const { 1216 switch (getOpcode()) { 1217 case Instruction::Call: 1218 return 0; 1219 case Instruction::Invoke: 1220 return 2; 1221 case Instruction::CallBr: 1222 return getNumSubclassExtraOperandsDynamic(); 1223 } 1224 llvm_unreachable("Invalid opcode!"); 1225 } 1226 1227 /// Get the number of extra operands for instructions that don't have a fixed 1228 /// number of extra operands. 1229 unsigned getNumSubclassExtraOperandsDynamic() const; 1230 1231 public: 1232 using Instruction::getContext; 1233 1234 /// Create a clone of \p CB with a different set of operand bundles and 1235 /// insert it before \p InsertPt. 1236 /// 1237 /// The returned call instruction is identical \p CB in every way except that 1238 /// the operand bundles for the new instruction are set to the operand bundles 1239 /// in \p Bundles. 1240 static CallBase *Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles, 1241 Instruction *InsertPt = nullptr); 1242 1243 /// Create a clone of \p CB with the operand bundle with the tag matching 1244 /// \p Bundle's tag replaced with Bundle, and insert it before \p InsertPt. 1245 /// 1246 /// The returned call instruction is identical \p CI in every way except that 1247 /// the specified operand bundle has been replaced. 1248 static CallBase *Create(CallBase *CB, 1249 OperandBundleDef Bundle, 1250 Instruction *InsertPt = nullptr); 1251 1252 /// Create a clone of \p CB with operand bundle \p OB added. 1253 static CallBase *addOperandBundle(CallBase *CB, uint32_t ID, 1254 OperandBundleDef OB, 1255 Instruction *InsertPt = nullptr); 1256 1257 /// Create a clone of \p CB with operand bundle \p ID removed. 1258 static CallBase *removeOperandBundle(CallBase *CB, uint32_t ID, 1259 Instruction *InsertPt = nullptr); 1260 1261 static bool classof(const Instruction *I) { 1262 return I->getOpcode() == Instruction::Call || 1263 I->getOpcode() == Instruction::Invoke || 1264 I->getOpcode() == Instruction::CallBr; 1265 } 1266 static bool classof(const Value *V) { 1267 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 1268 } 1269 1270 FunctionType *getFunctionType() const { return FTy; } 1271 1272 void mutateFunctionType(FunctionType *FTy) { 1273 Value::mutateType(FTy->getReturnType()); 1274 this->FTy = FTy; 1275 } 1276 1277 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 1278 1279 /// data_operands_begin/data_operands_end - Return iterators iterating over 1280 /// the call / invoke argument list and bundle operands. For invokes, this is 1281 /// the set of instruction operands except the invoke target and the two 1282 /// successor blocks; and for calls this is the set of instruction operands 1283 /// except the call target. 1284 User::op_iterator data_operands_begin() { return op_begin(); } 1285 User::const_op_iterator data_operands_begin() const { 1286 return const_cast<CallBase *>(this)->data_operands_begin(); 1287 } 1288 User::op_iterator data_operands_end() { 1289 // Walk from the end of the operands over the called operand and any 1290 // subclass operands. 1291 return op_end() - getNumSubclassExtraOperands() - 1; 1292 } 1293 User::const_op_iterator data_operands_end() const { 1294 return const_cast<CallBase *>(this)->data_operands_end(); 1295 } 1296 iterator_range<User::op_iterator> data_ops() { 1297 return make_range(data_operands_begin(), data_operands_end()); 1298 } 1299 iterator_range<User::const_op_iterator> data_ops() const { 1300 return make_range(data_operands_begin(), data_operands_end()); 1301 } 1302 bool data_operands_empty() const { 1303 return data_operands_end() == data_operands_begin(); 1304 } 1305 unsigned data_operands_size() const { 1306 return std::distance(data_operands_begin(), data_operands_end()); 1307 } 1308 1309 bool isDataOperand(const Use *U) const { 1310 assert(this == U->getUser() && 1311 "Only valid to query with a use of this instruction!"); 1312 return data_operands_begin() <= U && U < data_operands_end(); 1313 } 1314 bool isDataOperand(Value::const_user_iterator UI) const { 1315 return isDataOperand(&UI.getUse()); 1316 } 1317 1318 /// Given a value use iterator, return the data operand corresponding to it. 1319 /// Iterator must actually correspond to a data operand. 1320 unsigned getDataOperandNo(Value::const_user_iterator UI) const { 1321 return getDataOperandNo(&UI.getUse()); 1322 } 1323 1324 /// Given a use for a data operand, get the data operand number that 1325 /// corresponds to it. 1326 unsigned getDataOperandNo(const Use *U) const { 1327 assert(isDataOperand(U) && "Data operand # out of range!"); 1328 return U - data_operands_begin(); 1329 } 1330 1331 /// Return the iterator pointing to the beginning of the argument list. 1332 User::op_iterator arg_begin() { return op_begin(); } 1333 User::const_op_iterator arg_begin() const { 1334 return const_cast<CallBase *>(this)->arg_begin(); 1335 } 1336 1337 /// Return the iterator pointing to the end of the argument list. 1338 User::op_iterator arg_end() { 1339 // From the end of the data operands, walk backwards past the bundle 1340 // operands. 1341 return data_operands_end() - getNumTotalBundleOperands(); 1342 } 1343 User::const_op_iterator arg_end() const { 1344 return const_cast<CallBase *>(this)->arg_end(); 1345 } 1346 1347 /// Iteration adapter for range-for loops. 1348 iterator_range<User::op_iterator> args() { 1349 return make_range(arg_begin(), arg_end()); 1350 } 1351 iterator_range<User::const_op_iterator> args() const { 1352 return make_range(arg_begin(), arg_end()); 1353 } 1354 bool arg_empty() const { return arg_end() == arg_begin(); } 1355 unsigned arg_size() const { return arg_end() - arg_begin(); } 1356 1357 Value *getArgOperand(unsigned i) const { 1358 assert(i < arg_size() && "Out of bounds!"); 1359 return getOperand(i); 1360 } 1361 1362 void setArgOperand(unsigned i, Value *v) { 1363 assert(i < arg_size() && "Out of bounds!"); 1364 setOperand(i, v); 1365 } 1366 1367 /// Wrappers for getting the \c Use of a call argument. 1368 const Use &getArgOperandUse(unsigned i) const { 1369 assert(i < arg_size() && "Out of bounds!"); 1370 return User::getOperandUse(i); 1371 } 1372 Use &getArgOperandUse(unsigned i) { 1373 assert(i < arg_size() && "Out of bounds!"); 1374 return User::getOperandUse(i); 1375 } 1376 1377 bool isArgOperand(const Use *U) const { 1378 assert(this == U->getUser() && 1379 "Only valid to query with a use of this instruction!"); 1380 return arg_begin() <= U && U < arg_end(); 1381 } 1382 bool isArgOperand(Value::const_user_iterator UI) const { 1383 return isArgOperand(&UI.getUse()); 1384 } 1385 1386 /// Given a use for a arg operand, get the arg operand number that 1387 /// corresponds to it. 1388 unsigned getArgOperandNo(const Use *U) const { 1389 assert(isArgOperand(U) && "Arg operand # out of range!"); 1390 return U - arg_begin(); 1391 } 1392 1393 /// Given a value use iterator, return the arg operand number corresponding to 1394 /// it. Iterator must actually correspond to a data operand. 1395 unsigned getArgOperandNo(Value::const_user_iterator UI) const { 1396 return getArgOperandNo(&UI.getUse()); 1397 } 1398 1399 /// Returns true if this CallSite passes the given Value* as an argument to 1400 /// the called function. 1401 bool hasArgument(const Value *V) const { 1402 return llvm::is_contained(args(), V); 1403 } 1404 1405 Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); } 1406 1407 const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); } 1408 Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); } 1409 1410 /// Returns the function called, or null if this is an indirect function 1411 /// invocation or the function signature does not match the call signature. 1412 Function *getCalledFunction() const { 1413 if (auto *F = dyn_cast_or_null<Function>(getCalledOperand())) 1414 if (F->getValueType() == getFunctionType()) 1415 return F; 1416 return nullptr; 1417 } 1418 1419 /// Return true if the callsite is an indirect call. 1420 bool isIndirectCall() const; 1421 1422 /// Determine whether the passed iterator points to the callee operand's Use. 1423 bool isCallee(Value::const_user_iterator UI) const { 1424 return isCallee(&UI.getUse()); 1425 } 1426 1427 /// Determine whether this Use is the callee operand's Use. 1428 bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; } 1429 1430 /// Helper to get the caller (the parent function). 1431 Function *getCaller(); 1432 const Function *getCaller() const { 1433 return const_cast<CallBase *>(this)->getCaller(); 1434 } 1435 1436 /// Tests if this call site must be tail call optimized. Only a CallInst can 1437 /// be tail call optimized. 1438 bool isMustTailCall() const; 1439 1440 /// Tests if this call site is marked as a tail call. 1441 bool isTailCall() const; 1442 1443 /// Returns the intrinsic ID of the intrinsic called or 1444 /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if 1445 /// this is an indirect call. 1446 Intrinsic::ID getIntrinsicID() const; 1447 1448 void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; } 1449 1450 /// Sets the function called, including updating the function type. 1451 void setCalledFunction(Function *Fn) { 1452 setCalledFunction(Fn->getFunctionType(), Fn); 1453 } 1454 1455 /// Sets the function called, including updating the function type. 1456 void setCalledFunction(FunctionCallee Fn) { 1457 setCalledFunction(Fn.getFunctionType(), Fn.getCallee()); 1458 } 1459 1460 /// Sets the function called, including updating to the specified function 1461 /// type. 1462 void setCalledFunction(FunctionType *FTy, Value *Fn) { 1463 this->FTy = FTy; 1464 // This function doesn't mutate the return type, only the function 1465 // type. Seems broken, but I'm just gonna stick an assert in for now. 1466 assert(getType() == FTy->getReturnType()); 1467 setCalledOperand(Fn); 1468 } 1469 1470 CallingConv::ID getCallingConv() const { 1471 return getSubclassData<CallingConvField>(); 1472 } 1473 1474 void setCallingConv(CallingConv::ID CC) { 1475 setSubclassData<CallingConvField>(CC); 1476 } 1477 1478 /// Check if this call is an inline asm statement. 1479 bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); } 1480 1481 /// \name Attribute API 1482 /// 1483 /// These methods access and modify attributes on this call (including 1484 /// looking through to the attributes on the called function when necessary). 1485 ///@{ 1486 1487 /// Return the parameter attributes for this call. 1488 /// 1489 AttributeList getAttributes() const { return Attrs; } 1490 1491 /// Set the parameter attributes for this call. 1492 /// 1493 void setAttributes(AttributeList A) { Attrs = A; } 1494 1495 /// Determine whether this call has the given attribute. If it does not 1496 /// then determine if the called function has the attribute, but only if 1497 /// the attribute is allowed for the call. 1498 bool hasFnAttr(Attribute::AttrKind Kind) const { 1499 assert(Kind != Attribute::NoBuiltin && 1500 "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin"); 1501 return hasFnAttrImpl(Kind); 1502 } 1503 1504 /// Determine whether this call has the given attribute. If it does not 1505 /// then determine if the called function has the attribute, but only if 1506 /// the attribute is allowed for the call. 1507 bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); } 1508 1509 // TODO: remove non-AtIndex versions of these methods. 1510 /// adds the attribute to the list of attributes. 1511 void addAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) { 1512 Attrs = Attrs.addAttributeAtIndex(getContext(), i, Kind); 1513 } 1514 1515 /// adds the attribute to the list of attributes. 1516 void addAttributeAtIndex(unsigned i, Attribute Attr) { 1517 Attrs = Attrs.addAttributeAtIndex(getContext(), i, Attr); 1518 } 1519 1520 /// Adds the attribute to the function. 1521 void addFnAttr(Attribute::AttrKind Kind) { 1522 Attrs = Attrs.addFnAttribute(getContext(), Kind); 1523 } 1524 1525 /// Adds the attribute to the function. 1526 void addFnAttr(Attribute Attr) { 1527 Attrs = Attrs.addFnAttribute(getContext(), Attr); 1528 } 1529 1530 /// Adds the attribute to the return value. 1531 void addRetAttr(Attribute::AttrKind Kind) { 1532 Attrs = Attrs.addRetAttribute(getContext(), Kind); 1533 } 1534 1535 /// Adds the attribute to the return value. 1536 void addRetAttr(Attribute Attr) { 1537 Attrs = Attrs.addRetAttribute(getContext(), Attr); 1538 } 1539 1540 /// Adds the attribute to the indicated argument 1541 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 1542 assert(ArgNo < arg_size() && "Out of bounds"); 1543 Attrs = Attrs.addParamAttribute(getContext(), ArgNo, Kind); 1544 } 1545 1546 /// Adds the attribute to the indicated argument 1547 void addParamAttr(unsigned ArgNo, Attribute Attr) { 1548 assert(ArgNo < arg_size() && "Out of bounds"); 1549 Attrs = Attrs.addParamAttribute(getContext(), ArgNo, Attr); 1550 } 1551 1552 /// removes the attribute from the list of attributes. 1553 void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) { 1554 Attrs = Attrs.removeAttributeAtIndex(getContext(), i, Kind); 1555 } 1556 1557 /// removes the attribute from the list of attributes. 1558 void removeAttributeAtIndex(unsigned i, StringRef Kind) { 1559 Attrs = Attrs.removeAttributeAtIndex(getContext(), i, Kind); 1560 } 1561 1562 /// Removes the attributes from the function 1563 void removeFnAttrs(const AttributeMask &AttrsToRemove) { 1564 Attrs = Attrs.removeFnAttributes(getContext(), AttrsToRemove); 1565 } 1566 1567 /// Removes the attribute from the function 1568 void removeFnAttr(Attribute::AttrKind Kind) { 1569 Attrs = Attrs.removeFnAttribute(getContext(), Kind); 1570 } 1571 1572 /// Removes the attribute from the function 1573 void removeFnAttr(StringRef Kind) { 1574 Attrs = Attrs.removeFnAttribute(getContext(), Kind); 1575 } 1576 1577 /// Removes the attribute from the return value 1578 void removeRetAttr(Attribute::AttrKind Kind) { 1579 Attrs = Attrs.removeRetAttribute(getContext(), Kind); 1580 } 1581 1582 /// Removes the attributes from the return value 1583 void removeRetAttrs(const AttributeMask &AttrsToRemove) { 1584 Attrs = Attrs.removeRetAttributes(getContext(), AttrsToRemove); 1585 } 1586 1587 /// Removes the attribute from the given argument 1588 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 1589 assert(ArgNo < arg_size() && "Out of bounds"); 1590 Attrs = Attrs.removeParamAttribute(getContext(), ArgNo, Kind); 1591 } 1592 1593 /// Removes the attribute from the given argument 1594 void removeParamAttr(unsigned ArgNo, StringRef Kind) { 1595 assert(ArgNo < arg_size() && "Out of bounds"); 1596 Attrs = Attrs.removeParamAttribute(getContext(), ArgNo, Kind); 1597 } 1598 1599 /// Removes the attributes from the given argument 1600 void removeParamAttrs(unsigned ArgNo, const AttributeMask &AttrsToRemove) { 1601 Attrs = Attrs.removeParamAttributes(getContext(), ArgNo, AttrsToRemove); 1602 } 1603 1604 /// adds the dereferenceable attribute to the list of attributes. 1605 void addDereferenceableParamAttr(unsigned i, uint64_t Bytes) { 1606 Attrs = Attrs.addDereferenceableParamAttr(getContext(), i, Bytes); 1607 } 1608 1609 /// adds the dereferenceable attribute to the list of attributes. 1610 void addDereferenceableRetAttr(uint64_t Bytes) { 1611 Attrs = Attrs.addDereferenceableRetAttr(getContext(), Bytes); 1612 } 1613 1614 /// Determine whether the return value has the given attribute. 1615 bool hasRetAttr(Attribute::AttrKind Kind) const { 1616 return hasRetAttrImpl(Kind); 1617 } 1618 /// Determine whether the return value has the given attribute. 1619 bool hasRetAttr(StringRef Kind) const { return hasRetAttrImpl(Kind); } 1620 1621 /// Determine whether the argument or parameter has the given attribute. 1622 bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const; 1623 1624 /// Get the attribute of a given kind at a position. 1625 Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const { 1626 return getAttributes().getAttributeAtIndex(i, Kind); 1627 } 1628 1629 /// Get the attribute of a given kind at a position. 1630 Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const { 1631 return getAttributes().getAttributeAtIndex(i, Kind); 1632 } 1633 1634 /// Get the attribute of a given kind for the function. 1635 Attribute getFnAttr(StringRef Kind) const { 1636 Attribute Attr = getAttributes().getFnAttr(Kind); 1637 if (Attr.isValid()) 1638 return Attr; 1639 return getFnAttrOnCalledFunction(Kind); 1640 } 1641 1642 /// Get the attribute of a given kind for the function. 1643 Attribute getFnAttr(Attribute::AttrKind Kind) const { 1644 Attribute A = getAttributes().getFnAttr(Kind); 1645 if (A.isValid()) 1646 return A; 1647 return getFnAttrOnCalledFunction(Kind); 1648 } 1649 1650 /// Get the attribute of a given kind from a given arg 1651 Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const { 1652 assert(ArgNo < arg_size() && "Out of bounds"); 1653 return getAttributes().getParamAttr(ArgNo, Kind); 1654 } 1655 1656 /// Get the attribute of a given kind from a given arg 1657 Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const { 1658 assert(ArgNo < arg_size() && "Out of bounds"); 1659 return getAttributes().getParamAttr(ArgNo, Kind); 1660 } 1661 1662 /// Return true if the data operand at index \p i has the attribute \p 1663 /// A. 1664 /// 1665 /// Data operands include call arguments and values used in operand bundles, 1666 /// but does not include the callee operand. 1667 /// 1668 /// The index \p i is interpreted as 1669 /// 1670 /// \p i in [0, arg_size) -> argument number (\p i) 1671 /// \p i in [arg_size, data_operand_size) -> bundle operand at index 1672 /// (\p i) in the operand list. 1673 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const { 1674 // Note that we have to add one because `i` isn't zero-indexed. 1675 assert(i < arg_size() + getNumTotalBundleOperands() && 1676 "Data operand index out of bounds!"); 1677 1678 // The attribute A can either be directly specified, if the operand in 1679 // question is a call argument; or be indirectly implied by the kind of its 1680 // containing operand bundle, if the operand is a bundle operand. 1681 1682 if (i < arg_size()) 1683 return paramHasAttr(i, Kind); 1684 1685 assert(hasOperandBundles() && i >= getBundleOperandsStartIndex() && 1686 "Must be either a call argument or an operand bundle!"); 1687 return bundleOperandHasAttr(i, Kind); 1688 } 1689 1690 /// Determine whether this data operand is not captured. 1691 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to 1692 // better indicate that this may return a conservative answer. 1693 bool doesNotCapture(unsigned OpNo) const { 1694 return dataOperandHasImpliedAttr(OpNo, Attribute::NoCapture); 1695 } 1696 1697 /// Determine whether this argument is passed by value. 1698 bool isByValArgument(unsigned ArgNo) const { 1699 return paramHasAttr(ArgNo, Attribute::ByVal); 1700 } 1701 1702 /// Determine whether this argument is passed in an alloca. 1703 bool isInAllocaArgument(unsigned ArgNo) const { 1704 return paramHasAttr(ArgNo, Attribute::InAlloca); 1705 } 1706 1707 /// Determine whether this argument is passed by value, in an alloca, or is 1708 /// preallocated. 1709 bool isPassPointeeByValueArgument(unsigned ArgNo) const { 1710 return paramHasAttr(ArgNo, Attribute::ByVal) || 1711 paramHasAttr(ArgNo, Attribute::InAlloca) || 1712 paramHasAttr(ArgNo, Attribute::Preallocated); 1713 } 1714 1715 /// Determine whether passing undef to this argument is undefined behavior. 1716 /// If passing undef to this argument is UB, passing poison is UB as well 1717 /// because poison is more undefined than undef. 1718 bool isPassingUndefUB(unsigned ArgNo) const { 1719 return paramHasAttr(ArgNo, Attribute::NoUndef) || 1720 // dereferenceable implies noundef. 1721 paramHasAttr(ArgNo, Attribute::Dereferenceable) || 1722 // dereferenceable implies noundef, and null is a well-defined value. 1723 paramHasAttr(ArgNo, Attribute::DereferenceableOrNull); 1724 } 1725 1726 /// Determine if there are is an inalloca argument. Only the last argument can 1727 /// have the inalloca attribute. 1728 bool hasInAllocaArgument() const { 1729 return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca); 1730 } 1731 1732 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to 1733 // better indicate that this may return a conservative answer. 1734 bool doesNotAccessMemory(unsigned OpNo) const { 1735 return dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone); 1736 } 1737 1738 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to 1739 // better indicate that this may return a conservative answer. 1740 bool onlyReadsMemory(unsigned OpNo) const { 1741 return dataOperandHasImpliedAttr(OpNo, Attribute::ReadOnly) || 1742 dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone); 1743 } 1744 1745 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to 1746 // better indicate that this may return a conservative answer. 1747 bool onlyWritesMemory(unsigned OpNo) const { 1748 return dataOperandHasImpliedAttr(OpNo, Attribute::WriteOnly) || 1749 dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone); 1750 } 1751 1752 /// Extract the alignment of the return value. 1753 MaybeAlign getRetAlign() const { 1754 if (auto Align = Attrs.getRetAlignment()) 1755 return Align; 1756 if (const Function *F = getCalledFunction()) 1757 return F->getAttributes().getRetAlignment(); 1758 return std::nullopt; 1759 } 1760 1761 /// Extract the alignment for a call or parameter (0=unknown). 1762 MaybeAlign getParamAlign(unsigned ArgNo) const { 1763 return Attrs.getParamAlignment(ArgNo); 1764 } 1765 1766 MaybeAlign getParamStackAlign(unsigned ArgNo) const { 1767 return Attrs.getParamStackAlignment(ArgNo); 1768 } 1769 1770 /// Extract the byval type for a call or parameter. 1771 Type *getParamByValType(unsigned ArgNo) const { 1772 if (auto *Ty = Attrs.getParamByValType(ArgNo)) 1773 return Ty; 1774 if (const Function *F = getCalledFunction()) 1775 return F->getAttributes().getParamByValType(ArgNo); 1776 return nullptr; 1777 } 1778 1779 /// Extract the preallocated type for a call or parameter. 1780 Type *getParamPreallocatedType(unsigned ArgNo) const { 1781 if (auto *Ty = Attrs.getParamPreallocatedType(ArgNo)) 1782 return Ty; 1783 if (const Function *F = getCalledFunction()) 1784 return F->getAttributes().getParamPreallocatedType(ArgNo); 1785 return nullptr; 1786 } 1787 1788 /// Extract the inalloca type for a call or parameter. 1789 Type *getParamInAllocaType(unsigned ArgNo) const { 1790 if (auto *Ty = Attrs.getParamInAllocaType(ArgNo)) 1791 return Ty; 1792 if (const Function *F = getCalledFunction()) 1793 return F->getAttributes().getParamInAllocaType(ArgNo); 1794 return nullptr; 1795 } 1796 1797 /// Extract the sret type for a call or parameter. 1798 Type *getParamStructRetType(unsigned ArgNo) const { 1799 if (auto *Ty = Attrs.getParamStructRetType(ArgNo)) 1800 return Ty; 1801 if (const Function *F = getCalledFunction()) 1802 return F->getAttributes().getParamStructRetType(ArgNo); 1803 return nullptr; 1804 } 1805 1806 /// Extract the elementtype type for a parameter. 1807 /// Note that elementtype() can only be applied to call arguments, not 1808 /// function declaration parameters. 1809 Type *getParamElementType(unsigned ArgNo) const { 1810 return Attrs.getParamElementType(ArgNo); 1811 } 1812 1813 /// Extract the number of dereferenceable bytes for a call or 1814 /// parameter (0=unknown). 1815 uint64_t getRetDereferenceableBytes() const { 1816 uint64_t Bytes = Attrs.getRetDereferenceableBytes(); 1817 if (const Function *F = getCalledFunction()) 1818 Bytes = std::max(Bytes, F->getAttributes().getRetDereferenceableBytes()); 1819 return Bytes; 1820 } 1821 1822 /// Extract the number of dereferenceable bytes for a call or 1823 /// parameter (0=unknown). 1824 uint64_t getParamDereferenceableBytes(unsigned i) const { 1825 return Attrs.getParamDereferenceableBytes(i); 1826 } 1827 1828 /// Extract the number of dereferenceable_or_null bytes for a call 1829 /// (0=unknown). 1830 uint64_t getRetDereferenceableOrNullBytes() const { 1831 uint64_t Bytes = Attrs.getRetDereferenceableOrNullBytes(); 1832 if (const Function *F = getCalledFunction()) { 1833 Bytes = std::max(Bytes, 1834 F->getAttributes().getRetDereferenceableOrNullBytes()); 1835 } 1836 1837 return Bytes; 1838 } 1839 1840 /// Extract the number of dereferenceable_or_null bytes for a 1841 /// parameter (0=unknown). 1842 uint64_t getParamDereferenceableOrNullBytes(unsigned i) const { 1843 return Attrs.getParamDereferenceableOrNullBytes(i); 1844 } 1845 1846 /// Extract a test mask for disallowed floating-point value classes for the 1847 /// return value. 1848 FPClassTest getRetNoFPClass() const; 1849 1850 /// Extract a test mask for disallowed floating-point value classes for the 1851 /// parameter. 1852 FPClassTest getParamNoFPClass(unsigned i) const; 1853 1854 /// Return true if the return value is known to be not null. 1855 /// This may be because it has the nonnull attribute, or because at least 1856 /// one byte is dereferenceable and the pointer is in addrspace(0). 1857 bool isReturnNonNull() const; 1858 1859 /// Determine if the return value is marked with NoAlias attribute. 1860 bool returnDoesNotAlias() const { 1861 return Attrs.hasRetAttr(Attribute::NoAlias); 1862 } 1863 1864 /// If one of the arguments has the 'returned' attribute, returns its 1865 /// operand value. Otherwise, return nullptr. 1866 Value *getReturnedArgOperand() const { 1867 return getArgOperandWithAttribute(Attribute::Returned); 1868 } 1869 1870 /// If one of the arguments has the specified attribute, returns its 1871 /// operand value. Otherwise, return nullptr. 1872 Value *getArgOperandWithAttribute(Attribute::AttrKind Kind) const; 1873 1874 /// Return true if the call should not be treated as a call to a 1875 /// builtin. 1876 bool isNoBuiltin() const { 1877 return hasFnAttrImpl(Attribute::NoBuiltin) && 1878 !hasFnAttrImpl(Attribute::Builtin); 1879 } 1880 1881 /// Determine if the call requires strict floating point semantics. 1882 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); } 1883 1884 /// Return true if the call should not be inlined. 1885 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); } 1886 void setIsNoInline() { addFnAttr(Attribute::NoInline); } 1887 1888 MemoryEffects getMemoryEffects() const; 1889 void setMemoryEffects(MemoryEffects ME); 1890 1891 /// Determine if the call does not access memory. 1892 bool doesNotAccessMemory() const; 1893 void setDoesNotAccessMemory(); 1894 1895 /// Determine if the call does not access or only reads memory. 1896 bool onlyReadsMemory() const; 1897 void setOnlyReadsMemory(); 1898 1899 /// Determine if the call does not access or only writes memory. 1900 bool onlyWritesMemory() const; 1901 void setOnlyWritesMemory(); 1902 1903 /// Determine if the call can access memmory only using pointers based 1904 /// on its arguments. 1905 bool onlyAccessesArgMemory() const; 1906 void setOnlyAccessesArgMemory(); 1907 1908 /// Determine if the function may only access memory that is 1909 /// inaccessible from the IR. 1910 bool onlyAccessesInaccessibleMemory() const; 1911 void setOnlyAccessesInaccessibleMemory(); 1912 1913 /// Determine if the function may only access memory that is 1914 /// either inaccessible from the IR or pointed to by its arguments. 1915 bool onlyAccessesInaccessibleMemOrArgMem() const; 1916 void setOnlyAccessesInaccessibleMemOrArgMem(); 1917 1918 /// Determine if the call cannot return. 1919 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); } 1920 void setDoesNotReturn() { addFnAttr(Attribute::NoReturn); } 1921 1922 /// Determine if the call should not perform indirect branch tracking. 1923 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); } 1924 1925 /// Determine if the call cannot unwind. 1926 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); } 1927 void setDoesNotThrow() { addFnAttr(Attribute::NoUnwind); } 1928 1929 /// Determine if the invoke cannot be duplicated. 1930 bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); } 1931 void setCannotDuplicate() { addFnAttr(Attribute::NoDuplicate); } 1932 1933 /// Determine if the call cannot be tail merged. 1934 bool cannotMerge() const { return hasFnAttr(Attribute::NoMerge); } 1935 void setCannotMerge() { addFnAttr(Attribute::NoMerge); } 1936 1937 /// Determine if the invoke is convergent 1938 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); } 1939 void setConvergent() { addFnAttr(Attribute::Convergent); } 1940 void setNotConvergent() { removeFnAttr(Attribute::Convergent); } 1941 1942 /// Determine if the call returns a structure through first 1943 /// pointer argument. 1944 bool hasStructRetAttr() const { 1945 if (arg_empty()) 1946 return false; 1947 1948 // Be friendly and also check the callee. 1949 return paramHasAttr(0, Attribute::StructRet); 1950 } 1951 1952 /// Determine if any call argument is an aggregate passed by value. 1953 bool hasByValArgument() const { 1954 return Attrs.hasAttrSomewhere(Attribute::ByVal); 1955 } 1956 1957 ///@} 1958 // End of attribute API. 1959 1960 /// \name Operand Bundle API 1961 /// 1962 /// This group of methods provides the API to access and manipulate operand 1963 /// bundles on this call. 1964 /// @{ 1965 1966 /// Return the number of operand bundles associated with this User. 1967 unsigned getNumOperandBundles() const { 1968 return std::distance(bundle_op_info_begin(), bundle_op_info_end()); 1969 } 1970 1971 /// Return true if this User has any operand bundles. 1972 bool hasOperandBundles() const { return getNumOperandBundles() != 0; } 1973 1974 /// Return the index of the first bundle operand in the Use array. 1975 unsigned getBundleOperandsStartIndex() const { 1976 assert(hasOperandBundles() && "Don't call otherwise!"); 1977 return bundle_op_info_begin()->Begin; 1978 } 1979 1980 /// Return the index of the last bundle operand in the Use array. 1981 unsigned getBundleOperandsEndIndex() const { 1982 assert(hasOperandBundles() && "Don't call otherwise!"); 1983 return bundle_op_info_end()[-1].End; 1984 } 1985 1986 /// Return true if the operand at index \p Idx is a bundle operand. 1987 bool isBundleOperand(unsigned Idx) const { 1988 return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() && 1989 Idx < getBundleOperandsEndIndex(); 1990 } 1991 1992 /// Return true if the operand at index \p Idx is a bundle operand that has 1993 /// tag ID \p ID. 1994 bool isOperandBundleOfType(uint32_t ID, unsigned Idx) const { 1995 return isBundleOperand(Idx) && 1996 getOperandBundleForOperand(Idx).getTagID() == ID; 1997 } 1998 1999 /// Returns true if the use is a bundle operand. 2000 bool isBundleOperand(const Use *U) const { 2001 assert(this == U->getUser() && 2002 "Only valid to query with a use of this instruction!"); 2003 return hasOperandBundles() && isBundleOperand(U - op_begin()); 2004 } 2005 bool isBundleOperand(Value::const_user_iterator UI) const { 2006 return isBundleOperand(&UI.getUse()); 2007 } 2008 2009 /// Return the total number operands (not operand bundles) used by 2010 /// every operand bundle in this OperandBundleUser. 2011 unsigned getNumTotalBundleOperands() const { 2012 if (!hasOperandBundles()) 2013 return 0; 2014 2015 unsigned Begin = getBundleOperandsStartIndex(); 2016 unsigned End = getBundleOperandsEndIndex(); 2017 2018 assert(Begin <= End && "Should be!"); 2019 return End - Begin; 2020 } 2021 2022 /// Return the operand bundle at a specific index. 2023 OperandBundleUse getOperandBundleAt(unsigned Index) const { 2024 assert(Index < getNumOperandBundles() && "Index out of bounds!"); 2025 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index)); 2026 } 2027 2028 /// Return the number of operand bundles with the tag Name attached to 2029 /// this instruction. 2030 unsigned countOperandBundlesOfType(StringRef Name) const { 2031 unsigned Count = 0; 2032 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 2033 if (getOperandBundleAt(i).getTagName() == Name) 2034 Count++; 2035 2036 return Count; 2037 } 2038 2039 /// Return the number of operand bundles with the tag ID attached to 2040 /// this instruction. 2041 unsigned countOperandBundlesOfType(uint32_t ID) const { 2042 unsigned Count = 0; 2043 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 2044 if (getOperandBundleAt(i).getTagID() == ID) 2045 Count++; 2046 2047 return Count; 2048 } 2049 2050 /// Return an operand bundle by name, if present. 2051 /// 2052 /// It is an error to call this for operand bundle types that may have 2053 /// multiple instances of them on the same instruction. 2054 std::optional<OperandBundleUse> getOperandBundle(StringRef Name) const { 2055 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!"); 2056 2057 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 2058 OperandBundleUse U = getOperandBundleAt(i); 2059 if (U.getTagName() == Name) 2060 return U; 2061 } 2062 2063 return std::nullopt; 2064 } 2065 2066 /// Return an operand bundle by tag ID, if present. 2067 /// 2068 /// It is an error to call this for operand bundle types that may have 2069 /// multiple instances of them on the same instruction. 2070 std::optional<OperandBundleUse> getOperandBundle(uint32_t ID) const { 2071 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!"); 2072 2073 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 2074 OperandBundleUse U = getOperandBundleAt(i); 2075 if (U.getTagID() == ID) 2076 return U; 2077 } 2078 2079 return std::nullopt; 2080 } 2081 2082 /// Return the list of operand bundles attached to this instruction as 2083 /// a vector of OperandBundleDefs. 2084 /// 2085 /// This function copies the OperandBundeUse instances associated with this 2086 /// OperandBundleUser to a vector of OperandBundleDefs. Note: 2087 /// OperandBundeUses and OperandBundleDefs are non-trivially *different* 2088 /// representations of operand bundles (see documentation above). 2089 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const; 2090 2091 /// Return the operand bundle for the operand at index OpIdx. 2092 /// 2093 /// It is an error to call this with an OpIdx that does not correspond to an 2094 /// bundle operand. 2095 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const { 2096 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx)); 2097 } 2098 2099 /// Return true if this operand bundle user has operand bundles that 2100 /// may read from the heap. 2101 bool hasReadingOperandBundles() const; 2102 2103 /// Return true if this operand bundle user has operand bundles that 2104 /// may write to the heap. 2105 bool hasClobberingOperandBundles() const; 2106 2107 /// Return true if the bundle operand at index \p OpIdx has the 2108 /// attribute \p A. 2109 bool bundleOperandHasAttr(unsigned OpIdx, Attribute::AttrKind A) const { 2110 auto &BOI = getBundleOpInfoForOperand(OpIdx); 2111 auto OBU = operandBundleFromBundleOpInfo(BOI); 2112 return OBU.operandHasAttr(OpIdx - BOI.Begin, A); 2113 } 2114 2115 /// Return true if \p Other has the same sequence of operand bundle 2116 /// tags with the same number of operands on each one of them as this 2117 /// OperandBundleUser. 2118 bool hasIdenticalOperandBundleSchema(const CallBase &Other) const { 2119 if (getNumOperandBundles() != Other.getNumOperandBundles()) 2120 return false; 2121 2122 return std::equal(bundle_op_info_begin(), bundle_op_info_end(), 2123 Other.bundle_op_info_begin()); 2124 } 2125 2126 /// Return true if this operand bundle user contains operand bundles 2127 /// with tags other than those specified in \p IDs. 2128 bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const { 2129 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 2130 uint32_t ID = getOperandBundleAt(i).getTagID(); 2131 if (!is_contained(IDs, ID)) 2132 return true; 2133 } 2134 return false; 2135 } 2136 2137 /// Used to keep track of an operand bundle. See the main comment on 2138 /// OperandBundleUser above. 2139 struct BundleOpInfo { 2140 /// The operand bundle tag, interned by 2141 /// LLVMContextImpl::getOrInsertBundleTag. 2142 StringMapEntry<uint32_t> *Tag; 2143 2144 /// The index in the Use& vector where operands for this operand 2145 /// bundle starts. 2146 uint32_t Begin; 2147 2148 /// The index in the Use& vector where operands for this operand 2149 /// bundle ends. 2150 uint32_t End; 2151 2152 bool operator==(const BundleOpInfo &Other) const { 2153 return Tag == Other.Tag && Begin == Other.Begin && End == Other.End; 2154 } 2155 }; 2156 2157 /// Simple helper function to map a BundleOpInfo to an 2158 /// OperandBundleUse. 2159 OperandBundleUse 2160 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const { 2161 const auto *begin = op_begin(); 2162 ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End); 2163 return OperandBundleUse(BOI.Tag, Inputs); 2164 } 2165 2166 using bundle_op_iterator = BundleOpInfo *; 2167 using const_bundle_op_iterator = const BundleOpInfo *; 2168 2169 /// Return the start of the list of BundleOpInfo instances associated 2170 /// with this OperandBundleUser. 2171 /// 2172 /// OperandBundleUser uses the descriptor area co-allocated with the host User 2173 /// to store some meta information about which operands are "normal" operands, 2174 /// and which ones belong to some operand bundle. 2175 /// 2176 /// The layout of an operand bundle user is 2177 /// 2178 /// +-----------uint32_t End-------------------------------------+ 2179 /// | | 2180 /// | +--------uint32_t Begin--------------------+ | 2181 /// | | | | 2182 /// ^ ^ v v 2183 /// |------|------|----|----|----|----|----|---------|----|---------|----|----- 2184 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un 2185 /// |------|------|----|----|----|----|----|---------|----|---------|----|----- 2186 /// v v ^ ^ 2187 /// | | | | 2188 /// | +--------uint32_t Begin------------+ | 2189 /// | | 2190 /// +-----------uint32_t End-----------------------------+ 2191 /// 2192 /// 2193 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use 2194 /// list. These descriptions are installed and managed by this class, and 2195 /// they're all instances of OperandBundleUser<T>::BundleOpInfo. 2196 /// 2197 /// DU is an additional descriptor installed by User's 'operator new' to keep 2198 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not 2199 /// access or modify DU in any way, it's an implementation detail private to 2200 /// User. 2201 /// 2202 /// The regular Use& vector for the User starts at U0. The operand bundle 2203 /// uses are part of the Use& vector, just like normal uses. In the diagram 2204 /// above, the operand bundle uses start at BOI0_U0. Each instance of 2205 /// BundleOpInfo has information about a contiguous set of uses constituting 2206 /// an operand bundle, and the total set of operand bundle uses themselves 2207 /// form a contiguous set of uses (i.e. there are no gaps between uses 2208 /// corresponding to individual operand bundles). 2209 /// 2210 /// This class does not know the location of the set of operand bundle uses 2211 /// within the use list -- that is decided by the User using this class via 2212 /// the BeginIdx argument in populateBundleOperandInfos. 2213 /// 2214 /// Currently operand bundle users with hung-off operands are not supported. 2215 bundle_op_iterator bundle_op_info_begin() { 2216 if (!hasDescriptor()) 2217 return nullptr; 2218 2219 uint8_t *BytesBegin = getDescriptor().begin(); 2220 return reinterpret_cast<bundle_op_iterator>(BytesBegin); 2221 } 2222 2223 /// Return the start of the list of BundleOpInfo instances associated 2224 /// with this OperandBundleUser. 2225 const_bundle_op_iterator bundle_op_info_begin() const { 2226 auto *NonConstThis = const_cast<CallBase *>(this); 2227 return NonConstThis->bundle_op_info_begin(); 2228 } 2229 2230 /// Return the end of the list of BundleOpInfo instances associated 2231 /// with this OperandBundleUser. 2232 bundle_op_iterator bundle_op_info_end() { 2233 if (!hasDescriptor()) 2234 return nullptr; 2235 2236 uint8_t *BytesEnd = getDescriptor().end(); 2237 return reinterpret_cast<bundle_op_iterator>(BytesEnd); 2238 } 2239 2240 /// Return the end of the list of BundleOpInfo instances associated 2241 /// with this OperandBundleUser. 2242 const_bundle_op_iterator bundle_op_info_end() const { 2243 auto *NonConstThis = const_cast<CallBase *>(this); 2244 return NonConstThis->bundle_op_info_end(); 2245 } 2246 2247 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end). 2248 iterator_range<bundle_op_iterator> bundle_op_infos() { 2249 return make_range(bundle_op_info_begin(), bundle_op_info_end()); 2250 } 2251 2252 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end). 2253 iterator_range<const_bundle_op_iterator> bundle_op_infos() const { 2254 return make_range(bundle_op_info_begin(), bundle_op_info_end()); 2255 } 2256 2257 /// Populate the BundleOpInfo instances and the Use& vector from \p 2258 /// Bundles. Return the op_iterator pointing to the Use& one past the last 2259 /// last bundle operand use. 2260 /// 2261 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo 2262 /// instance allocated in this User's descriptor. 2263 op_iterator populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles, 2264 const unsigned BeginIndex); 2265 2266 public: 2267 /// Return the BundleOpInfo for the operand at index OpIdx. 2268 /// 2269 /// It is an error to call this with an OpIdx that does not correspond to an 2270 /// bundle operand. 2271 BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx); 2272 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const { 2273 return const_cast<CallBase *>(this)->getBundleOpInfoForOperand(OpIdx); 2274 } 2275 2276 protected: 2277 /// Return the total number of values used in \p Bundles. 2278 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) { 2279 unsigned Total = 0; 2280 for (const auto &B : Bundles) 2281 Total += B.input_size(); 2282 return Total; 2283 } 2284 2285 /// @} 2286 // End of operand bundle API. 2287 2288 private: 2289 bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const; 2290 bool hasFnAttrOnCalledFunction(StringRef Kind) const; 2291 2292 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const { 2293 if (Attrs.hasFnAttr(Kind)) 2294 return true; 2295 2296 return hasFnAttrOnCalledFunction(Kind); 2297 } 2298 template <typename AK> Attribute getFnAttrOnCalledFunction(AK Kind) const; 2299 2300 /// Determine whether the return value has the given attribute. Supports 2301 /// Attribute::AttrKind and StringRef as \p AttrKind types. 2302 template <typename AttrKind> bool hasRetAttrImpl(AttrKind Kind) const { 2303 if (Attrs.hasRetAttr(Kind)) 2304 return true; 2305 2306 // Look at the callee, if available. 2307 if (const Function *F = getCalledFunction()) 2308 return F->getAttributes().hasRetAttr(Kind); 2309 return false; 2310 } 2311 }; 2312 2313 template <> 2314 struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase, 1> {}; 2315 2316 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value) 2317 2318 //===----------------------------------------------------------------------===// 2319 // FuncletPadInst Class 2320 //===----------------------------------------------------------------------===// 2321 class FuncletPadInst : public Instruction { 2322 private: 2323 FuncletPadInst(const FuncletPadInst &CPI); 2324 2325 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 2326 ArrayRef<Value *> Args, unsigned Values, 2327 const Twine &NameStr, Instruction *InsertBefore); 2328 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 2329 ArrayRef<Value *> Args, unsigned Values, 2330 const Twine &NameStr, BasicBlock *InsertAtEnd); 2331 2332 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr); 2333 2334 protected: 2335 // Note: Instruction needs to be a friend here to call cloneImpl. 2336 friend class Instruction; 2337 friend class CatchPadInst; 2338 friend class CleanupPadInst; 2339 2340 FuncletPadInst *cloneImpl() const; 2341 2342 public: 2343 /// Provide fast operand accessors 2344 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 2345 2346 /// arg_size - Return the number of funcletpad arguments. 2347 /// 2348 unsigned arg_size() const { return getNumOperands() - 1; } 2349 2350 /// Convenience accessors 2351 2352 /// Return the outer EH-pad this funclet is nested within. 2353 /// 2354 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst 2355 /// is a CatchPadInst. 2356 Value *getParentPad() const { return Op<-1>(); } 2357 void setParentPad(Value *ParentPad) { 2358 assert(ParentPad); 2359 Op<-1>() = ParentPad; 2360 } 2361 2362 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument. 2363 /// 2364 Value *getArgOperand(unsigned i) const { return getOperand(i); } 2365 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); } 2366 2367 /// arg_operands - iteration adapter for range-for loops. 2368 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); } 2369 2370 /// arg_operands - iteration adapter for range-for loops. 2371 const_op_range arg_operands() const { 2372 return const_op_range(op_begin(), op_end() - 1); 2373 } 2374 2375 // Methods for support type inquiry through isa, cast, and dyn_cast: 2376 static bool classof(const Instruction *I) { return I->isFuncletPad(); } 2377 static bool classof(const Value *V) { 2378 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 2379 } 2380 }; 2381 2382 template <> 2383 struct OperandTraits<FuncletPadInst> 2384 : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {}; 2385 2386 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value) 2387 2388 } // end namespace llvm 2389 2390 #endif // LLVM_IR_INSTRTYPES_H 2391