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