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