1 //===-- llvm/Constants.h - Constant class subclass definitions --*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// @file 10 /// This file contains the declarations for the subclasses of Constant, 11 /// which represent the different flavors of constant values that live in LLVM. 12 /// Note that Constants are immutable (once created they never change) and are 13 /// fully shared by structural equivalence. This means that two structurally 14 /// equivalent constants will always have the same address. Constants are 15 /// created on demand as needed and never deleted: thus clients don't have to 16 /// worry about the lifetime of the objects. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #ifndef LLVM_IR_CONSTANTS_H 21 #define LLVM_IR_CONSTANTS_H 22 23 #include "llvm/ADT/APFloat.h" 24 #include "llvm/ADT/APInt.h" 25 #include "llvm/ADT/ArrayRef.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/IR/Constant.h" 29 #include "llvm/IR/ConstantRange.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/GEPNoWrapFlags.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/IR/OperandTraits.h" 34 #include "llvm/IR/User.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/Casting.h" 37 #include "llvm/Support/Compiler.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include <cassert> 40 #include <cstddef> 41 #include <cstdint> 42 #include <optional> 43 44 namespace llvm { 45 46 template <class ConstantClass> struct ConstantAggrKeyType; 47 48 /// Base class for constants with no operands. 49 /// 50 /// These constants have no operands; they represent their data directly. 51 /// Since they can be in use by unrelated modules (and are never based on 52 /// GlobalValues), it never makes sense to RAUW them. 53 class ConstantData : public Constant { 54 constexpr static IntrusiveOperandsAllocMarker AllocMarker{0}; 55 56 friend class Constant; 57 58 Value *handleOperandChangeImpl(Value *From, Value *To) { 59 llvm_unreachable("Constant data does not have operands!"); 60 } 61 62 protected: 63 explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, AllocMarker) {} 64 65 void *operator new(size_t S) { return User::operator new(S, AllocMarker); } 66 67 public: 68 void operator delete(void *Ptr) { User::operator delete(Ptr); } 69 70 ConstantData(const ConstantData &) = delete; 71 72 /// Methods to support type inquiry through isa, cast, and dyn_cast. 73 static bool classof(const Value *V) { 74 return V->getValueID() >= ConstantDataFirstVal && 75 V->getValueID() <= ConstantDataLastVal; 76 } 77 }; 78 79 //===----------------------------------------------------------------------===// 80 /// This is the shared class of boolean and integer constants. This class 81 /// represents both boolean and integral constants. 82 /// Class for constant integers. 83 class ConstantInt final : public ConstantData { 84 friend class Constant; 85 friend class ConstantVector; 86 87 APInt Val; 88 89 ConstantInt(Type *Ty, const APInt &V); 90 91 void destroyConstantImpl(); 92 93 /// Return a ConstantInt with the specified value and an implied Type. The 94 /// type is the vector type whose integer element type corresponds to the bit 95 /// width of the value. 96 static ConstantInt *get(LLVMContext &Context, ElementCount EC, 97 const APInt &V); 98 99 public: 100 ConstantInt(const ConstantInt &) = delete; 101 102 static ConstantInt *getTrue(LLVMContext &Context); 103 static ConstantInt *getFalse(LLVMContext &Context); 104 static ConstantInt *getBool(LLVMContext &Context, bool V); 105 static Constant *getTrue(Type *Ty); 106 static Constant *getFalse(Type *Ty); 107 static Constant *getBool(Type *Ty, bool V); 108 109 /// If Ty is a vector type, return a Constant with a splat of the given 110 /// value. Otherwise return a ConstantInt for the given value. 111 static Constant *get(Type *Ty, uint64_t V, bool IsSigned = false); 112 113 /// Return a ConstantInt with the specified integer value for the specified 114 /// type. If the type is wider than 64 bits, the value will be zero-extended 115 /// to fit the type, unless IsSigned is true, in which case the value will 116 /// be interpreted as a 64-bit signed integer and sign-extended to fit 117 /// the type. 118 /// Get a ConstantInt for a specific value. 119 static ConstantInt *get(IntegerType *Ty, uint64_t V, bool IsSigned = false); 120 121 /// Return a ConstantInt with the specified value for the specified type. The 122 /// value V will be canonicalized to a an unsigned APInt. Accessing it with 123 /// either getSExtValue() or getZExtValue() will yield a correctly sized and 124 /// signed value for the type Ty. 125 /// Get a ConstantInt for a specific signed value. 126 static ConstantInt *getSigned(IntegerType *Ty, int64_t V) { 127 return get(Ty, V, true); 128 } 129 static Constant *getSigned(Type *Ty, int64_t V) { 130 return get(Ty, V, true); 131 } 132 133 /// Return a ConstantInt with the specified value and an implied Type. The 134 /// type is the integer type that corresponds to the bit width of the value. 135 static ConstantInt *get(LLVMContext &Context, const APInt &V); 136 137 /// Return a ConstantInt constructed from the string strStart with the given 138 /// radix. 139 static ConstantInt *get(IntegerType *Ty, StringRef Str, uint8_t Radix); 140 141 /// If Ty is a vector type, return a Constant with a splat of the given 142 /// value. Otherwise return a ConstantInt for the given value. 143 static Constant *get(Type *Ty, const APInt &V); 144 145 /// Return the constant as an APInt value reference. This allows clients to 146 /// obtain a full-precision copy of the value. 147 /// Return the constant's value. 148 inline const APInt &getValue() const { return Val; } 149 150 /// getBitWidth - Return the scalar bitwidth of this constant. 151 unsigned getBitWidth() const { return Val.getBitWidth(); } 152 153 /// Return the constant as a 64-bit unsigned integer value after it 154 /// has been zero extended as appropriate for the type of this constant. Note 155 /// that this method can assert if the value does not fit in 64 bits. 156 /// Return the zero extended value. 157 inline uint64_t getZExtValue() const { return Val.getZExtValue(); } 158 159 /// Return the constant as a 64-bit integer value after it has been sign 160 /// extended as appropriate for the type of this constant. Note that 161 /// this method can assert if the value does not fit in 64 bits. 162 /// Return the sign extended value. 163 inline int64_t getSExtValue() const { return Val.getSExtValue(); } 164 165 /// Return the constant as an llvm::MaybeAlign. 166 /// Note that this method can assert if the value does not fit in 64 bits or 167 /// is not a power of two. 168 inline MaybeAlign getMaybeAlignValue() const { 169 return MaybeAlign(getZExtValue()); 170 } 171 172 /// Return the constant as an llvm::Align, interpreting `0` as `Align(1)`. 173 /// Note that this method can assert if the value does not fit in 64 bits or 174 /// is not a power of two. 175 inline Align getAlignValue() const { 176 return getMaybeAlignValue().valueOrOne(); 177 } 178 179 /// A helper method that can be used to determine if the constant contained 180 /// within is equal to a constant. This only works for very small values, 181 /// because this is all that can be represented with all types. 182 /// Determine if this constant's value is same as an unsigned char. 183 bool equalsInt(uint64_t V) const { return Val == V; } 184 185 /// Variant of the getType() method to always return an IntegerType, which 186 /// reduces the amount of casting needed in parts of the compiler. 187 inline IntegerType *getIntegerType() const { 188 return cast<IntegerType>(Value::getType()); 189 } 190 191 /// This static method returns true if the type Ty is big enough to 192 /// represent the value V. This can be used to avoid having the get method 193 /// assert when V is larger than Ty can represent. Note that there are two 194 /// versions of this method, one for unsigned and one for signed integers. 195 /// Although ConstantInt canonicalizes everything to an unsigned integer, 196 /// the signed version avoids callers having to convert a signed quantity 197 /// to the appropriate unsigned type before calling the method. 198 /// @returns true if V is a valid value for type Ty 199 /// Determine if the value is in range for the given type. 200 static bool isValueValidForType(Type *Ty, uint64_t V); 201 static bool isValueValidForType(Type *Ty, int64_t V); 202 203 bool isNegative() const { return Val.isNegative(); } 204 205 /// This is just a convenience method to make client code smaller for a 206 /// common code. It also correctly performs the comparison without the 207 /// potential for an assertion from getZExtValue(). 208 bool isZero() const { return Val.isZero(); } 209 210 /// This is just a convenience method to make client code smaller for a 211 /// common case. It also correctly performs the comparison without the 212 /// potential for an assertion from getZExtValue(). 213 /// Determine if the value is one. 214 bool isOne() const { return Val.isOne(); } 215 216 /// This function will return true iff every bit in this constant is set 217 /// to true. 218 /// @returns true iff this constant's bits are all set to true. 219 /// Determine if the value is all ones. 220 bool isMinusOne() const { return Val.isAllOnes(); } 221 222 /// This function will return true iff this constant represents the largest 223 /// value that may be represented by the constant's type. 224 /// @returns true iff this is the largest value that may be represented 225 /// by this type. 226 /// Determine if the value is maximal. 227 bool isMaxValue(bool IsSigned) const { 228 if (IsSigned) 229 return Val.isMaxSignedValue(); 230 else 231 return Val.isMaxValue(); 232 } 233 234 /// This function will return true iff this constant represents the smallest 235 /// value that may be represented by this constant's type. 236 /// @returns true if this is the smallest value that may be represented by 237 /// this type. 238 /// Determine if the value is minimal. 239 bool isMinValue(bool IsSigned) const { 240 if (IsSigned) 241 return Val.isMinSignedValue(); 242 else 243 return Val.isMinValue(); 244 } 245 246 /// This function will return true iff this constant represents a value with 247 /// active bits bigger than 64 bits or a value greater than the given uint64_t 248 /// value. 249 /// @returns true iff this constant is greater or equal to the given number. 250 /// Determine if the value is greater or equal to the given number. 251 bool uge(uint64_t Num) const { return Val.uge(Num); } 252 253 /// getLimitedValue - If the value is smaller than the specified limit, 254 /// return it, otherwise return the limit value. This causes the value 255 /// to saturate to the limit. 256 /// @returns the min of the value of the constant and the specified value 257 /// Get the constant's value with a saturation limit 258 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const { 259 return Val.getLimitedValue(Limit); 260 } 261 262 /// Methods to support type inquiry through isa, cast, and dyn_cast. 263 static bool classof(const Value *V) { 264 return V->getValueID() == ConstantIntVal; 265 } 266 }; 267 268 //===----------------------------------------------------------------------===// 269 /// ConstantFP - Floating Point Values [float, double] 270 /// 271 class ConstantFP final : public ConstantData { 272 friend class Constant; 273 friend class ConstantVector; 274 275 APFloat Val; 276 277 ConstantFP(Type *Ty, const APFloat &V); 278 279 void destroyConstantImpl(); 280 281 /// Return a ConstantFP with the specified value and an implied Type. The 282 /// type is the vector type whose element type has the same floating point 283 /// semantics as the value. 284 static ConstantFP *get(LLVMContext &Context, ElementCount EC, 285 const APFloat &V); 286 287 public: 288 ConstantFP(const ConstantFP &) = delete; 289 290 /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP, 291 /// for the specified value in the specified type. This should only be used 292 /// for simple constant values like 2.0/1.0 etc, that are known-valid both as 293 /// host double and as the target format. 294 static Constant *get(Type *Ty, double V); 295 296 /// If Ty is a vector type, return a Constant with a splat of the given 297 /// value. Otherwise return a ConstantFP for the given value. 298 static Constant *get(Type *Ty, const APFloat &V); 299 300 static Constant *get(Type *Ty, StringRef Str); 301 static ConstantFP *get(LLVMContext &Context, const APFloat &V); 302 static Constant *getNaN(Type *Ty, bool Negative = false, 303 uint64_t Payload = 0); 304 static Constant *getQNaN(Type *Ty, bool Negative = false, 305 APInt *Payload = nullptr); 306 static Constant *getSNaN(Type *Ty, bool Negative = false, 307 APInt *Payload = nullptr); 308 static Constant *getZero(Type *Ty, bool Negative = false); 309 static Constant *getNegativeZero(Type *Ty) { return getZero(Ty, true); } 310 static Constant *getInfinity(Type *Ty, bool Negative = false); 311 312 /// Return true if Ty is big enough to represent V. 313 static bool isValueValidForType(Type *Ty, const APFloat &V); 314 inline const APFloat &getValueAPF() const { return Val; } 315 inline const APFloat &getValue() const { return Val; } 316 317 /// Return true if the value is positive or negative zero. 318 bool isZero() const { return Val.isZero(); } 319 320 /// Return true if the sign bit is set. 321 bool isNegative() const { return Val.isNegative(); } 322 323 /// Return true if the value is infinity 324 bool isInfinity() const { return Val.isInfinity(); } 325 326 /// Return true if the value is a NaN. 327 bool isNaN() const { return Val.isNaN(); } 328 329 /// We don't rely on operator== working on double values, as it returns true 330 /// for things that are clearly not equal, like -0.0 and 0.0. 331 /// As such, this method can be used to do an exact bit-for-bit comparison of 332 /// two floating point values. The version with a double operand is retained 333 /// because it's so convenient to write isExactlyValue(2.0), but please use 334 /// it only for simple constants. 335 bool isExactlyValue(const APFloat &V) const; 336 337 bool isExactlyValue(double V) const { 338 bool ignored; 339 APFloat FV(V); 340 FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored); 341 return isExactlyValue(FV); 342 } 343 344 /// Methods for support type inquiry through isa, cast, and dyn_cast: 345 static bool classof(const Value *V) { 346 return V->getValueID() == ConstantFPVal; 347 } 348 }; 349 350 //===----------------------------------------------------------------------===// 351 /// All zero aggregate value 352 /// 353 class ConstantAggregateZero final : public ConstantData { 354 friend class Constant; 355 356 explicit ConstantAggregateZero(Type *Ty) 357 : ConstantData(Ty, ConstantAggregateZeroVal) {} 358 359 void destroyConstantImpl(); 360 361 public: 362 ConstantAggregateZero(const ConstantAggregateZero &) = delete; 363 364 static ConstantAggregateZero *get(Type *Ty); 365 366 /// If this CAZ has array or vector type, return a zero with the right element 367 /// type. 368 Constant *getSequentialElement() const; 369 370 /// If this CAZ has struct type, return a zero with the right element type for 371 /// the specified element. 372 Constant *getStructElement(unsigned Elt) const; 373 374 /// Return a zero of the right value for the specified GEP index if we can, 375 /// otherwise return null (e.g. if C is a ConstantExpr). 376 Constant *getElementValue(Constant *C) const; 377 378 /// Return a zero of the right value for the specified GEP index. 379 Constant *getElementValue(unsigned Idx) const; 380 381 /// Return the number of elements in the array, vector, or struct. 382 ElementCount getElementCount() const; 383 384 /// Methods for support type inquiry through isa, cast, and dyn_cast: 385 /// 386 static bool classof(const Value *V) { 387 return V->getValueID() == ConstantAggregateZeroVal; 388 } 389 }; 390 391 /// Base class for aggregate constants (with operands). 392 /// 393 /// These constants are aggregates of other constants, which are stored as 394 /// operands. 395 /// 396 /// Subclasses are \a ConstantStruct, \a ConstantArray, and \a 397 /// ConstantVector. 398 /// 399 /// \note Some subclasses of \a ConstantData are semantically aggregates -- 400 /// such as \a ConstantDataArray -- but are not subclasses of this because they 401 /// use operands. 402 class ConstantAggregate : public Constant { 403 protected: 404 ConstantAggregate(Type *T, ValueTy VT, ArrayRef<Constant *> V, 405 AllocInfo AllocInfo); 406 407 public: 408 /// Transparently provide more efficient getOperand methods. 409 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant); 410 411 /// Methods for support type inquiry through isa, cast, and dyn_cast: 412 static bool classof(const Value *V) { 413 return V->getValueID() >= ConstantAggregateFirstVal && 414 V->getValueID() <= ConstantAggregateLastVal; 415 } 416 }; 417 418 template <> 419 struct OperandTraits<ConstantAggregate> 420 : public VariadicOperandTraits<ConstantAggregate> {}; 421 422 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantAggregate, Constant) 423 424 //===----------------------------------------------------------------------===// 425 /// ConstantArray - Constant Array Declarations 426 /// 427 class ConstantArray final : public ConstantAggregate { 428 friend struct ConstantAggrKeyType<ConstantArray>; 429 friend class Constant; 430 431 ConstantArray(ArrayType *T, ArrayRef<Constant *> Val, AllocInfo AllocInfo); 432 433 void destroyConstantImpl(); 434 Value *handleOperandChangeImpl(Value *From, Value *To); 435 436 public: 437 // ConstantArray accessors 438 static Constant *get(ArrayType *T, ArrayRef<Constant *> V); 439 440 private: 441 static Constant *getImpl(ArrayType *T, ArrayRef<Constant *> V); 442 443 public: 444 /// Specialize the getType() method to always return an ArrayType, 445 /// which reduces the amount of casting needed in parts of the compiler. 446 inline ArrayType *getType() const { 447 return cast<ArrayType>(Value::getType()); 448 } 449 450 /// Methods for support type inquiry through isa, cast, and dyn_cast: 451 static bool classof(const Value *V) { 452 return V->getValueID() == ConstantArrayVal; 453 } 454 }; 455 456 //===----------------------------------------------------------------------===// 457 // Constant Struct Declarations 458 // 459 class ConstantStruct final : public ConstantAggregate { 460 friend struct ConstantAggrKeyType<ConstantStruct>; 461 friend class Constant; 462 463 ConstantStruct(StructType *T, ArrayRef<Constant *> Val, AllocInfo AllocInfo); 464 465 void destroyConstantImpl(); 466 Value *handleOperandChangeImpl(Value *From, Value *To); 467 468 public: 469 // ConstantStruct accessors 470 static Constant *get(StructType *T, ArrayRef<Constant *> V); 471 472 template <typename... Csts> 473 static std::enable_if_t<are_base_of<Constant, Csts...>::value, Constant *> 474 get(StructType *T, Csts *...Vs) { 475 return get(T, ArrayRef<Constant *>({Vs...})); 476 } 477 478 /// Return an anonymous struct that has the specified elements. 479 /// If the struct is possibly empty, then you must specify a context. 480 static Constant *getAnon(ArrayRef<Constant *> V, bool Packed = false) { 481 return get(getTypeForElements(V, Packed), V); 482 } 483 static Constant *getAnon(LLVMContext &Ctx, ArrayRef<Constant *> V, 484 bool Packed = false) { 485 return get(getTypeForElements(Ctx, V, Packed), V); 486 } 487 488 /// Return an anonymous struct type to use for a constant with the specified 489 /// set of elements. The list must not be empty. 490 static StructType *getTypeForElements(ArrayRef<Constant *> V, 491 bool Packed = false); 492 /// This version of the method allows an empty list. 493 static StructType *getTypeForElements(LLVMContext &Ctx, 494 ArrayRef<Constant *> V, 495 bool Packed = false); 496 497 /// Specialization - reduce amount of casting. 498 inline StructType *getType() const { 499 return cast<StructType>(Value::getType()); 500 } 501 502 /// Methods for support type inquiry through isa, cast, and dyn_cast: 503 static bool classof(const Value *V) { 504 return V->getValueID() == ConstantStructVal; 505 } 506 }; 507 508 //===----------------------------------------------------------------------===// 509 /// Constant Vector Declarations 510 /// 511 class ConstantVector final : public ConstantAggregate { 512 friend struct ConstantAggrKeyType<ConstantVector>; 513 friend class Constant; 514 515 ConstantVector(VectorType *T, ArrayRef<Constant *> Val, AllocInfo AllocInfo); 516 517 void destroyConstantImpl(); 518 Value *handleOperandChangeImpl(Value *From, Value *To); 519 520 public: 521 // ConstantVector accessors 522 static Constant *get(ArrayRef<Constant *> V); 523 524 private: 525 static Constant *getImpl(ArrayRef<Constant *> V); 526 527 public: 528 /// Return a ConstantVector with the specified constant in each element. 529 /// Note that this might not return an instance of ConstantVector 530 static Constant *getSplat(ElementCount EC, Constant *Elt); 531 532 /// Specialize the getType() method to always return a FixedVectorType, 533 /// which reduces the amount of casting needed in parts of the compiler. 534 inline FixedVectorType *getType() const { 535 return cast<FixedVectorType>(Value::getType()); 536 } 537 538 /// If all elements of the vector constant have the same value, return that 539 /// value. Otherwise, return nullptr. Ignore poison elements by setting 540 /// AllowPoison to true. 541 Constant *getSplatValue(bool AllowPoison = false) const; 542 543 /// Methods for support type inquiry through isa, cast, and dyn_cast: 544 static bool classof(const Value *V) { 545 return V->getValueID() == ConstantVectorVal; 546 } 547 }; 548 549 //===----------------------------------------------------------------------===// 550 /// A constant pointer value that points to null 551 /// 552 class ConstantPointerNull final : public ConstantData { 553 friend class Constant; 554 555 explicit ConstantPointerNull(PointerType *T) 556 : ConstantData(T, Value::ConstantPointerNullVal) {} 557 558 void destroyConstantImpl(); 559 560 public: 561 ConstantPointerNull(const ConstantPointerNull &) = delete; 562 563 /// Static factory methods - Return objects of the specified value 564 static ConstantPointerNull *get(PointerType *T); 565 566 /// Specialize the getType() method to always return an PointerType, 567 /// which reduces the amount of casting needed in parts of the compiler. 568 inline PointerType *getType() const { 569 return cast<PointerType>(Value::getType()); 570 } 571 572 /// Methods for support type inquiry through isa, cast, and dyn_cast: 573 static bool classof(const Value *V) { 574 return V->getValueID() == ConstantPointerNullVal; 575 } 576 }; 577 578 //===----------------------------------------------------------------------===// 579 /// ConstantDataSequential - A vector or array constant whose element type is a 580 /// simple 1/2/4/8-byte integer or half/bfloat/float/double, and whose elements 581 /// are just simple data values (i.e. ConstantInt/ConstantFP). This Constant 582 /// node has no operands because it stores all of the elements of the constant 583 /// as densely packed data, instead of as Value*'s. 584 /// 585 /// This is the common base class of ConstantDataArray and ConstantDataVector. 586 /// 587 class ConstantDataSequential : public ConstantData { 588 friend class LLVMContextImpl; 589 friend class Constant; 590 591 /// A pointer to the bytes underlying this constant (which is owned by the 592 /// uniquing StringMap). 593 const char *DataElements; 594 595 /// This forms a link list of ConstantDataSequential nodes that have 596 /// the same value but different type. For example, 0,0,0,1 could be a 4 597 /// element array of i8, or a 1-element array of i32. They'll both end up in 598 /// the same StringMap bucket, linked up. 599 std::unique_ptr<ConstantDataSequential> Next; 600 601 void destroyConstantImpl(); 602 603 protected: 604 explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data) 605 : ConstantData(ty, VT), DataElements(Data) {} 606 607 static Constant *getImpl(StringRef Bytes, Type *Ty); 608 609 public: 610 ConstantDataSequential(const ConstantDataSequential &) = delete; 611 612 /// Return true if a ConstantDataSequential can be formed with a vector or 613 /// array of the specified element type. 614 /// ConstantDataArray only works with normal float and int types that are 615 /// stored densely in memory, not with things like i42 or x86_f80. 616 static bool isElementTypeCompatible(Type *Ty); 617 618 /// If this is a sequential container of integers (of any size), return the 619 /// specified element in the low bits of a uint64_t. 620 uint64_t getElementAsInteger(unsigned i) const; 621 622 /// If this is a sequential container of integers (of any size), return the 623 /// specified element as an APInt. 624 APInt getElementAsAPInt(unsigned i) const; 625 626 /// If this is a sequential container of floating point type, return the 627 /// specified element as an APFloat. 628 APFloat getElementAsAPFloat(unsigned i) const; 629 630 /// If this is an sequential container of floats, return the specified element 631 /// as a float. 632 float getElementAsFloat(unsigned i) const; 633 634 /// If this is an sequential container of doubles, return the specified 635 /// element as a double. 636 double getElementAsDouble(unsigned i) const; 637 638 /// Return a Constant for a specified index's element. 639 /// Note that this has to compute a new constant to return, so it isn't as 640 /// efficient as getElementAsInteger/Float/Double. 641 Constant *getElementAsConstant(unsigned i) const; 642 643 /// Return the element type of the array/vector. 644 Type *getElementType() const; 645 646 /// Return the number of elements in the array or vector. 647 unsigned getNumElements() const; 648 649 /// Return the size (in bytes) of each element in the array/vector. 650 /// The size of the elements is known to be a multiple of one byte. 651 uint64_t getElementByteSize() const; 652 653 /// This method returns true if this is an array of \p CharSize integers. 654 bool isString(unsigned CharSize = 8) const; 655 656 /// This method returns true if the array "isString", ends with a null byte, 657 /// and does not contains any other null bytes. 658 bool isCString() const; 659 660 /// If this array is isString(), then this method returns the array as a 661 /// StringRef. Otherwise, it asserts out. 662 StringRef getAsString() const { 663 assert(isString() && "Not a string"); 664 return getRawDataValues(); 665 } 666 667 /// If this array is isCString(), then this method returns the array (without 668 /// the trailing null byte) as a StringRef. Otherwise, it asserts out. 669 StringRef getAsCString() const { 670 assert(isCString() && "Isn't a C string"); 671 StringRef Str = getAsString(); 672 return Str.substr(0, Str.size() - 1); 673 } 674 675 /// Return the raw, underlying, bytes of this data. Note that this is an 676 /// extremely tricky thing to work with, as it exposes the host endianness of 677 /// the data elements. 678 StringRef getRawDataValues() const; 679 680 /// Methods for support type inquiry through isa, cast, and dyn_cast: 681 static bool classof(const Value *V) { 682 return V->getValueID() == ConstantDataArrayVal || 683 V->getValueID() == ConstantDataVectorVal; 684 } 685 686 private: 687 const char *getElementPointer(unsigned Elt) const; 688 }; 689 690 //===----------------------------------------------------------------------===// 691 /// An array constant whose element type is a simple 1/2/4/8-byte integer or 692 /// float/double, and whose elements are just simple data values 693 /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it 694 /// stores all of the elements of the constant as densely packed data, instead 695 /// of as Value*'s. 696 class ConstantDataArray final : public ConstantDataSequential { 697 friend class ConstantDataSequential; 698 699 explicit ConstantDataArray(Type *ty, const char *Data) 700 : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {} 701 702 public: 703 ConstantDataArray(const ConstantDataArray &) = delete; 704 705 /// get() constructor - Return a constant with array type with an element 706 /// count and element type matching the ArrayRef passed in. Note that this 707 /// can return a ConstantAggregateZero object. 708 template <typename ElementTy> 709 static Constant *get(LLVMContext &Context, ArrayRef<ElementTy> Elts) { 710 const char *Data = reinterpret_cast<const char *>(Elts.data()); 711 return getRaw(StringRef(Data, Elts.size() * sizeof(ElementTy)), Elts.size(), 712 Type::getScalarTy<ElementTy>(Context)); 713 } 714 715 /// get() constructor - ArrayTy needs to be compatible with 716 /// ArrayRef<ElementTy>. Calls get(LLVMContext, ArrayRef<ElementTy>). 717 template <typename ArrayTy> 718 static Constant *get(LLVMContext &Context, ArrayTy &Elts) { 719 return ConstantDataArray::get(Context, ArrayRef(Elts)); 720 } 721 722 /// getRaw() constructor - Return a constant with array type with an element 723 /// count and element type matching the NumElements and ElementTy parameters 724 /// passed in. Note that this can return a ConstantAggregateZero object. 725 /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is 726 /// the buffer containing the elements. Be careful to make sure Data uses the 727 /// right endianness, the buffer will be used as-is. 728 static Constant *getRaw(StringRef Data, uint64_t NumElements, 729 Type *ElementTy) { 730 Type *Ty = ArrayType::get(ElementTy, NumElements); 731 return getImpl(Data, Ty); 732 } 733 734 /// getFP() constructors - Return a constant of array type with a float 735 /// element type taken from argument `ElementType', and count taken from 736 /// argument `Elts'. The amount of bits of the contained type must match the 737 /// number of bits of the type contained in the passed in ArrayRef. 738 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note 739 /// that this can return a ConstantAggregateZero object. 740 static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts); 741 static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts); 742 static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts); 743 744 /// This method constructs a CDS and initializes it with a text string. 745 /// The default behavior (AddNull==true) causes a null terminator to 746 /// be placed at the end of the array (increasing the length of the string by 747 /// one more than the StringRef would normally indicate. Pass AddNull=false 748 /// to disable this behavior. 749 static Constant *getString(LLVMContext &Context, StringRef Initializer, 750 bool AddNull = true); 751 752 /// Specialize the getType() method to always return an ArrayType, 753 /// which reduces the amount of casting needed in parts of the compiler. 754 inline ArrayType *getType() const { 755 return cast<ArrayType>(Value::getType()); 756 } 757 758 /// Methods for support type inquiry through isa, cast, and dyn_cast: 759 static bool classof(const Value *V) { 760 return V->getValueID() == ConstantDataArrayVal; 761 } 762 }; 763 764 //===----------------------------------------------------------------------===// 765 /// A vector constant whose element type is a simple 1/2/4/8-byte integer or 766 /// float/double, and whose elements are just simple data values 767 /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it 768 /// stores all of the elements of the constant as densely packed data, instead 769 /// of as Value*'s. 770 class ConstantDataVector final : public ConstantDataSequential { 771 friend class ConstantDataSequential; 772 773 explicit ConstantDataVector(Type *ty, const char *Data) 774 : ConstantDataSequential(ty, ConstantDataVectorVal, Data), 775 IsSplatSet(false) {} 776 // Cache whether or not the constant is a splat. 777 mutable bool IsSplatSet : 1; 778 mutable bool IsSplat : 1; 779 bool isSplatData() const; 780 781 public: 782 ConstantDataVector(const ConstantDataVector &) = delete; 783 784 /// get() constructors - Return a constant with vector type with an element 785 /// count and element type matching the ArrayRef passed in. Note that this 786 /// can return a ConstantAggregateZero object. 787 static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts); 788 static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts); 789 static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts); 790 static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts); 791 static Constant *get(LLVMContext &Context, ArrayRef<float> Elts); 792 static Constant *get(LLVMContext &Context, ArrayRef<double> Elts); 793 794 /// getRaw() constructor - Return a constant with vector type with an element 795 /// count and element type matching the NumElements and ElementTy parameters 796 /// passed in. Note that this can return a ConstantAggregateZero object. 797 /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is 798 /// the buffer containing the elements. Be careful to make sure Data uses the 799 /// right endianness, the buffer will be used as-is. 800 static Constant *getRaw(StringRef Data, uint64_t NumElements, 801 Type *ElementTy) { 802 Type *Ty = VectorType::get(ElementTy, ElementCount::getFixed(NumElements)); 803 return getImpl(Data, Ty); 804 } 805 806 /// getFP() constructors - Return a constant of vector type with a float 807 /// element type taken from argument `ElementType', and count taken from 808 /// argument `Elts'. The amount of bits of the contained type must match the 809 /// number of bits of the type contained in the passed in ArrayRef. 810 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note 811 /// that this can return a ConstantAggregateZero object. 812 static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts); 813 static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts); 814 static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts); 815 816 /// Return a ConstantVector with the specified constant in each element. 817 /// The specified constant has to be a of a compatible type (i8/i16/ 818 /// i32/i64/half/bfloat/float/double) and must be a ConstantFP or ConstantInt. 819 static Constant *getSplat(unsigned NumElts, Constant *Elt); 820 821 /// Returns true if this is a splat constant, meaning that all elements have 822 /// the same value. 823 bool isSplat() const; 824 825 /// If this is a splat constant, meaning that all of the elements have the 826 /// same value, return that value. Otherwise return NULL. 827 Constant *getSplatValue() const; 828 829 /// Specialize the getType() method to always return a FixedVectorType, 830 /// which reduces the amount of casting needed in parts of the compiler. 831 inline FixedVectorType *getType() const { 832 return cast<FixedVectorType>(Value::getType()); 833 } 834 835 /// Methods for support type inquiry through isa, cast, and dyn_cast: 836 static bool classof(const Value *V) { 837 return V->getValueID() == ConstantDataVectorVal; 838 } 839 }; 840 841 //===----------------------------------------------------------------------===// 842 /// A constant token which is empty 843 /// 844 class ConstantTokenNone final : public ConstantData { 845 friend class Constant; 846 847 explicit ConstantTokenNone(LLVMContext &Context) 848 : ConstantData(Type::getTokenTy(Context), ConstantTokenNoneVal) {} 849 850 void destroyConstantImpl(); 851 852 public: 853 ConstantTokenNone(const ConstantTokenNone &) = delete; 854 855 /// Return the ConstantTokenNone. 856 static ConstantTokenNone *get(LLVMContext &Context); 857 858 /// Methods to support type inquiry through isa, cast, and dyn_cast. 859 static bool classof(const Value *V) { 860 return V->getValueID() == ConstantTokenNoneVal; 861 } 862 }; 863 864 /// A constant target extension type default initializer 865 class ConstantTargetNone final : public ConstantData { 866 friend class Constant; 867 868 explicit ConstantTargetNone(TargetExtType *T) 869 : ConstantData(T, Value::ConstantTargetNoneVal) {} 870 871 void destroyConstantImpl(); 872 873 public: 874 ConstantTargetNone(const ConstantTargetNone &) = delete; 875 876 /// Static factory methods - Return objects of the specified value. 877 static ConstantTargetNone *get(TargetExtType *T); 878 879 /// Specialize the getType() method to always return an TargetExtType, 880 /// which reduces the amount of casting needed in parts of the compiler. 881 inline TargetExtType *getType() const { 882 return cast<TargetExtType>(Value::getType()); 883 } 884 885 /// Methods for support type inquiry through isa, cast, and dyn_cast. 886 static bool classof(const Value *V) { 887 return V->getValueID() == ConstantTargetNoneVal; 888 } 889 }; 890 891 /// The address of a basic block. 892 /// 893 class BlockAddress final : public Constant { 894 friend class Constant; 895 896 constexpr static IntrusiveOperandsAllocMarker AllocMarker{2}; 897 898 BlockAddress(Function *F, BasicBlock *BB); 899 900 void *operator new(size_t S) { return User::operator new(S, AllocMarker); } 901 902 void destroyConstantImpl(); 903 Value *handleOperandChangeImpl(Value *From, Value *To); 904 905 public: 906 void operator delete(void *Ptr) { User::operator delete(Ptr); } 907 908 /// Return a BlockAddress for the specified function and basic block. 909 static BlockAddress *get(Function *F, BasicBlock *BB); 910 911 /// Return a BlockAddress for the specified basic block. The basic 912 /// block must be embedded into a function. 913 static BlockAddress *get(BasicBlock *BB); 914 915 /// Lookup an existing \c BlockAddress constant for the given BasicBlock. 916 /// 917 /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress. 918 static BlockAddress *lookup(const BasicBlock *BB); 919 920 /// Transparently provide more efficient getOperand methods. 921 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 922 923 Function *getFunction() const { return (Function *)Op<0>().get(); } 924 BasicBlock *getBasicBlock() const { return (BasicBlock *)Op<1>().get(); } 925 926 /// Methods for support type inquiry through isa, cast, and dyn_cast: 927 static bool classof(const Value *V) { 928 return V->getValueID() == BlockAddressVal; 929 } 930 }; 931 932 template <> 933 struct OperandTraits<BlockAddress> 934 : public FixedNumOperandTraits<BlockAddress, 2> {}; 935 936 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value) 937 938 /// Wrapper for a function that represents a value that 939 /// functionally represents the original function. This can be a function, 940 /// global alias to a function, or an ifunc. 941 class DSOLocalEquivalent final : public Constant { 942 friend class Constant; 943 944 constexpr static IntrusiveOperandsAllocMarker AllocMarker{1}; 945 946 DSOLocalEquivalent(GlobalValue *GV); 947 948 void *operator new(size_t S) { return User::operator new(S, AllocMarker); } 949 950 void destroyConstantImpl(); 951 Value *handleOperandChangeImpl(Value *From, Value *To); 952 953 public: 954 void operator delete(void *Ptr) { User::operator delete(Ptr); } 955 956 /// Return a DSOLocalEquivalent for the specified global value. 957 static DSOLocalEquivalent *get(GlobalValue *GV); 958 959 /// Transparently provide more efficient getOperand methods. 960 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 961 962 GlobalValue *getGlobalValue() const { 963 return cast<GlobalValue>(Op<0>().get()); 964 } 965 966 /// Methods for support type inquiry through isa, cast, and dyn_cast: 967 static bool classof(const Value *V) { 968 return V->getValueID() == DSOLocalEquivalentVal; 969 } 970 }; 971 972 template <> 973 struct OperandTraits<DSOLocalEquivalent> 974 : public FixedNumOperandTraits<DSOLocalEquivalent, 1> {}; 975 976 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(DSOLocalEquivalent, Value) 977 978 /// Wrapper for a value that won't be replaced with a CFI jump table 979 /// pointer in LowerTypeTestsModule. 980 class NoCFIValue final : public Constant { 981 friend class Constant; 982 983 constexpr static IntrusiveOperandsAllocMarker AllocMarker{1}; 984 985 NoCFIValue(GlobalValue *GV); 986 987 void *operator new(size_t S) { return User::operator new(S, AllocMarker); } 988 989 void destroyConstantImpl(); 990 Value *handleOperandChangeImpl(Value *From, Value *To); 991 992 public: 993 /// Return a NoCFIValue for the specified function. 994 static NoCFIValue *get(GlobalValue *GV); 995 996 /// Transparently provide more efficient getOperand methods. 997 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 998 999 GlobalValue *getGlobalValue() const { 1000 return cast<GlobalValue>(Op<0>().get()); 1001 } 1002 1003 /// NoCFIValue is always a pointer. 1004 PointerType *getType() const { 1005 return cast<PointerType>(Value::getType()); 1006 } 1007 1008 /// Methods for support type inquiry through isa, cast, and dyn_cast: 1009 static bool classof(const Value *V) { 1010 return V->getValueID() == NoCFIValueVal; 1011 } 1012 }; 1013 1014 template <> 1015 struct OperandTraits<NoCFIValue> : public FixedNumOperandTraits<NoCFIValue, 1> { 1016 }; 1017 1018 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(NoCFIValue, Value) 1019 1020 /// A signed pointer, in the ptrauth sense. 1021 class ConstantPtrAuth final : public Constant { 1022 friend struct ConstantPtrAuthKeyType; 1023 friend class Constant; 1024 1025 constexpr static IntrusiveOperandsAllocMarker AllocMarker{4}; 1026 1027 ConstantPtrAuth(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, 1028 Constant *AddrDisc); 1029 1030 void *operator new(size_t s) { return User::operator new(s, AllocMarker); } 1031 1032 void destroyConstantImpl(); 1033 Value *handleOperandChangeImpl(Value *From, Value *To); 1034 1035 public: 1036 /// Return a pointer signed with the specified parameters. 1037 static ConstantPtrAuth *get(Constant *Ptr, ConstantInt *Key, 1038 ConstantInt *Disc, Constant *AddrDisc); 1039 1040 /// Produce a new ptrauth expression signing the given value using 1041 /// the same schema as is stored in one. 1042 ConstantPtrAuth *getWithSameSchema(Constant *Pointer) const; 1043 1044 /// Transparently provide more efficient getOperand methods. 1045 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant); 1046 1047 /// The pointer that is signed in this ptrauth signed pointer. 1048 Constant *getPointer() const { return cast<Constant>(Op<0>().get()); } 1049 1050 /// The Key ID, an i32 constant. 1051 ConstantInt *getKey() const { return cast<ConstantInt>(Op<1>().get()); } 1052 1053 /// The integer discriminator, an i64 constant, or 0. 1054 ConstantInt *getDiscriminator() const { 1055 return cast<ConstantInt>(Op<2>().get()); 1056 } 1057 1058 /// The address discriminator if any, or the null constant. 1059 /// If present, this must be a value equivalent to the storage location of 1060 /// the only global-initializer user of the ptrauth signed pointer. 1061 Constant *getAddrDiscriminator() const { 1062 return cast<Constant>(Op<3>().get()); 1063 } 1064 1065 /// Whether there is any non-null address discriminator. 1066 bool hasAddressDiscriminator() const { 1067 return !getAddrDiscriminator()->isNullValue(); 1068 } 1069 1070 /// A constant value for the address discriminator which has special 1071 /// significance to ctors/dtors lowering. Regular address discrimination can't 1072 /// be applied for them since uses of llvm.global_{c|d}tors are disallowed 1073 /// (see Verifier::visitGlobalVariable) and we can't emit getelementptr 1074 /// expressions referencing these special arrays. 1075 enum { AddrDiscriminator_CtorsDtors = 1 }; 1076 1077 /// Whether the address uses a special address discriminator. 1078 /// These discriminators can't be used in real pointer-auth values; they 1079 /// can only be used in "prototype" values that indicate how some real 1080 /// schema is supposed to be produced. 1081 bool hasSpecialAddressDiscriminator(uint64_t Value) const; 1082 1083 /// Check whether an authentication operation with key \p Key and (possibly 1084 /// blended) discriminator \p Discriminator is known to be compatible with 1085 /// this ptrauth signed pointer. 1086 bool isKnownCompatibleWith(const Value *Key, const Value *Discriminator, 1087 const DataLayout &DL) const; 1088 1089 /// Methods for support type inquiry through isa, cast, and dyn_cast: 1090 static bool classof(const Value *V) { 1091 return V->getValueID() == ConstantPtrAuthVal; 1092 } 1093 }; 1094 1095 template <> 1096 struct OperandTraits<ConstantPtrAuth> 1097 : public FixedNumOperandTraits<ConstantPtrAuth, 4> {}; 1098 1099 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPtrAuth, Constant) 1100 1101 //===----------------------------------------------------------------------===// 1102 /// A constant value that is initialized with an expression using 1103 /// other constant values. 1104 /// 1105 /// This class uses the standard Instruction opcodes to define the various 1106 /// constant expressions. The Opcode field for the ConstantExpr class is 1107 /// maintained in the Value::SubclassData field. 1108 class ConstantExpr : public Constant { 1109 friend struct ConstantExprKeyType; 1110 friend class Constant; 1111 1112 void destroyConstantImpl(); 1113 Value *handleOperandChangeImpl(Value *From, Value *To); 1114 1115 protected: 1116 ConstantExpr(Type *ty, unsigned Opcode, AllocInfo AllocInfo) 1117 : Constant(ty, ConstantExprVal, AllocInfo) { 1118 // Operation type (an Instruction opcode) is stored as the SubclassData. 1119 setValueSubclassData(Opcode); 1120 } 1121 1122 ~ConstantExpr() = default; 1123 1124 public: 1125 // Static methods to construct a ConstantExpr of different kinds. Note that 1126 // these methods may return a object that is not an instance of the 1127 // ConstantExpr class, because they will attempt to fold the constant 1128 // expression into something simpler if possible. 1129 1130 /// getAlignOf constant expr - computes the alignment of a type in a target 1131 /// independent way (Note: the return type is an i64). 1132 static Constant *getAlignOf(Type *Ty); 1133 1134 /// getSizeOf constant expr - computes the (alloc) size of a type (in 1135 /// address-units, not bits) in a target independent way (Note: the return 1136 /// type is an i64). 1137 /// 1138 static Constant *getSizeOf(Type *Ty); 1139 1140 static Constant *getNeg(Constant *C, bool HasNSW = false); 1141 static Constant *getNot(Constant *C); 1142 static Constant *getAdd(Constant *C1, Constant *C2, bool HasNUW = false, 1143 bool HasNSW = false); 1144 static Constant *getSub(Constant *C1, Constant *C2, bool HasNUW = false, 1145 bool HasNSW = false); 1146 static Constant *getMul(Constant *C1, Constant *C2, bool HasNUW = false, 1147 bool HasNSW = false); 1148 static Constant *getXor(Constant *C1, Constant *C2); 1149 static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false); 1150 static Constant *getPtrToInt(Constant *C, Type *Ty, 1151 bool OnlyIfReduced = false); 1152 static Constant *getIntToPtr(Constant *C, Type *Ty, 1153 bool OnlyIfReduced = false); 1154 static Constant *getBitCast(Constant *C, Type *Ty, 1155 bool OnlyIfReduced = false); 1156 static Constant *getAddrSpaceCast(Constant *C, Type *Ty, 1157 bool OnlyIfReduced = false); 1158 1159 static Constant *getNSWNeg(Constant *C) { return getNeg(C, /*HasNSW=*/true); } 1160 1161 static Constant *getNSWAdd(Constant *C1, Constant *C2) { 1162 return getAdd(C1, C2, false, true); 1163 } 1164 1165 static Constant *getNUWAdd(Constant *C1, Constant *C2) { 1166 return getAdd(C1, C2, true, false); 1167 } 1168 1169 static Constant *getNSWSub(Constant *C1, Constant *C2) { 1170 return getSub(C1, C2, false, true); 1171 } 1172 1173 static Constant *getNUWSub(Constant *C1, Constant *C2) { 1174 return getSub(C1, C2, true, false); 1175 } 1176 1177 static Constant *getNSWMul(Constant *C1, Constant *C2) { 1178 return getMul(C1, C2, false, true); 1179 } 1180 1181 static Constant *getNUWMul(Constant *C1, Constant *C2) { 1182 return getMul(C1, C2, true, false); 1183 } 1184 1185 /// If C is a scalar/fixed width vector of known powers of 2, then this 1186 /// function returns a new scalar/fixed width vector obtained from logBase2 1187 /// of C. Undef vector elements are set to zero. 1188 /// Return a null pointer otherwise. 1189 static Constant *getExactLogBase2(Constant *C); 1190 1191 /// Return the identity constant for a binary opcode. 1192 /// If the binop is not commutative, callers can acquire the operand 1 1193 /// identity constant by setting AllowRHSConstant to true. For example, any 1194 /// shift has a zero identity constant for operand 1: X shift 0 = X. If this 1195 /// is a fadd/fsub operation and we don't care about signed zeros, then 1196 /// setting NSZ to true returns the identity +0.0 instead of -0.0. Return 1197 /// nullptr if the operator does not have an identity constant. 1198 static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty, 1199 bool AllowRHSConstant = false, 1200 bool NSZ = false); 1201 1202 static Constant *getIntrinsicIdentity(Intrinsic::ID, Type *Ty); 1203 1204 /// Return the identity constant for a binary or intrinsic Instruction. 1205 /// The identity constant C is defined as X op C = X and C op X = X where C 1206 /// and X are the first two operands, and the operation is commutative. 1207 static Constant *getIdentity(Instruction *I, Type *Ty, 1208 bool AllowRHSConstant = false, bool NSZ = false); 1209 1210 /// Return the absorbing element for the given binary 1211 /// operation, i.e. a constant C such that X op C = C and C op X = C for 1212 /// every X. For example, this returns zero for integer multiplication. 1213 /// If AllowLHSConstant is true, the LHS operand is a constant C that must be 1214 /// defined as C op X = C. It returns null if the operator doesn't have 1215 /// an absorbing element. 1216 static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty, 1217 bool AllowLHSConstant = false); 1218 1219 /// Transparently provide more efficient getOperand methods. 1220 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant); 1221 1222 /// Convenience function for getting a Cast operation. 1223 /// 1224 /// \param ops The opcode for the conversion 1225 /// \param C The constant to be converted 1226 /// \param Ty The type to which the constant is converted 1227 /// \param OnlyIfReduced see \a getWithOperands() docs. 1228 static Constant *getCast(unsigned ops, Constant *C, Type *Ty, 1229 bool OnlyIfReduced = false); 1230 1231 // Create a Trunc or BitCast cast constant expression 1232 static Constant * 1233 getTruncOrBitCast(Constant *C, ///< The constant to trunc or bitcast 1234 Type *Ty ///< The type to trunc or bitcast C to 1235 ); 1236 1237 /// Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant 1238 /// expression. 1239 static Constant * 1240 getPointerCast(Constant *C, ///< The pointer value to be casted (operand 0) 1241 Type *Ty ///< The type to which cast should be made 1242 ); 1243 1244 /// Create a BitCast or AddrSpaceCast for a pointer type depending on 1245 /// the address space. 1246 static Constant *getPointerBitCastOrAddrSpaceCast( 1247 Constant *C, ///< The constant to addrspacecast or bitcast 1248 Type *Ty ///< The type to bitcast or addrspacecast C to 1249 ); 1250 1251 /// Return true if this is a convert constant expression 1252 bool isCast() const; 1253 1254 /// get - Return a binary or shift operator constant expression, 1255 /// folding if possible. 1256 /// 1257 /// \param OnlyIfReducedTy see \a getWithOperands() docs. 1258 static Constant *get(unsigned Opcode, Constant *C1, Constant *C2, 1259 unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr); 1260 1261 /// Getelementptr form. Value* is only accepted for convenience; 1262 /// all elements must be Constants. 1263 /// 1264 /// \param InRange the inrange range if present or std::nullopt. 1265 /// \param OnlyIfReducedTy see \a getWithOperands() docs. 1266 static Constant * 1267 getGetElementPtr(Type *Ty, Constant *C, ArrayRef<Constant *> IdxList, 1268 GEPNoWrapFlags NW = GEPNoWrapFlags::none(), 1269 std::optional<ConstantRange> InRange = std::nullopt, 1270 Type *OnlyIfReducedTy = nullptr) { 1271 return getGetElementPtr( 1272 Ty, C, ArrayRef((Value *const *)IdxList.data(), IdxList.size()), NW, 1273 InRange, OnlyIfReducedTy); 1274 } 1275 static Constant * 1276 getGetElementPtr(Type *Ty, Constant *C, Constant *Idx, 1277 GEPNoWrapFlags NW = GEPNoWrapFlags::none(), 1278 std::optional<ConstantRange> InRange = std::nullopt, 1279 Type *OnlyIfReducedTy = nullptr) { 1280 // This form of the function only exists to avoid ambiguous overload 1281 // warnings about whether to convert Idx to ArrayRef<Constant *> or 1282 // ArrayRef<Value *>. 1283 return getGetElementPtr(Ty, C, cast<Value>(Idx), NW, InRange, 1284 OnlyIfReducedTy); 1285 } 1286 static Constant * 1287 getGetElementPtr(Type *Ty, Constant *C, ArrayRef<Value *> IdxList, 1288 GEPNoWrapFlags NW = GEPNoWrapFlags::none(), 1289 std::optional<ConstantRange> InRange = std::nullopt, 1290 Type *OnlyIfReducedTy = nullptr); 1291 1292 /// Create an "inbounds" getelementptr. See the documentation for the 1293 /// "inbounds" flag in LangRef.html for details. 1294 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C, 1295 ArrayRef<Constant *> IdxList) { 1296 return getGetElementPtr(Ty, C, IdxList, GEPNoWrapFlags::inBounds()); 1297 } 1298 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C, 1299 Constant *Idx) { 1300 // This form of the function only exists to avoid ambiguous overload 1301 // warnings about whether to convert Idx to ArrayRef<Constant *> or 1302 // ArrayRef<Value *>. 1303 return getGetElementPtr(Ty, C, Idx, GEPNoWrapFlags::inBounds()); 1304 } 1305 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C, 1306 ArrayRef<Value *> IdxList) { 1307 return getGetElementPtr(Ty, C, IdxList, GEPNoWrapFlags::inBounds()); 1308 } 1309 1310 static Constant *getExtractElement(Constant *Vec, Constant *Idx, 1311 Type *OnlyIfReducedTy = nullptr); 1312 static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, 1313 Type *OnlyIfReducedTy = nullptr); 1314 static Constant *getShuffleVector(Constant *V1, Constant *V2, 1315 ArrayRef<int> Mask, 1316 Type *OnlyIfReducedTy = nullptr); 1317 1318 /// Return the opcode at the root of this constant expression 1319 unsigned getOpcode() const { return getSubclassDataFromValue(); } 1320 1321 /// Assert that this is a shufflevector and return the mask. See class 1322 /// ShuffleVectorInst for a description of the mask representation. 1323 ArrayRef<int> getShuffleMask() const; 1324 1325 /// Assert that this is a shufflevector and return the mask. 1326 /// 1327 /// TODO: This is a temporary hack until we update the bitcode format for 1328 /// shufflevector. 1329 Constant *getShuffleMaskForBitcode() const; 1330 1331 /// Return a string representation for an opcode. 1332 const char *getOpcodeName() const; 1333 1334 /// This returns the current constant expression with the operands replaced 1335 /// with the specified values. The specified array must have the same number 1336 /// of operands as our current one. 1337 Constant *getWithOperands(ArrayRef<Constant *> Ops) const { 1338 return getWithOperands(Ops, getType()); 1339 } 1340 1341 /// Get the current expression with the operands replaced. 1342 /// 1343 /// Return the current constant expression with the operands replaced with \c 1344 /// Ops and the type with \c Ty. The new operands must have the same number 1345 /// as the current ones. 1346 /// 1347 /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something 1348 /// gets constant-folded, the type changes, or the expression is otherwise 1349 /// canonicalized. This parameter should almost always be \c false. 1350 Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty, 1351 bool OnlyIfReduced = false, 1352 Type *SrcTy = nullptr) const; 1353 1354 /// Returns an Instruction which implements the same operation as this 1355 /// ConstantExpr. It is not inserted into any basic block. 1356 /// 1357 /// A better approach to this could be to have a constructor for Instruction 1358 /// which would take a ConstantExpr parameter, but that would have spread 1359 /// implementation details of ConstantExpr outside of Constants.cpp, which 1360 /// would make it harder to remove ConstantExprs altogether. 1361 Instruction *getAsInstruction() const; 1362 1363 /// Whether creating a constant expression for this binary operator is 1364 /// desirable. 1365 static bool isDesirableBinOp(unsigned Opcode); 1366 1367 /// Whether creating a constant expression for this binary operator is 1368 /// supported. 1369 static bool isSupportedBinOp(unsigned Opcode); 1370 1371 /// Whether creating a constant expression for this cast is desirable. 1372 static bool isDesirableCastOp(unsigned Opcode); 1373 1374 /// Whether creating a constant expression for this cast is supported. 1375 static bool isSupportedCastOp(unsigned Opcode); 1376 1377 /// Whether creating a constant expression for this getelementptr type is 1378 /// supported. 1379 static bool isSupportedGetElementPtr(const Type *SrcElemTy) { 1380 return !SrcElemTy->isScalableTy(); 1381 } 1382 1383 /// Methods for support type inquiry through isa, cast, and dyn_cast: 1384 static bool classof(const Value *V) { 1385 return V->getValueID() == ConstantExprVal; 1386 } 1387 1388 private: 1389 // Shadow Value::setValueSubclassData with a private forwarding method so that 1390 // subclasses cannot accidentally use it. 1391 void setValueSubclassData(unsigned short D) { 1392 Value::setValueSubclassData(D); 1393 } 1394 }; 1395 1396 template <> 1397 struct OperandTraits<ConstantExpr> 1398 : public VariadicOperandTraits<ConstantExpr> {}; 1399 1400 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant) 1401 1402 //===----------------------------------------------------------------------===// 1403 /// 'undef' values are things that do not have specified contents. 1404 /// These are used for a variety of purposes, including global variable 1405 /// initializers and operands to instructions. 'undef' values can occur with 1406 /// any first-class type. 1407 /// 1408 /// Undef values aren't exactly constants; if they have multiple uses, they 1409 /// can appear to have different bit patterns at each use. See 1410 /// LangRef.html#undefvalues for details. 1411 /// 1412 class UndefValue : public ConstantData { 1413 friend class Constant; 1414 1415 explicit UndefValue(Type *T) : ConstantData(T, UndefValueVal) {} 1416 1417 void destroyConstantImpl(); 1418 1419 protected: 1420 explicit UndefValue(Type *T, ValueTy vty) : ConstantData(T, vty) {} 1421 1422 public: 1423 UndefValue(const UndefValue &) = delete; 1424 1425 /// Static factory methods - Return an 'undef' object of the specified type. 1426 static UndefValue *get(Type *T); 1427 1428 /// If this Undef has array or vector type, return a undef with the right 1429 /// element type. 1430 UndefValue *getSequentialElement() const; 1431 1432 /// If this undef has struct type, return a undef with the right element type 1433 /// for the specified element. 1434 UndefValue *getStructElement(unsigned Elt) const; 1435 1436 /// Return an undef of the right value for the specified GEP index if we can, 1437 /// otherwise return null (e.g. if C is a ConstantExpr). 1438 UndefValue *getElementValue(Constant *C) const; 1439 1440 /// Return an undef of the right value for the specified GEP index. 1441 UndefValue *getElementValue(unsigned Idx) const; 1442 1443 /// Return the number of elements in the array, vector, or struct. 1444 unsigned getNumElements() const; 1445 1446 /// Methods for support type inquiry through isa, cast, and dyn_cast: 1447 static bool classof(const Value *V) { 1448 return V->getValueID() == UndefValueVal || 1449 V->getValueID() == PoisonValueVal; 1450 } 1451 }; 1452 1453 //===----------------------------------------------------------------------===// 1454 /// In order to facilitate speculative execution, many instructions do not 1455 /// invoke immediate undefined behavior when provided with illegal operands, 1456 /// and return a poison value instead. 1457 /// 1458 /// see LangRef.html#poisonvalues for details. 1459 /// 1460 class PoisonValue final : public UndefValue { 1461 friend class Constant; 1462 1463 explicit PoisonValue(Type *T) : UndefValue(T, PoisonValueVal) {} 1464 1465 void destroyConstantImpl(); 1466 1467 public: 1468 PoisonValue(const PoisonValue &) = delete; 1469 1470 /// Static factory methods - Return an 'poison' object of the specified type. 1471 static PoisonValue *get(Type *T); 1472 1473 /// If this poison has array or vector type, return a poison with the right 1474 /// element type. 1475 PoisonValue *getSequentialElement() const; 1476 1477 /// If this poison has struct type, return a poison with the right element 1478 /// type for the specified element. 1479 PoisonValue *getStructElement(unsigned Elt) const; 1480 1481 /// Return an poison of the right value for the specified GEP index if we can, 1482 /// otherwise return null (e.g. if C is a ConstantExpr). 1483 PoisonValue *getElementValue(Constant *C) const; 1484 1485 /// Return an poison of the right value for the specified GEP index. 1486 PoisonValue *getElementValue(unsigned Idx) const; 1487 1488 /// Methods for support type inquiry through isa, cast, and dyn_cast: 1489 static bool classof(const Value *V) { 1490 return V->getValueID() == PoisonValueVal; 1491 } 1492 }; 1493 1494 } // end namespace llvm 1495 1496 #endif // LLVM_IR_CONSTANTS_H 1497