LLVM 23.0.0git
DataLayout.cpp
Go to the documentation of this file.
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"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/IR/Constants.h"
26#include "llvm/IR/Type.h"
27#include "llvm/IR/Value.h"
29#include "llvm/Support/Error.h"
35#include <algorithm>
36#include <cassert>
37#include <cstdint>
38#include <cstdlib>
39#include <new>
40#include <utility>
41
42using namespace llvm;
43
44//===----------------------------------------------------------------------===//
45// Support for StructLayout
46//===----------------------------------------------------------------------===//
47
48StructLayout::StructLayout(StructType *ST, const DataLayout &DL)
49 : StructSize(TypeSize::getFixed(0)) {
50 assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
51 IsPadded = false;
52 NumElements = ST->getNumElements();
53
54 // Loop over each of the elements, placing them in memory.
55 for (unsigned i = 0, e = NumElements; i != e; ++i) {
56 Type *Ty = ST->getElementType(i);
57 if (i == 0 && Ty->isScalableTy())
58 StructSize = TypeSize::getScalable(0);
59
60 const Align TyAlign = ST->isPacked() ? Align(1) : DL.getABITypeAlign(Ty);
61
62 // Add padding if necessary to align the data element properly.
63 // Currently the only structure with scalable size will be the homogeneous
64 // scalable vector types. Homogeneous scalable vector types have members of
65 // the same data type so no alignment issue will happen. The condition here
66 // assumes so and needs to be adjusted if this assumption changes (e.g. we
67 // support structures with arbitrary scalable data type, or structure that
68 // contains both fixed size and scalable size data type members).
69 if (!StructSize.isScalable() && !isAligned(TyAlign, StructSize)) {
70 IsPadded = true;
71 StructSize = TypeSize::getFixed(alignTo(StructSize, TyAlign));
72 }
73
74 // Keep track of maximum alignment constraint.
75 StructAlignment = std::max(TyAlign, StructAlignment);
76
77 getMemberOffsets()[i] = StructSize;
78 // Consume space for this data item
79 StructSize += DL.getTypeAllocSize(Ty);
80 }
81
82 // Add padding to the end of the struct so that it could be put in an array
83 // and all array elements would be aligned correctly.
84 if (!StructSize.isScalable() && !isAligned(StructAlignment, StructSize)) {
85 IsPadded = true;
86 StructSize = TypeSize::getFixed(alignTo(StructSize, StructAlignment));
87 }
88}
89
90/// getElementContainingOffset - Given a valid offset into the structure,
91/// return the structure index that contains it.
93 assert(!StructSize.isScalable() &&
94 "Cannot get element at offset for structure containing scalable "
95 "vector types");
96 TypeSize Offset = TypeSize::getFixed(FixedOffset);
97 ArrayRef<TypeSize> MemberOffsets = getMemberOffsets();
98
99 const auto *SI = llvm::upper_bound(MemberOffsets, Offset,
100 [](TypeSize LHS, TypeSize RHS) -> bool {
101 return TypeSize::isKnownLT(LHS, RHS);
102 });
103 assert(SI != MemberOffsets.begin() && "Offset not in structure type!");
104 --SI;
105 assert(TypeSize::isKnownLE(*SI, Offset) && "upper_bound didn't work");
106 assert(
107 (SI == MemberOffsets.begin() || TypeSize::isKnownLE(*(SI - 1), Offset)) &&
108 (SI + 1 == MemberOffsets.end() ||
109 TypeSize::isKnownGT(*(SI + 1), Offset)) &&
110 "Upper bound didn't work!");
111
112 // Multiple fields can have the same offset if any of them are zero sized.
113 // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
114 // at the i32 element, because it is the last element at that offset. This is
115 // the right one to return, because anything after it will have a higher
116 // offset, implying that this element is non-empty.
117 return SI - MemberOffsets.begin();
118}
119
120namespace {
121
122class StructLayoutMap {
123 using LayoutInfoTy = DenseMap<StructType *, StructLayout *>;
124 LayoutInfoTy LayoutInfo;
125
126public:
127 ~StructLayoutMap() {
128 // Remove any layouts.
129 for (const auto &I : LayoutInfo) {
130 StructLayout *Value = I.second;
131 Value->~StructLayout();
132 free(Value);
133 }
134 }
135
136 StructLayout *&operator[](StructType *STy) { return LayoutInfo[STy]; }
137};
138
139} // end anonymous namespace
140
141//===----------------------------------------------------------------------===//
142// DataLayout Class Implementation
143//===----------------------------------------------------------------------===//
144
146 return BitWidth == Other.BitWidth && ABIAlign == Other.ABIAlign &&
147 PrefAlign == Other.PrefAlign;
148}
149
151 return AddrSpace == Other.AddrSpace && BitWidth == Other.BitWidth &&
152 ABIAlign == Other.ABIAlign && PrefAlign == Other.PrefAlign &&
153 IndexBitWidth == Other.IndexBitWidth &&
154 HasUnstableRepresentation == Other.HasUnstableRepresentation &&
155 HasExternalState == Other.HasExternalState &&
156 NullPtrValue == Other.NullPtrValue &&
157 AddrSpaceName == Other.AddrSpaceName;
158}
159
160namespace {
161/// Predicate to sort primitive specs by bit width.
162struct LessPrimitiveBitWidth {
163 bool operator()(const DataLayout::PrimitiveSpec &LHS,
164 unsigned RHSBitWidth) const {
165 return LHS.BitWidth < RHSBitWidth;
166 }
167};
168
169/// Predicate to sort pointer specs by address space number.
170struct LessPointerAddrSpace {
171 bool operator()(const DataLayout::PointerSpec &LHS,
172 unsigned RHSAddrSpace) const {
173 return LHS.AddrSpace < RHSAddrSpace;
174 }
175};
176} // namespace
177
178// Default primitive type specifications.
179// NOTE: These arrays must be sorted by type bit width.
181 {8, Align::Constant<1>(), Align::Constant<1>()}, // i8:8:8
182 {16, Align::Constant<2>(), Align::Constant<2>()}, // i16:16:16
183 {32, Align::Constant<4>(), Align::Constant<4>()}, // i32:32:32
184 {64, Align::Constant<4>(), Align::Constant<8>()}, // i64:32:64
185};
187 {16, Align::Constant<2>(), Align::Constant<2>()}, // f16:16:16
188 {32, Align::Constant<4>(), Align::Constant<4>()}, // f32:32:32
189 {64, Align::Constant<8>(), Align::Constant<8>()}, // f64:64:64
190 {128, Align::Constant<16>(), Align::Constant<16>()}, // f128:128:128
191};
192
194 : IntSpecs(ArrayRef(DefaultIntSpecs)),
195 FloatSpecs(ArrayRef(DefaultFloatSpecs)) {
196 // Default pointer type specifications.
197 setPointerSpec(0, 64, Align::Constant<8>(), Align::Constant<8>(), 64, false,
198 false, "", APInt::getZero(64));
199}
200
202 if (Error Err = parseLayoutString(LayoutString))
203 report_fatal_error(std::move(Err));
204}
205
207 delete static_cast<StructLayoutMap *>(LayoutMap);
208 LayoutMap = nullptr;
209 StringRepresentation = Other.StringRepresentation;
210 BigEndian = Other.BigEndian;
211 VectorsAreElementAligned = Other.VectorsAreElementAligned;
212 AllocaAddrSpace = Other.AllocaAddrSpace;
213 ProgramAddrSpace = Other.ProgramAddrSpace;
214 DefaultGlobalsAddrSpace = Other.DefaultGlobalsAddrSpace;
215 StackNaturalAlign = Other.StackNaturalAlign;
216 FunctionPtrAlign = Other.FunctionPtrAlign;
217 TheFunctionPtrAlignType = Other.TheFunctionPtrAlignType;
218 ManglingMode = Other.ManglingMode;
219 LegalIntWidths = Other.LegalIntWidths;
220 IntSpecs = Other.IntSpecs;
221 FloatSpecs = Other.FloatSpecs;
222 VectorSpecs = Other.VectorSpecs;
223 PointerSpecs = Other.PointerSpecs;
224 StructABIAlignment = Other.StructABIAlignment;
225 StructPrefAlignment = Other.StructPrefAlignment;
226 return *this;
227}
228
230 // NOTE: StringRepresentation might differ, it is not canonicalized.
231 return BigEndian == Other.BigEndian &&
232 VectorsAreElementAligned == Other.VectorsAreElementAligned &&
233 AllocaAddrSpace == Other.AllocaAddrSpace &&
234 ProgramAddrSpace == Other.ProgramAddrSpace &&
235 DefaultGlobalsAddrSpace == Other.DefaultGlobalsAddrSpace &&
236 StackNaturalAlign == Other.StackNaturalAlign &&
237 FunctionPtrAlign == Other.FunctionPtrAlign &&
238 TheFunctionPtrAlignType == Other.TheFunctionPtrAlignType &&
239 ManglingMode == Other.ManglingMode &&
240 LegalIntWidths == Other.LegalIntWidths && IntSpecs == Other.IntSpecs &&
241 FloatSpecs == Other.FloatSpecs && VectorSpecs == Other.VectorSpecs &&
242 PointerSpecs == Other.PointerSpecs &&
243 StructABIAlignment == Other.StructABIAlignment &&
244 StructPrefAlignment == Other.StructPrefAlignment;
245}
246
248 DataLayout Layout;
249 if (Error Err = Layout.parseLayoutString(LayoutString))
250 return std::move(Err);
251 return Layout;
252}
253
255 return createStringError("malformed specification, must be of the form \"" +
256 Format + "\"");
257}
258
259/// Attempts to parse an address space component of a specification.
260static Error parseAddrSpace(StringRef Str, unsigned &AddrSpace) {
261 if (Str.empty())
262 return createStringError("address space component cannot be empty");
263
264 if (!to_integer(Str, AddrSpace, 10) || !isUInt<24>(AddrSpace))
265 return createStringError("address space must be a 24-bit integer");
266
267 return Error::success();
268}
269
270/// Attempts to parse an address space component of a specification allowing
271/// name to be specified as well. The input is expected to be of the form
272/// <number> '(' name ' )', with the name otional and the number is optional as
273/// well.
274static Error parseAddrSpaceAndName(StringRef Str, unsigned &AddrSpace,
275 StringRef &AddrSpaceName) {
276 if (Str.empty())
277 return createStringError("address space component cannot be empty");
278
279 if (isDigit(Str.front())) {
280 if (Str.consumeInteger(10, AddrSpace) || !isUInt<24>(AddrSpace))
281 return createStringError("address space must be a 24-bit integer");
282 }
283
284 if (Str.empty())
285 return Error::success();
286
287 if (Str.front() != '(')
288 return createStringError("address space must be a 24-bit integer");
289
290 // Expect atleast one character in between the ( and ).
291 if (Str.back() != ')' || Str.size() == 2)
292 return createStringError("Expected `( address space name )`");
293
294 AddrSpaceName = Str.drop_front().drop_back();
295 // TODO: Do we need any additional verification for address space name? Like
296 // should be a valid identifier of some sort? Its not strictly needed.
297
298 // LLVM's assembly parser used names "P", "G" and "A" to represent the
299 // program, default global, and alloca address space. This mapping is not 1:1
300 // in the sense that all of them can map to the same numberic address space.
301 // Diallow using these predefined symbolic address space names as address
302 // space names specified in the data layout.
303 if (AddrSpaceName.size() == 1) {
304 char C = AddrSpaceName.front();
305 if (C == 'P' || C == 'G' || C == 'A')
306 return createStringError(
307 "Cannot use predefined address space names P/G/A in data layout");
308 }
309 return Error::success();
310}
311
312/// Attempts to parse a size component of a specification.
313static Error parseSize(StringRef Str, unsigned &BitWidth,
314 StringRef Name = "size") {
315 if (Str.empty())
316 return createStringError(Name + " component cannot be empty");
317
318 if (!to_integer(Str, BitWidth, 10) || BitWidth == 0 || !isUInt<24>(BitWidth))
319 return createStringError(Name + " must be a non-zero 24-bit integer");
320
321 return Error::success();
322}
323
324/// Attempts to parse an alignment component of a specification.
325///
326/// On success, returns the value converted to byte amount in \p Alignment.
327/// If the value is zero and \p AllowZero is true, \p Alignment is set to one.
328///
329/// Return an error in a number of cases:
330/// - \p Str is empty or contains characters other than decimal digits;
331/// - the value is zero and \p AllowZero is false;
332/// - the value is too large;
333/// - the value is not a multiple of the byte width;
334/// - the value converted to byte amount is not not a power of two.
335static Error parseAlignment(StringRef Str, Align &Alignment, StringRef Name,
336 bool AllowZero = false) {
337 if (Str.empty())
338 return createStringError(Name + " alignment component cannot be empty");
339
340 unsigned Value;
341 if (!to_integer(Str, Value, 10) || !isUInt<16>(Value))
342 return createStringError(Name + " alignment must be a 16-bit integer");
343
344 if (Value == 0) {
345 if (!AllowZero)
346 return createStringError(Name + " alignment must be non-zero");
347 Alignment = Align(1);
348 return Error::success();
349 }
350
351 constexpr unsigned ByteWidth = 8;
352 if (Value % ByteWidth || !isPowerOf2_32(Value / ByteWidth))
353 return createStringError(
354 Name + " alignment must be a power of two times the byte width");
355
356 Alignment = Align(Value / ByteWidth);
357 return Error::success();
358}
359
360Error DataLayout::parsePrimitiveSpec(StringRef Spec) {
361 // [ifv]<size>:<abi>[:<pref>]
362 SmallVector<StringRef, 3> Components;
363 char Specifier = Spec.front();
364 assert(Specifier == 'i' || Specifier == 'f' || Specifier == 'v');
365 Spec.drop_front().split(Components, ':');
366
367 if (Components.size() < 2 || Components.size() > 3)
368 return createSpecFormatError(Twine(Specifier) + "<size>:<abi>[:<pref>]");
369
370 // Size. Required, cannot be zero.
371 unsigned BitWidth;
372 if (Error Err = parseSize(Components[0], BitWidth))
373 return Err;
374
375 // ABI alignment.
376 Align ABIAlign;
377 if (Error Err = parseAlignment(Components[1], ABIAlign, "ABI"))
378 return Err;
379
380 if (Specifier == 'i' && BitWidth == 8 && ABIAlign != 1)
381 return createStringError("i8 must be 8-bit aligned");
382
383 // Preferred alignment. Optional, defaults to the ABI alignment.
384 Align PrefAlign = ABIAlign;
385 if (Components.size() > 2)
386 if (Error Err = parseAlignment(Components[2], PrefAlign, "preferred"))
387 return Err;
388
389 if (PrefAlign < ABIAlign)
390 return createStringError(
391 "preferred alignment cannot be less than the ABI alignment");
392
393 setPrimitiveSpec(Specifier, BitWidth, ABIAlign, PrefAlign);
394 return Error::success();
395}
396
397Error DataLayout::parseAggregateSpec(StringRef Spec) {
398 // a<size>:<abi>[:<pref>]
399 SmallVector<StringRef, 3> Components;
400 assert(Spec.front() == 'a');
401 Spec.drop_front().split(Components, ':');
402
403 if (Components.size() < 2 || Components.size() > 3)
404 return createSpecFormatError("a:<abi>[:<pref>]");
405
406 // According to LangRef, <size> component must be absent altogether.
407 // For backward compatibility, allow it to be specified, but require
408 // it to be zero.
409 if (!Components[0].empty()) {
410 unsigned BitWidth;
411 if (!to_integer(Components[0], BitWidth, 10) || BitWidth != 0)
412 return createStringError("size must be zero");
413 }
414
415 // ABI alignment. Required. Can be zero, meaning use one byte alignment.
416 Align ABIAlign;
417 if (Error Err =
418 parseAlignment(Components[1], ABIAlign, "ABI", /*AllowZero=*/true))
419 return Err;
420
421 // Preferred alignment. Optional, defaults to the ABI alignment.
422 Align PrefAlign = ABIAlign;
423 if (Components.size() > 2)
424 if (Error Err = parseAlignment(Components[2], PrefAlign, "preferred"))
425 return Err;
426
427 if (PrefAlign < ABIAlign)
428 return createStringError(
429 "preferred alignment cannot be less than the ABI alignment");
430
431 StructABIAlignment = ABIAlign;
432 StructPrefAlignment = PrefAlign;
433 return Error::success();
434}
435
436Error DataLayout::parsePointerSpec(
437 StringRef Spec, SmallDenseSet<StringRef, 8> &AddrSpaceNames) {
438 // p[<n>]:<size>:<abi>[:<pref>[:<idx>]]
439 SmallVector<StringRef, 5> Components;
440 assert(Spec.front() == 'p');
441 Spec.drop_front().split(Components, ':');
442
443 if (Components.size() < 3 || Components.size() > 5)
444 return createSpecFormatError("p[<n>]:<size>:<abi>[:<pref>[:<idx>]]");
445
446 // Address space. Optional, defaults to 0.
447 unsigned AddrSpace = 0;
448 bool ExternalState = false;
449 bool UnstableRepr = false;
450 // Null pointer value flags: default, z = all-zeros, o = all-ones.
451 enum class NullPtrKind { Default, Zero, AllOnes };
452 NullPtrKind NullPtrFlag = NullPtrKind::Default;
453 StringRef AddrSpaceName;
454 StringRef AddrSpaceStr = Components[0];
455 while (!AddrSpaceStr.empty()) {
456 char C = AddrSpaceStr.front();
457 if (C == 'e') {
458 ExternalState = true;
459 } else if (C == 'u') {
460 UnstableRepr = true;
461 } else if (C == 'z') {
462 if (NullPtrFlag != NullPtrKind::Default)
463 return createStringError("only one of 'z' or 'o' may be specified");
464 NullPtrFlag = NullPtrKind::Zero;
465 } else if (C == 'o') {
466 if (NullPtrFlag != NullPtrKind::Default)
467 return createStringError("only one of 'z' or 'o' may be specified");
468 NullPtrFlag = NullPtrKind::AllOnes;
469 } else if (isAlpha(C)) {
470 return createStringError("'%c' is not a valid pointer specification flag",
471 C);
472 } else {
473 break; // not a valid flag, remaining must be the address space number.
474 }
475 AddrSpaceStr = AddrSpaceStr.drop_front(1);
476 }
477 if (!AddrSpaceStr.empty())
478 if (Error Err =
479 parseAddrSpaceAndName(AddrSpaceStr, AddrSpace, AddrSpaceName))
480 return Err; // Failed to parse the remaining characters as a number
481 if (AddrSpace == 0 && (ExternalState || UnstableRepr))
482 return createStringError(
483 "address space 0 cannot be unstable or have external state");
484
485 // Check for duplicate address space names.
486 if (!AddrSpaceName.empty() && !AddrSpaceNames.insert(AddrSpaceName).second)
487 return createStringError("address space name `" + AddrSpaceName +
488 "` already used");
489
490 // Size. Required, cannot be zero.
491 unsigned BitWidth;
492 if (Error Err = parseSize(Components[1], BitWidth, "pointer size"))
493 return Err;
494
495 // ABI alignment. Required, cannot be zero.
496 Align ABIAlign;
497 if (Error Err = parseAlignment(Components[2], ABIAlign, "ABI"))
498 return Err;
499
500 // Preferred alignment. Optional, defaults to the ABI alignment.
501 // Cannot be zero.
502 Align PrefAlign = ABIAlign;
503 if (Components.size() > 3)
504 if (Error Err = parseAlignment(Components[3], PrefAlign, "preferred"))
505 return Err;
506
507 if (PrefAlign < ABIAlign)
508 return createStringError(
509 "preferred alignment cannot be less than the ABI alignment");
510
511 // Index size. Optional, defaults to pointer size. Cannot be zero.
512 unsigned IndexBitWidth = BitWidth;
513 if (Components.size() > 4)
514 if (Error Err = parseSize(Components[4], IndexBitWidth, "index size"))
515 return Err;
516
517 if (IndexBitWidth > BitWidth)
518 return createStringError(
519 "index size cannot be larger than the pointer size");
520
521 APInt NullPtrValue = NullPtrFlag == NullPtrKind::AllOnes
523 : APInt::getZero(BitWidth);
524
525 setPointerSpec(AddrSpace, BitWidth, ABIAlign, PrefAlign, IndexBitWidth,
526 UnstableRepr, ExternalState, AddrSpaceName, NullPtrValue);
527 return Error::success();
528}
529
530Error DataLayout::parseSpecification(
531 StringRef Spec, SmallVectorImpl<unsigned> &NonIntegralAddressSpaces,
532 SmallDenseSet<StringRef, 8> &AddrSpaceNames) {
533 // The "ni" specifier is the only two-character specifier. Handle it first.
534 if (Spec.starts_with("ni")) {
535 // ni:<address space>[:<address space>]...
536 StringRef Rest = Spec.drop_front(2);
537
538 // Drop the first ':', then split the rest of the string the usual way.
539 if (!Rest.consume_front(":"))
540 return createSpecFormatError("ni:<address space>[:<address space>]...");
541
542 for (StringRef Str : split(Rest, ':')) {
543 unsigned AddrSpace;
544 if (Error Err = parseAddrSpace(Str, AddrSpace))
545 return Err;
546 if (AddrSpace == 0)
547 return createStringError("address space 0 cannot be non-integral");
548 NonIntegralAddressSpaces.push_back(AddrSpace);
549 }
550 return Error::success();
551 }
552
553 if (Spec == "ve") {
554 VectorsAreElementAligned = true;
555 return Error::success();
556 }
557
558 // The rest of the specifiers are single-character.
559 assert(!Spec.empty() && "Empty specification is handled by the caller");
560 char Specifier = Spec.front();
561
562 if (Specifier == 'i' || Specifier == 'f' || Specifier == 'v')
563 return parsePrimitiveSpec(Spec);
564
565 if (Specifier == 'a')
566 return parseAggregateSpec(Spec);
567
568 if (Specifier == 'p')
569 return parsePointerSpec(Spec, AddrSpaceNames);
570
571 StringRef Rest = Spec.drop_front();
572 switch (Specifier) {
573 case 's':
574 // Deprecated, but ignoring here to preserve loading older textual llvm
575 // ASM file
576 break;
577 case 'e':
578 case 'E':
579 if (!Rest.empty())
580 return createStringError(
581 "malformed specification, must be just 'e' or 'E'");
582 BigEndian = Specifier == 'E';
583 break;
584 case 'n': // Native integer types.
585 // n<size>[:<size>]...
586 for (StringRef Str : split(Rest, ':')) {
587 unsigned BitWidth;
588 if (Error Err = parseSize(Str, BitWidth))
589 return Err;
590 LegalIntWidths.push_back(BitWidth);
591 }
592 break;
593 case 'S': { // Stack natural alignment.
594 // S<size>
595 if (Rest.empty())
596 return createSpecFormatError("S<size>");
597 Align Alignment;
598 if (Error Err = parseAlignment(Rest, Alignment, "stack natural"))
599 return Err;
600 StackNaturalAlign = Alignment;
601 break;
602 }
603 case 'F': {
604 // F<type><abi>
605 if (Rest.empty())
606 return createSpecFormatError("F<type><abi>");
607 char Type = Rest.front();
608 Rest = Rest.drop_front();
609 switch (Type) {
610 case 'i':
611 TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
612 break;
613 case 'n':
614 TheFunctionPtrAlignType = FunctionPtrAlignType::MultipleOfFunctionAlign;
615 break;
616 default:
617 return createStringError("unknown function pointer alignment type '" +
618 Twine(Type) + "'");
619 }
620 Align Alignment;
621 if (Error Err = parseAlignment(Rest, Alignment, "ABI"))
622 return Err;
623 FunctionPtrAlign = Alignment;
624 break;
625 }
626 case 'P': { // Function address space.
627 if (Rest.empty())
628 return createSpecFormatError("P<address space>");
629 if (Error Err = parseAddrSpace(Rest, ProgramAddrSpace))
630 return Err;
631 break;
632 }
633 case 'A': { // Default stack/alloca address space.
634 if (Rest.empty())
635 return createSpecFormatError("A<address space>");
636 if (Error Err = parseAddrSpace(Rest, AllocaAddrSpace))
637 return Err;
638 break;
639 }
640 case 'G': { // Default address space for global variables.
641 if (Rest.empty())
642 return createSpecFormatError("G<address space>");
643 if (Error Err = parseAddrSpace(Rest, DefaultGlobalsAddrSpace))
644 return Err;
645 break;
646 }
647 case 'm':
648 if (!Rest.consume_front(":") || Rest.empty())
649 return createSpecFormatError("m:<mangling>");
650 if (Rest.size() > 1)
651 return createStringError("unknown mangling mode");
652 switch (Rest[0]) {
653 default:
654 return createStringError("unknown mangling mode");
655 case 'e':
656 ManglingMode = MM_ELF;
657 break;
658 case 'l':
659 ManglingMode = MM_GOFF;
660 break;
661 case 'o':
662 ManglingMode = MM_MachO;
663 break;
664 case 'm':
665 ManglingMode = MM_Mips;
666 break;
667 case 'w':
668 ManglingMode = MM_WinCOFF;
669 break;
670 case 'x':
671 ManglingMode = MM_WinCOFFX86;
672 break;
673 case 'a':
674 ManglingMode = MM_XCOFF;
675 break;
676 }
677 break;
678 default:
679 return createStringError("unknown specifier '" + Twine(Specifier) + "'");
680 }
681
682 return Error::success();
683}
684
685Error DataLayout::parseLayoutString(StringRef LayoutString) {
686 StringRepresentation = LayoutString.str();
687
688 if (LayoutString.empty())
689 return Error::success();
690
691 // Split the data layout string into specifications separated by '-' and
692 // parse each specification individually, updating internal data structures.
693 SmallVector<unsigned, 8> NonIntegralAddressSpaces;
694 SmallDenseSet<StringRef, 8> AddessSpaceNames;
695 for (StringRef Spec : split(StringRepresentation, '-')) {
696 if (Spec.empty())
697 return createStringError("empty specification is not allowed");
698 if (Error Err = parseSpecification(Spec, NonIntegralAddressSpaces,
699 AddessSpaceNames))
700 return Err;
701 }
702 // Mark all address spaces that were qualified as non-integral now. This has
703 // to be done later since the non-integral property is not part of the data
704 // layout pointer specification.
705 for (unsigned AS : NonIntegralAddressSpaces) {
706 // If there is no special spec for a given AS, getPointerSpec(AS) returns
707 // the spec for AS0, and we then update that to mark it non-integral.
708 const PointerSpec &PS = getPointerSpec(AS);
709 setPointerSpec(AS, PS.BitWidth, PS.ABIAlign, PS.PrefAlign, PS.IndexBitWidth,
710 /*HasUnstableRepr=*/true, /*HasExternalState=*/false,
711 getAddressSpaceName(AS), PS.NullPtrValue);
712 }
713
714 return Error::success();
715}
716
717void DataLayout::setPrimitiveSpec(char Specifier, uint32_t BitWidth,
718 Align ABIAlign, Align PrefAlign) {
719 SmallVectorImpl<PrimitiveSpec> *Specs;
720 switch (Specifier) {
721 default:
722 llvm_unreachable("Unexpected specifier");
723 case 'i':
724 Specs = &IntSpecs;
725 break;
726 case 'f':
727 Specs = &FloatSpecs;
728 break;
729 case 'v':
730 Specs = &VectorSpecs;
731 break;
732 }
733
734 auto I = lower_bound(*Specs, BitWidth, LessPrimitiveBitWidth());
735 if (I != Specs->end() && I->BitWidth == BitWidth) {
736 // Update the abi, preferred alignments.
737 I->ABIAlign = ABIAlign;
738 I->PrefAlign = PrefAlign;
739 } else {
740 // Insert before I to keep the vector sorted.
741 Specs->insert(I, PrimitiveSpec{BitWidth, ABIAlign, PrefAlign});
742 }
743}
744
746DataLayout::getPointerSpec(uint32_t AddrSpace) const {
747 if (AddrSpace != 0) {
748 auto I = lower_bound(PointerSpecs, AddrSpace, LessPointerAddrSpace());
749 if (I != PointerSpecs.end() && I->AddrSpace == AddrSpace)
750 return *I;
751 }
752
753 assert(PointerSpecs[0].AddrSpace == 0);
754 return PointerSpecs[0];
755}
756
757void DataLayout::setPointerSpec(uint32_t AddrSpace, uint32_t BitWidth,
758 Align ABIAlign, Align PrefAlign,
759 uint32_t IndexBitWidth, bool HasUnstableRepr,
760 bool HasExternalState, StringRef AddrSpaceName,
761 APInt NullPtrValue) {
762 auto I = lower_bound(PointerSpecs, AddrSpace, LessPointerAddrSpace());
763 if (I == PointerSpecs.end() || I->AddrSpace != AddrSpace) {
764 PointerSpecs.insert(I, PointerSpec{AddrSpace, BitWidth, ABIAlign, PrefAlign,
765 IndexBitWidth, HasUnstableRepr,
766 HasExternalState, AddrSpaceName.str(),
767 std::move(NullPtrValue)});
768 } else {
769 I->BitWidth = BitWidth;
770 I->ABIAlign = ABIAlign;
771 I->PrefAlign = PrefAlign;
772 I->IndexBitWidth = IndexBitWidth;
773 I->HasUnstableRepresentation = HasUnstableRepr;
774 I->HasExternalState = HasExternalState;
775 I->AddrSpaceName = AddrSpaceName.str();
776 I->NullPtrValue = std::move(NullPtrValue);
777 }
778}
779
780Align DataLayout::getIntegerAlignment(uint32_t BitWidth,
781 bool abi_or_pref) const {
782 auto I = IntSpecs.begin();
783 for (; I != IntSpecs.end(); ++I) {
784 if (I->BitWidth >= BitWidth)
785 break;
786 }
787
788 // If we don't have an exact match, use alignment of next larger integer
789 // type. If there is none, use alignment of largest integer type by going
790 // back one element.
791 if (I == IntSpecs.end())
792 --I;
793 return abi_or_pref ? I->ABIAlign : I->PrefAlign;
794}
795
796DataLayout::~DataLayout() { delete static_cast<StructLayoutMap *>(LayoutMap); }
797
799 if (!LayoutMap)
800 LayoutMap = new StructLayoutMap();
801
802 StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
803 StructLayout *&SL = (*STM)[Ty];
804 if (SL) return SL;
805
806 // Otherwise, create the struct layout. Because it is variable length, we
807 // malloc it, then use placement new.
809 StructLayout::totalSizeToAlloc<TypeSize>(Ty->getNumElements()));
810
811 // Set SL before calling StructLayout's ctor. The ctor could cause other
812 // entries to be added to TheMap, invalidating our reference.
813 SL = L;
814
815 new (L) StructLayout(Ty, *this);
816
817 return L;
818}
819
821 return getPointerSpec(AS).ABIAlign;
822}
823
825 return getPointerSpec(AS).AddrSpaceName;
826}
827
828std::optional<unsigned> DataLayout::getNamedAddressSpace(StringRef Name) const {
829 auto II = llvm::find_if(PointerSpecs, [Name](const PointerSpec &PS) {
830 return PS.AddrSpaceName == Name;
831 });
832 if (II != PointerSpecs.end())
833 return II->AddrSpace;
834 return std::nullopt;
835}
836
838 return getPointerSpec(AS).PrefAlign;
839}
840
841unsigned DataLayout::getPointerSize(unsigned AS) const {
842 return divideCeil(getPointerSpec(AS).BitWidth, 8);
843}
844
846 assert(Ty->isPtrOrPtrVectorTy() &&
847 "This should only be called with a pointer or pointer vector type");
848 Ty = Ty->getScalarType();
850}
851
852unsigned DataLayout::getIndexSize(unsigned AS) const {
853 return divideCeil(getPointerSpec(AS).IndexBitWidth, 8);
854}
855
857 assert(Ty->isPtrOrPtrVectorTy() &&
858 "This should only be called with a pointer or pointer vector type");
859 Ty = Ty->getScalarType();
861}
862
863/*!
864 \param abi_or_pref Flag that determines which alignment is returned. true
865 returns the ABI alignment, false returns the preferred alignment.
866 \param Ty The underlying type for which alignment is determined.
867
868 Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
869 == false) for the requested type \a Ty.
870 */
871Align DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
872 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
873 switch (Ty->getTypeID()) {
874 // Early escape for the non-numeric types.
875 case Type::LabelTyID:
876 return abi_or_pref ? getPointerABIAlignment(0) : getPointerPrefAlignment(0);
877 case Type::PointerTyID: {
878 unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
879 return abi_or_pref ? getPointerABIAlignment(AS)
881 }
882 case Type::ArrayTyID:
883 return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
884
885 case Type::StructTyID: {
886 // Packed structure types always have an ABI alignment of one.
887 if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
888 return Align(1);
889
890 // Get the layout annotation... which is lazily created on demand.
891 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
892 const Align Align = abi_or_pref ? StructABIAlignment : StructPrefAlignment;
893 return std::max(Align, Layout->getAlignment());
894 }
895 case Type::ByteTyID:
896 // The byte type has the same alignment as the equally sized integer type.
897 return getIntegerAlignment(Ty->getByteBitWidth(), abi_or_pref);
899 return getIntegerAlignment(Ty->getIntegerBitWidth(), abi_or_pref);
900 case Type::HalfTyID:
901 case Type::BFloatTyID:
902 case Type::FloatTyID:
903 case Type::DoubleTyID:
904 // PPC_FP128TyID and FP128TyID have different data contents, but the
905 // same size and alignment, so they look the same here.
907 case Type::FP128TyID:
908 case Type::X86_FP80TyID: {
910 auto I = lower_bound(FloatSpecs, BitWidth, LessPrimitiveBitWidth());
911 if (I != FloatSpecs.end() && I->BitWidth == BitWidth)
912 return abi_or_pref ? I->ABIAlign : I->PrefAlign;
913
914 // If we still couldn't find a reasonable default alignment, fall back
915 // to a simple heuristic that the alignment is the first power of two
916 // greater-or-equal to the store size of the type. This is a reasonable
917 // approximation of reality, and if the user wanted something less
918 // less conservative, they should have specified it explicitly in the data
919 // layout.
920 return Align(PowerOf2Ceil(BitWidth / 8));
921 }
925 auto I = lower_bound(VectorSpecs, BitWidth, LessPrimitiveBitWidth());
926 if (I != VectorSpecs.end() && I->BitWidth == BitWidth)
927 return abi_or_pref ? I->ABIAlign : I->PrefAlign;
928
930 return getAlignment(cast<VectorType>(Ty)->getElementType(), abi_or_pref);
931
932 // By default, use natural alignment for vector types. This is consistent
933 // with what clang and llvm-gcc do.
934 //
935 // We're only calculating a natural alignment, so it doesn't have to be
936 // based on the full size for scalable vectors. Using the minimum element
937 // count should be enough here.
938 return Align(PowerOf2Ceil(getTypeStoreSize(Ty).getKnownMinValue()));
939 }
941 return Align(64);
942 case Type::TargetExtTyID: {
943 Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
944 return getAlignment(LayoutTy, abi_or_pref);
945 }
946 default:
947 llvm_unreachable("Bad type for getAlignment!!!");
948 }
949}
950
952 switch (Ty->getTypeID()) {
953 case Type::ArrayTyID: {
954 // The alignment of the array is the alignment of the element, so there
955 // is no need for further adjustment.
956 auto *ATy = cast<ArrayType>(Ty);
957 return ATy->getNumElements() * getTypeAllocSize(ATy->getElementType());
958 }
959 case Type::StructTyID: {
960 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
961 TypeSize Size = Layout->getSizeInBytes();
962
963 if (cast<StructType>(Ty)->isPacked())
964 return Size;
965
966 Align A = std::max(StructABIAlignment, Layout->getAlignment());
967 return alignTo(Size, A.value());
968 }
969 case Type::IntegerTyID: {
970 unsigned BitWidth = Ty->getIntegerBitWidth();
972 Align A = getIntegerAlignment(BitWidth, /*ABI=*/true);
973 return alignTo(Size, A.value());
974 }
975 case Type::PointerTyID: {
976 unsigned AS = Ty->getPointerAddressSpace();
978 return alignTo(Size, getPointerABIAlignment(AS).value());
979 }
980 case Type::TargetExtTyID: {
981 Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
982 return getTypeAllocSize(LayoutTy);
983 }
984 default:
985 return alignTo(getTypeStoreSize(Ty), getABITypeAlign(Ty).value());
986 }
987}
988
990 return getAlignment(Ty, true);
991}
992
994 return getAlignment(Ty, false);
995}
996
1001
1003 assert(Ty->isPtrOrPtrVectorTy() &&
1004 "Expected a pointer or pointer vector type.");
1005 unsigned NumBits = getPointerTypeSizeInBits(Ty);
1006 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
1007 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
1008 return VectorType::get(IntTy, VecTy);
1009 return IntTy;
1010}
1011
1016
1018 assert(Ty->isPtrOrPtrVectorTy() &&
1019 "Expected a pointer or pointer vector type.");
1020 unsigned NumBits = getPointerTypeSizeInBits(Ty);
1021 ByteType *ByteTy = ByteType::get(Ty->getContext(), NumBits);
1022 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
1023 return VectorType::get(ByteTy, VecTy);
1024 return ByteTy;
1025}
1026
1028 for (unsigned LegalIntWidth : LegalIntWidths)
1029 if (Width <= LegalIntWidth)
1030 return Type::getIntNTy(C, LegalIntWidth);
1031 return nullptr;
1032}
1033
1035 auto Max = llvm::max_element(LegalIntWidths);
1036 return Max != LegalIntWidths.end() ? *Max : 0;
1037}
1038
1043
1045 assert(Ty->isPtrOrPtrVectorTy() &&
1046 "Expected a pointer or pointer vector type.");
1047 unsigned NumBits = getIndexTypeSizeInBits(Ty);
1048 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
1049 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
1050 return VectorType::get(IntTy, VecTy);
1051 return IntTy;
1052}
1053
1055 ArrayRef<Value *> Indices) const {
1056 int64_t Result = 0;
1057
1059 GTI = gep_type_begin(ElemTy, Indices),
1060 GTE = gep_type_end(ElemTy, Indices);
1061 for (; GTI != GTE; ++GTI) {
1062 Value *Idx = GTI.getOperand();
1063 if (StructType *STy = GTI.getStructTypeOrNull()) {
1064 assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
1065 unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
1066
1067 // Get structure layout information...
1068 const StructLayout *Layout = getStructLayout(STy);
1069
1070 // Add in the offset, as calculated by the structure layout info...
1071 Result += Layout->getElementOffset(FieldNo);
1072 } else {
1073 if (int64_t ArrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
1074 Result += ArrayIdx * GTI.getSequentialElementStride(*this);
1075 }
1076 }
1077
1078 return Result;
1079}
1080
1082 // Skip over scalable or zero size elements. Also skip element sizes larger
1083 // than the positive index space, because the arithmetic below may not be
1084 // correct in that case.
1085 unsigned BitWidth = Offset.getBitWidth();
1086 if (ElemSize.isScalable() || ElemSize == 0 ||
1087 !isUIntN(BitWidth - 1, ElemSize)) {
1088 return APInt::getZero(BitWidth);
1089 }
1090
1091 uint64_t FixedElemSize = ElemSize.getFixedValue();
1092 APInt Index = Offset.sdiv(FixedElemSize);
1093 Offset -= Index * FixedElemSize;
1094 if (Offset.isNegative()) {
1095 // Prefer a positive remaining offset to allow struct indexing.
1096 --Index;
1097 Offset += FixedElemSize;
1098 assert(Offset.isNonNegative() && "Remaining offset shouldn't be negative");
1099 }
1100 return Index;
1101}
1102
1103std::optional<APInt> DataLayout::getGEPIndexForOffset(Type *&ElemTy,
1104 APInt &Offset) const {
1105 if (auto *ArrTy = dyn_cast<ArrayType>(ElemTy)) {
1106 ElemTy = ArrTy->getElementType();
1107 return getElementIndex(getTypeAllocSize(ElemTy), Offset);
1108 }
1109
1110 if (isa<VectorType>(ElemTy)) {
1111 // Vector GEPs are partially broken (e.g. for overaligned element types),
1112 // and may be forbidden in the future, so avoid generating GEPs into
1113 // vectors. See https://discourse.llvm.org/t/67497
1114 return std::nullopt;
1115 }
1116
1117 if (auto *STy = dyn_cast<StructType>(ElemTy)) {
1118 const StructLayout *SL = getStructLayout(STy);
1119 uint64_t IntOffset = Offset.getZExtValue();
1120 if (IntOffset >= SL->getSizeInBytes())
1121 return std::nullopt;
1122
1123 unsigned Index = SL->getElementContainingOffset(IntOffset);
1124 Offset -= SL->getElementOffset(Index);
1125 ElemTy = STy->getElementType(Index);
1126 return APInt(32, Index);
1127 }
1128
1129 // Non-aggregate type.
1130 return std::nullopt;
1131}
1132
1134 APInt &Offset) const {
1135 assert(ElemTy->isSized() && "Element type must be sized");
1136 SmallVector<APInt> Indices;
1138 while (Offset != 0) {
1139 std::optional<APInt> Index = getGEPIndexForOffset(ElemTy, Offset);
1140 if (!Index)
1141 break;
1142 Indices.push_back(*Index);
1143 }
1144
1145 return Indices;
1146}
1147
1148/// getPreferredAlign - Return the preferred alignment of the specified global.
1149/// This includes an explicitly requested alignment (if the global has one).
1151 MaybeAlign GVAlignment = GV->getAlign();
1152 // If a section is specified, always precisely honor explicit alignment,
1153 // so we don't insert padding into a section we don't control.
1154 if (GVAlignment && GV->hasSection())
1155 return *GVAlignment;
1156
1157 // If no explicit alignment is specified, compute the alignment based on
1158 // the IR type. If an alignment is specified, increase it to match the ABI
1159 // alignment of the IR type.
1160 //
1161 // FIXME: Not sure it makes sense to use the alignment of the type if
1162 // there's already an explicit alignment specification.
1163 Type *ElemType = GV->getValueType();
1164 Align Alignment = getPrefTypeAlign(ElemType);
1165 if (GVAlignment) {
1166 if (*GVAlignment >= Alignment)
1167 Alignment = *GVAlignment;
1168 else
1169 Alignment = std::max(*GVAlignment, getABITypeAlign(ElemType));
1170 }
1171
1172 // If no explicit alignment is specified, and the global is large, increase
1173 // the alignment to 16.
1174 // FIXME: Why 16, specifically?
1175 if (GV->hasInitializer() && !GVAlignment) {
1176 if (Alignment < Align(16)) {
1177 // If the global is not external, see if it is large. If so, give it a
1178 // larger alignment.
1179 if (getTypeSizeInBits(ElemType) > 128)
1180 Alignment = Align(16); // 16-byte alignment.
1181 }
1182 }
1183 return Alignment;
1184}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static SmallVector< size_t > getMemberOffsets(const DataLayout &DL, GlobalVariable *Handle, llvm::function_ref< bool(Type *)> IsPadding)
Definition CBuffer.cpp:19
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Error parseSize(StringRef Str, unsigned &BitWidth, StringRef Name="size")
Attempts to parse a size component of a specification.
static APInt getElementIndex(TypeSize ElemSize, APInt &Offset)
static Error parseAddrSpace(StringRef Str, unsigned &AddrSpace)
Attempts to parse an address space component of a specification.
static Error createSpecFormatError(Twine Format)
static Error parseAlignment(StringRef Str, Align &Alignment, StringRef Name, bool AllowZero=false)
Attempts to parse an alignment component of a specification.
constexpr DataLayout::PrimitiveSpec DefaultFloatSpecs[]
constexpr DataLayout::PrimitiveSpec DefaultIntSpecs[]
static Error parseAddrSpaceAndName(StringRef Str, unsigned &AddrSpace, StringRef &AddrSpaceName)
Attempts to parse an address space component of a specification allowing name to be specified as well...
This file defines the DenseMap class.
#define I(x, y, z)
Definition MD5.cpp:57
This file defines counterparts of C library allocation functions defined in the namespace 'std'.
static unsigned getAddressSpace(const Value *V, unsigned MaxLookup)
uint64_t IntrinsicInst * II
This file contains some functions that are useful when dealing with strings.
static uint32_t getAlignment(const MCSectionCOFF &Sec)
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:131
iterator begin() const
Definition ArrayRef.h:130
Class to represent byte types.
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
Definition Type.cpp:384
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI std::optional< unsigned > getNamedAddressSpace(StringRef Name) const
LLVM_ABI StringRef getAddressSpaceName(unsigned AS) const
unsigned getPointerSizeInBits(unsigned AS=0) const
The size in bits of the pointer representation in a given address space.
Definition DataLayout.h:501
@ MultipleOfFunctionAlign
The function pointer alignment is a multiple of the function alignment.
Definition DataLayout.h:108
@ Independent
The function pointer alignment is independent of the function alignment.
Definition DataLayout.h:106
LLVM_ABI SmallVector< APInt > getGEPIndicesForOffset(Type *&ElemTy, APInt &Offset) const
Get GEP indices to access Offset inside ElemTy.
LLVM_ABI unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
bool vectorsAreElementAligned() const
Whether vectors are element aligned, rather than naturally aligned.
Definition DataLayout.h:221
LLVM_ABI unsigned getIndexSize(unsigned AS) const
The index size in bytes used for address calculation, rounded up to a whole number of bytes.
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI DataLayout()
Constructs a DataLayout with default values.
LLVM_ABI 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.
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
LLVM_ABI ByteType * getBytePtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns a byte type with the same size of a pointer in the given address space.
LLVM_ABI DataLayout & operator=(const DataLayout &Other)
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
LLVM_ABI std::optional< APInt > getGEPIndexForOffset(Type *&ElemTy, APInt &Offset) const
Get single GEP index to access Offset inside ElemTy.
LLVM_ABI Type * getSmallestLegalIntType(LLVMContext &C, unsigned Width=0) const
Returns the smallest integer type with size at least as big as Width bits.
LLVM_ABI Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
LLVM_ABI ~DataLayout()
LLVM_ABI unsigned getPointerSize(unsigned AS=0) const
The pointer representation size in bytes, rounded up to a whole number of bytes.
LLVM_ABI Align getPointerPrefAlignment(unsigned AS=0) const
Return target's alignment for stack-based pointers FIXME: The defaults need to be removed once all of...
unsigned getIndexSizeInBits(unsigned AS) const
The size in bits of indices used for address calculation in getelementptr and for addresses in the gi...
Definition DataLayout.h:509
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:579
LLVM_ABI bool operator==(const DataLayout &Other) const
LLVM_ABI int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef< Value * > Indices) const
Returns the offset from the beginning of the type for the specified indices.
LLVM_ABI Align getPointerABIAlignment(unsigned AS) const
Layout pointer alignment.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
bool hasSection() const
Check if this global has a custom object file section.
Type * getValueType() const
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:354
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:291
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:222
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:629
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:143
char front() const
front - Get the first character in the string.
Definition StringRef.h:146
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:655
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
Definition StringRef.h:636
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getSizeInBytes() const
Definition DataLayout.h:752
MutableArrayRef< TypeSize > getMemberOffsets()
Definition DataLayout.h:766
LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const
Given a valid byte offset into the structure, returns the structure index that contains it.
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Align getAlignment() const
Definition DataLayout.h:756
Class to represent struct types.
static constexpr std::enable_if_t< std::is_same_v< Foo< TrailingTys... >, Foo< Tys... > >, size_t > totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType< TrailingTys, size_t >::type... Counts)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:346
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition Type.h:67
@ ArrayTyID
Arrays.
Definition Type.h:76
@ HalfTyID
16-bit floating point type
Definition Type.h:57
@ TargetExtTyID
Target extension type.
Definition Type.h:80
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:78
@ LabelTyID
Labels.
Definition Type.h:65
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ StructTyID
Structures.
Definition Type.h:75
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:77
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:61
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:63
@ ByteTyID
Arbitrary bit width bytes.
Definition Type.h:72
@ PointerTyID
Pointers.
Definition Type.h:74
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
LLVM_ABI unsigned getByteBitWidth() const
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:317
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
Base class of all SIMD vector types.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:216
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:223
TypeSize getSequentialElementStride(const DataLayout &DL) const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
constexpr double e
bool empty() const
Definition BasicBlock.h:101
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:557
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:134
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
gep_type_iterator gep_type_end(const User *GEP)
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2064
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:385
bool isAlpha(char C)
Checks if character C is a valid letter as classified by "C" locale.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
bool isDigit(char C)
Checks if character C is one of the 10 decimal digits.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_malloc(size_t Sz)
Definition MemAlloc.h:25
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
@ Other
Any other memory.
Definition ModRef.h:68
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2051
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2087
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1771
gep_type_iterator gep_type_begin(const User *GEP)
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static constexpr Align Constant()
Allow constructions of constexpr Align.
Definition Alignment.h:88
Pointer type specification.
Definition DataLayout.h:76
APInt NullPtrValue
The null pointer bit representation for this address space.
Definition DataLayout.h:99
bool HasUnstableRepresentation
Pointers in this address space don't have a well-defined bitwise representation (e....
Definition DataLayout.h:90
LLVM_ABI bool operator==(const PointerSpec &Other) const
bool HasExternalState
Pointers in this address space have additional state bits that are located at a target-defined locati...
Definition DataLayout.h:95
uint32_t IndexBitWidth
The index bit width also defines the address size in this address space.
Definition DataLayout.h:86
Primitive type specification.
Definition DataLayout.h:67
LLVM_ABI bool operator==(const PrimitiveSpec &Other) const
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106