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 AddrSpaceName == Other.AddrSpaceName;
157}
158
159namespace {
160/// Predicate to sort primitive specs by bit width.
161struct LessPrimitiveBitWidth {
162 bool operator()(const DataLayout::PrimitiveSpec &LHS,
163 unsigned RHSBitWidth) const {
164 return LHS.BitWidth < RHSBitWidth;
165 }
166};
167
168/// Predicate to sort pointer specs by address space number.
169struct LessPointerAddrSpace {
170 bool operator()(const DataLayout::PointerSpec &LHS,
171 unsigned RHSAddrSpace) const {
172 return LHS.AddrSpace < RHSAddrSpace;
173 }
174};
175} // namespace
176
177// Default primitive type specifications.
178// NOTE: These arrays must be sorted by type bit width.
180 {8, Align::Constant<1>(), Align::Constant<1>()}, // i8:8:8
181 {16, Align::Constant<2>(), Align::Constant<2>()}, // i16:16:16
182 {32, Align::Constant<4>(), Align::Constant<4>()}, // i32:32:32
183 {64, Align::Constant<4>(), Align::Constant<8>()}, // i64:32:64
184};
186 {16, Align::Constant<2>(), Align::Constant<2>()}, // f16:16:16
187 {32, Align::Constant<4>(), Align::Constant<4>()}, // f32:32:32
188 {64, Align::Constant<8>(), Align::Constant<8>()}, // f64:64:64
189 {128, Align::Constant<16>(), Align::Constant<16>()}, // f128:128:128
190};
191
193 : IntSpecs(ArrayRef(DefaultIntSpecs)),
194 FloatSpecs(ArrayRef(DefaultFloatSpecs)) {
195 // Default pointer type specifications.
196 setPointerSpec(0, 64, Align::Constant<8>(), Align::Constant<8>(), 64, false,
197 false, "");
198}
199
201 if (Error Err = parseLayoutString(LayoutString))
202 report_fatal_error(std::move(Err));
203}
204
206 delete static_cast<StructLayoutMap *>(LayoutMap);
207 LayoutMap = nullptr;
208 StringRepresentation = Other.StringRepresentation;
209 BigEndian = Other.BigEndian;
210 VectorsAreElementAligned = Other.VectorsAreElementAligned;
211 AllocaAddrSpace = Other.AllocaAddrSpace;
212 ProgramAddrSpace = Other.ProgramAddrSpace;
213 DefaultGlobalsAddrSpace = Other.DefaultGlobalsAddrSpace;
214 StackNaturalAlign = Other.StackNaturalAlign;
215 FunctionPtrAlign = Other.FunctionPtrAlign;
216 TheFunctionPtrAlignType = Other.TheFunctionPtrAlignType;
217 ManglingMode = Other.ManglingMode;
218 LegalIntWidths = Other.LegalIntWidths;
219 IntSpecs = Other.IntSpecs;
220 FloatSpecs = Other.FloatSpecs;
221 VectorSpecs = Other.VectorSpecs;
222 PointerSpecs = Other.PointerSpecs;
223 StructABIAlignment = Other.StructABIAlignment;
224 StructPrefAlignment = Other.StructPrefAlignment;
225 return *this;
226}
227
229 // NOTE: StringRepresentation might differ, it is not canonicalized.
230 return BigEndian == Other.BigEndian &&
231 VectorsAreElementAligned == Other.VectorsAreElementAligned &&
232 AllocaAddrSpace == Other.AllocaAddrSpace &&
233 ProgramAddrSpace == Other.ProgramAddrSpace &&
234 DefaultGlobalsAddrSpace == Other.DefaultGlobalsAddrSpace &&
235 StackNaturalAlign == Other.StackNaturalAlign &&
236 FunctionPtrAlign == Other.FunctionPtrAlign &&
237 TheFunctionPtrAlignType == Other.TheFunctionPtrAlignType &&
238 ManglingMode == Other.ManglingMode &&
239 LegalIntWidths == Other.LegalIntWidths && IntSpecs == Other.IntSpecs &&
240 FloatSpecs == Other.FloatSpecs && VectorSpecs == Other.VectorSpecs &&
241 PointerSpecs == Other.PointerSpecs &&
242 StructABIAlignment == Other.StructABIAlignment &&
243 StructPrefAlignment == Other.StructPrefAlignment;
244}
245
247 DataLayout Layout;
248 if (Error Err = Layout.parseLayoutString(LayoutString))
249 return std::move(Err);
250 return Layout;
251}
252
254 return createStringError("malformed specification, must be of the form \"" +
255 Format + "\"");
256}
257
258/// Attempts to parse an address space component of a specification.
259static Error parseAddrSpace(StringRef Str, unsigned &AddrSpace) {
260 if (Str.empty())
261 return createStringError("address space component cannot be empty");
262
263 if (!to_integer(Str, AddrSpace, 10) || !isUInt<24>(AddrSpace))
264 return createStringError("address space must be a 24-bit integer");
265
266 return Error::success();
267}
268
269/// Attempts to parse an address space component of a specification allowing
270/// name to be specified as well. The input is expected to be of the form
271/// <number> '(' name ' )', with the name otional and the number is optional as
272/// well.
273static Error parseAddrSpaceAndName(StringRef Str, unsigned &AddrSpace,
274 StringRef &AddrSpaceName) {
275 if (Str.empty())
276 return createStringError("address space component cannot be empty");
277
278 if (isDigit(Str.front())) {
279 if (Str.consumeInteger(10, AddrSpace) || !isUInt<24>(AddrSpace))
280 return createStringError("address space must be a 24-bit integer");
281 }
282
283 if (Str.empty())
284 return Error::success();
285
286 if (Str.front() != '(')
287 return createStringError("address space must be a 24-bit integer");
288
289 // Expect atleast one character in between the ( and ).
290 if (Str.back() != ')' || Str.size() == 2)
291 return createStringError("Expected `( address space name )`");
292
293 AddrSpaceName = Str.drop_front().drop_back();
294 // TODO: Do we need any additional verification for address space name? Like
295 // should be a valid identifier of some sort? Its not strictly needed.
296
297 // LLVM's assembly parser used names "P", "G" and "A" to represent the
298 // program, default global, and alloca address space. This mapping is not 1:1
299 // in the sense that all of them can map to the same numberic address space.
300 // Diallow using these predefined symbolic address space names as address
301 // space names specified in the data layout.
302 if (AddrSpaceName.size() == 1) {
303 char C = AddrSpaceName.front();
304 if (C == 'P' || C == 'G' || C == 'A')
305 return createStringError(
306 "Cannot use predefined address space names P/G/A in data layout");
307 }
308 return Error::success();
309}
310
311/// Attempts to parse a size component of a specification.
312static Error parseSize(StringRef Str, unsigned &BitWidth,
313 StringRef Name = "size") {
314 if (Str.empty())
315 return createStringError(Name + " component cannot be empty");
316
317 if (!to_integer(Str, BitWidth, 10) || BitWidth == 0 || !isUInt<24>(BitWidth))
318 return createStringError(Name + " must be a non-zero 24-bit integer");
319
320 return Error::success();
321}
322
323/// Attempts to parse an alignment component of a specification.
324///
325/// On success, returns the value converted to byte amount in \p Alignment.
326/// If the value is zero and \p AllowZero is true, \p Alignment is set to one.
327///
328/// Return an error in a number of cases:
329/// - \p Str is empty or contains characters other than decimal digits;
330/// - the value is zero and \p AllowZero is false;
331/// - the value is too large;
332/// - the value is not a multiple of the byte width;
333/// - the value converted to byte amount is not not a power of two.
334static Error parseAlignment(StringRef Str, Align &Alignment, StringRef Name,
335 bool AllowZero = false) {
336 if (Str.empty())
337 return createStringError(Name + " alignment component cannot be empty");
338
339 unsigned Value;
340 if (!to_integer(Str, Value, 10) || !isUInt<16>(Value))
341 return createStringError(Name + " alignment must be a 16-bit integer");
342
343 if (Value == 0) {
344 if (!AllowZero)
345 return createStringError(Name + " alignment must be non-zero");
346 Alignment = Align(1);
347 return Error::success();
348 }
349
350 constexpr unsigned ByteWidth = 8;
351 if (Value % ByteWidth || !isPowerOf2_32(Value / ByteWidth))
352 return createStringError(
353 Name + " alignment must be a power of two times the byte width");
354
355 Alignment = Align(Value / ByteWidth);
356 return Error::success();
357}
358
359Error DataLayout::parsePrimitiveSpec(StringRef Spec) {
360 // [ifv]<size>:<abi>[:<pref>]
361 SmallVector<StringRef, 3> Components;
362 char Specifier = Spec.front();
363 assert(Specifier == 'i' || Specifier == 'f' || Specifier == 'v');
364 Spec.drop_front().split(Components, ':');
365
366 if (Components.size() < 2 || Components.size() > 3)
367 return createSpecFormatError(Twine(Specifier) + "<size>:<abi>[:<pref>]");
368
369 // Size. Required, cannot be zero.
370 unsigned BitWidth;
371 if (Error Err = parseSize(Components[0], BitWidth))
372 return Err;
373
374 // ABI alignment.
375 Align ABIAlign;
376 if (Error Err = parseAlignment(Components[1], ABIAlign, "ABI"))
377 return Err;
378
379 if (Specifier == 'i' && BitWidth == 8 && ABIAlign != 1)
380 return createStringError("i8 must be 8-bit aligned");
381
382 // Preferred alignment. Optional, defaults to the ABI alignment.
383 Align PrefAlign = ABIAlign;
384 if (Components.size() > 2)
385 if (Error Err = parseAlignment(Components[2], PrefAlign, "preferred"))
386 return Err;
387
388 if (PrefAlign < ABIAlign)
389 return createStringError(
390 "preferred alignment cannot be less than the ABI alignment");
391
392 setPrimitiveSpec(Specifier, BitWidth, ABIAlign, PrefAlign);
393 return Error::success();
394}
395
396Error DataLayout::parseAggregateSpec(StringRef Spec) {
397 // a<size>:<abi>[:<pref>]
398 SmallVector<StringRef, 3> Components;
399 assert(Spec.front() == 'a');
400 Spec.drop_front().split(Components, ':');
401
402 if (Components.size() < 2 || Components.size() > 3)
403 return createSpecFormatError("a:<abi>[:<pref>]");
404
405 // According to LangRef, <size> component must be absent altogether.
406 // For backward compatibility, allow it to be specified, but require
407 // it to be zero.
408 if (!Components[0].empty()) {
409 unsigned BitWidth;
410 if (!to_integer(Components[0], BitWidth, 10) || BitWidth != 0)
411 return createStringError("size must be zero");
412 }
413
414 // ABI alignment. Required. Can be zero, meaning use one byte alignment.
415 Align ABIAlign;
416 if (Error Err =
417 parseAlignment(Components[1], ABIAlign, "ABI", /*AllowZero=*/true))
418 return Err;
419
420 // Preferred alignment. Optional, defaults to the ABI alignment.
421 Align PrefAlign = ABIAlign;
422 if (Components.size() > 2)
423 if (Error Err = parseAlignment(Components[2], PrefAlign, "preferred"))
424 return Err;
425
426 if (PrefAlign < ABIAlign)
427 return createStringError(
428 "preferred alignment cannot be less than the ABI alignment");
429
430 StructABIAlignment = ABIAlign;
431 StructPrefAlignment = PrefAlign;
432 return Error::success();
433}
434
435Error DataLayout::parsePointerSpec(
436 StringRef Spec, SmallDenseSet<StringRef, 8> &AddrSpaceNames) {
437 // p[<n>]:<size>:<abi>[:<pref>[:<idx>]]
438 SmallVector<StringRef, 5> Components;
439 assert(Spec.front() == 'p');
440 Spec.drop_front().split(Components, ':');
441
442 if (Components.size() < 3 || Components.size() > 5)
443 return createSpecFormatError("p[<n>]:<size>:<abi>[:<pref>[:<idx>]]");
444
445 // Address space. Optional, defaults to 0.
446 unsigned AddrSpace = 0;
447 bool ExternalState = false;
448 bool UnstableRepr = false;
449 StringRef AddrSpaceName;
450 StringRef AddrSpaceStr = Components[0];
451 while (!AddrSpaceStr.empty()) {
452 char C = AddrSpaceStr.front();
453 if (C == 'e') {
454 ExternalState = true;
455 } else if (C == 'u') {
456 UnstableRepr = true;
457 } else if (isAlpha(C)) {
458 return createStringError("'%c' is not a valid pointer specification flag",
459 C);
460 } else {
461 break; // not a valid flag, remaining must be the address space number.
462 }
463 AddrSpaceStr = AddrSpaceStr.drop_front(1);
464 }
465 if (!AddrSpaceStr.empty())
466 if (Error Err =
467 parseAddrSpaceAndName(AddrSpaceStr, AddrSpace, AddrSpaceName))
468 return Err; // Failed to parse the remaining characters as a number
469 if (AddrSpace == 0 && (ExternalState || UnstableRepr))
470 return createStringError(
471 "address space 0 cannot be unstable or have external state");
472
473 // Check for duplicate address space names.
474 if (!AddrSpaceName.empty() && !AddrSpaceNames.insert(AddrSpaceName).second)
475 return createStringError("address space name `" + AddrSpaceName +
476 "` already used");
477
478 // Size. Required, cannot be zero.
479 unsigned BitWidth;
480 if (Error Err = parseSize(Components[1], BitWidth, "pointer size"))
481 return Err;
482
483 // ABI alignment. Required, cannot be zero.
484 Align ABIAlign;
485 if (Error Err = parseAlignment(Components[2], ABIAlign, "ABI"))
486 return Err;
487
488 // Preferred alignment. Optional, defaults to the ABI alignment.
489 // Cannot be zero.
490 Align PrefAlign = ABIAlign;
491 if (Components.size() > 3)
492 if (Error Err = parseAlignment(Components[3], PrefAlign, "preferred"))
493 return Err;
494
495 if (PrefAlign < ABIAlign)
496 return createStringError(
497 "preferred alignment cannot be less than the ABI alignment");
498
499 // Index size. Optional, defaults to pointer size. Cannot be zero.
500 unsigned IndexBitWidth = BitWidth;
501 if (Components.size() > 4)
502 if (Error Err = parseSize(Components[4], IndexBitWidth, "index size"))
503 return Err;
504
505 if (IndexBitWidth > BitWidth)
506 return createStringError(
507 "index size cannot be larger than the pointer size");
508
509 setPointerSpec(AddrSpace, BitWidth, ABIAlign, PrefAlign, IndexBitWidth,
510 UnstableRepr, ExternalState, AddrSpaceName);
511 return Error::success();
512}
513
514Error DataLayout::parseSpecification(
515 StringRef Spec, SmallVectorImpl<unsigned> &NonIntegralAddressSpaces,
516 SmallDenseSet<StringRef, 8> &AddrSpaceNames) {
517 // The "ni" specifier is the only two-character specifier. Handle it first.
518 if (Spec.starts_with("ni")) {
519 // ni:<address space>[:<address space>]...
520 StringRef Rest = Spec.drop_front(2);
521
522 // Drop the first ':', then split the rest of the string the usual way.
523 if (!Rest.consume_front(":"))
524 return createSpecFormatError("ni:<address space>[:<address space>]...");
525
526 for (StringRef Str : split(Rest, ':')) {
527 unsigned AddrSpace;
528 if (Error Err = parseAddrSpace(Str, AddrSpace))
529 return Err;
530 if (AddrSpace == 0)
531 return createStringError("address space 0 cannot be non-integral");
532 NonIntegralAddressSpaces.push_back(AddrSpace);
533 }
534 return Error::success();
535 }
536
537 if (Spec == "ve") {
538 VectorsAreElementAligned = true;
539 return Error::success();
540 }
541
542 // The rest of the specifiers are single-character.
543 assert(!Spec.empty() && "Empty specification is handled by the caller");
544 char Specifier = Spec.front();
545
546 if (Specifier == 'i' || Specifier == 'f' || Specifier == 'v')
547 return parsePrimitiveSpec(Spec);
548
549 if (Specifier == 'a')
550 return parseAggregateSpec(Spec);
551
552 if (Specifier == 'p')
553 return parsePointerSpec(Spec, AddrSpaceNames);
554
555 StringRef Rest = Spec.drop_front();
556 switch (Specifier) {
557 case 's':
558 // Deprecated, but ignoring here to preserve loading older textual llvm
559 // ASM file
560 break;
561 case 'e':
562 case 'E':
563 if (!Rest.empty())
564 return createStringError(
565 "malformed specification, must be just 'e' or 'E'");
566 BigEndian = Specifier == 'E';
567 break;
568 case 'n': // Native integer types.
569 // n<size>[:<size>]...
570 for (StringRef Str : split(Rest, ':')) {
571 unsigned BitWidth;
572 if (Error Err = parseSize(Str, BitWidth))
573 return Err;
574 LegalIntWidths.push_back(BitWidth);
575 }
576 break;
577 case 'S': { // Stack natural alignment.
578 // S<size>
579 if (Rest.empty())
580 return createSpecFormatError("S<size>");
581 Align Alignment;
582 if (Error Err = parseAlignment(Rest, Alignment, "stack natural"))
583 return Err;
584 StackNaturalAlign = Alignment;
585 break;
586 }
587 case 'F': {
588 // F<type><abi>
589 if (Rest.empty())
590 return createSpecFormatError("F<type><abi>");
591 char Type = Rest.front();
592 Rest = Rest.drop_front();
593 switch (Type) {
594 case 'i':
595 TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
596 break;
597 case 'n':
598 TheFunctionPtrAlignType = FunctionPtrAlignType::MultipleOfFunctionAlign;
599 break;
600 default:
601 return createStringError("unknown function pointer alignment type '" +
602 Twine(Type) + "'");
603 }
604 Align Alignment;
605 if (Error Err = parseAlignment(Rest, Alignment, "ABI"))
606 return Err;
607 FunctionPtrAlign = Alignment;
608 break;
609 }
610 case 'P': { // Function address space.
611 if (Rest.empty())
612 return createSpecFormatError("P<address space>");
613 if (Error Err = parseAddrSpace(Rest, ProgramAddrSpace))
614 return Err;
615 break;
616 }
617 case 'A': { // Default stack/alloca address space.
618 if (Rest.empty())
619 return createSpecFormatError("A<address space>");
620 if (Error Err = parseAddrSpace(Rest, AllocaAddrSpace))
621 return Err;
622 break;
623 }
624 case 'G': { // Default address space for global variables.
625 if (Rest.empty())
626 return createSpecFormatError("G<address space>");
627 if (Error Err = parseAddrSpace(Rest, DefaultGlobalsAddrSpace))
628 return Err;
629 break;
630 }
631 case 'm':
632 if (!Rest.consume_front(":") || Rest.empty())
633 return createSpecFormatError("m:<mangling>");
634 if (Rest.size() > 1)
635 return createStringError("unknown mangling mode");
636 switch (Rest[0]) {
637 default:
638 return createStringError("unknown mangling mode");
639 case 'e':
640 ManglingMode = MM_ELF;
641 break;
642 case 'l':
643 ManglingMode = MM_GOFF;
644 break;
645 case 'o':
646 ManglingMode = MM_MachO;
647 break;
648 case 'm':
649 ManglingMode = MM_Mips;
650 break;
651 case 'w':
652 ManglingMode = MM_WinCOFF;
653 break;
654 case 'x':
655 ManglingMode = MM_WinCOFFX86;
656 break;
657 case 'a':
658 ManglingMode = MM_XCOFF;
659 break;
660 }
661 break;
662 default:
663 return createStringError("unknown specifier '" + Twine(Specifier) + "'");
664 }
665
666 return Error::success();
667}
668
669Error DataLayout::parseLayoutString(StringRef LayoutString) {
670 StringRepresentation = LayoutString.str();
671
672 if (LayoutString.empty())
673 return Error::success();
674
675 // Split the data layout string into specifications separated by '-' and
676 // parse each specification individually, updating internal data structures.
677 SmallVector<unsigned, 8> NonIntegralAddressSpaces;
678 SmallDenseSet<StringRef, 8> AddessSpaceNames;
679 for (StringRef Spec : split(StringRepresentation, '-')) {
680 if (Spec.empty())
681 return createStringError("empty specification is not allowed");
682 if (Error Err = parseSpecification(Spec, NonIntegralAddressSpaces,
683 AddessSpaceNames))
684 return Err;
685 }
686 // Mark all address spaces that were qualified as non-integral now. This has
687 // to be done later since the non-integral property is not part of the data
688 // layout pointer specification.
689 for (unsigned AS : NonIntegralAddressSpaces) {
690 // If there is no special spec for a given AS, getPointerSpec(AS) returns
691 // the spec for AS0, and we then update that to mark it non-integral.
692 const PointerSpec &PS = getPointerSpec(AS);
693 setPointerSpec(AS, PS.BitWidth, PS.ABIAlign, PS.PrefAlign, PS.IndexBitWidth,
694 /*HasUnstableRepr=*/true, /*HasExternalState=*/false,
696 }
697
698 return Error::success();
699}
700
701void DataLayout::setPrimitiveSpec(char Specifier, uint32_t BitWidth,
702 Align ABIAlign, Align PrefAlign) {
703 SmallVectorImpl<PrimitiveSpec> *Specs;
704 switch (Specifier) {
705 default:
706 llvm_unreachable("Unexpected specifier");
707 case 'i':
708 Specs = &IntSpecs;
709 break;
710 case 'f':
711 Specs = &FloatSpecs;
712 break;
713 case 'v':
714 Specs = &VectorSpecs;
715 break;
716 }
717
718 auto I = lower_bound(*Specs, BitWidth, LessPrimitiveBitWidth());
719 if (I != Specs->end() && I->BitWidth == BitWidth) {
720 // Update the abi, preferred alignments.
721 I->ABIAlign = ABIAlign;
722 I->PrefAlign = PrefAlign;
723 } else {
724 // Insert before I to keep the vector sorted.
725 Specs->insert(I, PrimitiveSpec{BitWidth, ABIAlign, PrefAlign});
726 }
727}
728
730DataLayout::getPointerSpec(uint32_t AddrSpace) const {
731 if (AddrSpace != 0) {
732 auto I = lower_bound(PointerSpecs, AddrSpace, LessPointerAddrSpace());
733 if (I != PointerSpecs.end() && I->AddrSpace == AddrSpace)
734 return *I;
735 }
736
737 assert(PointerSpecs[0].AddrSpace == 0);
738 return PointerSpecs[0];
739}
740
741void DataLayout::setPointerSpec(uint32_t AddrSpace, uint32_t BitWidth,
742 Align ABIAlign, Align PrefAlign,
743 uint32_t IndexBitWidth, bool HasUnstableRepr,
744 bool HasExternalState,
745 StringRef AddrSpaceName) {
746 auto I = lower_bound(PointerSpecs, AddrSpace, LessPointerAddrSpace());
747 if (I == PointerSpecs.end() || I->AddrSpace != AddrSpace) {
748 PointerSpecs.insert(I, PointerSpec{AddrSpace, BitWidth, ABIAlign, PrefAlign,
749 IndexBitWidth, HasUnstableRepr,
750 HasExternalState, AddrSpaceName.str()});
751 } else {
752 I->BitWidth = BitWidth;
753 I->ABIAlign = ABIAlign;
754 I->PrefAlign = PrefAlign;
755 I->IndexBitWidth = IndexBitWidth;
756 I->HasUnstableRepresentation = HasUnstableRepr;
757 I->HasExternalState = HasExternalState;
758 I->AddrSpaceName = AddrSpaceName.str();
759 }
760}
761
762Align DataLayout::getIntegerAlignment(uint32_t BitWidth,
763 bool abi_or_pref) const {
764 auto I = IntSpecs.begin();
765 for (; I != IntSpecs.end(); ++I) {
766 if (I->BitWidth >= BitWidth)
767 break;
768 }
769
770 // If we don't have an exact match, use alignment of next larger integer
771 // type. If there is none, use alignment of largest integer type by going
772 // back one element.
773 if (I == IntSpecs.end())
774 --I;
775 return abi_or_pref ? I->ABIAlign : I->PrefAlign;
776}
777
778DataLayout::~DataLayout() { delete static_cast<StructLayoutMap *>(LayoutMap); }
779
781 if (!LayoutMap)
782 LayoutMap = new StructLayoutMap();
783
784 StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
785 StructLayout *&SL = (*STM)[Ty];
786 if (SL) return SL;
787
788 // Otherwise, create the struct layout. Because it is variable length, we
789 // malloc it, then use placement new.
791 StructLayout::totalSizeToAlloc<TypeSize>(Ty->getNumElements()));
792
793 // Set SL before calling StructLayout's ctor. The ctor could cause other
794 // entries to be added to TheMap, invalidating our reference.
795 SL = L;
796
797 new (L) StructLayout(Ty, *this);
798
799 return L;
800}
801
803 return getPointerSpec(AS).ABIAlign;
804}
805
807 return getPointerSpec(AS).AddrSpaceName;
808}
809
810std::optional<unsigned> DataLayout::getNamedAddressSpace(StringRef Name) const {
811 auto II = llvm::find_if(PointerSpecs, [Name](const PointerSpec &PS) {
812 return PS.AddrSpaceName == Name;
813 });
814 if (II != PointerSpecs.end())
815 return II->AddrSpace;
816 return std::nullopt;
817}
818
820 return getPointerSpec(AS).PrefAlign;
821}
822
823unsigned DataLayout::getPointerSize(unsigned AS) const {
824 return divideCeil(getPointerSpec(AS).BitWidth, 8);
825}
826
828 assert(Ty->isPtrOrPtrVectorTy() &&
829 "This should only be called with a pointer or pointer vector type");
830 Ty = Ty->getScalarType();
832}
833
834unsigned DataLayout::getIndexSize(unsigned AS) const {
835 return divideCeil(getPointerSpec(AS).IndexBitWidth, 8);
836}
837
839 assert(Ty->isPtrOrPtrVectorTy() &&
840 "This should only be called with a pointer or pointer vector type");
841 Ty = Ty->getScalarType();
843}
844
845/*!
846 \param abi_or_pref Flag that determines which alignment is returned. true
847 returns the ABI alignment, false returns the preferred alignment.
848 \param Ty The underlying type for which alignment is determined.
849
850 Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
851 == false) for the requested type \a Ty.
852 */
853Align DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
854 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
855 switch (Ty->getTypeID()) {
856 // Early escape for the non-numeric types.
857 case Type::LabelTyID:
858 return abi_or_pref ? getPointerABIAlignment(0) : getPointerPrefAlignment(0);
859 case Type::PointerTyID: {
860 unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
861 return abi_or_pref ? getPointerABIAlignment(AS)
863 }
864 case Type::ArrayTyID:
865 return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
866
867 case Type::StructTyID: {
868 // Packed structure types always have an ABI alignment of one.
869 if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
870 return Align(1);
871
872 // Get the layout annotation... which is lazily created on demand.
873 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
874 const Align Align = abi_or_pref ? StructABIAlignment : StructPrefAlignment;
875 return std::max(Align, Layout->getAlignment());
876 }
878 return getIntegerAlignment(Ty->getIntegerBitWidth(), abi_or_pref);
879 case Type::HalfTyID:
880 case Type::BFloatTyID:
881 case Type::FloatTyID:
882 case Type::DoubleTyID:
883 // PPC_FP128TyID and FP128TyID have different data contents, but the
884 // same size and alignment, so they look the same here.
886 case Type::FP128TyID:
887 case Type::X86_FP80TyID: {
889 auto I = lower_bound(FloatSpecs, BitWidth, LessPrimitiveBitWidth());
890 if (I != FloatSpecs.end() && I->BitWidth == BitWidth)
891 return abi_or_pref ? I->ABIAlign : I->PrefAlign;
892
893 // If we still couldn't find a reasonable default alignment, fall back
894 // to a simple heuristic that the alignment is the first power of two
895 // greater-or-equal to the store size of the type. This is a reasonable
896 // approximation of reality, and if the user wanted something less
897 // less conservative, they should have specified it explicitly in the data
898 // layout.
899 return Align(PowerOf2Ceil(BitWidth / 8));
900 }
904 auto I = lower_bound(VectorSpecs, BitWidth, LessPrimitiveBitWidth());
905 if (I != VectorSpecs.end() && I->BitWidth == BitWidth)
906 return abi_or_pref ? I->ABIAlign : I->PrefAlign;
907
909 return getAlignment(cast<VectorType>(Ty)->getElementType(), abi_or_pref);
910
911 // By default, use natural alignment for vector types. This is consistent
912 // with what clang and llvm-gcc do.
913 //
914 // We're only calculating a natural alignment, so it doesn't have to be
915 // based on the full size for scalable vectors. Using the minimum element
916 // count should be enough here.
917 return Align(PowerOf2Ceil(getTypeStoreSize(Ty).getKnownMinValue()));
918 }
920 return Align(64);
921 case Type::TargetExtTyID: {
922 Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
923 return getAlignment(LayoutTy, abi_or_pref);
924 }
925 default:
926 llvm_unreachable("Bad type for getAlignment!!!");
927 }
928}
929
931 switch (Ty->getTypeID()) {
932 case Type::ArrayTyID: {
933 // The alignment of the array is the alignment of the element, so there
934 // is no need for further adjustment.
935 auto *ATy = cast<ArrayType>(Ty);
936 return ATy->getNumElements() * getTypeAllocSize(ATy->getElementType());
937 }
938 case Type::StructTyID: {
939 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
940 TypeSize Size = Layout->getSizeInBytes();
941
942 if (cast<StructType>(Ty)->isPacked())
943 return Size;
944
945 Align A = std::max(StructABIAlignment, Layout->getAlignment());
946 return alignTo(Size, A.value());
947 }
948 case Type::IntegerTyID: {
949 unsigned BitWidth = Ty->getIntegerBitWidth();
951 Align A = getIntegerAlignment(BitWidth, /*ABI=*/true);
952 return alignTo(Size, A.value());
953 }
954 case Type::PointerTyID: {
955 unsigned AS = Ty->getPointerAddressSpace();
957 return alignTo(Size, getPointerABIAlignment(AS).value());
958 }
959 case Type::TargetExtTyID: {
960 Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
961 return getTypeAllocSize(LayoutTy);
962 }
963 default:
964 return alignTo(getTypeStoreSize(Ty), getABITypeAlign(Ty).value());
965 }
966}
967
969 return getAlignment(Ty, true);
970}
971
973 return getAlignment(Ty, false);
974}
975
980
982 assert(Ty->isPtrOrPtrVectorTy() &&
983 "Expected a pointer or pointer vector type.");
984 unsigned NumBits = getPointerTypeSizeInBits(Ty);
985 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
986 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
987 return VectorType::get(IntTy, VecTy);
988 return IntTy;
989}
990
992 for (unsigned LegalIntWidth : LegalIntWidths)
993 if (Width <= LegalIntWidth)
994 return Type::getIntNTy(C, LegalIntWidth);
995 return nullptr;
996}
997
999 auto Max = llvm::max_element(LegalIntWidths);
1000 return Max != LegalIntWidths.end() ? *Max : 0;
1001}
1002
1007
1009 assert(Ty->isPtrOrPtrVectorTy() &&
1010 "Expected a pointer or pointer vector type.");
1011 unsigned NumBits = getIndexTypeSizeInBits(Ty);
1012 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
1013 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
1014 return VectorType::get(IntTy, VecTy);
1015 return IntTy;
1016}
1017
1019 ArrayRef<Value *> Indices) const {
1020 int64_t Result = 0;
1021
1023 GTI = gep_type_begin(ElemTy, Indices),
1024 GTE = gep_type_end(ElemTy, Indices);
1025 for (; GTI != GTE; ++GTI) {
1026 Value *Idx = GTI.getOperand();
1027 if (StructType *STy = GTI.getStructTypeOrNull()) {
1028 assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
1029 unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
1030
1031 // Get structure layout information...
1032 const StructLayout *Layout = getStructLayout(STy);
1033
1034 // Add in the offset, as calculated by the structure layout info...
1035 Result += Layout->getElementOffset(FieldNo);
1036 } else {
1037 if (int64_t ArrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
1038 Result += ArrayIdx * GTI.getSequentialElementStride(*this);
1039 }
1040 }
1041
1042 return Result;
1043}
1044
1046 // Skip over scalable or zero size elements. Also skip element sizes larger
1047 // than the positive index space, because the arithmetic below may not be
1048 // correct in that case.
1049 unsigned BitWidth = Offset.getBitWidth();
1050 if (ElemSize.isScalable() || ElemSize == 0 ||
1051 !isUIntN(BitWidth - 1, ElemSize)) {
1052 return APInt::getZero(BitWidth);
1053 }
1054
1055 uint64_t FixedElemSize = ElemSize.getFixedValue();
1056 APInt Index = Offset.sdiv(FixedElemSize);
1057 Offset -= Index * FixedElemSize;
1058 if (Offset.isNegative()) {
1059 // Prefer a positive remaining offset to allow struct indexing.
1060 --Index;
1061 Offset += FixedElemSize;
1062 assert(Offset.isNonNegative() && "Remaining offset shouldn't be negative");
1063 }
1064 return Index;
1065}
1066
1067std::optional<APInt> DataLayout::getGEPIndexForOffset(Type *&ElemTy,
1068 APInt &Offset) const {
1069 if (auto *ArrTy = dyn_cast<ArrayType>(ElemTy)) {
1070 ElemTy = ArrTy->getElementType();
1071 return getElementIndex(getTypeAllocSize(ElemTy), Offset);
1072 }
1073
1074 if (isa<VectorType>(ElemTy)) {
1075 // Vector GEPs are partially broken (e.g. for overaligned element types),
1076 // and may be forbidden in the future, so avoid generating GEPs into
1077 // vectors. See https://discourse.llvm.org/t/67497
1078 return std::nullopt;
1079 }
1080
1081 if (auto *STy = dyn_cast<StructType>(ElemTy)) {
1082 const StructLayout *SL = getStructLayout(STy);
1083 uint64_t IntOffset = Offset.getZExtValue();
1084 if (IntOffset >= SL->getSizeInBytes())
1085 return std::nullopt;
1086
1087 unsigned Index = SL->getElementContainingOffset(IntOffset);
1088 Offset -= SL->getElementOffset(Index);
1089 ElemTy = STy->getElementType(Index);
1090 return APInt(32, Index);
1091 }
1092
1093 // Non-aggregate type.
1094 return std::nullopt;
1095}
1096
1098 APInt &Offset) const {
1099 assert(ElemTy->isSized() && "Element type must be sized");
1100 SmallVector<APInt> Indices;
1102 while (Offset != 0) {
1103 std::optional<APInt> Index = getGEPIndexForOffset(ElemTy, Offset);
1104 if (!Index)
1105 break;
1106 Indices.push_back(*Index);
1107 }
1108
1109 return Indices;
1110}
1111
1112/// getPreferredAlign - Return the preferred alignment of the specified global.
1113/// This includes an explicitly requested alignment (if the global has one).
1115 MaybeAlign GVAlignment = GV->getAlign();
1116 // If a section is specified, always precisely honor explicit alignment,
1117 // so we don't insert padding into a section we don't control.
1118 if (GVAlignment && GV->hasSection())
1119 return *GVAlignment;
1120
1121 // If no explicit alignment is specified, compute the alignment based on
1122 // the IR type. If an alignment is specified, increase it to match the ABI
1123 // alignment of the IR type.
1124 //
1125 // FIXME: Not sure it makes sense to use the alignment of the type if
1126 // there's already an explicit alignment specification.
1127 Type *ElemType = GV->getValueType();
1128 Align Alignment = getPrefTypeAlign(ElemType);
1129 if (GVAlignment) {
1130 if (*GVAlignment >= Alignment)
1131 Alignment = *GVAlignment;
1132 else
1133 Alignment = std::max(*GVAlignment, getABITypeAlign(ElemType));
1134 }
1135
1136 // If no explicit alignment is specified, and the global is large, increase
1137 // the alignment to 16.
1138 // FIXME: Why 16, specifically?
1139 if (GV->hasInitializer() && !GVAlignment) {
1140 if (Alignment < Align(16)) {
1141 // If the global is not external, see if it is large. If so, give it a
1142 // larger alignment.
1143 if (getTypeSizeInBits(ElemType) > 128)
1144 Alignment = Align(16); // 16-byte alignment.
1145 }
1146 }
1147 return Alignment;
1148}
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 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
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:494
@ MultipleOfFunctionAlign
The function pointer alignment is a multiple of the function alignment.
Definition DataLayout.h:106
@ Independent
The function pointer alignment is independent of the function alignment.
Definition DataLayout.h:104
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:219
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 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:502
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:775
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:572
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:318
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:727
TypeSize getSizeInBytes() const
Definition DataLayout.h:736
MutableArrayRef< TypeSize > getMemberOffsets()
Definition DataLayout.h:750
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:758
Align getAlignment() const
Definition DataLayout.h:740
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:45
LLVM_ABI unsigned getIntegerBitWidth() const
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition Type.h:66
@ ArrayTyID
Arrays.
Definition Type.h:74
@ HalfTyID
16-bit floating point type
Definition Type.h:56
@ TargetExtTyID
Target extension type.
Definition Type.h:78
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:76
@ LabelTyID
Labels.
Definition Type.h:64
@ FloatTyID
32-bit floating point type
Definition Type.h:58
@ StructTyID
Structures.
Definition Type.h:73
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:70
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:75
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:57
@ DoubleTyID
64-bit floating point type
Definition Type.h:59
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:60
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:62
@ PointerTyID
Pointers.
Definition Type.h:72
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:300
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
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.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
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:2065
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
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
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:2052
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
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:2088
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:1772
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,...
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
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