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