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