1 //===--------- llvm/DataLayout.h - Data size & alignment info ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_IR_DATALAYOUT_H
21 #define LLVM_IR_DATALAYOUT_H
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/DataTypes.h"
40 /// Enum used to categorize the alignment types stored by LayoutAlignElem
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
50 /// Layout alignment element.
52 /// Stores the alignment data associated with a given alignment type (integer,
53 /// vector, float) and type bit width.
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
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;
70 /// Layout pointer alignment element.
72 /// Stores the alignment data associated with a given pointer and address space.
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
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;
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 {
98 bool LittleEndian; ///< Defaults to false
99 unsigned StackNaturalAlign; ///< Stack natural alignment
101 SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
103 /// Alignments - Where the primitive type alignment data is stored.
106 /// @note Could support multiple size pointer alignments, e.g., 32-bit
107 /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
109 SmallVector<LayoutAlignElem, 16> Alignments;
110 DenseMap<unsigned, PointerAlignElem> Pointers;
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;
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;
120 // The StructType -> StructLayout map.
121 mutable void *LayoutMap;
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;
129 //! Set/initialize pointer alignments
130 void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
131 unsigned pref_align, uint32_t bit_width);
133 //! Internal helper method that returns requested alignment for type.
134 unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
136 /// Valid alignment predicate.
138 /// Predicate that tests a LayoutAlignElem reference returned by get() against
139 /// InvalidAlignmentElem.
140 bool validAlignment(const LayoutAlignElem &align) const {
141 return &align != &InvalidAlignmentElem;
144 /// Valid pointer predicate.
146 /// Predicate that tests a PointerAlignElem reference returned by get() against
147 /// InvalidPointerElem.
148 bool validPointer(const PointerAlignElem &align) const {
149 return &align != &InvalidPointerElem;
152 /// Parses a target data specification string. Assert if the string is
154 void parseSpecifier(StringRef LayoutDescription);
159 /// @note This has to exist, because this is a pass, but it should never be
163 /// Constructs a DataLayout from a specification string. See init().
164 explicit DataLayout(StringRef LayoutDescription)
165 : ImmutablePass(ID) {
166 init(LayoutDescription);
169 /// Initialize target data from properties stored in the module.
170 explicit DataLayout(const Module *M);
172 DataLayout(const DataLayout &TD) :
174 LittleEndian(TD.isLittleEndian()),
175 StackNaturalAlign(TD.StackNaturalAlign),
176 LegalIntWidths(TD.LegalIntWidths),
177 Alignments(TD.Alignments),
178 Pointers(TD.Pointers),
182 ~DataLayout(); // Not virtual, do not subclass this class
184 /// Parse a data layout string (with fallback to default values). Ensure that
185 /// the data layout pass is registered.
186 void init(StringRef LayoutDescription);
188 /// Layout endianness...
189 bool isLittleEndian() const { return LittleEndian; }
190 bool isBigEndian() const { return !LittleEndian; }
192 /// getStringRepresentation - Return the string representation of the
193 /// DataLayout. This representation is in the same format accepted by the
194 /// string constructor above.
195 std::string getStringRepresentation() const;
197 /// isLegalInteger - This function returns true if the specified type is
198 /// known to be a native integer type supported by the CPU. For example,
199 /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
200 /// one. This returns false if the integer width is not legal.
202 /// The width is specified in bits.
204 bool isLegalInteger(unsigned Width) const {
205 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
206 if (LegalIntWidths[i] == Width)
211 bool isIllegalInteger(unsigned Width) const {
212 return !isLegalInteger(Width);
215 /// Returns true if the given alignment exceeds the natural stack alignment.
216 bool exceedsNaturalStackAlignment(unsigned Align) const {
217 return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
220 /// fitsInLegalInteger - This function returns true if the specified type fits
221 /// in a native integer type supported by the CPU. For example, if the CPU
222 /// only supports i32 as a native integer type, then i27 fits in a legal
223 // integer type but i45 does not.
224 bool fitsInLegalInteger(unsigned Width) const {
225 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
226 if (Width <= LegalIntWidths[i])
231 /// Layout pointer alignment
232 /// FIXME: The defaults need to be removed once all of
233 /// the backends/clients are updated.
234 unsigned getPointerABIAlignment(unsigned AS = 0) const {
235 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
236 if (val == Pointers.end()) {
237 val = Pointers.find(0);
239 return val->second.ABIAlign;
241 /// Return target's alignment for stack-based pointers
242 /// FIXME: The defaults need to be removed once all of
243 /// the backends/clients are updated.
244 unsigned getPointerPrefAlignment(unsigned AS = 0) const {
245 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
246 if (val == Pointers.end()) {
247 val = Pointers.find(0);
249 return val->second.PrefAlign;
251 /// Layout pointer size
252 /// FIXME: The defaults need to be removed once all of
253 /// the backends/clients are updated.
254 unsigned getPointerSize(unsigned AS = 0) const {
255 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
256 if (val == Pointers.end()) {
257 val = Pointers.find(0);
259 return val->second.TypeBitWidth;
261 /// Layout pointer size, in bits
262 /// FIXME: The defaults need to be removed once all of
263 /// the backends/clients are updated.
264 unsigned getPointerSizeInBits(unsigned AS = 0) const {
265 return getPointerSize(AS) * 8;
269 /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
270 /// ---- ---------- --------------- ---------------
279 /// X86_FP80 80 80 96
281 /// [*] The alloc size depends on the alignment, and thus on the target.
282 /// These values are for x86-32 linux.
284 /// getTypeSizeInBits - Return the number of bits necessary to hold the
285 /// specified type. For example, returns 36 for i36 and 80 for x86_fp80.
286 /// The type passed must have a size (Type::isSized() must return true).
287 uint64_t getTypeSizeInBits(Type* Ty) const;
289 /// getTypeStoreSize - Return the maximum number of bytes that may be
290 /// overwritten by storing the specified type. For example, returns 5
291 /// for i36 and 10 for x86_fp80.
292 uint64_t getTypeStoreSize(Type *Ty) const {
293 return (getTypeSizeInBits(Ty)+7)/8;
296 /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
297 /// overwritten by storing the specified type; always a multiple of 8. For
298 /// example, returns 40 for i36 and 80 for x86_fp80.
299 uint64_t getTypeStoreSizeInBits(Type *Ty) const {
300 return 8*getTypeStoreSize(Ty);
303 /// getTypeAllocSize - Return the offset in bytes between successive objects
304 /// of the specified type, including alignment padding. This is the amount
305 /// that alloca reserves for this type. For example, returns 12 or 16 for
306 /// x86_fp80, depending on alignment.
307 uint64_t getTypeAllocSize(Type* Ty) const {
308 // Round up to the next alignment boundary.
309 return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
312 /// getTypeAllocSizeInBits - Return the offset in bits between successive
313 /// objects of the specified type, including alignment padding; always a
314 /// multiple of 8. This is the amount that alloca reserves for this type.
315 /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
316 uint64_t getTypeAllocSizeInBits(Type* Ty) const {
317 return 8*getTypeAllocSize(Ty);
320 /// getABITypeAlignment - Return the minimum ABI-required alignment for the
322 unsigned getABITypeAlignment(Type *Ty) const;
324 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
325 /// an integer type of the specified bitwidth.
326 unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
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;
332 /// getPrefTypeAlignment - Return the preferred stack/global alignment for
333 /// the specified type. This is always at least as good as the ABI alignment.
334 unsigned getPrefTypeAlignment(Type *Ty) const;
336 /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
337 /// specified type, returned as log2 of the value (a shift amount).
338 unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
340 /// getIntPtrType - Return an integer type with size at least as big as that
341 /// of a pointer in the given address space.
342 IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
344 /// getIntPtrType - Return an integer (vector of integer) type with size at
345 /// least as big as that of a pointer of the given pointer (vector of pointer)
347 Type *getIntPtrType(Type *) const;
349 /// getIndexedOffset - return the offset from the beginning of the type for
350 /// the specified indices. This is used to implement getelementptr.
351 uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
353 /// getStructLayout - Return a StructLayout object, indicating the alignment
354 /// of the struct, its size, and the offsets of its fields. Note that this
355 /// information is lazily cached.
356 const StructLayout *getStructLayout(StructType *Ty) const;
358 /// getPreferredAlignment - Return the preferred alignment of the specified
359 /// global. This includes an explicitly requested alignment (if the global
361 unsigned getPreferredAlignment(const GlobalVariable *GV) const;
363 /// getPreferredAlignmentLog - Return the preferred alignment of the
364 /// specified global, returned in log form. This includes an explicitly
365 /// requested alignment (if the global has one).
366 unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
368 /// RoundUpAlignment - Round the specified value up to the next alignment
369 /// boundary specified by Alignment. For example, 7 rounded up to an
370 /// alignment boundary of 4 is 8. 8 rounded up to the alignment boundary of 4
371 /// is 8 because it is already aligned.
372 template <typename UIntTy>
373 static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
374 assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
375 return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
378 static char ID; // Pass identification, replacement for typeid
381 /// StructLayout - used to lazily calculate structure layout information for a
382 /// target machine, based on the DataLayout structure.
386 unsigned StructAlignment;
387 unsigned NumElements;
388 uint64_t MemberOffsets[1]; // variable sized array!
391 uint64_t getSizeInBytes() const {
395 uint64_t getSizeInBits() const {
399 unsigned getAlignment() const {
400 return StructAlignment;
403 /// getElementContainingOffset - Given a valid byte offset into the structure,
404 /// return the structure index that contains it.
406 unsigned getElementContainingOffset(uint64_t Offset) const;
408 uint64_t getElementOffset(unsigned Idx) const {
409 assert(Idx < NumElements && "Invalid element idx!");
410 return MemberOffsets[Idx];
413 uint64_t getElementOffsetInBits(unsigned Idx) const {
414 return getElementOffset(Idx)*8;
418 friend class DataLayout; // Only DataLayout can create this class
419 StructLayout(StructType *ST, const DataLayout &TD);
422 } // End llvm namespace