Constants.h 57 KB

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