cc02017189943f471a6b4942531fdb7a58bb1149
[oota-llvm.git] / include / llvm / DataLayout.h
1 //===--------- llvm/DataLayout.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 layout 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_DATALAYOUT_H
21 #define LLVM_DATALAYOUT_H
22
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/DataTypes.h"
27
28 namespace llvm {
29
30 class Value;
31 class Type;
32 class IntegerType;
33 class StructType;
34 class StructLayout;
35 class GlobalVariable;
36 class LLVMContext;
37 template<typename T>
38 class ArrayRef;
39
40 /// Enum used to categorize the alignment types stored by LayoutAlignElem
41 enum AlignTypeEnum {
42   INVALID_ALIGN = 0,                 ///< An invalid alignment
43   INTEGER_ALIGN = 'i',               ///< Integer type alignment
44   VECTOR_ALIGN = 'v',                ///< Vector type alignment
45   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
46   AGGREGATE_ALIGN = 'a',             ///< Aggregate alignment
47   STACK_ALIGN = 's'                  ///< Stack objects alignment
48 };
49
50 /// Layout alignment element.
51 ///
52 /// Stores the alignment data associated with a given alignment type (integer,
53 /// vector, float) and type bit width.
54 ///
55 /// @note The unusual order of elements in the structure attempts to reduce
56 /// padding and make the structure slightly more cache friendly.
57 struct LayoutAlignElem {
58   unsigned AlignType    : 8;  ///< Alignment type (AlignTypeEnum)
59   unsigned TypeBitWidth : 24; ///< Type bit width
60   unsigned ABIAlign     : 16; ///< ABI alignment for this type/bitw
61   unsigned PrefAlign    : 16; ///< Pref. alignment for this type/bitw
62
63   /// Initializer
64   static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
65                              unsigned pref_align, uint32_t bit_width);
66   /// Equality predicate
67   bool operator==(const LayoutAlignElem &rhs) const;
68 };
69
70 /// Layout pointer alignment element.
71 ///
72 /// Stores the alignment data associated with a given pointer and address space.
73 ///
74 /// @note The unusual order of elements in the structure attempts to reduce
75 /// padding and make the structure slightly more cache friendly.
76 struct PointerAlignElem {
77   unsigned            ABIAlign;       ///< ABI alignment for this type/bitw
78   unsigned            PrefAlign;      ///< Pref. alignment for this type/bitw
79   uint32_t            TypeBitWidth;   ///< Type bit width
80   uint32_t            AddressSpace;   ///< Address space for the pointer type
81
82   /// Initializer
83   static PointerAlignElem get(uint32_t addr_space, unsigned abi_align,
84                              unsigned pref_align, uint32_t bit_width);
85   /// Equality predicate
86   bool operator==(const PointerAlignElem &rhs) const;
87 };
88
89
90 /// DataLayout - This class holds a parsed version of the target data layout
91 /// string in a module and provides methods for querying it.  The target data
92 /// layout string is specified *by the target* - a frontend generating LLVM IR
93 /// is required to generate the right target data for the target being codegen'd
94 /// to.  If some measure of portability is desired, an empty string may be
95 /// specified in the module.
96 class DataLayout : public ImmutablePass {
97 private:
98   bool          LittleEndian;          ///< Defaults to false
99   unsigned      StackNaturalAlign;     ///< Stack natural alignment
100
101   SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
102
103   /// Alignments- Where the primitive type alignment data is stored.
104   ///
105   /// @sa init().
106   /// @note Could support multiple size pointer alignments, e.g., 32-bit
107   /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
108   /// we don't.
109   SmallVector<LayoutAlignElem, 16> Alignments;
110   DenseMap<unsigned, PointerAlignElem> Pointers;
111
112   /// InvalidAlignmentElem - This member is a signal that a requested alignment
113   /// type and bit width were not found in the SmallVector.
114   static const LayoutAlignElem InvalidAlignmentElem;
115
116   /// InvalidPointerElem - This member is a signal that a requested pointer
117   /// type and bit width were not found in the DenseSet.
118   static const PointerAlignElem InvalidPointerElem;
119
120   // The StructType -> StructLayout map.
121   mutable void *LayoutMap;
122
123   //! Set/initialize target alignments
124   void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
125                     unsigned pref_align, uint32_t bit_width);
126   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
127                             bool ABIAlign, Type *Ty) const;
128
129   //! Set/initialize pointer alignments
130   void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
131       unsigned pref_align, uint32_t bit_width);
132
133   //! Internal helper method that returns requested alignment for type.
134   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
135
136   /// Valid alignment predicate.
137   ///
138   /// Predicate that tests a LayoutAlignElem reference returned by get() against
139   /// InvalidAlignmentElem.
140   bool validAlignment(const LayoutAlignElem &align) const {
141     return &align != &InvalidAlignmentElem;
142   }
143
144   /// Valid pointer predicate.
145   ///
146   /// Predicate that tests a PointerAlignElem reference returned by get() against
147   /// InvalidPointerElem.
148   bool validPointer(const PointerAlignElem &align) const {
149     return &align != &InvalidPointerElem;
150   }
151
152   /// Parses a target data specification string. Assert if the string is
153   /// malformed.
154   void parseSpecifier(StringRef LayoutDescription);
155
156 public:
157   /// Default ctor.
158   ///
159   /// @note This has to exist, because this is a pass, but it should never be
160   /// used.
161   DataLayout();
162
163   /// Constructs a DataLayout from a specification string. See init().
164   explicit DataLayout(StringRef LayoutDescription)
165     : ImmutablePass(ID) {
166     init(LayoutDescription);
167   }
168
169   /// Initialize target data from properties stored in the module.
170   explicit DataLayout(const Module *M);
171
172   DataLayout(const DataLayout &TD) :
173     ImmutablePass(ID),
174     LittleEndian(TD.isLittleEndian()),
175     LegalIntWidths(TD.LegalIntWidths),
176     Alignments(TD.Alignments),
177     Pointers(TD.Pointers),
178     LayoutMap(0)
179   { }
180
181   ~DataLayout();  // Not virtual, do not subclass this class
182
183   /// Parse a data layout string (with fallback to default values). Ensure that
184   /// the data layout pass is registered.
185   void init(StringRef LayoutDescription);
186
187   /// Layout endianness...
188   bool isLittleEndian() const { return LittleEndian; }
189   bool isBigEndian() const { return !LittleEndian; }
190
191   /// getStringRepresentation - Return the string representation of the
192   /// DataLayout.  This representation is in the same format accepted by the
193   /// string constructor above.
194   std::string getStringRepresentation() const;
195
196   /// isLegalInteger - This function returns true if the specified type is
197   /// known to be a native integer type supported by the CPU.  For example,
198   /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
199   /// one.  This returns false if the integer width is not legal.
200   ///
201   /// The width is specified in bits.
202   ///
203   bool isLegalInteger(unsigned Width) const {
204     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
205       if (LegalIntWidths[i] == Width)
206         return true;
207     return false;
208   }
209
210   bool isIllegalInteger(unsigned Width) const {
211     return !isLegalInteger(Width);
212   }
213
214   /// Returns true if the given alignment exceeds the natural stack alignment.
215   bool exceedsNaturalStackAlignment(unsigned Align) const {
216     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
217   }
218
219   /// fitsInLegalInteger - This function returns true if the specified type fits
220   /// in a native integer type supported by the CPU.  For example, if the CPU
221   /// only supports i32 as a native integer type, then i27 fits in a legal
222   // integer type but i45 does not.
223   bool fitsInLegalInteger(unsigned Width) const {
224     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
225       if (Width <= LegalIntWidths[i])
226         return true;
227     return false;
228   }
229
230   /// Layout pointer alignment
231   /// FIXME: The defaults need to be removed once all of
232   /// the backends/clients are updated.
233   unsigned getPointerABIAlignment(unsigned AS = 0)  const {
234     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
235     if (val == Pointers.end()) {
236       val = Pointers.find(0);
237     }
238     return val->second.ABIAlign;
239   }
240   /// Return target's alignment for stack-based pointers
241   /// FIXME: The defaults need to be removed once all of
242   /// the backends/clients are updated.
243   unsigned getPointerPrefAlignment(unsigned AS = 0) const {
244     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
245     if (val == Pointers.end()) {
246       val = Pointers.find(0);
247     }
248     return val->second.PrefAlign;
249   }
250   /// Layout pointer size
251   /// FIXME: The defaults need to be removed once all of
252   /// the backends/clients are updated.
253   unsigned getPointerSize(unsigned AS = 0)          const {
254     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
255     if (val == Pointers.end()) {
256       val = Pointers.find(0);
257     }
258     return val->second.TypeBitWidth;
259   }
260   /// Layout pointer size, in bits
261   /// FIXME: The defaults need to be removed once all of
262   /// the backends/clients are updated.
263   unsigned getPointerSizeInBits(unsigned AS = 0)    const {
264     return getPointerSize(AS) * 8;
265   }
266   /// Size examples:
267   ///
268   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
269   /// ----        ----------  ---------------  ---------------
270   ///  i1            1           8                8
271   ///  i8            8           8                8
272   ///  i19          19          24               32
273   ///  i32          32          32               32
274   ///  i100        100         104              128
275   ///  i128        128         128              128
276   ///  Float        32          32               32
277   ///  Double       64          64               64
278   ///  X86_FP80     80          80               96
279   ///
280   /// [*] The alloc size depends on the alignment, and thus on the target.
281   ///     These values are for x86-32 linux.
282
283   /// getTypeSizeInBits - Return the number of bits necessary to hold the
284   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
285   /// The type passed must have a size (Type::isSized() must return true).
286   uint64_t getTypeSizeInBits(Type* Ty) const;
287
288   /// getTypeStoreSize - Return the maximum number of bytes that may be
289   /// overwritten by storing the specified type.  For example, returns 5
290   /// for i36 and 10 for x86_fp80.
291   uint64_t getTypeStoreSize(Type *Ty) const {
292     return (getTypeSizeInBits(Ty)+7)/8;
293   }
294
295   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
296   /// overwritten by storing the specified type; always a multiple of 8.  For
297   /// example, returns 40 for i36 and 80 for x86_fp80.
298   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
299     return 8*getTypeStoreSize(Ty);
300   }
301
302   /// getTypeAllocSize - Return the offset in bytes between successive objects
303   /// of the specified type, including alignment padding.  This is the amount
304   /// that alloca reserves for this type.  For example, returns 12 or 16 for
305   /// x86_fp80, depending on alignment.
306   uint64_t getTypeAllocSize(Type* Ty) const {
307     // Round up to the next alignment boundary.
308     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
309   }
310
311   /// getTypeAllocSizeInBits - Return the offset in bits between successive
312   /// objects of the specified type, including alignment padding; always a
313   /// multiple of 8.  This is the amount that alloca reserves for this type.
314   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
315   uint64_t getTypeAllocSizeInBits(Type* Ty) const {
316     return 8*getTypeAllocSize(Ty);
317   }
318
319   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
320   /// specified type.
321   unsigned getABITypeAlignment(Type *Ty) const;
322
323   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
324   /// an integer type of the specified bitwidth.
325   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
326
327
328   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
329   /// for the specified type when it is part of a call frame.
330   unsigned getCallFrameTypeAlignment(Type *Ty) const;
331
332
333   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
334   /// the specified type.  This is always at least as good as the ABI alignment.
335   unsigned getPrefTypeAlignment(Type *Ty) const;
336
337   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
338   /// specified type, returned as log2 of the value (a shift amount).
339   ///
340   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
341
342   /// getIntPtrType - Return an integer type with size at least as big as that
343   /// of a pointer in the given address space.
344   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
345
346   /// getIntPtrType - Return an integer (vector of integer) type with size at
347   /// least as big as that of a pointer of the given pointer (vector of pointer)
348   /// type.
349   Type *getIntPtrType(Type *) const;
350
351   /// getIndexedOffset - return the offset from the beginning of the type for
352   /// the specified indices.  This is used to implement getelementptr.
353   ///
354   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
355
356   /// getStructLayout - Return a StructLayout object, indicating the alignment
357   /// of the struct, its size, and the offsets of its fields.  Note that this
358   /// information is lazily cached.
359   const StructLayout *getStructLayout(StructType *Ty) const;
360
361   /// getPreferredAlignment - Return the preferred alignment of the specified
362   /// global.  This includes an explicitly requested alignment (if the global
363   /// has one).
364   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
365
366   /// getPreferredAlignmentLog - Return the preferred alignment of the
367   /// specified global, returned in log form.  This includes an explicitly
368   /// requested alignment (if the global has one).
369   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
370
371   /// RoundUpAlignment - Round the specified value up to the next alignment
372   /// boundary specified by Alignment.  For example, 7 rounded up to an
373   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
374   /// is 8 because it is already aligned.
375   template <typename UIntTy>
376   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
377     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
378     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
379   }
380
381   static char ID; // Pass identification, replacement for typeid
382 };
383
384 /// StructLayout - used to lazily calculate structure layout information for a
385 /// target machine, based on the DataLayout structure.
386 ///
387 class StructLayout {
388   uint64_t StructSize;
389   unsigned StructAlignment;
390   unsigned NumElements;
391   uint64_t MemberOffsets[1];  // variable sized array!
392 public:
393
394   uint64_t getSizeInBytes() const {
395     return StructSize;
396   }
397
398   uint64_t getSizeInBits() const {
399     return 8*StructSize;
400   }
401
402   unsigned getAlignment() const {
403     return StructAlignment;
404   }
405
406   /// getElementContainingOffset - Given a valid byte offset into the structure,
407   /// return the structure index that contains it.
408   ///
409   unsigned getElementContainingOffset(uint64_t Offset) const;
410
411   uint64_t getElementOffset(unsigned Idx) const {
412     assert(Idx < NumElements && "Invalid element idx!");
413     return MemberOffsets[Idx];
414   }
415
416   uint64_t getElementOffsetInBits(unsigned Idx) const {
417     return getElementOffset(Idx)*8;
418   }
419
420 private:
421   friend class DataLayout;   // Only DataLayout can create this class
422   StructLayout(StructType *ST, const DataLayout &TD);
423 };
424
425 } // End llvm namespace
426
427 #endif