• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- DataLayout.cpp - Data size & alignment routines ---------------------==//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines layout properties related to datatype size/offset/alignment
10 // information.
11 //
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.
15 //
16 //===----------------------------------------------------------------------===//
17 
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/Error.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/TypeSize.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstdint>
37 #include <cstdlib>
38 #include <tuple>
39 #include <utility>
40 
41 using namespace llvm;
42 
43 //===----------------------------------------------------------------------===//
44 // Support for StructLayout
45 //===----------------------------------------------------------------------===//
46 
StructLayout(StructType * ST,const DataLayout & DL)47 StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
48   assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
49   StructSize = 0;
50   IsPadded = false;
51   NumElements = ST->getNumElements();
52 
53   // Loop over each of the elements, placing them in memory.
54   for (unsigned i = 0, e = NumElements; i != e; ++i) {
55     Type *Ty = ST->getElementType(i);
56     const Align TyAlign = ST->isPacked() ? Align(1) : DL.getABITypeAlign(Ty);
57 
58     // Add padding if necessary to align the data element properly.
59     if (!isAligned(TyAlign, StructSize)) {
60       IsPadded = true;
61       StructSize = alignTo(StructSize, TyAlign);
62     }
63 
64     // Keep track of maximum alignment constraint.
65     StructAlignment = std::max(TyAlign, StructAlignment);
66 
67     MemberOffsets[i] = StructSize;
68     StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item
69   }
70 
71   // Add padding to the end of the struct so that it could be put in an array
72   // and all array elements would be aligned correctly.
73   if (!isAligned(StructAlignment, StructSize)) {
74     IsPadded = true;
75     StructSize = alignTo(StructSize, StructAlignment);
76   }
77 }
78 
79 /// getElementContainingOffset - Given a valid offset into the structure,
80 /// return the structure index that contains it.
getElementContainingOffset(uint64_t Offset) const81 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
82   const uint64_t *SI =
83     std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
84   assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
85   --SI;
86   assert(*SI <= Offset && "upper_bound didn't work");
87   assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
88          (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
89          "Upper bound didn't work!");
90 
91   // Multiple fields can have the same offset if any of them are zero sized.
92   // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
93   // at the i32 element, because it is the last element at that offset.  This is
94   // the right one to return, because anything after it will have a higher
95   // offset, implying that this element is non-empty.
96   return SI-&MemberOffsets[0];
97 }
98 
99 //===----------------------------------------------------------------------===//
100 // LayoutAlignElem, LayoutAlign support
101 //===----------------------------------------------------------------------===//
102 
get(AlignTypeEnum align_type,Align abi_align,Align pref_align,uint32_t bit_width)103 LayoutAlignElem LayoutAlignElem::get(AlignTypeEnum align_type, Align abi_align,
104                                      Align pref_align, uint32_t bit_width) {
105   assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
106   LayoutAlignElem retval;
107   retval.AlignType = align_type;
108   retval.ABIAlign = abi_align;
109   retval.PrefAlign = pref_align;
110   retval.TypeBitWidth = bit_width;
111   return retval;
112 }
113 
114 bool
operator ==(const LayoutAlignElem & rhs) const115 LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
116   return (AlignType == rhs.AlignType
117           && ABIAlign == rhs.ABIAlign
118           && PrefAlign == rhs.PrefAlign
119           && TypeBitWidth == rhs.TypeBitWidth);
120 }
121 
122 //===----------------------------------------------------------------------===//
123 // PointerAlignElem, PointerAlign support
124 //===----------------------------------------------------------------------===//
125 
get(uint32_t AddressSpace,Align ABIAlign,Align PrefAlign,uint32_t TypeByteWidth,uint32_t IndexWidth)126 PointerAlignElem PointerAlignElem::get(uint32_t AddressSpace, Align ABIAlign,
127                                        Align PrefAlign, uint32_t TypeByteWidth,
128                                        uint32_t IndexWidth) {
129   assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
130   PointerAlignElem retval;
131   retval.AddressSpace = AddressSpace;
132   retval.ABIAlign = ABIAlign;
133   retval.PrefAlign = PrefAlign;
134   retval.TypeByteWidth = TypeByteWidth;
135   retval.IndexWidth = IndexWidth;
136   return retval;
137 }
138 
139 bool
operator ==(const PointerAlignElem & rhs) const140 PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
141   return (ABIAlign == rhs.ABIAlign
142           && AddressSpace == rhs.AddressSpace
143           && PrefAlign == rhs.PrefAlign
144           && TypeByteWidth == rhs.TypeByteWidth
145           && IndexWidth == rhs.IndexWidth);
146 }
147 
148 //===----------------------------------------------------------------------===//
149 //                       DataLayout Class Implementation
150 //===----------------------------------------------------------------------===//
151 
getManglingComponent(const Triple & T)152 const char *DataLayout::getManglingComponent(const Triple &T) {
153   if (T.isOSBinFormatMachO())
154     return "-m:o";
155   if (T.isOSWindows() && T.isOSBinFormatCOFF())
156     return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
157   if (T.isOSBinFormatXCOFF())
158     return "-m:a";
159   return "-m:e";
160 }
161 
162 static const LayoutAlignElem DefaultAlignments[] = {
163     {INTEGER_ALIGN, 1, Align(1), Align(1)},    // i1
164     {INTEGER_ALIGN, 8, Align(1), Align(1)},    // i8
165     {INTEGER_ALIGN, 16, Align(2), Align(2)},   // i16
166     {INTEGER_ALIGN, 32, Align(4), Align(4)},   // i32
167     {INTEGER_ALIGN, 64, Align(4), Align(8)},   // i64
168     {FLOAT_ALIGN, 16, Align(2), Align(2)},     // half, bfloat
169     {FLOAT_ALIGN, 32, Align(4), Align(4)},     // float
170     {FLOAT_ALIGN, 64, Align(8), Align(8)},     // double
171     {FLOAT_ALIGN, 128, Align(16), Align(16)},  // ppcf128, quad, ...
172     {VECTOR_ALIGN, 64, Align(8), Align(8)},    // v2i32, v1i64, ...
173     {VECTOR_ALIGN, 128, Align(16), Align(16)}, // v16i8, v8i16, v4i32, ...
174     {AGGREGATE_ALIGN, 0, Align(1), Align(8)}   // struct
175 };
176 
reset(StringRef Desc)177 void DataLayout::reset(StringRef Desc) {
178   clear();
179 
180   LayoutMap = nullptr;
181   BigEndian = false;
182   AllocaAddrSpace = 0;
183   StackNaturalAlign.reset();
184   ProgramAddrSpace = 0;
185   DefaultGlobalsAddrSpace = 0;
186   FunctionPtrAlign.reset();
187   TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
188   ManglingMode = MM_None;
189   NonIntegralAddressSpaces.clear();
190 
191   // Default alignments
192   for (const LayoutAlignElem &E : DefaultAlignments) {
193     if (Error Err = setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign,
194                                  E.PrefAlign, E.TypeBitWidth))
195       return report_fatal_error(std::move(Err));
196   }
197   if (Error Err = setPointerAlignment(0, Align(8), Align(8), 8, 8))
198     return report_fatal_error(std::move(Err));
199 
200   if (Error Err = parseSpecifier(Desc))
201     return report_fatal_error(std::move(Err));
202 }
203 
parse(StringRef LayoutDescription)204 Expected<DataLayout> DataLayout::parse(StringRef LayoutDescription) {
205   DataLayout Layout("");
206   if (Error Err = Layout.parseSpecifier(LayoutDescription))
207     return std::move(Err);
208   return Layout;
209 }
210 
reportError(const Twine & Message)211 static Error reportError(const Twine &Message) {
212   return createStringError(inconvertibleErrorCode(), Message);
213 }
214 
215 /// Checked version of split, to ensure mandatory subparts.
split(StringRef Str,char Separator,std::pair<StringRef,StringRef> & Split)216 static Error split(StringRef Str, char Separator,
217                    std::pair<StringRef, StringRef> &Split) {
218   assert(!Str.empty() && "parse error, string can't be empty here");
219   Split = Str.split(Separator);
220   if (Split.second.empty() && Split.first != Str)
221     return reportError("Trailing separator in datalayout string");
222   if (!Split.second.empty() && Split.first.empty())
223     return reportError("Expected token before separator in datalayout string");
224   return Error::success();
225 }
226 
227 /// Get an unsigned integer, including error checks.
getInt(StringRef R,IntTy & Result)228 template <typename IntTy> static Error getInt(StringRef R, IntTy &Result) {
229   bool error = R.getAsInteger(10, Result); (void)error;
230   if (error)
231     return reportError("not a number, or does not fit in an unsigned int");
232   return Error::success();
233 }
234 
235 /// Get an unsigned integer representing the number of bits and convert it into
236 /// bytes. Error out of not a byte width multiple.
237 template <typename IntTy>
getIntInBytes(StringRef R,IntTy & Result)238 static Error getIntInBytes(StringRef R, IntTy &Result) {
239   if (Error Err = getInt<IntTy>(R, Result))
240     return Err;
241   if (Result % 8)
242     return reportError("number of bits must be a byte width multiple");
243   Result /= 8;
244   return Error::success();
245 }
246 
getAddrSpace(StringRef R,unsigned & AddrSpace)247 static Error getAddrSpace(StringRef R, unsigned &AddrSpace) {
248   if (Error Err = getInt(R, AddrSpace))
249     return Err;
250   if (!isUInt<24>(AddrSpace))
251     return reportError("Invalid address space, must be a 24-bit integer");
252   return Error::success();
253 }
254 
parseSpecifier(StringRef Desc)255 Error DataLayout::parseSpecifier(StringRef Desc) {
256   StringRepresentation = std::string(Desc);
257   while (!Desc.empty()) {
258     // Split at '-'.
259     std::pair<StringRef, StringRef> Split;
260     if (Error Err = split(Desc, '-', Split))
261       return Err;
262     Desc = Split.second;
263 
264     // Split at ':'.
265     if (Error Err = split(Split.first, ':', Split))
266       return Err;
267 
268     // Aliases used below.
269     StringRef &Tok  = Split.first;  // Current token.
270     StringRef &Rest = Split.second; // The rest of the string.
271 
272     if (Tok == "ni") {
273       do {
274         if (Error Err = split(Rest, ':', Split))
275           return Err;
276         Rest = Split.second;
277         unsigned AS;
278         if (Error Err = getInt(Split.first, AS))
279           return Err;
280         if (AS == 0)
281           return reportError("Address space 0 can never be non-integral");
282         NonIntegralAddressSpaces.push_back(AS);
283       } while (!Rest.empty());
284 
285       continue;
286     }
287 
288     char Specifier = Tok.front();
289     Tok = Tok.substr(1);
290 
291     switch (Specifier) {
292     case 's':
293       // Deprecated, but ignoring here to preserve loading older textual llvm
294       // ASM file
295       break;
296     case 'E':
297       BigEndian = true;
298       break;
299     case 'e':
300       BigEndian = false;
301       break;
302     case 'p': {
303       // Address space.
304       unsigned AddrSpace = 0;
305       if (!Tok.empty())
306         if (Error Err = getInt(Tok, AddrSpace))
307           return Err;
308       if (!isUInt<24>(AddrSpace))
309         return reportError("Invalid address space, must be a 24bit integer");
310 
311       // Size.
312       if (Rest.empty())
313         return reportError(
314             "Missing size specification for pointer in datalayout string");
315       if (Error Err = split(Rest, ':', Split))
316         return Err;
317       unsigned PointerMemSize;
318       if (Error Err = getIntInBytes(Tok, PointerMemSize))
319         return Err;
320       if (!PointerMemSize)
321         return reportError("Invalid pointer size of 0 bytes");
322 
323       // ABI alignment.
324       if (Rest.empty())
325         return reportError(
326             "Missing alignment specification for pointer in datalayout string");
327       if (Error Err = split(Rest, ':', Split))
328         return Err;
329       unsigned PointerABIAlign;
330       if (Error Err = getIntInBytes(Tok, PointerABIAlign))
331         return Err;
332       if (!isPowerOf2_64(PointerABIAlign))
333         return reportError("Pointer ABI alignment must be a power of 2");
334 
335       // Size of index used in GEP for address calculation.
336       // The parameter is optional. By default it is equal to size of pointer.
337       unsigned IndexSize = PointerMemSize;
338 
339       // Preferred alignment.
340       unsigned PointerPrefAlign = PointerABIAlign;
341       if (!Rest.empty()) {
342         if (Error Err = split(Rest, ':', Split))
343           return Err;
344         if (Error Err = getIntInBytes(Tok, PointerPrefAlign))
345           return Err;
346         if (!isPowerOf2_64(PointerPrefAlign))
347           return reportError(
348               "Pointer preferred alignment must be a power of 2");
349 
350         // Now read the index. It is the second optional parameter here.
351         if (!Rest.empty()) {
352           if (Error Err = split(Rest, ':', Split))
353             return Err;
354           if (Error Err = getIntInBytes(Tok, IndexSize))
355             return Err;
356           if (!IndexSize)
357             return reportError("Invalid index size of 0 bytes");
358         }
359       }
360       if (Error Err = setPointerAlignment(
361               AddrSpace, assumeAligned(PointerABIAlign),
362               assumeAligned(PointerPrefAlign), PointerMemSize, IndexSize))
363         return Err;
364       break;
365     }
366     case 'i':
367     case 'v':
368     case 'f':
369     case 'a': {
370       AlignTypeEnum AlignType;
371       switch (Specifier) {
372       default: llvm_unreachable("Unexpected specifier!");
373       case 'i': AlignType = INTEGER_ALIGN; break;
374       case 'v': AlignType = VECTOR_ALIGN; break;
375       case 'f': AlignType = FLOAT_ALIGN; break;
376       case 'a': AlignType = AGGREGATE_ALIGN; break;
377       }
378 
379       // Bit size.
380       unsigned Size = 0;
381       if (!Tok.empty())
382         if (Error Err = getInt(Tok, Size))
383           return Err;
384 
385       if (AlignType == AGGREGATE_ALIGN && Size != 0)
386         return reportError(
387             "Sized aggregate specification in datalayout string");
388 
389       // ABI alignment.
390       if (Rest.empty())
391         return reportError(
392             "Missing alignment specification in datalayout string");
393       if (Error Err = split(Rest, ':', Split))
394         return Err;
395       unsigned ABIAlign;
396       if (Error Err = getIntInBytes(Tok, ABIAlign))
397         return Err;
398       if (AlignType != AGGREGATE_ALIGN && !ABIAlign)
399         return reportError(
400             "ABI alignment specification must be >0 for non-aggregate types");
401 
402       if (!isUInt<16>(ABIAlign))
403         return reportError("Invalid ABI alignment, must be a 16bit integer");
404       if (ABIAlign != 0 && !isPowerOf2_64(ABIAlign))
405         return reportError("Invalid ABI alignment, must be a power of 2");
406 
407       // Preferred alignment.
408       unsigned PrefAlign = ABIAlign;
409       if (!Rest.empty()) {
410         if (Error Err = split(Rest, ':', Split))
411           return Err;
412         if (Error Err = getIntInBytes(Tok, PrefAlign))
413           return Err;
414       }
415 
416       if (!isUInt<16>(PrefAlign))
417         return reportError(
418             "Invalid preferred alignment, must be a 16bit integer");
419       if (PrefAlign != 0 && !isPowerOf2_64(PrefAlign))
420         return reportError("Invalid preferred alignment, must be a power of 2");
421 
422       if (Error Err = setAlignment(AlignType, assumeAligned(ABIAlign),
423                                    assumeAligned(PrefAlign), Size))
424         return Err;
425 
426       break;
427     }
428     case 'n':  // Native integer types.
429       while (true) {
430         unsigned Width;
431         if (Error Err = getInt(Tok, Width))
432           return Err;
433         if (Width == 0)
434           return reportError(
435               "Zero width native integer type in datalayout string");
436         LegalIntWidths.push_back(Width);
437         if (Rest.empty())
438           break;
439         if (Error Err = split(Rest, ':', Split))
440           return Err;
441       }
442       break;
443     case 'S': { // Stack natural alignment.
444       uint64_t Alignment;
445       if (Error Err = getIntInBytes(Tok, Alignment))
446         return Err;
447       if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
448         return reportError("Alignment is neither 0 nor a power of 2");
449       StackNaturalAlign = MaybeAlign(Alignment);
450       break;
451     }
452     case 'F': {
453       switch (Tok.front()) {
454       case 'i':
455         TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
456         break;
457       case 'n':
458         TheFunctionPtrAlignType = FunctionPtrAlignType::MultipleOfFunctionAlign;
459         break;
460       default:
461         return reportError("Unknown function pointer alignment type in "
462                            "datalayout string");
463       }
464       Tok = Tok.substr(1);
465       uint64_t Alignment;
466       if (Error Err = getIntInBytes(Tok, Alignment))
467         return Err;
468       if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
469         return reportError("Alignment is neither 0 nor a power of 2");
470       FunctionPtrAlign = MaybeAlign(Alignment);
471       break;
472     }
473     case 'P': { // Function address space.
474       if (Error Err = getAddrSpace(Tok, ProgramAddrSpace))
475         return Err;
476       break;
477     }
478     case 'A': { // Default stack/alloca address space.
479       if (Error Err = getAddrSpace(Tok, AllocaAddrSpace))
480         return Err;
481       break;
482     }
483     case 'G': { // Default address space for global variables.
484       if (Error Err = getAddrSpace(Tok, DefaultGlobalsAddrSpace))
485         return Err;
486       break;
487     }
488     case 'm':
489       if (!Tok.empty())
490         return reportError("Unexpected trailing characters after mangling "
491                            "specifier in datalayout string");
492       if (Rest.empty())
493         return reportError("Expected mangling specifier in datalayout string");
494       if (Rest.size() > 1)
495         return reportError("Unknown mangling specifier in datalayout string");
496       switch(Rest[0]) {
497       default:
498         return reportError("Unknown mangling in datalayout string");
499       case 'e':
500         ManglingMode = MM_ELF;
501         break;
502       case 'o':
503         ManglingMode = MM_MachO;
504         break;
505       case 'm':
506         ManglingMode = MM_Mips;
507         break;
508       case 'w':
509         ManglingMode = MM_WinCOFF;
510         break;
511       case 'x':
512         ManglingMode = MM_WinCOFFX86;
513         break;
514       case 'a':
515         ManglingMode = MM_XCOFF;
516         break;
517       }
518       break;
519     default:
520       return reportError("Unknown specifier in datalayout string");
521       break;
522     }
523   }
524 
525   return Error::success();
526 }
527 
DataLayout(const Module * M)528 DataLayout::DataLayout(const Module *M) {
529   init(M);
530 }
531 
init(const Module * M)532 void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
533 
operator ==(const DataLayout & Other) const534 bool DataLayout::operator==(const DataLayout &Other) const {
535   bool Ret = BigEndian == Other.BigEndian &&
536              AllocaAddrSpace == Other.AllocaAddrSpace &&
537              StackNaturalAlign == Other.StackNaturalAlign &&
538              ProgramAddrSpace == Other.ProgramAddrSpace &&
539              DefaultGlobalsAddrSpace == Other.DefaultGlobalsAddrSpace &&
540              FunctionPtrAlign == Other.FunctionPtrAlign &&
541              TheFunctionPtrAlignType == Other.TheFunctionPtrAlignType &&
542              ManglingMode == Other.ManglingMode &&
543              LegalIntWidths == Other.LegalIntWidths &&
544              Alignments == Other.Alignments && Pointers == Other.Pointers;
545   // Note: getStringRepresentation() might differs, it is not canonicalized
546   return Ret;
547 }
548 
549 DataLayout::AlignmentsTy::iterator
findAlignmentLowerBound(AlignTypeEnum AlignType,uint32_t BitWidth)550 DataLayout::findAlignmentLowerBound(AlignTypeEnum AlignType,
551                                     uint32_t BitWidth) {
552   auto Pair = std::make_pair((unsigned)AlignType, BitWidth);
553   return partition_point(Alignments, [=](const LayoutAlignElem &E) {
554     return std::make_pair(E.AlignType, E.TypeBitWidth) < Pair;
555   });
556 }
557 
setAlignment(AlignTypeEnum align_type,Align abi_align,Align pref_align,uint32_t bit_width)558 Error DataLayout::setAlignment(AlignTypeEnum align_type, Align abi_align,
559                                Align pref_align, uint32_t bit_width) {
560   // AlignmentsTy::ABIAlign and AlignmentsTy::PrefAlign were once stored as
561   // uint16_t, it is unclear if there are requirements for alignment to be less
562   // than 2^16 other than storage. In the meantime we leave the restriction as
563   // an assert. See D67400 for context.
564   assert(Log2(abi_align) < 16 && Log2(pref_align) < 16 && "Alignment too big");
565   if (!isUInt<24>(bit_width))
566     return reportError("Invalid bit width, must be a 24bit integer");
567   if (pref_align < abi_align)
568     return reportError(
569         "Preferred alignment cannot be less than the ABI alignment");
570 
571   AlignmentsTy::iterator I = findAlignmentLowerBound(align_type, bit_width);
572   if (I != Alignments.end() &&
573       I->AlignType == (unsigned)align_type && I->TypeBitWidth == bit_width) {
574     // Update the abi, preferred alignments.
575     I->ABIAlign = abi_align;
576     I->PrefAlign = pref_align;
577   } else {
578     // Insert before I to keep the vector sorted.
579     Alignments.insert(I, LayoutAlignElem::get(align_type, abi_align,
580                                               pref_align, bit_width));
581   }
582   return Error::success();
583 }
584 
585 const PointerAlignElem &
getPointerAlignElem(uint32_t AddressSpace) const586 DataLayout::getPointerAlignElem(uint32_t AddressSpace) const {
587   if (AddressSpace != 0) {
588     auto I = lower_bound(Pointers, AddressSpace,
589                          [](const PointerAlignElem &A, uint32_t AddressSpace) {
590       return A.AddressSpace < AddressSpace;
591     });
592     if (I != Pointers.end() && I->AddressSpace == AddressSpace)
593       return *I;
594   }
595 
596   assert(Pointers[0].AddressSpace == 0);
597   return Pointers[0];
598 }
599 
setPointerAlignment(uint32_t AddrSpace,Align ABIAlign,Align PrefAlign,uint32_t TypeByteWidth,uint32_t IndexWidth)600 Error DataLayout::setPointerAlignment(uint32_t AddrSpace, Align ABIAlign,
601                                       Align PrefAlign, uint32_t TypeByteWidth,
602                                       uint32_t IndexWidth) {
603   if (PrefAlign < ABIAlign)
604     return reportError(
605         "Preferred alignment cannot be less than the ABI alignment");
606 
607   auto I = lower_bound(Pointers, AddrSpace,
608                        [](const PointerAlignElem &A, uint32_t AddressSpace) {
609     return A.AddressSpace < AddressSpace;
610   });
611   if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
612     Pointers.insert(I, PointerAlignElem::get(AddrSpace, ABIAlign, PrefAlign,
613                                              TypeByteWidth, IndexWidth));
614   } else {
615     I->ABIAlign = ABIAlign;
616     I->PrefAlign = PrefAlign;
617     I->TypeByteWidth = TypeByteWidth;
618     I->IndexWidth = IndexWidth;
619   }
620   return Error::success();
621 }
622 
getIntegerAlignment(uint32_t BitWidth,bool abi_or_pref) const623 Align DataLayout::getIntegerAlignment(uint32_t BitWidth,
624                                       bool abi_or_pref) const {
625   auto I = findAlignmentLowerBound(INTEGER_ALIGN, BitWidth);
626   // If we don't have an exact match, use alignment of next larger integer
627   // type. If there is none, use alignment of largest integer type by going
628   // back one element.
629   if (I == Alignments.end() || I->AlignType != INTEGER_ALIGN)
630     --I;
631   assert(I->AlignType == INTEGER_ALIGN && "Must be integer alignment");
632   return abi_or_pref ? I->ABIAlign : I->PrefAlign;
633 }
634 
635 namespace {
636 
637 class StructLayoutMap {
638   using LayoutInfoTy = DenseMap<StructType*, StructLayout*>;
639   LayoutInfoTy LayoutInfo;
640 
641 public:
~StructLayoutMap()642   ~StructLayoutMap() {
643     // Remove any layouts.
644     for (const auto &I : LayoutInfo) {
645       StructLayout *Value = I.second;
646       Value->~StructLayout();
647       free(Value);
648     }
649   }
650 
operator [](StructType * STy)651   StructLayout *&operator[](StructType *STy) {
652     return LayoutInfo[STy];
653   }
654 };
655 
656 } // end anonymous namespace
657 
clear()658 void DataLayout::clear() {
659   LegalIntWidths.clear();
660   Alignments.clear();
661   Pointers.clear();
662   delete static_cast<StructLayoutMap *>(LayoutMap);
663   LayoutMap = nullptr;
664 }
665 
~DataLayout()666 DataLayout::~DataLayout() {
667   clear();
668 }
669 
getStructLayout(StructType * Ty) const670 const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
671   if (!LayoutMap)
672     LayoutMap = new StructLayoutMap();
673 
674   StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
675   StructLayout *&SL = (*STM)[Ty];
676   if (SL) return SL;
677 
678   // Otherwise, create the struct layout.  Because it is variable length, we
679   // malloc it, then use placement new.
680   int NumElts = Ty->getNumElements();
681   StructLayout *L = (StructLayout *)
682       safe_malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
683 
684   // Set SL before calling StructLayout's ctor.  The ctor could cause other
685   // entries to be added to TheMap, invalidating our reference.
686   SL = L;
687 
688   new (L) StructLayout(Ty, *this);
689 
690   return L;
691 }
692 
getPointerABIAlignment(unsigned AS) const693 Align DataLayout::getPointerABIAlignment(unsigned AS) const {
694   return getPointerAlignElem(AS).ABIAlign;
695 }
696 
getPointerPrefAlignment(unsigned AS) const697 Align DataLayout::getPointerPrefAlignment(unsigned AS) const {
698   return getPointerAlignElem(AS).PrefAlign;
699 }
700 
getPointerSize(unsigned AS) const701 unsigned DataLayout::getPointerSize(unsigned AS) const {
702   return getPointerAlignElem(AS).TypeByteWidth;
703 }
704 
getMaxPointerSize() const705 unsigned DataLayout::getMaxPointerSize() const {
706   unsigned MaxPointerSize = 0;
707   for (auto &P : Pointers)
708     MaxPointerSize = std::max(MaxPointerSize, P.TypeByteWidth);
709 
710   return MaxPointerSize;
711 }
712 
getPointerTypeSizeInBits(Type * Ty) const713 unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
714   assert(Ty->isPtrOrPtrVectorTy() &&
715          "This should only be called with a pointer or pointer vector type");
716   Ty = Ty->getScalarType();
717   return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
718 }
719 
getIndexSize(unsigned AS) const720 unsigned DataLayout::getIndexSize(unsigned AS) const {
721   return getPointerAlignElem(AS).IndexWidth;
722 }
723 
getIndexTypeSizeInBits(Type * Ty) const724 unsigned DataLayout::getIndexTypeSizeInBits(Type *Ty) const {
725   assert(Ty->isPtrOrPtrVectorTy() &&
726          "This should only be called with a pointer or pointer vector type");
727   Ty = Ty->getScalarType();
728   return getIndexSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
729 }
730 
731 /*!
732   \param abi_or_pref Flag that determines which alignment is returned. true
733   returns the ABI alignment, false returns the preferred alignment.
734   \param Ty The underlying type for which alignment is determined.
735 
736   Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
737   == false) for the requested type \a Ty.
738  */
getAlignment(Type * Ty,bool abi_or_pref) const739 Align DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
740   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
741   switch (Ty->getTypeID()) {
742   // Early escape for the non-numeric types.
743   case Type::LabelTyID:
744     return abi_or_pref ? getPointerABIAlignment(0) : getPointerPrefAlignment(0);
745   case Type::PointerTyID: {
746     unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
747     return abi_or_pref ? getPointerABIAlignment(AS)
748                        : getPointerPrefAlignment(AS);
749     }
750   case Type::ArrayTyID:
751     return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
752 
753   case Type::StructTyID: {
754     // Packed structure types always have an ABI alignment of one.
755     if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
756       return Align(1);
757 
758     // Get the layout annotation... which is lazily created on demand.
759     const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
760     const LayoutAlignElem &AggregateAlign = Alignments[0];
761     assert(AggregateAlign.AlignType == AGGREGATE_ALIGN &&
762            "Aggregate alignment must be first alignment entry");
763     const Align Align =
764         abi_or_pref ? AggregateAlign.ABIAlign : AggregateAlign.PrefAlign;
765     return std::max(Align, Layout->getAlignment());
766   }
767   case Type::IntegerTyID:
768     return getIntegerAlignment(Ty->getIntegerBitWidth(), abi_or_pref);
769   case Type::HalfTyID:
770   case Type::BFloatTyID:
771   case Type::FloatTyID:
772   case Type::DoubleTyID:
773   // PPC_FP128TyID and FP128TyID have different data contents, but the
774   // same size and alignment, so they look the same here.
775   case Type::PPC_FP128TyID:
776   case Type::FP128TyID:
777   case Type::X86_FP80TyID: {
778     unsigned BitWidth = getTypeSizeInBits(Ty).getFixedSize();
779     auto I = findAlignmentLowerBound(FLOAT_ALIGN, BitWidth);
780     if (I != Alignments.end() && I->AlignType == FLOAT_ALIGN &&
781         I->TypeBitWidth == BitWidth)
782       return abi_or_pref ? I->ABIAlign : I->PrefAlign;
783 
784     // If we still couldn't find a reasonable default alignment, fall back
785     // to a simple heuristic that the alignment is the first power of two
786     // greater-or-equal to the store size of the type.  This is a reasonable
787     // approximation of reality, and if the user wanted something less
788     // less conservative, they should have specified it explicitly in the data
789     // layout.
790     return Align(PowerOf2Ceil(BitWidth / 8));
791   }
792   case Type::X86_MMXTyID:
793   case Type::FixedVectorTyID:
794   case Type::ScalableVectorTyID: {
795     unsigned BitWidth = getTypeSizeInBits(Ty).getKnownMinSize();
796     auto I = findAlignmentLowerBound(VECTOR_ALIGN, BitWidth);
797     if (I != Alignments.end() && I->AlignType == VECTOR_ALIGN &&
798         I->TypeBitWidth == BitWidth)
799       return abi_or_pref ? I->ABIAlign : I->PrefAlign;
800 
801     // By default, use natural alignment for vector types. This is consistent
802     // with what clang and llvm-gcc do.
803     // TODO: This should probably not be using the alloc size.
804     unsigned Alignment =
805         getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
806     // We're only calculating a natural alignment, so it doesn't have to be
807     // based on the full size for scalable vectors. Using the minimum element
808     // count should be enough here.
809     Alignment *= cast<VectorType>(Ty)->getElementCount().getKnownMinValue();
810     Alignment = PowerOf2Ceil(Alignment);
811     return Align(Alignment);
812   }
813   default:
814     llvm_unreachable("Bad type for getAlignment!!!");
815   }
816 }
817 
818 /// TODO: Remove this function once the transition to Align is over.
getABITypeAlignment(Type * Ty) const819 unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
820   return getABITypeAlign(Ty).value();
821 }
822 
getABITypeAlign(Type * Ty) const823 Align DataLayout::getABITypeAlign(Type *Ty) const {
824   return getAlignment(Ty, true);
825 }
826 
827 /// TODO: Remove this function once the transition to Align is over.
getPrefTypeAlignment(Type * Ty) const828 unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
829   return getPrefTypeAlign(Ty).value();
830 }
831 
getPrefTypeAlign(Type * Ty) const832 Align DataLayout::getPrefTypeAlign(Type *Ty) const {
833   return getAlignment(Ty, false);
834 }
835 
getIntPtrType(LLVMContext & C,unsigned AddressSpace) const836 IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
837                                        unsigned AddressSpace) const {
838   return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
839 }
840 
getIntPtrType(Type * Ty) const841 Type *DataLayout::getIntPtrType(Type *Ty) const {
842   assert(Ty->isPtrOrPtrVectorTy() &&
843          "Expected a pointer or pointer vector type.");
844   unsigned NumBits = getPointerTypeSizeInBits(Ty);
845   IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
846   if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
847     return VectorType::get(IntTy, VecTy);
848   return IntTy;
849 }
850 
getSmallestLegalIntType(LLVMContext & C,unsigned Width) const851 Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
852   for (unsigned LegalIntWidth : LegalIntWidths)
853     if (Width <= LegalIntWidth)
854       return Type::getIntNTy(C, LegalIntWidth);
855   return nullptr;
856 }
857 
getLargestLegalIntTypeSizeInBits() const858 unsigned DataLayout::getLargestLegalIntTypeSizeInBits() const {
859   auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
860   return Max != LegalIntWidths.end() ? *Max : 0;
861 }
862 
getIndexType(Type * Ty) const863 Type *DataLayout::getIndexType(Type *Ty) const {
864   assert(Ty->isPtrOrPtrVectorTy() &&
865          "Expected a pointer or pointer vector type.");
866   unsigned NumBits = getIndexTypeSizeInBits(Ty);
867   IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
868   if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
869     return VectorType::get(IntTy, VecTy);
870   return IntTy;
871 }
872 
getIndexedOffsetInType(Type * ElemTy,ArrayRef<Value * > Indices) const873 int64_t DataLayout::getIndexedOffsetInType(Type *ElemTy,
874                                            ArrayRef<Value *> Indices) const {
875   int64_t Result = 0;
876 
877   generic_gep_type_iterator<Value* const*>
878     GTI = gep_type_begin(ElemTy, Indices),
879     GTE = gep_type_end(ElemTy, Indices);
880   for (; GTI != GTE; ++GTI) {
881     Value *Idx = GTI.getOperand();
882     if (StructType *STy = GTI.getStructTypeOrNull()) {
883       assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
884       unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
885 
886       // Get structure layout information...
887       const StructLayout *Layout = getStructLayout(STy);
888 
889       // Add in the offset, as calculated by the structure layout info...
890       Result += Layout->getElementOffset(FieldNo);
891     } else {
892       // Get the array index and the size of each array element.
893       if (int64_t arrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
894         Result += arrayIdx * getTypeAllocSize(GTI.getIndexedType());
895     }
896   }
897 
898   return Result;
899 }
900 
901 /// getPreferredAlign - Return the preferred alignment of the specified global.
902 /// This includes an explicitly requested alignment (if the global has one).
getPreferredAlign(const GlobalVariable * GV) const903 Align DataLayout::getPreferredAlign(const GlobalVariable *GV) const {
904   MaybeAlign GVAlignment = GV->getAlign();
905   // If a section is specified, always precisely honor explicit alignment,
906   // so we don't insert padding into a section we don't control.
907   if (GVAlignment && GV->hasSection())
908     return *GVAlignment;
909 
910   // If no explicit alignment is specified, compute the alignment based on
911   // the IR type. If an alignment is specified, increase it to match the ABI
912   // alignment of the IR type.
913   //
914   // FIXME: Not sure it makes sense to use the alignment of the type if
915   // there's already an explicit alignment specification.
916   Type *ElemType = GV->getValueType();
917   Align Alignment = getPrefTypeAlign(ElemType);
918   if (GVAlignment) {
919     if (*GVAlignment >= Alignment)
920       Alignment = *GVAlignment;
921     else
922       Alignment = std::max(*GVAlignment, getABITypeAlign(ElemType));
923   }
924 
925   // If no explicit alignment is specified, and the global is large, increase
926   // the alignment to 16.
927   // FIXME: Why 16, specifically?
928   if (GV->hasInitializer() && !GVAlignment) {
929     if (Alignment < Align(16)) {
930       // If the global is not external, see if it is large.  If so, give it a
931       // larger alignment.
932       if (getTypeSizeInBits(ElemType) > 128)
933         Alignment = Align(16); // 16-byte alignment.
934     }
935   }
936   return Alignment;
937 }
938