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_DATALAYOUT_H
21 #define LLVM_DATALAYOUT_H
23 #include "llvm/Pass.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/Support/DataTypes.h"
40 /// Enum used to categorize the alignment types stored by LayoutAlignElem
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
49 /// Layout alignment element.
51 /// Stores the alignment data associated with a given alignment type (integer,
52 /// vector, float) and type bit width.
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
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;
69 /// Layout pointer alignment element.
71 /// Stores the alignment data associated with a given pointer and address space.
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
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;
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 {
97 bool LittleEndian; ///< Defaults to false
98 unsigned StackNaturalAlign; ///< Stack natural alignment
100 SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
102 /// Alignments- Where the primitive type alignment data is stored.
105 /// @note Could support multiple size pointer alignments, e.g., 32-bit
106 /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
108 SmallVector<LayoutAlignElem, 16> Alignments;
109 DenseMap<unsigned, PointerAlignElem> Pointers;
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;
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;
119 // The StructType -> StructLayout map.
120 mutable void *LayoutMap;
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;
128 //! Set/initialize pointer alignments
129 void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
130 unsigned pref_align, uint32_t bit_width);
132 //! Internal helper method that returns requested alignment for type.
133 unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
135 /// Valid alignment predicate.
137 /// Predicate that tests a LayoutAlignElem reference returned by get() against
138 /// InvalidAlignmentElem.
139 bool validAlignment(const LayoutAlignElem &align) const {
140 return &align != &InvalidAlignmentElem;
143 /// Valid pointer predicate.
145 /// Predicate that tests a PointerAlignElem reference returned by get() against
146 /// InvalidPointerElem.
147 bool validPointer(const PointerAlignElem &align) const {
148 return &align != &InvalidPointerElem;
151 /// Parses a target data specification string. Returns an error message
152 /// if the string is malformed, or the empty string on success.
153 std::string parseSpecifier(StringRef LayoutDescription);
158 /// @note This has to exist, because this is a pass, but it should never be
162 /// Constructs a DataLayout from a specification string. See init().
163 explicit DataLayout(StringRef LayoutDescription)
164 : ImmutablePass(ID) {
165 init(LayoutDescription);
168 /// Initialize target data from properties stored in the module.
169 explicit DataLayout(const Module *M);
171 DataLayout(const DataLayout &TD) :
173 LittleEndian(TD.isLittleEndian()),
174 LegalIntWidths(TD.LegalIntWidths),
175 Alignments(TD.Alignments),
176 Pointers(TD.Pointers),
180 ~DataLayout(); // Not virtual, do not subclass this class
182 /// Parse a data layout string (with fallback to default values). Ensure that
183 /// the data layout pass is registered.
184 void init(StringRef LayoutDescription);
186 /// Layout endianness...
187 bool isLittleEndian() const { return LittleEndian; }
188 bool isBigEndian() const { return !LittleEndian; }
190 /// getStringRepresentation - Return the string representation of the
191 /// DataLayout. This representation is in the same format accepted by the
192 /// string constructor above.
193 std::string getStringRepresentation() const;
195 /// isLegalInteger - This function returns true if the specified type is
196 /// known to be a native integer type supported by the CPU. For example,
197 /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
198 /// one. This returns false if the integer width is not legal.
200 /// The width is specified in bits.
202 bool isLegalInteger(unsigned Width) const {
203 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
204 if (LegalIntWidths[i] == Width)
209 bool isIllegalInteger(unsigned Width) const {
210 return !isLegalInteger(Width);
213 /// Returns true if the given alignment exceeds the natural stack alignment.
214 bool exceedsNaturalStackAlignment(unsigned Align) const {
215 return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
218 /// fitsInLegalInteger - This function returns true if the specified type fits
219 /// in a native integer type supported by the CPU. For example, if the CPU
220 /// only supports i32 as a native integer type, then i27 fits in a legal
221 // integer type but i45 does not.
222 bool fitsInLegalInteger(unsigned Width) const {
223 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
224 if (Width <= LegalIntWidths[i])
229 /// Layout pointer alignment
230 /// FIXME: The defaults need to be removed once all of
231 /// the backends/clients are updated.
232 unsigned getPointerABIAlignment(unsigned AS = 0) const {
233 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
234 if (val == Pointers.end()) {
235 val = Pointers.find(0);
237 return val->second.ABIAlign;
239 /// Return target's alignment for stack-based pointers
240 /// FIXME: The defaults need to be removed once all of
241 /// the backends/clients are updated.
242 unsigned getPointerPrefAlignment(unsigned AS = 0) const {
243 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
244 if (val == Pointers.end()) {
245 val = Pointers.find(0);
247 return val->second.PrefAlign;
249 /// Layout pointer size
250 /// FIXME: The defaults need to be removed once all of
251 /// the backends/clients are updated.
252 unsigned getPointerSize(unsigned AS = 0) const {
253 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
254 if (val == Pointers.end()) {
255 val = Pointers.find(0);
257 return val->second.TypeBitWidth;
259 /// Layout pointer size, in bits
260 /// FIXME: The defaults need to be removed once all of
261 /// the backends/clients are updated.
262 unsigned getPointerSizeInBits(unsigned AS = 0) const {
263 return getPointerSize(AS) * 8;
267 /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
268 /// ---- ---------- --------------- ---------------
277 /// X86_FP80 80 80 96
279 /// [*] The alloc size depends on the alignment, and thus on the target.
280 /// These values are for x86-32 linux.
282 /// getTypeSizeInBits - Return the number of bits necessary to hold the
283 /// specified type. For example, returns 36 for i36 and 80 for x86_fp80.
284 /// The type passed must have a size (Type::isSized() must return true).
285 uint64_t getTypeSizeInBits(Type* Ty) const;
287 /// getTypeStoreSize - Return the maximum number of bytes that may be
288 /// overwritten by storing the specified type. For example, returns 5
289 /// for i36 and 10 for x86_fp80.
290 uint64_t getTypeStoreSize(Type *Ty) const {
291 return (getTypeSizeInBits(Ty)+7)/8;
294 /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
295 /// overwritten by storing the specified type; always a multiple of 8. For
296 /// example, returns 40 for i36 and 80 for x86_fp80.
297 uint64_t getTypeStoreSizeInBits(Type *Ty) const {
298 return 8*getTypeStoreSize(Ty);
301 /// getTypeAllocSize - Return the offset in bytes between successive objects
302 /// of the specified type, including alignment padding. This is the amount
303 /// that alloca reserves for this type. For example, returns 12 or 16 for
304 /// x86_fp80, depending on alignment.
305 uint64_t getTypeAllocSize(Type* Ty) const {
306 // Round up to the next alignment boundary.
307 return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
310 /// getTypeAllocSizeInBits - Return the offset in bits between successive
311 /// objects of the specified type, including alignment padding; always a
312 /// multiple of 8. This is the amount that alloca reserves for this type.
313 /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
314 uint64_t getTypeAllocSizeInBits(Type* Ty) const {
315 return 8*getTypeAllocSize(Ty);
318 /// getABITypeAlignment - Return the minimum ABI-required alignment for the
320 unsigned getABITypeAlignment(Type *Ty) const;
322 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
323 /// an integer type of the specified bitwidth.
324 unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
327 /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
328 /// for the specified type when it is part of a call frame.
329 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).
339 unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
341 /// getIntPtrType - Return an integer type with size at least as big as that
342 /// of a pointer in the given address space.
343 IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
345 /// getIntPtrType - Return an integer (vector of integer) type with size at
346 /// least as big as that of a pointer of the given pointer (vector of pointer)
348 Type *getIntPtrType(Type *) const;
350 /// getIndexedOffset - return the offset from the beginning of the type for
351 /// the specified indices. This is used to implement getelementptr.
353 uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
355 /// getStructLayout - Return a StructLayout object, indicating the alignment
356 /// of the struct, its size, and the offsets of its fields. Note that this
357 /// information is lazily cached.
358 const StructLayout *getStructLayout(StructType *Ty) const;
360 /// getPreferredAlignment - Return the preferred alignment of the specified
361 /// global. This includes an explicitly requested alignment (if the global
363 unsigned getPreferredAlignment(const GlobalVariable *GV) const;
365 /// getPreferredAlignmentLog - Return the preferred alignment of the
366 /// specified global, returned in log form. This includes an explicitly
367 /// requested alignment (if the global has one).
368 unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
370 /// RoundUpAlignment - Round the specified value up to the next alignment
371 /// boundary specified by Alignment. For example, 7 rounded up to an
372 /// alignment boundary of 4 is 8. 8 rounded up to the alignment boundary of 4
373 /// is 8 because it is already aligned.
374 template <typename UIntTy>
375 static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
376 assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
377 return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
380 static char ID; // Pass identification, replacement for typeid
383 /// StructLayout - used to lazily calculate structure layout information for a
384 /// target machine, based on the DataLayout structure.
388 unsigned StructAlignment;
389 unsigned NumElements;
390 uint64_t MemberOffsets[1]; // variable sized array!
393 uint64_t getSizeInBytes() const {
397 uint64_t getSizeInBits() const {
401 unsigned getAlignment() const {
402 return StructAlignment;
405 /// getElementContainingOffset - Given a valid byte offset into the structure,
406 /// return the structure index that contains it.
408 unsigned getElementContainingOffset(uint64_t Offset) const;
410 uint64_t getElementOffset(unsigned Idx) const {
411 assert(Idx < NumElements && "Invalid element idx!");
412 return MemberOffsets[Idx];
415 uint64_t getElementOffsetInBits(unsigned Idx) const {
416 return getElementOffset(Idx)*8;
420 friend class DataLayout; // Only DataLayout can create this class
421 StructLayout(StructType *ST, const DataLayout &TD);
424 } // End llvm namespace