Change TargetData::getIntPtrType() to return an IntegerType instead of
[oota-llvm.git] / include / llvm / Target / TargetData.h
1 //===-- llvm/Target/TargetData.h - Data size & alignment info ---*- 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 // This file defines target properties related to datatype size/offset/alignment
11 // information.  It uses lazy annotations to cache information about how
12 // structure types are laid out and used.
13 //
14 // This structure should be created once, filled in if the defaults are not
15 // correct and then passed around by const&.  None of the members functions
16 // require modification to the object.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_TARGET_TARGETDATA_H
21 #define LLVM_TARGET_TARGETDATA_H
22
23 #include "llvm/Pass.h"
24 #include "llvm/Support/DataTypes.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/DerivedTypes.h"
27 #include <string>
28
29 namespace llvm {
30
31 class Value;
32 class StructLayout;
33 class GlobalVariable;
34
35 /// Enum used to categorize the alignment types stored by TargetAlignElem
36 enum AlignTypeEnum {
37   INTEGER_ALIGN = 'i',               ///< Integer type alignment
38   VECTOR_ALIGN = 'v',                ///< Vector type alignment
39   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
40   AGGREGATE_ALIGN = 'a',             ///< Aggregate alignment
41   STACK_ALIGN = 's'                  ///< Stack objects alignment
42 };
43 /// Target alignment element.
44 ///
45 /// Stores the alignment data associated with a given alignment type (pointer,
46 /// integer, vector, float) and type bit width.
47 ///
48 /// @note The unusual order of elements in the structure attempts to reduce
49 /// padding and make the structure slightly more cache friendly.
50 struct TargetAlignElem {
51   AlignTypeEnum       AlignType : 8;  //< Alignment type (AlignTypeEnum)
52   unsigned char       ABIAlign;       //< ABI alignment for this type/bitw
53   unsigned char       PrefAlign;      //< Pref. alignment for this type/bitw
54   uint32_t            TypeBitWidth;   //< Type bit width
55
56   /// Initializer
57   static TargetAlignElem get(AlignTypeEnum align_type, unsigned char abi_align,
58                              unsigned char pref_align, uint32_t bit_width);
59   /// Equality predicate
60   bool operator==(const TargetAlignElem &rhs) const;
61   /// output stream operator
62   std::ostream &dump(std::ostream &os) const;
63 };
64
65 class TargetData : public ImmutablePass {
66 private:
67   bool          LittleEndian;          ///< Defaults to false
68   unsigned char PointerMemSize;        ///< Pointer size in bytes
69   unsigned char PointerABIAlign;       ///< Pointer ABI alignment
70   unsigned char PointerPrefAlign;      ///< Pointer preferred alignment
71
72   //! Where the primitive type alignment data is stored.
73   /*!
74    @sa init().
75    @note Could support multiple size pointer alignments, e.g., 32-bit pointers
76    vs. 64-bit pointers by extending TargetAlignment, but for now, we don't.
77    */
78   SmallVector<TargetAlignElem, 16> Alignments;
79   //! Alignment iterator shorthand
80   typedef SmallVector<TargetAlignElem, 16>::iterator align_iterator;
81   //! Constant alignment iterator shorthand
82   typedef SmallVector<TargetAlignElem, 16>::const_iterator align_const_iterator;
83   //! Invalid alignment.
84   /*!
85     This member is a signal that a requested alignment type and bit width were
86     not found in the SmallVector.
87    */
88   static const TargetAlignElem InvalidAlignmentElem;
89
90   //! Set/initialize target alignments
91   void setAlignment(AlignTypeEnum align_type, unsigned char abi_align,
92                     unsigned char pref_align, uint32_t bit_width);
93   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
94                             bool ABIAlign, const Type *Ty) const;
95   //! Internal helper method that returns requested alignment for type.
96   unsigned char getAlignment(const Type *Ty, bool abi_or_pref) const;
97
98   /// Valid alignment predicate.
99   ///
100   /// Predicate that tests a TargetAlignElem reference returned by get() against
101   /// InvalidAlignmentElem.
102   inline bool validAlignment(const TargetAlignElem &align) const {
103     return (&align != &InvalidAlignmentElem);
104   }
105
106 public:
107   /// Default ctor.
108   ///
109   /// @note This has to exist, because this is a pass, but it should never be
110   /// used.
111   TargetData() : ImmutablePass(&ID) {
112     assert(0 && "ERROR: Bad TargetData ctor used.  "
113            "Tool did not specify a TargetData to use?");
114     abort();
115   }
116
117   /// Constructs a TargetData from a specification string. See init().
118   explicit TargetData(const std::string &TargetDescription)
119     : ImmutablePass(&ID) {
120     init(TargetDescription);
121   }
122
123   /// Initialize target data from properties stored in the module.
124   explicit TargetData(const Module *M);
125
126   TargetData(const TargetData &TD) :
127     ImmutablePass(&ID),
128     LittleEndian(TD.isLittleEndian()),
129     PointerMemSize(TD.PointerMemSize),
130     PointerABIAlign(TD.PointerABIAlign),
131     PointerPrefAlign(TD.PointerPrefAlign),
132     Alignments(TD.Alignments)
133   { }
134
135   ~TargetData();  // Not virtual, do not subclass this class
136
137   //! Parse a target data layout string and initialize TargetData alignments.
138   void init(const std::string &TargetDescription);
139
140   /// Target endianness...
141   bool          isLittleEndian()       const { return     LittleEndian; }
142   bool          isBigEndian()          const { return    !LittleEndian; }
143
144   /// getStringRepresentation - Return the string representation of the
145   /// TargetData.  This representation is in the same format accepted by the
146   /// string constructor above.
147   std::string getStringRepresentation() const;
148   /// Target pointer alignment
149   unsigned char getPointerABIAlignment() const { return PointerABIAlign; }
150   /// Return target's alignment for stack-based pointers
151   unsigned char getPointerPrefAlignment() const { return PointerPrefAlign; }
152   /// Target pointer size
153   unsigned char getPointerSize()         const { return PointerMemSize; }
154   /// Target pointer size, in bits
155   unsigned char getPointerSizeInBits()   const { return 8*PointerMemSize; }
156
157   /// Size examples:
158   ///
159   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
160   /// ----        ----------  ---------------  ---------------
161   ///  i1            1           8                8
162   ///  i8            8           8                8
163   ///  i19          19          24               32
164   ///  i32          32          32               32
165   ///  i100        100         104              128
166   ///  i128        128         128              128
167   ///  Float        32          32               32
168   ///  Double       64          64               64
169   ///  X86_FP80     80          80               96
170   ///
171   /// [*] The alloc size depends on the alignment, and thus on the target.
172   ///     These values are for x86-32 linux.
173
174   /// getTypeSizeInBits - Return the number of bits necessary to hold the
175   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
176   uint64_t getTypeSizeInBits(const Type* Ty) const;
177
178   /// getTypeStoreSize - Return the maximum number of bytes that may be
179   /// overwritten by storing the specified type.  For example, returns 5
180   /// for i36 and 10 for x86_fp80.
181   uint64_t getTypeStoreSize(const Type *Ty) const {
182     return (getTypeSizeInBits(Ty)+7)/8;
183   }
184
185   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
186   /// overwritten by storing the specified type; always a multiple of 8.  For
187   /// example, returns 40 for i36 and 80 for x86_fp80.
188   uint64_t getTypeStoreSizeInBits(const Type *Ty) const {
189     return 8*getTypeStoreSize(Ty);
190   }
191
192   /// getTypeAllocSize - Return the offset in bytes between successive objects
193   /// of the specified type, including alignment padding.  This is the amount
194   /// that alloca reserves for this type.  For example, returns 12 or 16 for
195   /// x86_fp80, depending on alignment.
196   uint64_t getTypeAllocSize(const Type* Ty) const {
197     // Round up to the next alignment boundary.
198     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
199   }
200
201   /// getTypeAllocSizeInBits - Return the offset in bits between successive
202   /// objects of the specified type, including alignment padding; always a
203   /// multiple of 8.  This is the amount that alloca reserves for this type.
204   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
205   uint64_t getTypeAllocSizeInBits(const Type* Ty) const {
206     return 8*getTypeAllocSize(Ty);
207   }
208
209   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
210   /// specified type.
211   unsigned char getABITypeAlignment(const Type *Ty) const;
212
213   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
214   /// for the specified type when it is part of a call frame.
215   unsigned char getCallFrameTypeAlignment(const Type *Ty) const;
216
217
218   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
219   /// the specified type.  This is always at least as good as the ABI alignment.
220   unsigned char getPrefTypeAlignment(const Type *Ty) const;
221
222   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
223   /// specified type, returned as log2 of the value (a shift amount).
224   ///
225   unsigned char getPreferredTypeAlignmentShift(const Type *Ty) const;
226
227   /// getIntPtrType - Return an unsigned integer type that is the same size or
228   /// greater to the host pointer size.
229   ///
230   const IntegerType *getIntPtrType() const;
231
232   /// getIndexedOffset - return the offset from the beginning of the type for
233   /// the specified indices.  This is used to implement getelementptr.
234   ///
235   uint64_t getIndexedOffset(const Type *Ty,
236                             Value* const* Indices, unsigned NumIndices) const;
237
238   /// getStructLayout - Return a StructLayout object, indicating the alignment
239   /// of the struct, its size, and the offsets of its fields.  Note that this
240   /// information is lazily cached.
241   const StructLayout *getStructLayout(const StructType *Ty) const;
242
243   /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
244   /// objects.  If a TargetData object is alive when types are being refined and
245   /// removed, this method must be called whenever a StructType is removed to
246   /// avoid a dangling pointer in this cache.
247   void InvalidateStructLayoutInfo(const StructType *Ty) const;
248
249   /// getPreferredAlignment - Return the preferred alignment of the specified
250   /// global.  This includes an explicitly requested alignment (if the global
251   /// has one).
252   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
253
254   /// getPreferredAlignmentLog - Return the preferred alignment of the
255   /// specified global, returned in log form.  This includes an explicitly
256   /// requested alignment (if the global has one).
257   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
258
259   /// RoundUpAlignment - Round the specified value up to the next alignment
260   /// boundary specified by Alignment.  For example, 7 rounded up to an
261   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
262   /// is 8 because it is already aligned.
263   template <typename UIntTy>
264   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
265     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
266     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
267   }
268   
269   static char ID; // Pass identification, replacement for typeid
270 };
271
272 /// StructLayout - used to lazily calculate structure layout information for a
273 /// target machine, based on the TargetData structure.
274 ///
275 class StructLayout {
276   uint64_t StructSize;
277   unsigned StructAlignment;
278   unsigned NumElements;
279   uint64_t MemberOffsets[1];  // variable sized array!
280 public:
281
282   uint64_t getSizeInBytes() const {
283     return StructSize;
284   }
285
286   uint64_t getSizeInBits() const {
287     return 8*StructSize;
288   }
289
290   unsigned getAlignment() const {
291     return StructAlignment;
292   }
293
294   /// getElementContainingOffset - Given a valid offset into the structure,
295   /// return the structure index that contains it.
296   ///
297   unsigned getElementContainingOffset(uint64_t Offset) const;
298
299   uint64_t getElementOffset(unsigned Idx) const {
300     assert(Idx < NumElements && "Invalid element idx!");
301     return MemberOffsets[Idx];
302   }
303
304   uint64_t getElementOffsetInBits(unsigned Idx) const {
305     return getElementOffset(Idx)*8;
306   }
307
308 private:
309   friend class TargetData;   // Only TargetData can create this class
310   StructLayout(const StructType *ST, const TargetData &TD);
311 };
312
313 } // End llvm namespace
314
315 #endif