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