LLVM  6.0.0svn
DataLayout.cpp
Go to the documentation of this file.
1 //===- DataLayout.cpp - Data size & alignment routines ---------------------==//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines layout properties related to datatype size/offset/alignment
11 // information.
12 //
13 // This structure should be created once, filled in if the defaults are not
14 // correct and then passed around by const&. None of the members functions
15 // require modification to the object.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/IR/Value.h"
30 #include "llvm/Support/Casting.h"
33 #include <algorithm>
34 #include <cassert>
35 #include <cstdint>
36 #include <cstdlib>
37 #include <tuple>
38 #include <utility>
39 
40 using namespace llvm;
41 
42 //===----------------------------------------------------------------------===//
43 // Support for StructLayout
44 //===----------------------------------------------------------------------===//
45 
46 StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
47  assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
48  StructAlignment = 0;
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  unsigned TyAlign = ST->isPacked() ? 1 : DL.getABITypeAlignment(Ty);
57 
58  // Add padding if necessary to align the data element properly.
59  if ((StructSize & (TyAlign-1)) != 0) {
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  // Empty structures have alignment of 1 byte.
72  if (StructAlignment == 0) StructAlignment = 1;
73 
74  // Add padding to the end of the struct so that it could be put in an array
75  // and all array elements would be aligned correctly.
76  if ((StructSize & (StructAlignment-1)) != 0) {
77  IsPadded = true;
78  StructSize = alignTo(StructSize, StructAlignment);
79  }
80 }
81 
82 /// getElementContainingOffset - Given a valid offset into the structure,
83 /// return the structure index that contains it.
85  const uint64_t *SI =
86  std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
87  assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
88  --SI;
89  assert(*SI <= Offset && "upper_bound didn't work");
90  assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
91  (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
92  "Upper bound didn't work!");
93 
94  // Multiple fields can have the same offset if any of them are zero sized.
95  // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
96  // at the i32 element, because it is the last element at that offset. This is
97  // the right one to return, because anything after it will have a higher
98  // offset, implying that this element is non-empty.
99  return SI-&MemberOffsets[0];
100 }
101 
102 //===----------------------------------------------------------------------===//
103 // LayoutAlignElem, LayoutAlign support
104 //===----------------------------------------------------------------------===//
105 
107 LayoutAlignElem::get(AlignTypeEnum align_type, unsigned abi_align,
108  unsigned pref_align, uint32_t bit_width) {
109  assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
110  LayoutAlignElem retval;
111  retval.AlignType = align_type;
112  retval.ABIAlign = abi_align;
113  retval.PrefAlign = pref_align;
114  retval.TypeBitWidth = bit_width;
115  return retval;
116 }
117 
118 bool
120  return (AlignType == rhs.AlignType
121  && ABIAlign == rhs.ABIAlign
122  && PrefAlign == rhs.PrefAlign
123  && TypeBitWidth == rhs.TypeBitWidth);
124 }
125 
126 //===----------------------------------------------------------------------===//
127 // PointerAlignElem, PointerAlign support
128 //===----------------------------------------------------------------------===//
129 
132  unsigned PrefAlign, uint32_t TypeByteWidth) {
133  assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
134  PointerAlignElem retval;
135  retval.AddressSpace = AddressSpace;
136  retval.ABIAlign = ABIAlign;
137  retval.PrefAlign = PrefAlign;
138  retval.TypeByteWidth = TypeByteWidth;
139  return retval;
140 }
141 
142 bool
144  return (ABIAlign == rhs.ABIAlign
145  && AddressSpace == rhs.AddressSpace
146  && PrefAlign == rhs.PrefAlign
147  && TypeByteWidth == rhs.TypeByteWidth);
148 }
149 
150 //===----------------------------------------------------------------------===//
151 // DataLayout Class Implementation
152 //===----------------------------------------------------------------------===//
153 
155  if (T.isOSBinFormatMachO())
156  return "-m:o";
157  if (T.isOSWindows() && T.isOSBinFormatCOFF())
158  return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
159  return "-m:e";
160 }
161 
163  { INTEGER_ALIGN, 1, 1, 1 }, // i1
164  { INTEGER_ALIGN, 8, 1, 1 }, // i8
165  { INTEGER_ALIGN, 16, 2, 2 }, // i16
166  { INTEGER_ALIGN, 32, 4, 4 }, // i32
167  { INTEGER_ALIGN, 64, 4, 8 }, // i64
168  { FLOAT_ALIGN, 16, 2, 2 }, // half
169  { FLOAT_ALIGN, 32, 4, 4 }, // float
170  { FLOAT_ALIGN, 64, 8, 8 }, // double
171  { FLOAT_ALIGN, 128, 16, 16 }, // ppcf128, quad, ...
172  { VECTOR_ALIGN, 64, 8, 8 }, // v2i32, v1i64, ...
173  { VECTOR_ALIGN, 128, 16, 16 }, // v16i8, v8i16, v4i32, ...
174  { AGGREGATE_ALIGN, 0, 0, 8 } // struct
175 };
176 
178  clear();
179 
180  LayoutMap = nullptr;
181  BigEndian = false;
182  AllocaAddrSpace = 0;
183  StackNaturalAlign = 0;
184  ManglingMode = MM_None;
185  NonIntegralAddressSpaces.clear();
186 
187  // Default alignments
188  for (const LayoutAlignElem &E : DefaultAlignments) {
189  setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign, E.PrefAlign,
190  E.TypeBitWidth);
191  }
192  setPointerAlignment(0, 8, 8, 8);
193 
194  parseSpecifier(Desc);
195 }
196 
197 /// Checked version of split, to ensure mandatory subparts.
198 static std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
199  assert(!Str.empty() && "parse error, string can't be empty here");
200  std::pair<StringRef, StringRef> Split = Str.split(Separator);
201  if (Split.second.empty() && Split.first != Str)
202  report_fatal_error("Trailing separator in datalayout string");
203  if (!Split.second.empty() && Split.first.empty())
204  report_fatal_error("Expected token before separator in datalayout string");
205  return Split;
206 }
207 
208 /// Get an unsigned integer, including error checks.
209 static unsigned getInt(StringRef R) {
210  unsigned Result;
211  bool error = R.getAsInteger(10, Result); (void)error;
212  if (error)
213  report_fatal_error("not a number, or does not fit in an unsigned int");
214  return Result;
215 }
216 
217 /// Convert bits into bytes. Assert if not a byte width multiple.
218 static unsigned inBytes(unsigned Bits) {
219  if (Bits % 8)
220  report_fatal_error("number of bits must be a byte width multiple");
221  return Bits / 8;
222 }
223 
224 void DataLayout::parseSpecifier(StringRef Desc) {
225  StringRepresentation = Desc;
226  while (!Desc.empty()) {
227  // Split at '-'.
228  std::pair<StringRef, StringRef> Split = split(Desc, '-');
229  Desc = Split.second;
230 
231  // Split at ':'.
232  Split = split(Split.first, ':');
233 
234  // Aliases used below.
235  StringRef &Tok = Split.first; // Current token.
236  StringRef &Rest = Split.second; // The rest of the string.
237 
238  if (Tok == "ni") {
239  do {
240  Split = split(Rest, ':');
241  Rest = Split.second;
242  unsigned AS = getInt(Split.first);
243  if (AS == 0)
244  report_fatal_error("Address space 0 can never be non-integral");
245  NonIntegralAddressSpaces.push_back(AS);
246  } while (!Rest.empty());
247 
248  continue;
249  }
250 
251  char Specifier = Tok.front();
252  Tok = Tok.substr(1);
253 
254  switch (Specifier) {
255  case 's':
256  // Ignored for backward compatibility.
257  // FIXME: remove this on LLVM 4.0.
258  break;
259  case 'E':
260  BigEndian = true;
261  break;
262  case 'e':
263  BigEndian = false;
264  break;
265  case 'p': {
266  // Address space.
267  unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
268  if (!isUInt<24>(AddrSpace))
269  report_fatal_error("Invalid address space, must be a 24bit integer");
270 
271  // Size.
272  if (Rest.empty())
274  "Missing size specification for pointer in datalayout string");
275  Split = split(Rest, ':');
276  unsigned PointerMemSize = inBytes(getInt(Tok));
277  if (!PointerMemSize)
278  report_fatal_error("Invalid pointer size of 0 bytes");
279 
280  // ABI alignment.
281  if (Rest.empty())
283  "Missing alignment specification for pointer in datalayout string");
284  Split = split(Rest, ':');
285  unsigned PointerABIAlign = inBytes(getInt(Tok));
286  if (!isPowerOf2_64(PointerABIAlign))
288  "Pointer ABI alignment must be a power of 2");
289 
290  // Preferred alignment.
291  unsigned PointerPrefAlign = PointerABIAlign;
292  if (!Rest.empty()) {
293  Split = split(Rest, ':');
294  PointerPrefAlign = inBytes(getInt(Tok));
295  if (!isPowerOf2_64(PointerPrefAlign))
297  "Pointer preferred alignment must be a power of 2");
298  }
299 
300  setPointerAlignment(AddrSpace, PointerABIAlign, PointerPrefAlign,
301  PointerMemSize);
302  break;
303  }
304  case 'i':
305  case 'v':
306  case 'f':
307  case 'a': {
308  AlignTypeEnum AlignType;
309  switch (Specifier) {
310  default: llvm_unreachable("Unexpected specifier!");
311  case 'i': AlignType = INTEGER_ALIGN; break;
312  case 'v': AlignType = VECTOR_ALIGN; break;
313  case 'f': AlignType = FLOAT_ALIGN; break;
314  case 'a': AlignType = AGGREGATE_ALIGN; break;
315  }
316 
317  // Bit size.
318  unsigned Size = Tok.empty() ? 0 : getInt(Tok);
319 
320  if (AlignType == AGGREGATE_ALIGN && Size != 0)
322  "Sized aggregate specification in datalayout string");
323 
324  // ABI alignment.
325  if (Rest.empty())
327  "Missing alignment specification in datalayout string");
328  Split = split(Rest, ':');
329  unsigned ABIAlign = inBytes(getInt(Tok));
330  if (AlignType != AGGREGATE_ALIGN && !ABIAlign)
332  "ABI alignment specification must be >0 for non-aggregate types");
333 
334  // Preferred alignment.
335  unsigned PrefAlign = ABIAlign;
336  if (!Rest.empty()) {
337  Split = split(Rest, ':');
338  PrefAlign = inBytes(getInt(Tok));
339  }
340 
341  setAlignment(AlignType, ABIAlign, PrefAlign, Size);
342 
343  break;
344  }
345  case 'n': // Native integer types.
346  while (true) {
347  unsigned Width = getInt(Tok);
348  if (Width == 0)
350  "Zero width native integer type in datalayout string");
351  LegalIntWidths.push_back(Width);
352  if (Rest.empty())
353  break;
354  Split = split(Rest, ':');
355  }
356  break;
357  case 'S': { // Stack natural alignment.
358  StackNaturalAlign = inBytes(getInt(Tok));
359  break;
360  }
361  case 'A': { // Default stack/alloca address space.
362  AllocaAddrSpace = getInt(Tok);
363  if (!isUInt<24>(AllocaAddrSpace))
364  report_fatal_error("Invalid address space, must be a 24bit integer");
365  break;
366  }
367  case 'm':
368  if (!Tok.empty())
369  report_fatal_error("Unexpected trailing characters after mangling specifier in datalayout string");
370  if (Rest.empty())
371  report_fatal_error("Expected mangling specifier in datalayout string");
372  if (Rest.size() > 1)
373  report_fatal_error("Unknown mangling specifier in datalayout string");
374  switch(Rest[0]) {
375  default:
376  report_fatal_error("Unknown mangling in datalayout string");
377  case 'e':
378  ManglingMode = MM_ELF;
379  break;
380  case 'o':
381  ManglingMode = MM_MachO;
382  break;
383  case 'm':
384  ManglingMode = MM_Mips;
385  break;
386  case 'w':
387  ManglingMode = MM_WinCOFF;
388  break;
389  case 'x':
390  ManglingMode = MM_WinCOFFX86;
391  break;
392  }
393  break;
394  default:
395  report_fatal_error("Unknown specifier in datalayout string");
396  break;
397  }
398  }
399 }
400 
402  init(M);
403 }
404 
405 void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
406 
407 bool DataLayout::operator==(const DataLayout &Other) const {
408  bool Ret = BigEndian == Other.BigEndian &&
409  AllocaAddrSpace == Other.AllocaAddrSpace &&
410  StackNaturalAlign == Other.StackNaturalAlign &&
411  ManglingMode == Other.ManglingMode &&
412  LegalIntWidths == Other.LegalIntWidths &&
413  Alignments == Other.Alignments && Pointers == Other.Pointers;
414  // Note: getStringRepresentation() might differs, it is not canonicalized
415  return Ret;
416 }
417 
419 DataLayout::findAlignmentLowerBound(AlignTypeEnum AlignType,
420  uint32_t BitWidth) {
421  auto Pair = std::make_pair((unsigned)AlignType, BitWidth);
422  return std::lower_bound(Alignments.begin(), Alignments.end(), Pair,
423  [](const LayoutAlignElem &LHS,
424  const std::pair<unsigned, uint32_t> &RHS) {
425  return std::tie(LHS.AlignType, LHS.TypeBitWidth) <
426  std::tie(RHS.first, RHS.second);
427  });
428 }
429 
430 void
431 DataLayout::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
432  unsigned pref_align, uint32_t bit_width) {
433  if (!isUInt<24>(bit_width))
434  report_fatal_error("Invalid bit width, must be a 24bit integer");
435  if (!isUInt<16>(abi_align))
436  report_fatal_error("Invalid ABI alignment, must be a 16bit integer");
437  if (!isUInt<16>(pref_align))
438  report_fatal_error("Invalid preferred alignment, must be a 16bit integer");
439  if (abi_align != 0 && !isPowerOf2_64(abi_align))
440  report_fatal_error("Invalid ABI alignment, must be a power of 2");
441  if (pref_align != 0 && !isPowerOf2_64(pref_align))
442  report_fatal_error("Invalid preferred alignment, must be a power of 2");
443 
444  if (pref_align < abi_align)
446  "Preferred alignment cannot be less than the ABI alignment");
447 
448  AlignmentsTy::iterator I = findAlignmentLowerBound(align_type, bit_width);
449  if (I != Alignments.end() &&
450  I->AlignType == (unsigned)align_type && I->TypeBitWidth == bit_width) {
451  // Update the abi, preferred alignments.
452  I->ABIAlign = abi_align;
453  I->PrefAlign = pref_align;
454  } else {
455  // Insert before I to keep the vector sorted.
456  Alignments.insert(I, LayoutAlignElem::get(align_type, abi_align,
457  pref_align, bit_width));
458  }
459 }
460 
462 DataLayout::findPointerLowerBound(uint32_t AddressSpace) {
463  return std::lower_bound(Pointers.begin(), Pointers.end(), AddressSpace,
464  [](const PointerAlignElem &A, uint32_t AddressSpace) {
465  return A.AddressSpace < AddressSpace;
466  });
467 }
468 
469 void DataLayout::setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
470  unsigned PrefAlign,
471  uint32_t TypeByteWidth) {
472  if (PrefAlign < ABIAlign)
474  "Preferred alignment cannot be less than the ABI alignment");
475 
476  PointersTy::iterator I = findPointerLowerBound(AddrSpace);
477  if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
478  Pointers.insert(I, PointerAlignElem::get(AddrSpace, ABIAlign, PrefAlign,
479  TypeByteWidth));
480  } else {
481  I->ABIAlign = ABIAlign;
482  I->PrefAlign = PrefAlign;
483  I->TypeByteWidth = TypeByteWidth;
484  }
485 }
486 
487 /// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
488 /// preferred if ABIInfo = false) the layout wants for the specified datatype.
489 unsigned DataLayout::getAlignmentInfo(AlignTypeEnum AlignType,
490  uint32_t BitWidth, bool ABIInfo,
491  Type *Ty) const {
492  AlignmentsTy::const_iterator I = findAlignmentLowerBound(AlignType, BitWidth);
493  // See if we found an exact match. Of if we are looking for an integer type,
494  // but don't have an exact match take the next largest integer. This is where
495  // the lower_bound will point to when it fails an exact match.
496  if (I != Alignments.end() && I->AlignType == (unsigned)AlignType &&
497  (I->TypeBitWidth == BitWidth || AlignType == INTEGER_ALIGN))
498  return ABIInfo ? I->ABIAlign : I->PrefAlign;
499 
500  if (AlignType == INTEGER_ALIGN) {
501  // If we didn't have a larger value try the largest value we have.
502  if (I != Alignments.begin()) {
503  --I; // Go to the previous entry and see if its an integer.
504  if (I->AlignType == INTEGER_ALIGN)
505  return ABIInfo ? I->ABIAlign : I->PrefAlign;
506  }
507  } else if (AlignType == VECTOR_ALIGN) {
508  // By default, use natural alignment for vector types. This is consistent
509  // with what clang and llvm-gcc do.
510  unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
511  Align *= cast<VectorType>(Ty)->getNumElements();
512  Align = PowerOf2Ceil(Align);
513  return Align;
514  }
515 
516  // If we still couldn't find a reasonable default alignment, fall back
517  // to a simple heuristic that the alignment is the first power of two
518  // greater-or-equal to the store size of the type. This is a reasonable
519  // approximation of reality, and if the user wanted something less
520  // less conservative, they should have specified it explicitly in the data
521  // layout.
522  unsigned Align = getTypeStoreSize(Ty);
523  Align = PowerOf2Ceil(Align);
524  return Align;
525 }
526 
527 namespace {
528 
529 class StructLayoutMap {
530  using LayoutInfoTy = DenseMap<StructType*, StructLayout*>;
531  LayoutInfoTy LayoutInfo;
532 
533 public:
534  ~StructLayoutMap() {
535  // Remove any layouts.
536  for (const auto &I : LayoutInfo) {
537  StructLayout *Value = I.second;
538  Value->~StructLayout();
539  free(Value);
540  }
541  }
542 
543  StructLayout *&operator[](StructType *STy) {
544  return LayoutInfo[STy];
545  }
546 };
547 
548 } // end anonymous namespace
549 
550 void DataLayout::clear() {
551  LegalIntWidths.clear();
552  Alignments.clear();
553  Pointers.clear();
554  delete static_cast<StructLayoutMap *>(LayoutMap);
555  LayoutMap = nullptr;
556 }
557 
559  clear();
560 }
561 
563  if (!LayoutMap)
564  LayoutMap = new StructLayoutMap();
565 
566  StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
567  StructLayout *&SL = (*STM)[Ty];
568  if (SL) return SL;
569 
570  // Otherwise, create the struct layout. Because it is variable length, we
571  // malloc it, then use placement new.
572  int NumElts = Ty->getNumElements();
573  StructLayout *L =
574  (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
575  if (L == nullptr)
576  report_bad_alloc_error("Allocation of StructLayout elements failed.");
577 
578  // Set SL before calling StructLayout's ctor. The ctor could cause other
579  // entries to be added to TheMap, invalidating our reference.
580  SL = L;
581 
582  new (L) StructLayout(Ty, *this);
583 
584  return L;
585 }
586 
587 unsigned DataLayout::getPointerABIAlignment(unsigned AS) const {
588  PointersTy::const_iterator I = findPointerLowerBound(AS);
589  if (I == Pointers.end() || I->AddressSpace != AS) {
590  I = findPointerLowerBound(0);
591  assert(I->AddressSpace == 0);
592  }
593  return I->ABIAlign;
594 }
595 
596 unsigned DataLayout::getPointerPrefAlignment(unsigned AS) const {
597  PointersTy::const_iterator I = findPointerLowerBound(AS);
598  if (I == Pointers.end() || I->AddressSpace != AS) {
599  I = findPointerLowerBound(0);
600  assert(I->AddressSpace == 0);
601  }
602  return I->PrefAlign;
603 }
604 
605 unsigned DataLayout::getPointerSize(unsigned AS) const {
606  PointersTy::const_iterator I = findPointerLowerBound(AS);
607  if (I == Pointers.end() || I->AddressSpace != AS) {
608  I = findPointerLowerBound(0);
609  assert(I->AddressSpace == 0);
610  }
611  return I->TypeByteWidth;
612 }
613 
615  assert(Ty->isPtrOrPtrVectorTy() &&
616  "This should only be called with a pointer or pointer vector type");
617  Ty = Ty->getScalarType();
618  return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
619 }
620 
621 /*!
622  \param abi_or_pref Flag that determines which alignment is returned. true
623  returns the ABI alignment, false returns the preferred alignment.
624  \param Ty The underlying type for which alignment is determined.
625 
626  Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
627  == false) for the requested type \a Ty.
628  */
629 unsigned DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
630  AlignTypeEnum AlignType;
631 
632  assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
633  switch (Ty->getTypeID()) {
634  // Early escape for the non-numeric types.
635  case Type::LabelTyID:
636  return (abi_or_pref
637  ? getPointerABIAlignment(0)
638  : getPointerPrefAlignment(0));
639  case Type::PointerTyID: {
640  unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
641  return (abi_or_pref
642  ? getPointerABIAlignment(AS)
643  : getPointerPrefAlignment(AS));
644  }
645  case Type::ArrayTyID:
646  return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
647 
648  case Type::StructTyID: {
649  // Packed structure types always have an ABI alignment of one.
650  if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
651  return 1;
652 
653  // Get the layout annotation... which is lazily created on demand.
654  const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
655  unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
656  return std::max(Align, Layout->getAlignment());
657  }
658  case Type::IntegerTyID:
659  AlignType = INTEGER_ALIGN;
660  break;
661  case Type::HalfTyID:
662  case Type::FloatTyID:
663  case Type::DoubleTyID:
664  // PPC_FP128TyID and FP128TyID have different data contents, but the
665  // same size and alignment, so they look the same here.
666  case Type::PPC_FP128TyID:
667  case Type::FP128TyID:
668  case Type::X86_FP80TyID:
669  AlignType = FLOAT_ALIGN;
670  break;
671  case Type::X86_MMXTyID:
672  case Type::VectorTyID:
673  AlignType = VECTOR_ALIGN;
674  break;
675  default:
676  llvm_unreachable("Bad type for getAlignment!!!");
677  }
678 
679  return getAlignmentInfo(AlignType, getTypeSizeInBits(Ty), abi_or_pref, Ty);
680 }
681 
683  return getAlignment(Ty, true);
684 }
685 
686 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
687 /// an integer type of the specified bitwidth.
688 unsigned DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
689  return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, nullptr);
690 }
691 
693  return getAlignment(Ty, false);
694 }
695 
697  unsigned Align = getPrefTypeAlignment(Ty);
698  assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
699  return Log2_32(Align);
700 }
701 
703  unsigned AddressSpace) const {
704  return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
705 }
706 
708  assert(Ty->isPtrOrPtrVectorTy() &&
709  "Expected a pointer or pointer vector type.");
710  unsigned NumBits = getPointerTypeSizeInBits(Ty);
711  IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
712  if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
713  return VectorType::get(IntTy, VecTy->getNumElements());
714  return IntTy;
715 }
716 
718  for (unsigned LegalIntWidth : LegalIntWidths)
719  if (Width <= LegalIntWidth)
720  return Type::getIntNTy(C, LegalIntWidth);
721  return nullptr;
722 }
723 
725  auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
726  return Max != LegalIntWidths.end() ? *Max : 0;
727 }
728 
730  ArrayRef<Value *> Indices) const {
731  int64_t Result = 0;
732 
734  GTI = gep_type_begin(ElemTy, Indices),
735  GTE = gep_type_end(ElemTy, Indices);
736  for (; GTI != GTE; ++GTI) {
737  Value *Idx = GTI.getOperand();
738  if (StructType *STy = GTI.getStructTypeOrNull()) {
739  assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
740  unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
741 
742  // Get structure layout information...
743  const StructLayout *Layout = getStructLayout(STy);
744 
745  // Add in the offset, as calculated by the structure layout info...
746  Result += Layout->getElementOffset(FieldNo);
747  } else {
748  // Get the array index and the size of each array element.
749  if (int64_t arrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
750  Result += arrayIdx * getTypeAllocSize(GTI.getIndexedType());
751  }
752  }
753 
754  return Result;
755 }
756 
757 /// getPreferredAlignment - Return the preferred alignment of the specified
758 /// global. This includes an explicitly requested alignment (if the global
759 /// has one).
761  Type *ElemType = GV->getValueType();
762  unsigned Alignment = getPrefTypeAlignment(ElemType);
763  unsigned GVAlignment = GV->getAlignment();
764  if (GVAlignment >= Alignment) {
765  Alignment = GVAlignment;
766  } else if (GVAlignment != 0) {
767  Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
768  }
769 
770  if (GV->hasInitializer() && GVAlignment == 0) {
771  if (Alignment < 16) {
772  // If the global is not external, see if it is large. If so, give it a
773  // larger alignment.
774  if (getTypeSizeInBits(ElemType) > 128)
775  Alignment = 16; // 16-byte alignment.
776  }
777  }
778  return Alignment;
779 }
780 
781 /// getPreferredAlignmentLog - Return the preferred alignment of the
782 /// specified global, returned in log form. This includes an explicitly
783 /// requested alignment (if the global has one).
785  return Log2_32(getPreferredAlignment(GV));
786 }
uint64_t CallInst * C
unsigned getAlignment() const
Definition: GlobalObject.h:59
7: Labels
Definition: Type.h:64
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
void reset(StringRef LayoutDescription)
Parse a data layout string (with fallback to default values).
Definition: DataLayout.cpp:177
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
typename SuperClass::const_iterator const_iterator
Definition: SmallVector.h:329
AlignTypeEnum
Enum used to categorize the alignment types stored by LayoutAlignElem.
Definition: DataLayout.h:51
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Type * getElementType(unsigned N) const
Definition: DerivedTypes.h:314
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:262
unsigned getPointerPrefAlignment(unsigned AS=0) const
Return target&#39;s alignment for stack-based pointers FIXME: The defaults need to be removed once all of...
Definition: DataLayout.cpp:596
2: 32-bit floating point type
Definition: Type.h:59
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:313
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:562
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
gep_type_iterator gep_type_end(const User *GEP)
#define error(X)
13: Structures
Definition: Type.h:73
static std::pair< StringRef, StringRef > split(StringRef Str, char Separator)
Checked version of split, to ensure mandatory subparts.
Definition: DataLayout.cpp:198
4: 80-bit floating point type (X87)
Definition: Type.h:61
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
1: 16-bit floating point type
Definition: Type.h:58
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Definition: DerivedTypes.h:269
15: Pointers
Definition: Type.h:75
Type * getSmallestLegalIntType(LLVMContext &C, unsigned Width=0) const
Returns the smallest integer type with size at least as big as Width bits.
Definition: DataLayout.cpp:717
unsigned getPointerABIAlignment(unsigned AS) const
Layout pointer alignment.
Definition: DataLayout.cpp:587
static const char * getManglingComponent(const Triple &T)
Definition: DataLayout.cpp:154
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
Definition: DataLayout.cpp:84
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:491
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:614
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:138
static unsigned getInt(StringRef R)
Get an unsigned integer, including error checks.
Definition: DataLayout.cpp:209
Class to represent struct types.
Definition: DerivedTypes.h:201
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
unsigned getPreferredTypeAlignmentShift(Type *Ty) const
Returns the preferred alignment for the specified type, returned as log2 of the value (a shift amount...
Definition: DataLayout.cpp:696
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:285
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align, unsigned pref_align, uint32_t bit_width)
Definition: DataLayout.cpp:107
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:904
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:598
static const LayoutAlignElem DefaultAlignments[]
Definition: DataLayout.cpp:162
Layout pointer alignment element.
Definition: DataLayout.h:90
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:301
11: Arbitrary bit width integers
Definition: Type.h:71
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:562
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:702
unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global, returned in log form.
Definition: DataLayout.cpp:784
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:406
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:593
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:605
This file contains the declarations for the subclasses of Constant, which represent the different fla...
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:692
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:426
bool operator==(const PointerAlignElem &rhs) const
Definition: DataLayout.cpp:143
unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
Definition: DataLayout.cpp:724
6: 128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:63
Class to represent integer types.
Definition: DerivedTypes.h:40
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:598
const AMDGPUAS & AS
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool operator==(const DataLayout &Other) const
Definition: DataLayout.cpp:407
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:497
14: Arrays
Definition: Type.h:74
void report_bad_alloc_error(const char *Reason, bool GenCrashDiag=true)
Reports a bad alloc error, calling any user defined bad alloc error handler.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:224
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:240
16: SIMD &#39;packed&#39; format, or other vector type
Definition: Type.h:76
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:727
AddressSpace
Definition: NVPTXBaseInfo.h:22
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:682
unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const
Returns the minimum ABI-required alignment for an integer type of the specified bitwidth.
Definition: DataLayout.cpp:688
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:180
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:531
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:760
Class to represent vector types.
Definition: DerivedTypes.h:393
typename SuperClass::iterator iterator
Definition: SmallVector.h:328
DataLayout(StringRef LayoutDescription)
Constructs a DataLayout from a specification string. See reset().
Definition: DataLayout.h:182
static void clear(coro::Shape &Shape)
Definition: Coroutines.cpp:210
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:403
bool isPacked() const
Definition: DerivedTypes.h:261
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:513
Layout alignment element.
Definition: DataLayout.h:71
#define I(x, y, z)
Definition: MD5.cpp:58
Type * getValueType() const
Definition: GlobalValue.h:267
unsigned AlignType
Alignment type from AlignTypeEnum.
Definition: DataLayout.h:73
constexpr bool isUInt< 16 >(uint64_t x)
Definition: MathExtras.h:338
static unsigned inBytes(unsigned Bits)
Convert bits into bytes. Assert if not a byte width multiple.
Definition: DataLayout.cpp:218
3: 64-bit floating point type
Definition: Type.h:60
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM_NODISCARD char front() const
front - Get the first character in the string.
Definition: StringRef.h:142
LLVM Value Representation.
Definition: Value.h:73
bool hasInitializer() const
Definitions have initializers, declarations don&#39;t.
unsigned getAlignment() const
Definition: DataLayout.h:503
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:593
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool operator==(const LayoutAlignElem &rhs) const
Definition: DataLayout.cpp:119
9: MMX vectors (64 bits, X86 specific)
Definition: Type.h:66
static void Split(std::vector< std::string > &V, StringRef S)
Splits a string of comma separated items in to a vector of strings.
static PointerAlignElem get(uint32_t AddressSpace, unsigned ABIAlign, unsigned PrefAlign, uint32_t TypeByteWidth)
Initializer.
Definition: DataLayout.cpp:131
int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef< Value *> Indices) const
Returns the offset from the beginning of the type for the specified indices.
Definition: DataLayout.cpp:729
void init(const Module *M)
Definition: DataLayout.cpp:405
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition: MathExtras.h:651
5: 128-bit floating point type (112-bit mantissa)
Definition: Type.h:62
gep_type_iterator gep_type_begin(const User *GEP)