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