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