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/IR/DerivedTypes.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/DataTypes.h"
43 /// Enum used to categorize the alignment types stored by LayoutAlignElem
45 INVALID_ALIGN = 0, ///< An invalid alignment
46 INTEGER_ALIGN = 'i', ///< Integer type alignment
47 VECTOR_ALIGN = 'v', ///< Vector type alignment
48 FLOAT_ALIGN = 'f', ///< Floating point type alignment
49 AGGREGATE_ALIGN = 'a' ///< Aggregate alignment
52 /// Layout alignment element.
54 /// Stores the alignment data associated with a given alignment type (integer,
55 /// vector, float) and type bit width.
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
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;
72 /// Layout pointer alignment element.
74 /// Stores the alignment data associated with a given pointer and address space.
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 TypeByteWidth; ///< Type byte width
82 uint32_t AddressSpace; ///< Address space for the pointer type
85 static PointerAlignElem get(uint32_t AddressSpace, unsigned ABIAlign,
86 unsigned PrefAlign, uint32_t TypeByteWidth);
87 /// Equality predicate
88 bool operator==(const PointerAlignElem &rhs) const;
91 /// This class holds a parsed version of the target data layout string in a
92 /// module and provides methods for querying it. The target data layout string
93 /// is specified *by the target* - a frontend generating LLVM IR is required to
94 /// generate the right target data for the target being codegen'd to.
97 bool LittleEndian; ///< Defaults to false
98 unsigned StackNaturalAlign; ///< Stack natural alignment
107 ManglingModeT ManglingMode;
109 SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
111 /// Alignments - Where the primitive type alignment data is stored.
114 /// @note Could support multiple size pointer alignments, e.g., 32-bit
115 /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
117 SmallVector<LayoutAlignElem, 16> Alignments;
118 typedef SmallVector<PointerAlignElem, 8> PointersTy;
121 PointersTy::const_iterator findPoiterLowerBound(uint32_t AddressSpace) const {
122 return const_cast<DataLayout *>(this)->findPoiterLowerBound(AddressSpace);
125 PointersTy::iterator findPoiterLowerBound(uint32_t AddressSpace);
127 /// InvalidAlignmentElem - This member is a signal that a requested alignment
128 /// type and bit width were not found in the SmallVector.
129 static const LayoutAlignElem InvalidAlignmentElem;
131 /// InvalidPointerElem - This member is a signal that a requested pointer
132 /// type and bit width were not found in the DenseSet.
133 static const PointerAlignElem InvalidPointerElem;
135 // The StructType -> StructLayout map.
136 mutable void *LayoutMap;
138 //! Set/initialize target alignments
139 void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
140 unsigned pref_align, uint32_t bit_width);
141 unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
142 bool ABIAlign, Type *Ty) const;
144 //! Set/initialize pointer alignments
145 void setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
146 unsigned PrefAlign, uint32_t TypeByteWidth);
148 //! Internal helper method that returns requested alignment for type.
149 unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
151 /// Valid alignment predicate.
153 /// Predicate that tests a LayoutAlignElem reference returned by get() against
154 /// InvalidAlignmentElem.
155 bool validAlignment(const LayoutAlignElem &align) const {
156 return &align != &InvalidAlignmentElem;
159 /// Valid pointer predicate.
161 /// Predicate that tests a PointerAlignElem reference returned by get() against
162 /// InvalidPointerElem.
163 bool validPointer(const PointerAlignElem &align) const {
164 return &align != &InvalidPointerElem;
167 /// Parses a target data specification string. Assert if the string is
169 void parseSpecifier(StringRef LayoutDescription);
171 // Free all internal data structures.
175 /// Constructs a DataLayout from a specification string. See reset().
176 explicit DataLayout(StringRef LayoutDescription) : LayoutMap(0) {
177 reset(LayoutDescription);
180 /// Initialize target data from properties stored in the module.
181 explicit DataLayout(const Module *M);
183 DataLayout(const DataLayout &DL) : LayoutMap(0) { *this = DL; }
185 DataLayout &operator=(const DataLayout &DL) {
187 LittleEndian = DL.isLittleEndian();
188 StackNaturalAlign = DL.StackNaturalAlign;
189 ManglingMode = DL.ManglingMode;
190 LegalIntWidths = DL.LegalIntWidths;
191 Alignments = DL.Alignments;
192 Pointers = DL.Pointers;
196 ~DataLayout(); // Not virtual, do not subclass this class
198 /// Parse a data layout string (with fallback to default values).
199 void reset(StringRef LayoutDescription);
201 /// Layout endianness...
202 bool isLittleEndian() const { return LittleEndian; }
203 bool isBigEndian() const { return !LittleEndian; }
205 /// getStringRepresentation - Return the string representation of the
206 /// DataLayout. This representation is in the same format accepted by the
207 /// string constructor above.
208 std::string getStringRepresentation() const;
210 /// isLegalInteger - This function returns true if the specified type is
211 /// known to be a native integer type supported by the CPU. For example,
212 /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
213 /// one. This returns false if the integer width is not legal.
215 /// The width is specified in bits.
217 bool isLegalInteger(unsigned Width) const {
218 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
219 if (LegalIntWidths[i] == Width)
224 bool isIllegalInteger(unsigned Width) const {
225 return !isLegalInteger(Width);
228 /// Returns true if the given alignment exceeds the natural stack alignment.
229 bool exceedsNaturalStackAlignment(unsigned Align) const {
230 return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
233 bool hasMicrosoftFastStdCallMangling() const {
234 return ManglingMode == MM_WINCOFF;
237 bool hasLinkerPrivateGlobalPrefix() const {
238 return ManglingMode == MM_MachO;
241 const char *getLinkerPrivateGlobalPrefix() const {
242 if (ManglingMode == MM_MachO)
244 return getPrivateGlobalPrefix();
247 char getGlobalPrefix() const {
248 switch (ManglingMode) {
257 llvm_unreachable("invalid mangling mode");
260 const char *getPrivateGlobalPrefix() const {
261 switch (ManglingMode) {
272 llvm_unreachable("invalid mangling mode");
275 static const char *getManglingComponent(const Triple &T);
277 /// fitsInLegalInteger - This function returns true if the specified type fits
278 /// in a native integer type supported by the CPU. For example, if the CPU
279 /// only supports i32 as a native integer type, then i27 fits in a legal
280 // integer type but i45 does not.
281 bool fitsInLegalInteger(unsigned Width) const {
282 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
283 if (Width <= LegalIntWidths[i])
288 /// Layout pointer alignment
289 /// FIXME: The defaults need to be removed once all of
290 /// the backends/clients are updated.
291 unsigned getPointerABIAlignment(unsigned AS = 0) const;
293 /// Return target's alignment for stack-based pointers
294 /// FIXME: The defaults need to be removed once all of
295 /// the backends/clients are updated.
296 unsigned getPointerPrefAlignment(unsigned AS = 0) const;
298 /// Layout pointer size
299 /// FIXME: The defaults need to be removed once all of
300 /// the backends/clients are updated.
301 unsigned getPointerSize(unsigned AS = 0) const;
303 /// Layout pointer size, in bits
304 /// FIXME: The defaults need to be removed once all of
305 /// the backends/clients are updated.
306 unsigned getPointerSizeInBits(unsigned AS = 0) const {
307 return getPointerSize(AS) * 8;
310 /// Layout pointer size, in bits, based on the type. If this function is
311 /// called with a pointer type, then the type size of the pointer is returned.
312 /// If this function is called with a vector of pointers, then the type size
313 /// of the pointer is returned. This should only be called with a pointer or
314 /// vector of pointers.
315 unsigned getPointerTypeSizeInBits(Type *) const;
317 unsigned getPointerTypeSize(Type *Ty) const {
318 return getPointerTypeSizeInBits(Ty) / 8;
323 /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
324 /// ---- ---------- --------------- ---------------
333 /// X86_FP80 80 80 96
335 /// [*] The alloc size depends on the alignment, and thus on the target.
336 /// These values are for x86-32 linux.
338 /// getTypeSizeInBits - Return the number of bits necessary to hold the
339 /// specified type. For example, returns 36 for i36 and 80 for x86_fp80.
340 /// The type passed must have a size (Type::isSized() must return true).
341 uint64_t getTypeSizeInBits(Type *Ty) const;
343 /// getTypeStoreSize - Return the maximum number of bytes that may be
344 /// overwritten by storing the specified type. For example, returns 5
345 /// for i36 and 10 for x86_fp80.
346 uint64_t getTypeStoreSize(Type *Ty) const {
347 return (getTypeSizeInBits(Ty)+7)/8;
350 /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
351 /// overwritten by storing the specified type; always a multiple of 8. For
352 /// example, returns 40 for i36 and 80 for x86_fp80.
353 uint64_t getTypeStoreSizeInBits(Type *Ty) const {
354 return 8*getTypeStoreSize(Ty);
357 /// getTypeAllocSize - Return the offset in bytes between successive objects
358 /// of the specified type, including alignment padding. This is the amount
359 /// that alloca reserves for this type. For example, returns 12 or 16 for
360 /// x86_fp80, depending on alignment.
361 uint64_t getTypeAllocSize(Type *Ty) const {
362 // Round up to the next alignment boundary.
363 return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
366 /// getTypeAllocSizeInBits - Return the offset in bits between successive
367 /// objects of the specified type, including alignment padding; always a
368 /// multiple of 8. This is the amount that alloca reserves for this type.
369 /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
370 uint64_t getTypeAllocSizeInBits(Type *Ty) const {
371 return 8*getTypeAllocSize(Ty);
374 /// getABITypeAlignment - Return the minimum ABI-required alignment for the
376 unsigned getABITypeAlignment(Type *Ty) const;
378 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
379 /// an integer type of the specified bitwidth.
380 unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
382 /// getPrefTypeAlignment - Return the preferred stack/global alignment for
383 /// the specified type. This is always at least as good as the ABI alignment.
384 unsigned getPrefTypeAlignment(Type *Ty) const;
386 /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
387 /// specified type, returned as log2 of the value (a shift amount).
388 unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
390 /// getIntPtrType - Return an integer type with size at least as big as that
391 /// of a pointer in the given address space.
392 IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
394 /// getIntPtrType - Return an integer (vector of integer) type with size at
395 /// least as big as that of a pointer of the given pointer (vector of pointer)
397 Type *getIntPtrType(Type *) const;
399 /// getSmallestLegalIntType - Return the smallest integer type with size at
400 /// least as big as Width bits.
401 Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
403 /// getLargestLegalIntType - Return the largest legal integer type, or null if
405 Type *getLargestLegalIntType(LLVMContext &C) const {
406 unsigned LargestSize = getLargestLegalIntTypeSize();
407 return (LargestSize == 0) ? 0 : Type::getIntNTy(C, LargestSize);
410 /// getLargestLegalIntType - Return the size of largest legal integer type
411 /// size, or 0 if none are set.
412 unsigned getLargestLegalIntTypeSize() const;
414 /// getIndexedOffset - return the offset from the beginning of the type for
415 /// the specified indices. This is used to implement getelementptr.
416 uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
418 /// getStructLayout - Return a StructLayout object, indicating the alignment
419 /// of the struct, its size, and the offsets of its fields. Note that this
420 /// information is lazily cached.
421 const StructLayout *getStructLayout(StructType *Ty) const;
423 /// getPreferredAlignment - Return the preferred alignment of the specified
424 /// global. This includes an explicitly requested alignment (if the global
426 unsigned getPreferredAlignment(const GlobalVariable *GV) const;
428 /// getPreferredAlignmentLog - Return the preferred alignment of the
429 /// specified global, returned in log form. This includes an explicitly
430 /// requested alignment (if the global has one).
431 unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
433 /// RoundUpAlignment - Round the specified value up to the next alignment
434 /// boundary specified by Alignment. For example, 7 rounded up to an
435 /// alignment boundary of 4 is 8. 8 rounded up to the alignment boundary of 4
436 /// is 8 because it is already aligned.
437 template <typename UIntTy>
438 static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
439 assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
440 return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
444 class DataLayoutPass : public ImmutablePass {
448 /// This has to exist, because this is a pass, but it should never be used.
452 const DataLayout &getDataLayout() const { return DL; }
454 // For use with the C API. C++ code should always use the constructor that
456 explicit DataLayoutPass(const DataLayout &DL);
458 explicit DataLayoutPass(const Module *M);
460 static char ID; // Pass identification, replacement for typeid
463 /// StructLayout - used to lazily calculate structure layout information for a
464 /// target machine, based on the DataLayout structure.
468 unsigned StructAlignment;
469 unsigned NumElements;
470 uint64_t MemberOffsets[1]; // variable sized array!
473 uint64_t getSizeInBytes() const {
477 uint64_t getSizeInBits() const {
481 unsigned getAlignment() const {
482 return StructAlignment;
485 /// getElementContainingOffset - Given a valid byte offset into the structure,
486 /// return the structure index that contains it.
488 unsigned getElementContainingOffset(uint64_t Offset) const;
490 uint64_t getElementOffset(unsigned Idx) const {
491 assert(Idx < NumElements && "Invalid element idx!");
492 return MemberOffsets[Idx];
495 uint64_t getElementOffsetInBits(unsigned Idx) const {
496 return getElementOffset(Idx)*8;
500 friend class DataLayout; // Only DataLayout can create this class
501 StructLayout(StructType *ST, const DataLayout &DL);
505 // The implementation of this method is provided inline as it is particularly
506 // well suited to constant folding when called on a specific Type subclass.
507 inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
508 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
509 switch (Ty->getTypeID()) {
510 case Type::LabelTyID:
511 return getPointerSizeInBits(0);
512 case Type::PointerTyID:
513 return getPointerSizeInBits(Ty->getPointerAddressSpace());
514 case Type::ArrayTyID: {
515 ArrayType *ATy = cast<ArrayType>(Ty);
516 return ATy->getNumElements() *
517 getTypeAllocSizeInBits(ATy->getElementType());
519 case Type::StructTyID:
520 // Get the layout annotation... which is lazily created on demand.
521 return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
522 case Type::IntegerTyID:
523 return Ty->getIntegerBitWidth();
526 case Type::FloatTyID:
528 case Type::DoubleTyID:
529 case Type::X86_MMXTyID:
531 case Type::PPC_FP128TyID:
532 case Type::FP128TyID:
534 // In memory objects this is always aligned to a higher boundary, but
535 // only 80 bits contain information.
536 case Type::X86_FP80TyID:
538 case Type::VectorTyID: {
539 VectorType *VTy = cast<VectorType>(Ty);
540 return VTy->getNumElements() * getTypeSizeInBits(VTy->getElementType());
543 llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
547 } // End llvm namespace