1 //===-- llvm/Constants.h - Constant class subclass definitions --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file contains the declarations for the subclasses of Constant,
12 /// which represent the different flavors of constant values that live in LLVM.
13 /// Note that Constants are immutable (once created they never change) and are
14 /// fully shared by structural equivalence. This means that two structurally
15 /// equivalent constants will always have the same address. Constants are
16 /// created on demand as needed and never deleted: thus clients don't have to
17 /// worry about the lifetime of the objects.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_IR_CONSTANTS_H
22 #define LLVM_IR_CONSTANTS_H
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/None.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/OperandTraits.h"
33 #include "llvm/IR/User.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/ErrorHandling.h"
50 template <class ConstantClass> struct ConstantAggrKeyType;
52 /// Base class for constants with no operands.
54 /// These constants have no operands; they represent their data directly.
55 /// Since they can be in use by unrelated modules (and are never based on
56 /// GlobalValues), it never makes sense to RAUW them.
57 class ConstantData : public Constant {
58 friend class Constant;
60 void anchor() override;
62 Value *handleOperandChangeImpl(Value *From, Value *To) {
63 llvm_unreachable("Constant data does not have operands!");
67 explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, nullptr, 0) {}
69 void *operator new(size_t s) { return User::operator new(s, 0); }
72 ConstantData() = delete;
73 ConstantData(const ConstantData &) = delete;
75 void *operator new(size_t, unsigned) = delete;
77 /// Methods to support type inquiry through isa, cast, and dyn_cast.
78 static bool classof(const Value *V) {
79 return V->getValueID() >= ConstantDataFirstVal &&
80 V->getValueID() <= ConstantDataLastVal;
84 //===----------------------------------------------------------------------===//
85 /// This is the shared class of boolean and integer constants. This class
86 /// represents both boolean and integral constants.
87 /// @brief Class for constant integers.
88 class ConstantInt final : public ConstantData {
89 friend class Constant;
93 ConstantInt(IntegerType *Ty, const APInt& V);
95 void anchor() override;
96 void destroyConstantImpl();
99 ConstantInt(const ConstantInt &) = delete;
101 static ConstantInt *getTrue(LLVMContext &Context);
102 static ConstantInt *getFalse(LLVMContext &Context);
103 static Constant *getTrue(Type *Ty);
104 static Constant *getFalse(Type *Ty);
106 /// If Ty is a vector type, return a Constant with a splat of the given
107 /// value. Otherwise return a ConstantInt for the given value.
108 static Constant *get(Type *Ty, uint64_t V, bool isSigned = false);
110 /// Return a ConstantInt with the specified integer value for the specified
111 /// type. If the type is wider than 64 bits, the value will be zero-extended
112 /// to fit the type, unless isSigned is true, in which case the value will
113 /// be interpreted as a 64-bit signed integer and sign-extended to fit
115 /// @brief Get a ConstantInt for a specific value.
116 static ConstantInt *get(IntegerType *Ty, uint64_t V,
117 bool isSigned = false);
119 /// Return a ConstantInt with the specified value for the specified type. The
120 /// value V will be canonicalized to a an unsigned APInt. Accessing it with
121 /// either getSExtValue() or getZExtValue() will yield a correctly sized and
122 /// signed value for the type Ty.
123 /// @brief Get a ConstantInt for a specific signed value.
124 static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
125 static Constant *getSigned(Type *Ty, int64_t V);
127 /// Return a ConstantInt with the specified value and an implied Type. The
128 /// type is the integer type that corresponds to the bit width of the value.
129 static ConstantInt *get(LLVMContext &Context, const APInt &V);
131 /// Return a ConstantInt constructed from the string strStart with the given
133 static ConstantInt *get(IntegerType *Ty, StringRef Str,
136 /// If Ty is a vector type, return a Constant with a splat of the given
137 /// value. Otherwise return a ConstantInt for the given value.
138 static Constant *get(Type* Ty, const APInt& V);
140 /// Return the constant as an APInt value reference. This allows clients to
141 /// obtain a copy of the value, with all its precision in tact.
142 /// @brief Return the constant's value.
143 inline const APInt &getValue() const {
147 /// getBitWidth - Return the bitwidth of this constant.
148 unsigned getBitWidth() const { return Val.getBitWidth(); }
150 /// Return the constant as a 64-bit unsigned integer value after it
151 /// has been zero extended as appropriate for the type of this constant. Note
152 /// that this method can assert if the value does not fit in 64 bits.
153 /// @brief Return the zero extended value.
154 inline uint64_t getZExtValue() const {
155 return Val.getZExtValue();
158 /// Return the constant as a 64-bit integer value after it has been sign
159 /// extended as appropriate for the type of this constant. Note that
160 /// this method can assert if the value does not fit in 64 bits.
161 /// @brief Return the sign extended value.
162 inline int64_t getSExtValue() const {
163 return Val.getSExtValue();
166 /// A helper method that can be used to determine if the constant contained
167 /// within is equal to a constant. This only works for very small values,
168 /// because this is all that can be represented with all types.
169 /// @brief Determine if this constant's value is same as an unsigned char.
170 bool equalsInt(uint64_t V) const {
174 /// getType - Specialize the getType() method to always return an IntegerType,
175 /// which reduces the amount of casting needed in parts of the compiler.
177 inline IntegerType *getType() const {
178 return cast<IntegerType>(Value::getType());
181 /// This static method returns true if the type Ty is big enough to
182 /// represent the value V. This can be used to avoid having the get method
183 /// assert when V is larger than Ty can represent. Note that there are two
184 /// versions of this method, one for unsigned and one for signed integers.
185 /// Although ConstantInt canonicalizes everything to an unsigned integer,
186 /// the signed version avoids callers having to convert a signed quantity
187 /// to the appropriate unsigned type before calling the method.
188 /// @returns true if V is a valid value for type Ty
189 /// @brief Determine if the value is in range for the given type.
190 static bool isValueValidForType(Type *Ty, uint64_t V);
191 static bool isValueValidForType(Type *Ty, int64_t V);
193 bool isNegative() const { return Val.isNegative(); }
195 /// This is just a convenience method to make client code smaller for a
196 /// common code. It also correctly performs the comparison without the
197 /// potential for an assertion from getZExtValue().
198 bool isZero() const {
202 /// This is just a convenience method to make client code smaller for a
203 /// common case. It also correctly performs the comparison without the
204 /// potential for an assertion from getZExtValue().
205 /// @brief Determine if the value is one.
210 /// This function will return true iff every bit in this constant is set
212 /// @returns true iff this constant's bits are all set to true.
213 /// @brief Determine if the value is all ones.
214 bool isMinusOne() const {
215 return Val.isAllOnesValue();
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
222 /// @brief Determine if the value is maximal.
223 bool isMaxValue(bool isSigned) const {
225 return Val.isMaxSignedValue();
227 return Val.isMaxValue();
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
234 /// @brief Determine if the value is minimal.
235 bool isMinValue(bool isSigned) const {
237 return Val.isMinSignedValue();
239 return Val.isMinValue();
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
245 /// @returns true iff this constant is greater or equal to the given number.
246 /// @brief Determine if the value is greater or equal to the given number.
247 bool uge(uint64_t Num) const {
248 return Val.getActiveBits() > 64 || Val.getZExtValue() >= Num;
251 /// getLimitedValue - If the value is smaller than the specified limit,
252 /// return it, otherwise return the limit value. This causes the value
253 /// to saturate to the limit.
254 /// @returns the min of the value of the constant and the specified value
255 /// @brief Get the constant's value with a saturation limit
256 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
257 return Val.getLimitedValue(Limit);
260 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
261 static bool classof(const Value *V) {
262 return V->getValueID() == ConstantIntVal;
266 //===----------------------------------------------------------------------===//
267 /// ConstantFP - Floating Point Values [float, double]
269 class ConstantFP final : public ConstantData {
270 friend class Constant;
274 ConstantFP(Type *Ty, const APFloat& V);
276 void anchor() override;
277 void destroyConstantImpl();
280 ConstantFP(const ConstantFP &) = delete;
282 /// Floating point negation must be implemented with f(x) = -0.0 - x. This
283 /// method returns the negative zero constant for floating point or vector
284 /// floating point types; for all other types, it returns the null value.
285 static Constant *getZeroValueForNegation(Type *Ty);
287 /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP,
288 /// for the specified value in the specified type. This should only be used
289 /// for simple constant values like 2.0/1.0 etc, that are known-valid both as
290 /// host double and as the target format.
291 static Constant *get(Type* Ty, double V);
292 static Constant *get(Type* Ty, StringRef Str);
293 static ConstantFP *get(LLVMContext &Context, const APFloat &V);
294 static Constant *getNaN(Type *Ty, bool Negative = false, unsigned type = 0);
295 static Constant *getNegativeZero(Type *Ty);
296 static Constant *getInfinity(Type *Ty, bool Negative = false);
298 /// Return true if Ty is big enough to represent V.
299 static bool isValueValidForType(Type *Ty, const APFloat &V);
300 inline const APFloat &getValueAPF() const { return Val; }
302 /// Return true if the value is positive or negative zero.
303 bool isZero() const { return Val.isZero(); }
305 /// Return true if the sign bit is set.
306 bool isNegative() const { return Val.isNegative(); }
308 /// Return true if the value is infinity
309 bool isInfinity() const { return Val.isInfinity(); }
311 /// Return true if the value is a NaN.
312 bool isNaN() const { return Val.isNaN(); }
314 /// We don't rely on operator== working on double values, as it returns true
315 /// for things that are clearly not equal, like -0.0 and 0.0.
316 /// As such, this method can be used to do an exact bit-for-bit comparison of
317 /// two floating point values. The version with a double operand is retained
318 /// because it's so convenient to write isExactlyValue(2.0), but please use
319 /// it only for simple constants.
320 bool isExactlyValue(const APFloat &V) const;
322 bool isExactlyValue(double V) const {
325 FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
326 return isExactlyValue(FV);
329 /// Methods for support type inquiry through isa, cast, and dyn_cast:
330 static bool classof(const Value *V) {
331 return V->getValueID() == ConstantFPVal;
335 //===----------------------------------------------------------------------===//
336 /// All zero aggregate value
338 class ConstantAggregateZero final : public ConstantData {
339 friend class Constant;
341 explicit ConstantAggregateZero(Type *Ty)
342 : ConstantData(Ty, ConstantAggregateZeroVal) {}
344 void destroyConstantImpl();
347 ConstantAggregateZero(const ConstantAggregateZero &) = delete;
349 static ConstantAggregateZero *get(Type *Ty);
351 /// If this CAZ has array or vector type, return a zero with the right element
353 Constant *getSequentialElement() const;
355 /// If this CAZ has struct type, return a zero with the right element type for
356 /// the specified element.
357 Constant *getStructElement(unsigned Elt) const;
359 /// Return a zero of the right value for the specified GEP index if we can,
360 /// otherwise return null (e.g. if C is a ConstantExpr).
361 Constant *getElementValue(Constant *C) const;
363 /// Return a zero of the right value for the specified GEP index.
364 Constant *getElementValue(unsigned Idx) const;
366 /// Return the number of elements in the array, vector, or struct.
367 unsigned getNumElements() const;
369 /// Methods for support type inquiry through isa, cast, and dyn_cast:
371 static bool classof(const Value *V) {
372 return V->getValueID() == ConstantAggregateZeroVal;
376 /// Base class for aggregate constants (with operands).
378 /// These constants are aggregates of other constants, which are stored as
381 /// Subclasses are \a ConstantStruct, \a ConstantArray, and \a
384 /// \note Some subclasses of \a ConstantData are semantically aggregates --
385 /// such as \a ConstantDataArray -- but are not subclasses of this because they
387 class ConstantAggregate : public Constant {
389 ConstantAggregate(CompositeType *T, ValueTy VT, ArrayRef<Constant *> V);
392 /// Transparently provide more efficient getOperand methods.
393 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
395 /// Methods for support type inquiry through isa, cast, and dyn_cast:
396 static bool classof(const Value *V) {
397 return V->getValueID() >= ConstantAggregateFirstVal &&
398 V->getValueID() <= ConstantAggregateLastVal;
403 struct OperandTraits<ConstantAggregate>
404 : public VariadicOperandTraits<ConstantAggregate> {};
406 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantAggregate, Constant)
408 //===----------------------------------------------------------------------===//
409 /// ConstantArray - Constant Array Declarations
411 class ConstantArray final : public ConstantAggregate {
412 friend struct ConstantAggrKeyType<ConstantArray>;
413 friend class Constant;
415 ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
417 void destroyConstantImpl();
418 Value *handleOperandChangeImpl(Value *From, Value *To);
421 // ConstantArray accessors
422 static Constant *get(ArrayType *T, ArrayRef<Constant*> V);
425 static Constant *getImpl(ArrayType *T, ArrayRef<Constant *> V);
428 /// Specialize the getType() method to always return an ArrayType,
429 /// which reduces the amount of casting needed in parts of the compiler.
430 inline ArrayType *getType() const {
431 return cast<ArrayType>(Value::getType());
434 /// Methods for support type inquiry through isa, cast, and dyn_cast:
435 static bool classof(const Value *V) {
436 return V->getValueID() == ConstantArrayVal;
440 //===----------------------------------------------------------------------===//
441 // Constant Struct Declarations
443 class ConstantStruct final : public ConstantAggregate {
444 friend struct ConstantAggrKeyType<ConstantStruct>;
445 friend class Constant;
447 ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
449 void destroyConstantImpl();
450 Value *handleOperandChangeImpl(Value *From, Value *To);
453 // ConstantStruct accessors
454 static Constant *get(StructType *T, ArrayRef<Constant*> V);
455 static Constant *get(StructType *T, ...) LLVM_END_WITH_NULL;
457 /// Return an anonymous struct that has the specified elements.
458 /// If the struct is possibly empty, then you must specify a context.
459 static Constant *getAnon(ArrayRef<Constant*> V, bool Packed = false) {
460 return get(getTypeForElements(V, Packed), V);
462 static Constant *getAnon(LLVMContext &Ctx,
463 ArrayRef<Constant*> V, bool Packed = false) {
464 return get(getTypeForElements(Ctx, V, Packed), V);
467 /// Return an anonymous struct type to use for a constant with the specified
468 /// set of elements. The list must not be empty.
469 static StructType *getTypeForElements(ArrayRef<Constant*> V,
470 bool Packed = false);
471 /// This version of the method allows an empty list.
472 static StructType *getTypeForElements(LLVMContext &Ctx,
473 ArrayRef<Constant*> V,
474 bool Packed = false);
476 /// Specialization - reduce amount of casting.
477 inline StructType *getType() const {
478 return cast<StructType>(Value::getType());
481 /// Methods for support type inquiry through isa, cast, and dyn_cast:
482 static bool classof(const Value *V) {
483 return V->getValueID() == ConstantStructVal;
487 //===----------------------------------------------------------------------===//
488 /// Constant Vector Declarations
490 class ConstantVector final : public ConstantAggregate {
491 friend struct ConstantAggrKeyType<ConstantVector>;
492 friend class Constant;
494 ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
496 void destroyConstantImpl();
497 Value *handleOperandChangeImpl(Value *From, Value *To);
500 // ConstantVector accessors
501 static Constant *get(ArrayRef<Constant*> V);
504 static Constant *getImpl(ArrayRef<Constant *> V);
507 /// Return a ConstantVector with the specified constant in each element.
508 static Constant *getSplat(unsigned NumElts, Constant *Elt);
510 /// Specialize the getType() method to always return a VectorType,
511 /// which reduces the amount of casting needed in parts of the compiler.
512 inline VectorType *getType() const {
513 return cast<VectorType>(Value::getType());
516 /// If this is a splat constant, meaning that all of the elements have the
517 /// same value, return that value. Otherwise return NULL.
518 Constant *getSplatValue() const;
520 /// Methods for support type inquiry through isa, cast, and dyn_cast:
521 static bool classof(const Value *V) {
522 return V->getValueID() == ConstantVectorVal;
526 //===----------------------------------------------------------------------===//
527 /// A constant pointer value that points to null
529 class ConstantPointerNull final : public ConstantData {
530 friend class Constant;
532 explicit ConstantPointerNull(PointerType *T)
533 : ConstantData(T, Value::ConstantPointerNullVal) {}
535 void destroyConstantImpl();
538 ConstantPointerNull(const ConstantPointerNull &) = delete;
540 /// Static factory methods - Return objects of the specified value
541 static ConstantPointerNull *get(PointerType *T);
543 /// Specialize the getType() method to always return an PointerType,
544 /// which reduces the amount of casting needed in parts of the compiler.
545 inline PointerType *getType() const {
546 return cast<PointerType>(Value::getType());
549 /// Methods for support type inquiry through isa, cast, and dyn_cast:
550 static bool classof(const Value *V) {
551 return V->getValueID() == ConstantPointerNullVal;
555 //===----------------------------------------------------------------------===//
556 /// ConstantDataSequential - A vector or array constant whose element type is a
557 /// simple 1/2/4/8-byte integer or float/double, and whose elements are just
558 /// simple data values (i.e. ConstantInt/ConstantFP). This Constant node has no
559 /// operands because it stores all of the elements of the constant as densely
560 /// packed data, instead of as Value*'s.
562 /// This is the common base class of ConstantDataArray and ConstantDataVector.
564 class ConstantDataSequential : public ConstantData {
565 friend class LLVMContextImpl;
566 friend class Constant;
568 /// A pointer to the bytes underlying this constant (which is owned by the
569 /// uniquing StringMap).
570 const char *DataElements;
572 /// This forms a link list of ConstantDataSequential nodes that have
573 /// the same value but different type. For example, 0,0,0,1 could be a 4
574 /// element array of i8, or a 1-element array of i32. They'll both end up in
575 /// the same StringMap bucket, linked up.
576 ConstantDataSequential *Next;
578 void destroyConstantImpl();
581 explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
582 : ConstantData(ty, VT), DataElements(Data), Next(nullptr) {}
583 ~ConstantDataSequential() override { delete Next; }
585 static Constant *getImpl(StringRef Bytes, Type *Ty);
588 ConstantDataSequential(const ConstantDataSequential &) = delete;
590 /// Return true if a ConstantDataSequential can be formed with a vector or
591 /// array of the specified element type.
592 /// ConstantDataArray only works with normal float and int types that are
593 /// stored densely in memory, not with things like i42 or x86_f80.
594 static bool isElementTypeCompatible(Type *Ty);
596 /// If this is a sequential container of integers (of any size), return the
597 /// specified element in the low bits of a uint64_t.
598 uint64_t getElementAsInteger(unsigned i) const;
600 /// If this is a sequential container of floating point type, return the
601 /// specified element as an APFloat.
602 APFloat getElementAsAPFloat(unsigned i) const;
604 /// If this is an sequential container of floats, return the specified element
606 float getElementAsFloat(unsigned i) const;
608 /// If this is an sequential container of doubles, return the specified
609 /// element as a double.
610 double getElementAsDouble(unsigned i) const;
612 /// Return a Constant for a specified index's element.
613 /// Note that this has to compute a new constant to return, so it isn't as
614 /// efficient as getElementAsInteger/Float/Double.
615 Constant *getElementAsConstant(unsigned i) const;
617 /// Specialize the getType() method to always return a SequentialType, which
618 /// reduces the amount of casting needed in parts of the compiler.
619 inline SequentialType *getType() const {
620 return cast<SequentialType>(Value::getType());
623 /// Return the element type of the array/vector.
624 Type *getElementType() const;
626 /// Return the number of elements in the array or vector.
627 unsigned getNumElements() const;
629 /// Return the size (in bytes) of each element in the array/vector.
630 /// The size of the elements is known to be a multiple of one byte.
631 uint64_t getElementByteSize() const;
633 /// This method returns true if this is an array of i8.
634 bool isString() const;
636 /// This method returns true if the array "isString", ends with a null byte,
637 /// and does not contains any other null bytes.
638 bool isCString() const;
640 /// If this array is isString(), then this method returns the array as a
641 /// StringRef. Otherwise, it asserts out.
642 StringRef getAsString() const {
643 assert(isString() && "Not a string");
644 return getRawDataValues();
647 /// If this array is isCString(), then this method returns the array (without
648 /// the trailing null byte) as a StringRef. Otherwise, it asserts out.
649 StringRef getAsCString() const {
650 assert(isCString() && "Isn't a C string");
651 StringRef Str = getAsString();
652 return Str.substr(0, Str.size()-1);
655 /// Return the raw, underlying, bytes of this data. Note that this is an
656 /// extremely tricky thing to work with, as it exposes the host endianness of
657 /// the data elements.
658 StringRef getRawDataValues() const;
660 /// Methods for support type inquiry through isa, cast, and dyn_cast:
661 static bool classof(const Value *V) {
662 return V->getValueID() == ConstantDataArrayVal ||
663 V->getValueID() == ConstantDataVectorVal;
667 const char *getElementPointer(unsigned Elt) const;
670 //===----------------------------------------------------------------------===//
671 /// An array constant whose element type is a simple 1/2/4/8-byte integer or
672 /// float/double, and whose elements are just simple data values
673 /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
674 /// stores all of the elements of the constant as densely packed data, instead
676 class ConstantDataArray final : public ConstantDataSequential {
677 friend class ConstantDataSequential;
679 explicit ConstantDataArray(Type *ty, const char *Data)
680 : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
682 /// Allocate space for exactly zero operands.
683 void *operator new(size_t s) {
684 return User::operator new(s, 0);
687 void anchor() override;
690 ConstantDataArray(const ConstantDataArray &) = delete;
692 void *operator new(size_t, unsigned) = delete;
694 /// get() constructors - Return a constant with array type with an element
695 /// count and element type matching the ArrayRef passed in. Note that this
696 /// can return a ConstantAggregateZero object.
697 static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
698 static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
699 static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
700 static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
701 static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
702 static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
704 /// getFP() constructors - Return a constant with array type with an element
705 /// count and element type of float with precision matching the number of
706 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
707 /// double for 64bits) Note that this can return a ConstantAggregateZero
709 static Constant *getFP(LLVMContext &Context, ArrayRef<uint16_t> Elts);
710 static Constant *getFP(LLVMContext &Context, ArrayRef<uint32_t> Elts);
711 static Constant *getFP(LLVMContext &Context, ArrayRef<uint64_t> Elts);
713 /// This method constructs a CDS and initializes it with a text string.
714 /// The default behavior (AddNull==true) causes a null terminator to
715 /// be placed at the end of the array (increasing the length of the string by
716 /// one more than the StringRef would normally indicate. Pass AddNull=false
717 /// to disable this behavior.
718 static Constant *getString(LLVMContext &Context, StringRef Initializer,
719 bool AddNull = true);
721 /// Specialize the getType() method to always return an ArrayType,
722 /// which reduces the amount of casting needed in parts of the compiler.
723 inline ArrayType *getType() const {
724 return cast<ArrayType>(Value::getType());
727 /// Methods for support type inquiry through isa, cast, and dyn_cast:
728 static bool classof(const Value *V) {
729 return V->getValueID() == ConstantDataArrayVal;
733 //===----------------------------------------------------------------------===//
734 /// A vector constant whose element type is a simple 1/2/4/8-byte integer or
735 /// float/double, and whose elements are just simple data values
736 /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
737 /// stores all of the elements of the constant as densely packed data, instead
739 class ConstantDataVector final : public ConstantDataSequential {
740 friend class ConstantDataSequential;
742 explicit ConstantDataVector(Type *ty, const char *Data)
743 : ConstantDataSequential(ty, ConstantDataVectorVal, Data) {}
745 // allocate space for exactly zero operands.
746 void *operator new(size_t s) {
747 return User::operator new(s, 0);
750 void anchor() override;
753 ConstantDataVector(const ConstantDataVector &) = delete;
755 void *operator new(size_t, unsigned) = delete;
757 /// get() constructors - Return a constant with vector type with an element
758 /// count and element type matching the ArrayRef passed in. Note that this
759 /// can return a ConstantAggregateZero object.
760 static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
761 static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
762 static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
763 static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
764 static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
765 static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
767 /// getFP() constructors - Return a constant with vector type with an element
768 /// count and element type of float with the precision matching the number of
769 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
770 /// double for 64bits) Note that this can return a ConstantAggregateZero
772 static Constant *getFP(LLVMContext &Context, ArrayRef<uint16_t> Elts);
773 static Constant *getFP(LLVMContext &Context, ArrayRef<uint32_t> Elts);
774 static Constant *getFP(LLVMContext &Context, ArrayRef<uint64_t> Elts);
776 /// Return a ConstantVector with the specified constant in each element.
777 /// The specified constant has to be a of a compatible type (i8/i16/
778 /// i32/i64/float/double) and must be a ConstantFP or ConstantInt.
779 static Constant *getSplat(unsigned NumElts, Constant *Elt);
781 /// If this is a splat constant, meaning that all of the elements have the
782 /// same value, return that value. Otherwise return NULL.
783 Constant *getSplatValue() const;
785 /// Specialize the getType() method to always return a VectorType,
786 /// which reduces the amount of casting needed in parts of the compiler.
787 inline VectorType *getType() const {
788 return cast<VectorType>(Value::getType());
791 /// Methods for support type inquiry through isa, cast, and dyn_cast:
792 static bool classof(const Value *V) {
793 return V->getValueID() == ConstantDataVectorVal;
797 //===----------------------------------------------------------------------===//
798 /// A constant token which is empty
800 class ConstantTokenNone final : public ConstantData {
801 friend class Constant;
803 explicit ConstantTokenNone(LLVMContext &Context)
804 : ConstantData(Type::getTokenTy(Context), ConstantTokenNoneVal) {}
806 void destroyConstantImpl();
809 ConstantTokenNone(const ConstantTokenNone &) = delete;
811 /// Return the ConstantTokenNone.
812 static ConstantTokenNone *get(LLVMContext &Context);
814 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
815 static bool classof(const Value *V) {
816 return V->getValueID() == ConstantTokenNoneVal;
820 /// The address of a basic block.
822 class BlockAddress final : public Constant {
823 friend class Constant;
825 BlockAddress(Function *F, BasicBlock *BB);
827 void *operator new(size_t s) { return User::operator new(s, 2); }
829 void destroyConstantImpl();
830 Value *handleOperandChangeImpl(Value *From, Value *To);
833 void *operator new(size_t, unsigned) = delete;
835 /// Return a BlockAddress for the specified function and basic block.
836 static BlockAddress *get(Function *F, BasicBlock *BB);
838 /// Return a BlockAddress for the specified basic block. The basic
839 /// block must be embedded into a function.
840 static BlockAddress *get(BasicBlock *BB);
842 /// Lookup an existing \c BlockAddress constant for the given BasicBlock.
844 /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress.
845 static BlockAddress *lookup(const BasicBlock *BB);
847 /// Transparently provide more efficient getOperand methods.
848 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
850 Function *getFunction() const { return (Function*)Op<0>().get(); }
851 BasicBlock *getBasicBlock() const { return (BasicBlock*)Op<1>().get(); }
853 /// Methods for support type inquiry through isa, cast, and dyn_cast:
854 static inline bool classof(const Value *V) {
855 return V->getValueID() == BlockAddressVal;
860 struct OperandTraits<BlockAddress> :
861 public FixedNumOperandTraits<BlockAddress, 2> {
864 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)
866 //===----------------------------------------------------------------------===//
867 /// A constant value that is initialized with an expression using
868 /// other constant values.
870 /// This class uses the standard Instruction opcodes to define the various
871 /// constant expressions. The Opcode field for the ConstantExpr class is
872 /// maintained in the Value::SubclassData field.
873 class ConstantExpr : public Constant {
874 friend struct ConstantExprKeyType;
875 friend class Constant;
877 void destroyConstantImpl();
878 Value *handleOperandChangeImpl(Value *From, Value *To);
881 ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
882 : Constant(ty, ConstantExprVal, Ops, NumOps) {
883 // Operation type (an Instruction opcode) is stored as the SubclassData.
884 setValueSubclassData(Opcode);
888 // Static methods to construct a ConstantExpr of different kinds. Note that
889 // these methods may return a object that is not an instance of the
890 // ConstantExpr class, because they will attempt to fold the constant
891 // expression into something simpler if possible.
893 /// getAlignOf constant expr - computes the alignment of a type in a target
894 /// independent way (Note: the return type is an i64).
895 static Constant *getAlignOf(Type *Ty);
897 /// getSizeOf constant expr - computes the (alloc) size of a type (in
898 /// address-units, not bits) in a target independent way (Note: the return
901 static Constant *getSizeOf(Type *Ty);
903 /// getOffsetOf constant expr - computes the offset of a struct field in a
904 /// target independent way (Note: the return type is an i64).
906 static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
908 /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
909 /// which supports any aggregate type, and any Constant index.
911 static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
913 static Constant *getNeg(Constant *C, bool HasNUW = false, bool HasNSW =false);
914 static Constant *getFNeg(Constant *C);
915 static Constant *getNot(Constant *C);
916 static Constant *getAdd(Constant *C1, Constant *C2,
917 bool HasNUW = false, bool HasNSW = false);
918 static Constant *getFAdd(Constant *C1, Constant *C2);
919 static Constant *getSub(Constant *C1, Constant *C2,
920 bool HasNUW = false, bool HasNSW = false);
921 static Constant *getFSub(Constant *C1, Constant *C2);
922 static Constant *getMul(Constant *C1, Constant *C2,
923 bool HasNUW = false, bool HasNSW = false);
924 static Constant *getFMul(Constant *C1, Constant *C2);
925 static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false);
926 static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false);
927 static Constant *getFDiv(Constant *C1, Constant *C2);
928 static Constant *getURem(Constant *C1, Constant *C2);
929 static Constant *getSRem(Constant *C1, Constant *C2);
930 static Constant *getFRem(Constant *C1, Constant *C2);
931 static Constant *getAnd(Constant *C1, Constant *C2);
932 static Constant *getOr(Constant *C1, Constant *C2);
933 static Constant *getXor(Constant *C1, Constant *C2);
934 static Constant *getShl(Constant *C1, Constant *C2,
935 bool HasNUW = false, bool HasNSW = false);
936 static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
937 static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
938 static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false);
939 static Constant *getSExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
940 static Constant *getZExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
941 static Constant *getFPTrunc(Constant *C, Type *Ty,
942 bool OnlyIfReduced = false);
943 static Constant *getFPExtend(Constant *C, Type *Ty,
944 bool OnlyIfReduced = false);
945 static Constant *getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
946 static Constant *getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
947 static Constant *getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
948 static Constant *getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
949 static Constant *getPtrToInt(Constant *C, Type *Ty,
950 bool OnlyIfReduced = false);
951 static Constant *getIntToPtr(Constant *C, Type *Ty,
952 bool OnlyIfReduced = false);
953 static Constant *getBitCast(Constant *C, Type *Ty,
954 bool OnlyIfReduced = false);
955 static Constant *getAddrSpaceCast(Constant *C, Type *Ty,
956 bool OnlyIfReduced = false);
958 static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
959 static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
961 static Constant *getNSWAdd(Constant *C1, Constant *C2) {
962 return getAdd(C1, C2, false, true);
965 static Constant *getNUWAdd(Constant *C1, Constant *C2) {
966 return getAdd(C1, C2, true, false);
969 static Constant *getNSWSub(Constant *C1, Constant *C2) {
970 return getSub(C1, C2, false, true);
973 static Constant *getNUWSub(Constant *C1, Constant *C2) {
974 return getSub(C1, C2, true, false);
977 static Constant *getNSWMul(Constant *C1, Constant *C2) {
978 return getMul(C1, C2, false, true);
981 static Constant *getNUWMul(Constant *C1, Constant *C2) {
982 return getMul(C1, C2, true, false);
985 static Constant *getNSWShl(Constant *C1, Constant *C2) {
986 return getShl(C1, C2, false, true);
989 static Constant *getNUWShl(Constant *C1, Constant *C2) {
990 return getShl(C1, C2, true, false);
993 static Constant *getExactSDiv(Constant *C1, Constant *C2) {
994 return getSDiv(C1, C2, true);
997 static Constant *getExactUDiv(Constant *C1, Constant *C2) {
998 return getUDiv(C1, C2, true);
1001 static Constant *getExactAShr(Constant *C1, Constant *C2) {
1002 return getAShr(C1, C2, true);
1005 static Constant *getExactLShr(Constant *C1, Constant *C2) {
1006 return getLShr(C1, C2, true);
1009 /// Return the identity for the given binary operation,
1010 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
1011 /// returns null if the operator doesn't have an identity.
1012 static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty);
1014 /// Return the absorbing element for the given binary
1015 /// operation, i.e. a constant C such that X op C = C and C op X = C for
1016 /// every X. For example, this returns zero for integer multiplication.
1017 /// It returns null if the operator doesn't have an absorbing element.
1018 static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
1020 /// Transparently provide more efficient getOperand methods.
1021 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
1023 /// \brief Convenience function for getting a Cast operation.
1025 /// \param ops The opcode for the conversion
1026 /// \param C The constant to be converted
1027 /// \param Ty The type to which the constant is converted
1028 /// \param OnlyIfReduced see \a getWithOperands() docs.
1029 static Constant *getCast(unsigned ops, Constant *C, Type *Ty,
1030 bool OnlyIfReduced = false);
1032 // @brief Create a ZExt or BitCast cast constant expression
1033 static Constant *getZExtOrBitCast(
1034 Constant *C, ///< The constant to zext or bitcast
1035 Type *Ty ///< The type to zext or bitcast C to
1038 // @brief Create a SExt or BitCast cast constant expression
1039 static Constant *getSExtOrBitCast(
1040 Constant *C, ///< The constant to sext or bitcast
1041 Type *Ty ///< The type to sext or bitcast C to
1044 // @brief Create a Trunc or BitCast cast constant expression
1045 static Constant *getTruncOrBitCast(
1046 Constant *C, ///< The constant to trunc or bitcast
1047 Type *Ty ///< The type to trunc or bitcast C to
1050 /// @brief Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant
1052 static Constant *getPointerCast(
1053 Constant *C, ///< The pointer value to be casted (operand 0)
1054 Type *Ty ///< The type to which cast should be made
1057 /// @brief Create a BitCast or AddrSpaceCast for a pointer type depending on
1058 /// the address space.
1059 static Constant *getPointerBitCastOrAddrSpaceCast(
1060 Constant *C, ///< The constant to addrspacecast or bitcast
1061 Type *Ty ///< The type to bitcast or addrspacecast C to
1064 /// @brief Create a ZExt, Bitcast or Trunc for integer -> integer casts
1065 static Constant *getIntegerCast(
1066 Constant *C, ///< The integer constant to be casted
1067 Type *Ty, ///< The integer type to cast to
1068 bool isSigned ///< Whether C should be treated as signed or not
1071 /// @brief Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
1072 static Constant *getFPCast(
1073 Constant *C, ///< The integer constant to be casted
1074 Type *Ty ///< The integer type to cast to
1077 /// @brief Return true if this is a convert constant expression
1078 bool isCast() const;
1080 /// @brief Return true if this is a compare constant expression
1081 bool isCompare() const;
1083 /// @brief Return true if this is an insertvalue or extractvalue expression,
1084 /// and the getIndices() method may be used.
1085 bool hasIndices() const;
1087 /// @brief Return true if this is a getelementptr expression and all
1088 /// the index operands are compile-time known integers within the
1089 /// corresponding notional static array extents. Note that this is
1090 /// not equivalant to, a subset of, or a superset of the "inbounds"
1092 bool isGEPWithNoNotionalOverIndexing() const;
1094 /// Select constant expr
1096 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1097 static Constant *getSelect(Constant *C, Constant *V1, Constant *V2,
1098 Type *OnlyIfReducedTy = nullptr);
1100 /// get - Return a binary or shift operator constant expression,
1101 /// folding if possible.
1103 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1104 static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
1105 unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr);
1107 /// \brief Return an ICmp or FCmp comparison operator constant expression.
1109 /// \param OnlyIfReduced see \a getWithOperands() docs.
1110 static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2,
1111 bool OnlyIfReduced = false);
1113 /// get* - Return some common constants without having to
1114 /// specify the full Instruction::OPCODE identifier.
1116 static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS,
1117 bool OnlyIfReduced = false);
1118 static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS,
1119 bool OnlyIfReduced = false);
1121 /// Getelementptr form. Value* is only accepted for convenience;
1122 /// all elements must be Constants.
1124 /// \param InRangeIndex the inrange index if present or None.
1125 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1126 static Constant *getGetElementPtr(Type *Ty, Constant *C,
1127 ArrayRef<Constant *> IdxList,
1128 bool InBounds = false,
1129 Optional<unsigned> InRangeIndex = None,
1130 Type *OnlyIfReducedTy = nullptr) {
1131 return getGetElementPtr(
1132 Ty, C, makeArrayRef((Value * const *)IdxList.data(), IdxList.size()),
1133 InBounds, InRangeIndex, OnlyIfReducedTy);
1135 static Constant *getGetElementPtr(Type *Ty, Constant *C, Constant *Idx,
1136 bool InBounds = false,
1137 Optional<unsigned> InRangeIndex = None,
1138 Type *OnlyIfReducedTy = nullptr) {
1139 // This form of the function only exists to avoid ambiguous overload
1140 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1141 // ArrayRef<Value *>.
1142 return getGetElementPtr(Ty, C, cast<Value>(Idx), InBounds, InRangeIndex,
1145 static Constant *getGetElementPtr(Type *Ty, Constant *C,
1146 ArrayRef<Value *> IdxList,
1147 bool InBounds = false,
1148 Optional<unsigned> InRangeIndex = None,
1149 Type *OnlyIfReducedTy = nullptr);
1151 /// Create an "inbounds" getelementptr. See the documentation for the
1152 /// "inbounds" flag in LangRef.html for details.
1153 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1154 ArrayRef<Constant *> IdxList) {
1155 return getGetElementPtr(Ty, C, IdxList, true);
1157 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1159 // This form of the function only exists to avoid ambiguous overload
1160 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1161 // ArrayRef<Value *>.
1162 return getGetElementPtr(Ty, C, Idx, true);
1164 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1165 ArrayRef<Value *> IdxList) {
1166 return getGetElementPtr(Ty, C, IdxList, true);
1169 static Constant *getExtractElement(Constant *Vec, Constant *Idx,
1170 Type *OnlyIfReducedTy = nullptr);
1171 static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx,
1172 Type *OnlyIfReducedTy = nullptr);
1173 static Constant *getShuffleVector(Constant *V1, Constant *V2, Constant *Mask,
1174 Type *OnlyIfReducedTy = nullptr);
1175 static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
1176 Type *OnlyIfReducedTy = nullptr);
1177 static Constant *getInsertValue(Constant *Agg, Constant *Val,
1178 ArrayRef<unsigned> Idxs,
1179 Type *OnlyIfReducedTy = nullptr);
1181 /// Return the opcode at the root of this constant expression
1182 unsigned getOpcode() const { return getSubclassDataFromValue(); }
1184 /// Return the ICMP or FCMP predicate value. Assert if this is not an ICMP or
1185 /// FCMP constant expression.
1186 unsigned getPredicate() const;
1188 /// Assert that this is an insertvalue or exactvalue
1189 /// expression and return the list of indices.
1190 ArrayRef<unsigned> getIndices() const;
1192 /// Return a string representation for an opcode.
1193 const char *getOpcodeName() const;
1195 /// Return a constant expression identical to this one, but with the specified
1196 /// operand set to the specified value.
1197 Constant *getWithOperandReplaced(unsigned OpNo, Constant *Op) const;
1199 /// This returns the current constant expression with the operands replaced
1200 /// with the specified values. The specified array must have the same number
1201 /// of operands as our current one.
1202 Constant *getWithOperands(ArrayRef<Constant*> Ops) const {
1203 return getWithOperands(Ops, getType());
1206 /// Get the current expression with the operands replaced.
1208 /// Return the current constant expression with the operands replaced with \c
1209 /// Ops and the type with \c Ty. The new operands must have the same number
1210 /// as the current ones.
1212 /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something
1213 /// gets constant-folded, the type changes, or the expression is otherwise
1214 /// canonicalized. This parameter should almost always be \c false.
1215 Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1216 bool OnlyIfReduced = false,
1217 Type *SrcTy = nullptr) const;
1219 /// Returns an Instruction which implements the same operation as this
1220 /// ConstantExpr. The instruction is not linked to any basic block.
1222 /// A better approach to this could be to have a constructor for Instruction
1223 /// which would take a ConstantExpr parameter, but that would have spread
1224 /// implementation details of ConstantExpr outside of Constants.cpp, which
1225 /// would make it harder to remove ConstantExprs altogether.
1226 Instruction *getAsInstruction();
1228 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1229 static inline bool classof(const Value *V) {
1230 return V->getValueID() == ConstantExprVal;
1234 // Shadow Value::setValueSubclassData with a private forwarding method so that
1235 // subclasses cannot accidentally use it.
1236 void setValueSubclassData(unsigned short D) {
1237 Value::setValueSubclassData(D);
1242 struct OperandTraits<ConstantExpr> :
1243 public VariadicOperandTraits<ConstantExpr, 1> {
1246 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)
1248 //===----------------------------------------------------------------------===//
1249 /// 'undef' values are things that do not have specified contents.
1250 /// These are used for a variety of purposes, including global variable
1251 /// initializers and operands to instructions. 'undef' values can occur with
1252 /// any first-class type.
1254 /// Undef values aren't exactly constants; if they have multiple uses, they
1255 /// can appear to have different bit patterns at each use. See
1256 /// LangRef.html#undefvalues for details.
1258 class UndefValue final : public ConstantData {
1259 friend class Constant;
1261 explicit UndefValue(Type *T) : ConstantData(T, UndefValueVal) {}
1263 void destroyConstantImpl();
1266 UndefValue(const UndefValue &) = delete;
1268 /// Static factory methods - Return an 'undef' object of the specified type.
1269 static UndefValue *get(Type *T);
1271 /// If this Undef has array or vector type, return a undef with the right
1273 UndefValue *getSequentialElement() const;
1275 /// If this undef has struct type, return a undef with the right element type
1276 /// for the specified element.
1277 UndefValue *getStructElement(unsigned Elt) const;
1279 /// Return an undef of the right value for the specified GEP index if we can,
1280 /// otherwise return null (e.g. if C is a ConstantExpr).
1281 UndefValue *getElementValue(Constant *C) const;
1283 /// Return an undef of the right value for the specified GEP index.
1284 UndefValue *getElementValue(unsigned Idx) const;
1286 /// Return the number of elements in the array, vector, or struct.
1287 unsigned getNumElements() const;
1289 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1290 static bool classof(const Value *V) {
1291 return V->getValueID() == UndefValueVal;
1295 } // end namespace llvm
1297 #endif // LLVM_IR_CONSTANTS_H