1 //===- DataLayout.cpp - Data size & alignment routines ---------------------==//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines layout properties related to datatype size/offset/alignment
12 // This structure should be created once, filled in if the defaults are not
13 // correct and then passed around by const&. None of the members functions
14 // require modification to the object.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/IR/Value.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/TypeSize.h"
42 //===----------------------------------------------------------------------===//
43 // Support for StructLayout
44 //===----------------------------------------------------------------------===//
46 StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
47 assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
50 NumElements = ST->getNumElements();
52 // Loop over each of the elements, placing them in memory.
53 for (unsigned i = 0, e = NumElements; i != e; ++i) {
54 Type *Ty = ST->getElementType(i);
55 const Align TyAlign = ST->isPacked() ? Align(1) : DL.getABITypeAlign(Ty);
57 // Add padding if necessary to align the data element properly.
58 if (!isAligned(TyAlign, StructSize)) {
60 StructSize = alignTo(StructSize, TyAlign);
63 // Keep track of maximum alignment constraint.
64 StructAlignment = std::max(TyAlign, StructAlignment);
66 MemberOffsets[i] = StructSize;
67 StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item
70 // Add padding to the end of the struct so that it could be put in an array
71 // and all array elements would be aligned correctly.
72 if (!isAligned(StructAlignment, StructSize)) {
74 StructSize = alignTo(StructSize, StructAlignment);
78 /// getElementContainingOffset - Given a valid offset into the structure,
79 /// return the structure index that contains it.
80 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
82 std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
83 assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
85 assert(*SI <= Offset && "upper_bound didn't work");
86 assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
87 (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
88 "Upper bound didn't work!");
90 // Multiple fields can have the same offset if any of them are zero sized.
91 // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
92 // at the i32 element, because it is the last element at that offset. This is
93 // the right one to return, because anything after it will have a higher
94 // offset, implying that this element is non-empty.
95 return SI-&MemberOffsets[0];
98 //===----------------------------------------------------------------------===//
99 // LayoutAlignElem, LayoutAlign support
100 //===----------------------------------------------------------------------===//
102 LayoutAlignElem LayoutAlignElem::get(AlignTypeEnum align_type, Align abi_align,
103 Align pref_align, uint32_t bit_width) {
104 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
105 LayoutAlignElem retval;
106 retval.AlignType = align_type;
107 retval.ABIAlign = abi_align;
108 retval.PrefAlign = pref_align;
109 retval.TypeBitWidth = bit_width;
114 LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
115 return (AlignType == rhs.AlignType
116 && ABIAlign == rhs.ABIAlign
117 && PrefAlign == rhs.PrefAlign
118 && TypeBitWidth == rhs.TypeBitWidth);
121 //===----------------------------------------------------------------------===//
122 // PointerAlignElem, PointerAlign support
123 //===----------------------------------------------------------------------===//
125 PointerAlignElem PointerAlignElem::get(uint32_t AddressSpace, Align ABIAlign,
126 Align PrefAlign, uint32_t TypeByteWidth,
127 uint32_t IndexWidth) {
128 assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
129 PointerAlignElem retval;
130 retval.AddressSpace = AddressSpace;
131 retval.ABIAlign = ABIAlign;
132 retval.PrefAlign = PrefAlign;
133 retval.TypeByteWidth = TypeByteWidth;
134 retval.IndexWidth = IndexWidth;
139 PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
140 return (ABIAlign == rhs.ABIAlign
141 && AddressSpace == rhs.AddressSpace
142 && PrefAlign == rhs.PrefAlign
143 && TypeByteWidth == rhs.TypeByteWidth
144 && IndexWidth == rhs.IndexWidth);
147 //===----------------------------------------------------------------------===//
148 // DataLayout Class Implementation
149 //===----------------------------------------------------------------------===//
151 const char *DataLayout::getManglingComponent(const Triple &T) {
152 if (T.isOSBinFormatMachO())
154 if (T.isOSWindows() && T.isOSBinFormatCOFF())
155 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
156 if (T.isOSBinFormatXCOFF())
161 static const LayoutAlignElem DefaultAlignments[] = {
162 {INTEGER_ALIGN, 1, Align(1), Align(1)}, // i1
163 {INTEGER_ALIGN, 8, Align(1), Align(1)}, // i8
164 {INTEGER_ALIGN, 16, Align(2), Align(2)}, // i16
165 {INTEGER_ALIGN, 32, Align(4), Align(4)}, // i32
166 {INTEGER_ALIGN, 64, Align(4), Align(8)}, // i64
167 {FLOAT_ALIGN, 16, Align(2), Align(2)}, // half, bfloat
168 {FLOAT_ALIGN, 32, Align(4), Align(4)}, // float
169 {FLOAT_ALIGN, 64, Align(8), Align(8)}, // double
170 {FLOAT_ALIGN, 128, Align(16), Align(16)}, // ppcf128, quad, ...
171 {VECTOR_ALIGN, 64, Align(8), Align(8)}, // v2i32, v1i64, ...
172 {VECTOR_ALIGN, 128, Align(16), Align(16)}, // v16i8, v8i16, v4i32, ...
173 {AGGREGATE_ALIGN, 0, Align(1), Align(8)} // struct
176 void DataLayout::reset(StringRef Desc) {
182 StackNaturalAlign.reset();
183 ProgramAddrSpace = 0;
184 FunctionPtrAlign.reset();
185 TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
186 ManglingMode = MM_None;
187 NonIntegralAddressSpaces.clear();
189 // Default alignments
190 for (const LayoutAlignElem &E : DefaultAlignments) {
191 setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign, E.PrefAlign,
194 setPointerAlignment(0, Align(8), Align(8), 8, 8);
196 parseSpecifier(Desc);
199 /// Checked version of split, to ensure mandatory subparts.
200 static std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
201 assert(!Str.empty() && "parse error, string can't be empty here");
202 std::pair<StringRef, StringRef> Split = Str.split(Separator);
203 if (Split.second.empty() && Split.first != Str)
204 report_fatal_error("Trailing separator in datalayout string");
205 if (!Split.second.empty() && Split.first.empty())
206 report_fatal_error("Expected token before separator in datalayout string");
210 /// Get an unsigned integer, including error checks.
211 static unsigned getInt(StringRef R) {
213 bool error = R.getAsInteger(10, Result); (void)error;
215 report_fatal_error("not a number, or does not fit in an unsigned int");
219 /// Convert bits into bytes. Assert if not a byte width multiple.
220 static unsigned inBytes(unsigned Bits) {
222 report_fatal_error("number of bits must be a byte width multiple");
226 static unsigned getAddrSpace(StringRef R) {
227 unsigned AddrSpace = getInt(R);
228 if (!isUInt<24>(AddrSpace))
229 report_fatal_error("Invalid address space, must be a 24-bit integer");
233 void DataLayout::parseSpecifier(StringRef Desc) {
234 StringRepresentation = std::string(Desc);
235 while (!Desc.empty()) {
237 std::pair<StringRef, StringRef> Split = split(Desc, '-');
241 Split = split(Split.first, ':');
243 // Aliases used below.
244 StringRef &Tok = Split.first; // Current token.
245 StringRef &Rest = Split.second; // The rest of the string.
249 Split = split(Rest, ':');
251 unsigned AS = getInt(Split.first);
253 report_fatal_error("Address space 0 can never be non-integral");
254 NonIntegralAddressSpaces.push_back(AS);
255 } while (!Rest.empty());
260 char Specifier = Tok.front();
265 // Deprecated, but ignoring here to preserve loading older textual llvm
276 unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
277 if (!isUInt<24>(AddrSpace))
278 report_fatal_error("Invalid address space, must be a 24bit integer");
283 "Missing size specification for pointer in datalayout string");
284 Split = split(Rest, ':');
285 unsigned PointerMemSize = inBytes(getInt(Tok));
287 report_fatal_error("Invalid pointer size of 0 bytes");
292 "Missing alignment specification for pointer in datalayout string");
293 Split = split(Rest, ':');
294 unsigned PointerABIAlign = inBytes(getInt(Tok));
295 if (!isPowerOf2_64(PointerABIAlign))
297 "Pointer ABI alignment must be a power of 2");
299 // Size of index used in GEP for address calculation.
300 // The parameter is optional. By default it is equal to size of pointer.
301 unsigned IndexSize = PointerMemSize;
303 // Preferred alignment.
304 unsigned PointerPrefAlign = PointerABIAlign;
306 Split = split(Rest, ':');
307 PointerPrefAlign = inBytes(getInt(Tok));
308 if (!isPowerOf2_64(PointerPrefAlign))
310 "Pointer preferred alignment must be a power of 2");
312 // Now read the index. It is the second optional parameter here.
314 Split = split(Rest, ':');
315 IndexSize = inBytes(getInt(Tok));
317 report_fatal_error("Invalid index size of 0 bytes");
320 setPointerAlignment(AddrSpace, assumeAligned(PointerABIAlign),
321 assumeAligned(PointerPrefAlign), PointerMemSize,
329 AlignTypeEnum AlignType;
331 default: llvm_unreachable("Unexpected specifier!");
332 case 'i': AlignType = INTEGER_ALIGN; break;
333 case 'v': AlignType = VECTOR_ALIGN; break;
334 case 'f': AlignType = FLOAT_ALIGN; break;
335 case 'a': AlignType = AGGREGATE_ALIGN; break;
339 unsigned Size = Tok.empty() ? 0 : getInt(Tok);
341 if (AlignType == AGGREGATE_ALIGN && Size != 0)
343 "Sized aggregate specification in datalayout string");
348 "Missing alignment specification in datalayout string");
349 Split = split(Rest, ':');
350 const unsigned ABIAlign = inBytes(getInt(Tok));
351 if (AlignType != AGGREGATE_ALIGN && !ABIAlign)
353 "ABI alignment specification must be >0 for non-aggregate types");
355 if (!isUInt<16>(ABIAlign))
356 report_fatal_error("Invalid ABI alignment, must be a 16bit integer");
357 if (ABIAlign != 0 && !isPowerOf2_64(ABIAlign))
358 report_fatal_error("Invalid ABI alignment, must be a power of 2");
360 // Preferred alignment.
361 unsigned PrefAlign = ABIAlign;
363 Split = split(Rest, ':');
364 PrefAlign = inBytes(getInt(Tok));
367 if (!isUInt<16>(PrefAlign))
369 "Invalid preferred alignment, must be a 16bit integer");
370 if (PrefAlign != 0 && !isPowerOf2_64(PrefAlign))
371 report_fatal_error("Invalid preferred alignment, must be a power of 2");
373 setAlignment(AlignType, assumeAligned(ABIAlign), assumeAligned(PrefAlign),
378 case 'n': // Native integer types.
380 unsigned Width = getInt(Tok);
383 "Zero width native integer type in datalayout string");
384 LegalIntWidths.push_back(Width);
387 Split = split(Rest, ':');
390 case 'S': { // Stack natural alignment.
391 uint64_t Alignment = inBytes(getInt(Tok));
392 if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
393 report_fatal_error("Alignment is neither 0 nor a power of 2");
394 StackNaturalAlign = MaybeAlign(Alignment);
398 switch (Tok.front()) {
400 TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
403 TheFunctionPtrAlignType = FunctionPtrAlignType::MultipleOfFunctionAlign;
406 report_fatal_error("Unknown function pointer alignment type in "
407 "datalayout string");
410 uint64_t Alignment = inBytes(getInt(Tok));
411 if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
412 report_fatal_error("Alignment is neither 0 nor a power of 2");
413 FunctionPtrAlign = MaybeAlign(Alignment);
416 case 'P': { // Function address space.
417 ProgramAddrSpace = getAddrSpace(Tok);
420 case 'A': { // Default stack/alloca address space.
421 AllocaAddrSpace = getAddrSpace(Tok);
426 report_fatal_error("Unexpected trailing characters after mangling specifier in datalayout string");
428 report_fatal_error("Expected mangling specifier in datalayout string");
430 report_fatal_error("Unknown mangling specifier in datalayout string");
433 report_fatal_error("Unknown mangling in datalayout string");
435 ManglingMode = MM_ELF;
438 ManglingMode = MM_MachO;
441 ManglingMode = MM_Mips;
444 ManglingMode = MM_WinCOFF;
447 ManglingMode = MM_WinCOFFX86;
450 ManglingMode = MM_XCOFF;
455 report_fatal_error("Unknown specifier in datalayout string");
461 DataLayout::DataLayout(const Module *M) {
465 void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
467 bool DataLayout::operator==(const DataLayout &Other) const {
468 bool Ret = BigEndian == Other.BigEndian &&
469 AllocaAddrSpace == Other.AllocaAddrSpace &&
470 StackNaturalAlign == Other.StackNaturalAlign &&
471 ProgramAddrSpace == Other.ProgramAddrSpace &&
472 FunctionPtrAlign == Other.FunctionPtrAlign &&
473 TheFunctionPtrAlignType == Other.TheFunctionPtrAlignType &&
474 ManglingMode == Other.ManglingMode &&
475 LegalIntWidths == Other.LegalIntWidths &&
476 Alignments == Other.Alignments && Pointers == Other.Pointers;
477 // Note: getStringRepresentation() might differs, it is not canonicalized
481 DataLayout::AlignmentsTy::iterator
482 DataLayout::findAlignmentLowerBound(AlignTypeEnum AlignType,
484 auto Pair = std::make_pair((unsigned)AlignType, BitWidth);
485 return partition_point(Alignments, [=](const LayoutAlignElem &E) {
486 return std::make_pair(E.AlignType, E.TypeBitWidth) < Pair;
490 void DataLayout::setAlignment(AlignTypeEnum align_type, Align abi_align,
491 Align pref_align, uint32_t bit_width) {
492 // AlignmentsTy::ABIAlign and AlignmentsTy::PrefAlign were once stored as
493 // uint16_t, it is unclear if there are requirements for alignment to be less
494 // than 2^16 other than storage. In the meantime we leave the restriction as
495 // an assert. See D67400 for context.
496 assert(Log2(abi_align) < 16 && Log2(pref_align) < 16 && "Alignment too big");
497 if (!isUInt<24>(bit_width))
498 report_fatal_error("Invalid bit width, must be a 24bit integer");
499 if (pref_align < abi_align)
501 "Preferred alignment cannot be less than the ABI alignment");
503 AlignmentsTy::iterator I = findAlignmentLowerBound(align_type, bit_width);
504 if (I != Alignments.end() &&
505 I->AlignType == (unsigned)align_type && I->TypeBitWidth == bit_width) {
506 // Update the abi, preferred alignments.
507 I->ABIAlign = abi_align;
508 I->PrefAlign = pref_align;
510 // Insert before I to keep the vector sorted.
511 Alignments.insert(I, LayoutAlignElem::get(align_type, abi_align,
512 pref_align, bit_width));
516 DataLayout::PointersTy::iterator
517 DataLayout::findPointerLowerBound(uint32_t AddressSpace) {
518 return std::lower_bound(Pointers.begin(), Pointers.end(), AddressSpace,
519 [](const PointerAlignElem &A, uint32_t AddressSpace) {
520 return A.AddressSpace < AddressSpace;
524 void DataLayout::setPointerAlignment(uint32_t AddrSpace, Align ABIAlign,
525 Align PrefAlign, uint32_t TypeByteWidth,
526 uint32_t IndexWidth) {
527 if (PrefAlign < ABIAlign)
529 "Preferred alignment cannot be less than the ABI alignment");
531 PointersTy::iterator I = findPointerLowerBound(AddrSpace);
532 if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
533 Pointers.insert(I, PointerAlignElem::get(AddrSpace, ABIAlign, PrefAlign,
534 TypeByteWidth, IndexWidth));
536 I->ABIAlign = ABIAlign;
537 I->PrefAlign = PrefAlign;
538 I->TypeByteWidth = TypeByteWidth;
539 I->IndexWidth = IndexWidth;
543 /// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
544 /// preferred if ABIInfo = false) the layout wants for the specified datatype.
545 Align DataLayout::getAlignmentInfo(AlignTypeEnum AlignType, uint32_t BitWidth,
546 bool ABIInfo, Type *Ty) const {
547 AlignmentsTy::const_iterator I = findAlignmentLowerBound(AlignType, BitWidth);
548 // See if we found an exact match. Of if we are looking for an integer type,
549 // but don't have an exact match take the next largest integer. This is where
550 // the lower_bound will point to when it fails an exact match.
551 if (I != Alignments.end() && I->AlignType == (unsigned)AlignType &&
552 (I->TypeBitWidth == BitWidth || AlignType == INTEGER_ALIGN))
553 return ABIInfo ? I->ABIAlign : I->PrefAlign;
555 if (AlignType == INTEGER_ALIGN) {
556 // If we didn't have a larger value try the largest value we have.
557 if (I != Alignments.begin()) {
558 --I; // Go to the previous entry and see if its an integer.
559 if (I->AlignType == INTEGER_ALIGN)
560 return ABIInfo ? I->ABIAlign : I->PrefAlign;
562 } else if (AlignType == VECTOR_ALIGN) {
563 // By default, use natural alignment for vector types. This is consistent
564 // with what clang and llvm-gcc do.
566 getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
567 // We're only calculating a natural alignment, so it doesn't have to be
568 // based on the full size for scalable vectors. Using the minimum element
569 // count should be enough here.
570 Alignment *= cast<VectorType>(Ty)->getElementCount().Min;
571 Alignment = PowerOf2Ceil(Alignment);
572 return Align(Alignment);
575 // If we still couldn't find a reasonable default alignment, fall back
576 // to a simple heuristic that the alignment is the first power of two
577 // greater-or-equal to the store size of the type. This is a reasonable
578 // approximation of reality, and if the user wanted something less
579 // less conservative, they should have specified it explicitly in the data
581 unsigned Alignment = getTypeStoreSize(Ty);
582 Alignment = PowerOf2Ceil(Alignment);
583 return Align(Alignment);
588 class StructLayoutMap {
589 using LayoutInfoTy = DenseMap<StructType*, StructLayout*>;
590 LayoutInfoTy LayoutInfo;
594 // Remove any layouts.
595 for (const auto &I : LayoutInfo) {
596 StructLayout *Value = I.second;
597 Value->~StructLayout();
602 StructLayout *&operator[](StructType *STy) {
603 return LayoutInfo[STy];
607 } // end anonymous namespace
609 void DataLayout::clear() {
610 LegalIntWidths.clear();
613 delete static_cast<StructLayoutMap *>(LayoutMap);
617 DataLayout::~DataLayout() {
621 const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
623 LayoutMap = new StructLayoutMap();
625 StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
626 StructLayout *&SL = (*STM)[Ty];
629 // Otherwise, create the struct layout. Because it is variable length, we
630 // malloc it, then use placement new.
631 int NumElts = Ty->getNumElements();
632 StructLayout *L = (StructLayout *)
633 safe_malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
635 // Set SL before calling StructLayout's ctor. The ctor could cause other
636 // entries to be added to TheMap, invalidating our reference.
639 new (L) StructLayout(Ty, *this);
644 Align DataLayout::getPointerABIAlignment(unsigned AS) const {
645 PointersTy::const_iterator I = findPointerLowerBound(AS);
646 if (I == Pointers.end() || I->AddressSpace != AS) {
647 I = findPointerLowerBound(0);
648 assert(I->AddressSpace == 0);
653 Align DataLayout::getPointerPrefAlignment(unsigned AS) const {
654 PointersTy::const_iterator I = findPointerLowerBound(AS);
655 if (I == Pointers.end() || I->AddressSpace != AS) {
656 I = findPointerLowerBound(0);
657 assert(I->AddressSpace == 0);
662 unsigned DataLayout::getPointerSize(unsigned AS) const {
663 PointersTy::const_iterator I = findPointerLowerBound(AS);
664 if (I == Pointers.end() || I->AddressSpace != AS) {
665 I = findPointerLowerBound(0);
666 assert(I->AddressSpace == 0);
668 return I->TypeByteWidth;
671 unsigned DataLayout::getMaxPointerSize() const {
672 unsigned MaxPointerSize = 0;
673 for (auto &P : Pointers)
674 MaxPointerSize = std::max(MaxPointerSize, P.TypeByteWidth);
676 return MaxPointerSize;
679 unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
680 assert(Ty->isPtrOrPtrVectorTy() &&
681 "This should only be called with a pointer or pointer vector type");
682 Ty = Ty->getScalarType();
683 return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
686 unsigned DataLayout::getIndexSize(unsigned AS) const {
687 PointersTy::const_iterator I = findPointerLowerBound(AS);
688 if (I == Pointers.end() || I->AddressSpace != AS) {
689 I = findPointerLowerBound(0);
690 assert(I->AddressSpace == 0);
692 return I->IndexWidth;
695 unsigned DataLayout::getIndexTypeSizeInBits(Type *Ty) const {
696 assert(Ty->isPtrOrPtrVectorTy() &&
697 "This should only be called with a pointer or pointer vector type");
698 Ty = Ty->getScalarType();
699 return getIndexSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
703 \param abi_or_pref Flag that determines which alignment is returned. true
704 returns the ABI alignment, false returns the preferred alignment.
705 \param Ty The underlying type for which alignment is determined.
707 Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
708 == false) for the requested type \a Ty.
710 Align DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
711 AlignTypeEnum AlignType;
713 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
714 switch (Ty->getTypeID()) {
715 // Early escape for the non-numeric types.
716 case Type::LabelTyID:
717 return abi_or_pref ? getPointerABIAlignment(0) : getPointerPrefAlignment(0);
718 case Type::PointerTyID: {
719 unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
720 return abi_or_pref ? getPointerABIAlignment(AS)
721 : getPointerPrefAlignment(AS);
723 case Type::ArrayTyID:
724 return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
726 case Type::StructTyID: {
727 // Packed structure types always have an ABI alignment of one.
728 if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
731 // Get the layout annotation... which is lazily created on demand.
732 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
733 const Align Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
734 return std::max(Align, Layout->getAlignment());
736 case Type::IntegerTyID:
737 AlignType = INTEGER_ALIGN;
740 case Type::BFloatTyID:
741 case Type::FloatTyID:
742 case Type::DoubleTyID:
743 // PPC_FP128TyID and FP128TyID have different data contents, but the
744 // same size and alignment, so they look the same here.
745 case Type::PPC_FP128TyID:
746 case Type::FP128TyID:
747 case Type::X86_FP80TyID:
748 AlignType = FLOAT_ALIGN;
750 case Type::X86_MMXTyID:
751 case Type::FixedVectorTyID:
752 case Type::ScalableVectorTyID:
753 AlignType = VECTOR_ALIGN;
756 llvm_unreachable("Bad type for getAlignment!!!");
759 // If we're dealing with a scalable vector, we just need the known minimum
760 // size for determining alignment. If not, we'll get the exact size.
761 return getAlignmentInfo(AlignType, getTypeSizeInBits(Ty).getKnownMinSize(),
765 /// TODO: Remove this function once the transition to Align is over.
766 unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
767 return getABITypeAlign(Ty).value();
770 Align DataLayout::getABITypeAlign(Type *Ty) const {
771 return getAlignment(Ty, true);
774 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
775 /// an integer type of the specified bitwidth.
776 Align DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
777 return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, nullptr);
780 /// TODO: Remove this function once the transition to Align is over.
781 unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
782 return getPrefTypeAlign(Ty).value();
785 Align DataLayout::getPrefTypeAlign(Type *Ty) const {
786 return getAlignment(Ty, false);
789 IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
790 unsigned AddressSpace) const {
791 return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
794 Type *DataLayout::getIntPtrType(Type *Ty) const {
795 assert(Ty->isPtrOrPtrVectorTy() &&
796 "Expected a pointer or pointer vector type.");
797 unsigned NumBits = getPointerTypeSizeInBits(Ty);
798 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
799 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
800 return VectorType::get(IntTy, VecTy);
804 Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
805 for (unsigned LegalIntWidth : LegalIntWidths)
806 if (Width <= LegalIntWidth)
807 return Type::getIntNTy(C, LegalIntWidth);
811 unsigned DataLayout::getLargestLegalIntTypeSizeInBits() const {
812 auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
813 return Max != LegalIntWidths.end() ? *Max : 0;
816 Type *DataLayout::getIndexType(Type *Ty) const {
817 assert(Ty->isPtrOrPtrVectorTy() &&
818 "Expected a pointer or pointer vector type.");
819 unsigned NumBits = getIndexTypeSizeInBits(Ty);
820 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
821 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
822 return VectorType::get(IntTy, VecTy);
826 int64_t DataLayout::getIndexedOffsetInType(Type *ElemTy,
827 ArrayRef<Value *> Indices) const {
830 generic_gep_type_iterator<Value* const*>
831 GTI = gep_type_begin(ElemTy, Indices),
832 GTE = gep_type_end(ElemTy, Indices);
833 for (; GTI != GTE; ++GTI) {
834 Value *Idx = GTI.getOperand();
835 if (StructType *STy = GTI.getStructTypeOrNull()) {
836 assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
837 unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
839 // Get structure layout information...
840 const StructLayout *Layout = getStructLayout(STy);
842 // Add in the offset, as calculated by the structure layout info...
843 Result += Layout->getElementOffset(FieldNo);
845 // Get the array index and the size of each array element.
846 if (int64_t arrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
847 Result += arrayIdx * getTypeAllocSize(GTI.getIndexedType());
854 /// getPreferredAlign - Return the preferred alignment of the specified global.
855 /// This includes an explicitly requested alignment (if the global has one).
856 Align DataLayout::getPreferredAlign(const GlobalVariable *GV) const {
857 MaybeAlign GVAlignment = GV->getAlign();
858 // If a section is specified, always precisely honor explicit alignment,
859 // so we don't insert padding into a section we don't control.
860 if (GVAlignment && GV->hasSection())
863 // If no explicit alignment is specified, compute the alignment based on
864 // the IR type. If an alignment is specified, increase it to match the ABI
865 // alignment of the IR type.
867 // FIXME: Not sure it makes sense to use the alignment of the type if
868 // there's already an explicit alignment specification.
869 Type *ElemType = GV->getValueType();
870 Align Alignment = getPrefTypeAlign(ElemType);
872 if (*GVAlignment >= Alignment)
873 Alignment = *GVAlignment;
875 Alignment = std::max(*GVAlignment, getABITypeAlign(ElemType));
878 // If no explicit alignment is specified, and the global is large, increase
879 // the alignment to 16.
880 // FIXME: Why 16, specifically?
881 if (GV->hasInitializer() && !GVAlignment) {
882 if (Alignment < Align(16)) {
883 // If the global is not external, see if it is large. If so, give it a
885 if (getTypeSizeInBits(ElemType) > 128)
886 Alignment = Align(16); // 16-byte alignment.