LLVM 23.0.0git
DataLayout.h
Go to the documentation of this file.
1//===- llvm/DataLayout.h - Data size & alignment info -----------*- C++ -*-===//
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. It uses lazy annotations to cache information about how
11// structure types are laid out and used.
12//
13// This structure should be created once, filled in if the defaults are not
14// correct and then passed around by const&. None of the members functions
15// require modification to the object.
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_IR_DATALAYOUT_H
20#define LLVM_IR_DATALAYOUT_H
21
22#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/StringRef.h"
29#include "llvm/IR/Type.h"
37#include <cassert>
38#include <cstdint>
39#include <string>
40
41// This needs to be outside of the namespace, to avoid conflict with llvm-c
42// decl.
43using LLVMTargetDataRef = struct LLVMOpaqueTargetData *;
44
45namespace llvm {
46
47class GlobalVariable;
48class LLVMContext;
49class StructLayout;
50class Triple;
51class Value;
52
53// FIXME: Currently the DataLayout string carries a "preferred alignment"
54// for types. As the DataLayout is module/global, this should likely be
55// sunk down to an FTTI element that is queried rather than a global
56// preference.
57
58/// A parsed version of the target data layout string in and methods for
59/// querying it.
60///
61/// The target data layout string is specified *by the target* - a frontend
62/// generating LLVM IR is required to generate the right target data for the
63/// target being codegen'd to.
65public:
66 /// Primitive type specification.
74
75 /// Pointer type specification.
76 struct PointerSpec {
81 /// The index bit width also defines the address size in this address space.
82 /// If the index width is less than the representation bit width, the
83 /// pointer is non-integral and bits beyond the index width could be used
84 /// for additional metadata (e.g. AMDGPU buffer fat pointers with bounds
85 /// and other flags or CHERI capabilities that contain bounds+permissions).
87 /// Pointers in this address space don't have a well-defined bitwise
88 /// representation (e.g. they may be relocated by a copying garbage
89 /// collector and thus have different addresses at different times).
91 /// Pointers in this address space have additional state bits that are
92 /// located at a target-defined location when stored in memory. An example
93 /// of this would be CHERI capabilities where the validity bit is stored
94 /// separately from the pointer address+bounds information.
96 // Symbolic name of the address space.
97 std::string AddrSpaceName;
98
99 LLVM_ABI bool operator==(const PointerSpec &Other) const;
100 };
101
103 /// The function pointer alignment is independent of the function alignment.
105 /// The function pointer alignment is a multiple of the function alignment.
107 };
108
109private:
110 bool BigEndian = false;
111 bool VectorsAreElementAligned = false;
112
113 unsigned AllocaAddrSpace = 0;
114 unsigned ProgramAddrSpace = 0;
115 unsigned DefaultGlobalsAddrSpace = 0;
116
117 MaybeAlign StackNaturalAlign;
118 MaybeAlign FunctionPtrAlign;
119 FunctionPtrAlignType TheFunctionPtrAlignType =
121
122 enum ManglingModeT {
123 MM_None,
124 MM_ELF,
125 MM_MachO,
126 MM_WinCOFF,
127 MM_WinCOFFX86,
128 MM_GOFF,
129 MM_Mips,
130 MM_XCOFF
131 };
132 ManglingModeT ManglingMode = MM_None;
133
134 // FIXME: `unsigned char` truncates the value parsed by `parseSpecifier`.
135 SmallVector<unsigned char, 8> LegalIntWidths;
136
137 /// Primitive type specifications. Sorted and uniqued by type bit width.
141
142 /// Pointer type specifications. Sorted and uniqued by address space number.
143 SmallVector<PointerSpec, 8> PointerSpecs;
144
145 /// The string representation used to create this DataLayout
146 std::string StringRepresentation;
147
148 /// Struct type ABI and preferred alignments. The default spec is "a:8:64".
149 Align StructABIAlignment = Align::Constant<1>();
150 Align StructPrefAlignment = Align::Constant<8>();
151
152 // The StructType -> StructLayout map.
153 mutable void *LayoutMap = nullptr;
154
155 /// Sets or updates the specification for the given primitive type.
156 void setPrimitiveSpec(char Specifier, uint32_t BitWidth, Align ABIAlign,
157 Align PrefAlign);
158
159 /// Searches for a pointer specification that matches the given address space.
160 /// Returns the default address space specification if not found.
161 LLVM_ABI const PointerSpec &getPointerSpec(uint32_t AddrSpace) const;
162
163 /// Sets or updates the specification for pointer in the given address space.
164 void setPointerSpec(uint32_t AddrSpace, uint32_t BitWidth, Align ABIAlign,
165 Align PrefAlign, uint32_t IndexBitWidth,
166 bool HasUnstableRepr, bool HasExternalState,
167 StringRef AddrSpaceName);
168
169 /// Internal helper to get alignment for integer of given bitwidth.
170 LLVM_ABI Align getIntegerAlignment(uint32_t BitWidth, bool abi_or_pref) const;
171
172 /// Internal helper method that returns requested alignment for type.
173 Align getAlignment(Type *Ty, bool abi_or_pref) const;
174
175 /// Attempts to parse primitive specification ('i', 'f', or 'v').
176 Error parsePrimitiveSpec(StringRef Spec);
177
178 /// Attempts to parse aggregate specification ('a').
179 Error parseAggregateSpec(StringRef Spec);
180
181 /// Attempts to parse pointer specification ('p').
182 Error parsePointerSpec(StringRef Spec,
183 SmallDenseSet<StringRef, 8> &AddrSpaceNames);
184
185 /// Attempts to parse a single specification.
186 Error parseSpecification(StringRef Spec,
187 SmallVectorImpl<unsigned> &NonIntegralAddressSpaces,
188 SmallDenseSet<StringRef, 8> &AddrSpaceNames);
189
190 /// Attempts to parse a data layout string.
191 Error parseLayoutString(StringRef LayoutString);
192
193public:
194 /// Constructs a DataLayout with default values.
196
197 /// Constructs a DataLayout from a specification string.
198 /// WARNING: Aborts execution if the string is malformed. Use parse() instead.
199 LLVM_ABI explicit DataLayout(StringRef LayoutString);
200
201 DataLayout(const DataLayout &DL) { *this = DL; }
202
203 LLVM_ABI ~DataLayout(); // Not virtual, do not subclass this class
204
206
207 LLVM_ABI bool operator==(const DataLayout &Other) const;
208 bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
209
210 /// Parse a data layout string and return the layout. Return an error
211 /// description on failure.
212 LLVM_ABI static Expected<DataLayout> parse(StringRef LayoutString);
213
214 /// Layout endianness...
215 bool isLittleEndian() const { return !BigEndian; }
216 bool isBigEndian() const { return BigEndian; }
217
218 /// Whether vectors are element aligned, rather than naturally aligned.
219 bool vectorsAreElementAligned() const { return VectorsAreElementAligned; }
220
221 /// Returns the string representation of the DataLayout.
222 ///
223 /// This representation is in the same format accepted by the string
224 /// constructor above. This should not be used to compare two DataLayout as
225 /// different string can represent the same layout.
226 const std::string &getStringRepresentation() const {
227 return StringRepresentation;
228 }
229
230 /// Test if the DataLayout was constructed from an empty string.
231 bool isDefault() const { return StringRepresentation.empty(); }
232
233 /// Returns true if the specified type is known to be a native integer
234 /// type supported by the CPU.
235 ///
236 /// For example, i64 is not native on most 32-bit CPUs and i37 is not native
237 /// on any known one. This returns false if the integer width is not legal.
238 ///
239 /// The width is specified in bits.
240 bool isLegalInteger(uint64_t Width) const {
241 return llvm::is_contained(LegalIntWidths, Width);
242 }
243
244 bool isIllegalInteger(uint64_t Width) const { return !isLegalInteger(Width); }
245
246 /// Returns the natural stack alignment, or MaybeAlign() if one wasn't
247 /// specified.
248 MaybeAlign getStackAlignment() const { return StackNaturalAlign; }
249
250 unsigned getAllocaAddrSpace() const { return AllocaAddrSpace; }
251
253 return PointerType::get(Ctx, AllocaAddrSpace);
254 }
255
256 /// Returns the alignment of function pointers, which may or may not be
257 /// related to the alignment of functions.
258 /// \see getFunctionPtrAlignType
259 MaybeAlign getFunctionPtrAlign() const { return FunctionPtrAlign; }
260
261 /// Return the type of function pointer alignment.
262 /// \see getFunctionPtrAlign
264 return TheFunctionPtrAlignType;
265 }
266
267 unsigned getProgramAddressSpace() const { return ProgramAddrSpace; }
269 return DefaultGlobalsAddrSpace;
270 }
271
273 return ManglingMode == MM_WinCOFFX86;
274 }
275
276 /// Returns true if symbols with leading question marks should not receive IR
277 /// mangling. True for Windows mangling modes.
279 return ManglingMode == MM_WinCOFF || ManglingMode == MM_WinCOFFX86;
280 }
281
282 bool hasLinkerPrivateGlobalPrefix() const { return ManglingMode == MM_MachO; }
283
285 if (ManglingMode == MM_MachO)
286 return "l";
287 return "";
288 }
289
290 char getGlobalPrefix() const {
291 switch (ManglingMode) {
292 case MM_None:
293 case MM_ELF:
294 case MM_GOFF:
295 case MM_Mips:
296 case MM_WinCOFF:
297 case MM_XCOFF:
298 return '\0';
299 case MM_MachO:
300 case MM_WinCOFFX86:
301 return '_';
302 }
303 llvm_unreachable("invalid mangling mode");
304 }
305
307 switch (ManglingMode) {
308 case MM_None:
309 return "";
310 case MM_ELF:
311 case MM_WinCOFF:
312 return ".L";
313 case MM_GOFF:
314 return "L#";
315 case MM_Mips:
316 return "$";
317 case MM_MachO:
318 case MM_WinCOFFX86:
319 return "L";
320 case MM_XCOFF:
321 return "L..";
322 }
323 llvm_unreachable("invalid mangling mode");
324 }
325
326 /// Returns true if the specified type fits in a native integer type
327 /// supported by the CPU.
328 ///
329 /// For example, if the CPU only supports i32 as a native integer type, then
330 /// i27 fits in a legal integer type but i45 does not.
331 bool fitsInLegalInteger(unsigned Width) const {
332 for (unsigned LegalIntWidth : LegalIntWidths)
333 if (Width <= LegalIntWidth)
334 return true;
335 return false;
336 }
337
338 /// Layout pointer alignment.
339 LLVM_ABI Align getPointerABIAlignment(unsigned AS) const;
340
341 LLVM_ABI StringRef getAddressSpaceName(unsigned AS) const;
342
343 LLVM_ABI std::optional<unsigned> getNamedAddressSpace(StringRef Name) const;
344
345 /// Return target's alignment for stack-based pointers
346 /// FIXME: The defaults need to be removed once all of
347 /// the backends/clients are updated.
348 LLVM_ABI Align getPointerPrefAlignment(unsigned AS = 0) const;
349
350 /// The pointer representation size in bytes, rounded up to a whole number of
351 /// bytes. The difference between this function and getAddressSize() is that
352 /// this one returns the size of the entire pointer representation (including
353 /// metadata bits for fat pointers) and the latter only returns the number of
354 /// address bits.
355 /// \sa DataLayout::getAddressSizeInBits
356 /// FIXME: The defaults need to be removed once all of
357 /// the backends/clients are updated.
358 LLVM_ABI unsigned getPointerSize(unsigned AS = 0) const;
359
360 /// The index size in bytes used for address calculation, rounded up to a
361 /// whole number of bytes. This not only defines the size used in
362 /// getelementptr operations, but also the size of addresses in this \p AS.
363 /// For example, a 64-bit CHERI-enabled target has 128-bit pointers of which
364 /// only 64 are used to represent the address and the remaining ones are used
365 /// for metadata such as bounds and access permissions. In this case
366 /// getPointerSize() returns 16, but getIndexSize() returns 8.
367 /// To help with code understanding, the alias getAddressSize() can be used
368 /// instead of getIndexSize() to clarify that an address width is needed.
369 LLVM_ABI unsigned getIndexSize(unsigned AS) const;
370
371 /// The integral size of a pointer in a given address space in bytes, which
372 /// is defined to be the same as getIndexSize(). This exists as a separate
373 /// function to make it clearer when reading code that the size of an address
374 /// is being requested. While targets exist where index size and the
375 /// underlying address width are not identical (e.g. AMDGPU fat pointers with
376 /// 48-bit addresses and 32-bit offsets indexing), there is currently no need
377 /// to differentiate these properties in LLVM.
378 /// \sa DataLayout::getIndexSize
379 /// \sa DataLayout::getAddressSizeInBits
380 unsigned getAddressSize(unsigned AS) const { return getIndexSize(AS); }
381
382 /// Return the address spaces with special pointer semantics (such as being
383 /// unstable or non-integral).
385 SmallVector<unsigned, 8> AddrSpaces;
386 for (const PointerSpec &PS : PointerSpecs) {
387 if (PS.HasUnstableRepresentation || PS.HasExternalState ||
388 PS.BitWidth != PS.IndexBitWidth)
389 AddrSpaces.push_back(PS.AddrSpace);
390 }
391 return AddrSpaces;
392 }
393
394 /// Returns whether this address space has a non-integral pointer
395 /// representation, i.e. the pointer is not just an integer address but some
396 /// other bitwise representation. When true, passes cannot assume that all
397 /// bits of the representation map directly to the allocation address.
398 /// NOTE: This also returns true for "unstable" pointers where the
399 /// representation may be just an address, but this value can change at any
400 /// given time (e.g. due to copying garbage collection).
401 /// Examples include AMDGPU buffer descriptors with a 128-bit fat pointer
402 /// and a 32-bit offset or CHERI capabilities that contain bounds, permissions
403 /// and an out-of-band validity bit.
404 ///
405 /// In general, more specialized functions such as mustNotIntroduceIntToPtr(),
406 /// mustNotIntroducePtrToInt(), or hasExternalState() should be
407 /// preferred over this one when reasoning about the behavior of IR
408 /// analysis/transforms.
409 /// TODO: should remove/deprecate this once all uses have migrated.
410 bool isNonIntegralAddressSpace(unsigned AddrSpace) const {
411 const auto &PS = getPointerSpec(AddrSpace);
412 return PS.BitWidth != PS.IndexBitWidth || PS.HasUnstableRepresentation ||
413 PS.HasExternalState;
414 }
415
416 /// Returns whether this address space has an "unstable" pointer
417 /// representation. The bitwise pattern of such pointers is allowed to change
418 /// in a target-specific way. For example, this could be used for copying
419 /// garbage collection where the garbage collector could update the pointer
420 /// value as part of the collection sweep.
421 bool hasUnstableRepresentation(unsigned AddrSpace) const {
422 return getPointerSpec(AddrSpace).HasUnstableRepresentation;
423 }
425 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
426 return PTy && hasUnstableRepresentation(PTy->getPointerAddressSpace());
427 }
428
429 /// Returns whether this address space has external state (implies having
430 /// a non-integral pointer representation).
431 /// These pointer types must be loaded and stored using appropriate
432 /// instructions and cannot use integer loads/stores as this would not
433 /// propagate the out-of-band state. An example of such a pointer type is a
434 /// CHERI capability that contain bounds, permissions and an out-of-band
435 /// validity bit that is invalidated whenever an integer/FP store is performed
436 /// to the associated memory location.
437 bool hasExternalState(unsigned AddrSpace) const {
438 return getPointerSpec(AddrSpace).HasExternalState;
439 }
440 bool hasExternalState(Type *Ty) const {
441 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
442 return PTy && hasExternalState(PTy->getPointerAddressSpace());
443 }
444
445 /// Returns whether passes must avoid introducing `inttoptr` instructions
446 /// for this address space (unless they have target-specific knowledge).
447 ///
448 /// This is currently the case for non-integral pointer representations with
449 /// external state (hasExternalState()) since `inttoptr` cannot recreate the
450 /// external state bits.
451 /// New `inttoptr` instructions should also be avoided for "unstable" bitwise
452 /// representations (hasUnstableRepresentation()) unless the pass knows it is
453 /// within a critical section that retains the current representation.
454 bool mustNotIntroduceIntToPtr(unsigned AddrSpace) const {
455 return hasUnstableRepresentation(AddrSpace) || hasExternalState(AddrSpace);
456 }
457
458 /// Returns whether passes must avoid introducing `ptrtoint` instructions
459 /// for this address space (unless they have target-specific knowledge).
460 ///
461 /// This is currently the case for pointer address spaces that have an
462 /// "unstable" representation (hasUnstableRepresentation()) since the
463 /// bitwise pattern of such pointers could change unless the pass knows it is
464 /// within a critical section that retains the current representation.
465 bool mustNotIntroducePtrToInt(unsigned AddrSpace) const {
466 return hasUnstableRepresentation(AddrSpace);
467 }
468
472
474 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
475 return PTy && isNonIntegralPointerType(PTy);
476 }
477
479 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
480 return PTy && mustNotIntroducePtrToInt(PTy->getPointerAddressSpace());
481 }
482
484 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
485 return PTy && mustNotIntroduceIntToPtr(PTy->getPointerAddressSpace());
486 }
487
488 /// The size in bits of the pointer representation in a given address space.
489 /// This is not necessarily the same as the integer address of a pointer (e.g.
490 /// for fat pointers).
491 /// \sa DataLayout::getAddressSizeInBits()
492 /// FIXME: The defaults need to be removed once all of
493 /// the backends/clients are updated.
494 unsigned getPointerSizeInBits(unsigned AS = 0) const {
495 return getPointerSpec(AS).BitWidth;
496 }
497
498 /// The size in bits of indices used for address calculation in getelementptr
499 /// and for addresses in the given AS. See getIndexSize() for more
500 /// information.
501 /// \sa DataLayout::getAddressSizeInBits()
502 unsigned getIndexSizeInBits(unsigned AS) const {
503 return getPointerSpec(AS).IndexBitWidth;
504 }
505
506 /// The size in bits of an address in for the given AS. This is defined to
507 /// return the same value as getIndexSizeInBits() since there is currently no
508 /// target that requires these two properties to have different values. See
509 /// getIndexSize() for more information.
510 /// \sa DataLayout::getIndexSizeInBits()
511 unsigned getAddressSizeInBits(unsigned AS) const {
512 return getIndexSizeInBits(AS);
513 }
514
515 /// The pointer representation size in bits for this type. If this function is
516 /// called with a pointer type, then the type size of the pointer is returned.
517 /// If this function is called with a vector of pointers, then the type size
518 /// of the pointer is returned. This should only be called with a pointer or
519 /// vector of pointers.
520 LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const;
521
522 /// The size in bits of the index used in GEP calculation for this type.
523 /// The function should be called with pointer or vector of pointers type.
524 /// This is defined to return the same value as getAddressSizeInBits(),
525 /// but separate functions exist for code clarity.
526 LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const;
527
528 /// The size in bits of an address for this type.
529 /// This is defined to return the same value as getIndexTypeSizeInBits(),
530 /// but separate functions exist for code clarity.
531 unsigned getAddressSizeInBits(Type *Ty) const {
532 return getIndexTypeSizeInBits(Ty);
533 }
534
535 unsigned getPointerTypeSize(Type *Ty) const {
536 return getPointerTypeSizeInBits(Ty) / 8;
537 }
538
539 /// Size examples:
540 ///
541 /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
542 /// ---- ---------- --------------- ---------------
543 /// i1 1 8 8
544 /// i8 8 8 8
545 /// i19 19 24 32
546 /// i32 32 32 32
547 /// i100 100 104 128
548 /// i128 128 128 128
549 /// Float 32 32 32
550 /// Double 64 64 64
551 /// X86_FP80 80 80 96
552 ///
553 /// [*] The alloc size depends on the alignment, and thus on the target.
554 /// These values are for x86-32 linux.
555
556 /// Returns the number of bits necessary to hold the specified type.
557 ///
558 /// If Ty is a scalable vector type, the scalable property will be set and
559 /// the runtime size will be a positive integer multiple of the base size.
560 ///
561 /// For example, returns 36 for i36 and 80 for x86_fp80. The type passed must
562 /// have a size (Type::isSized() must return true).
564
565 /// Returns the maximum number of bytes that may be overwritten by
566 /// storing the specified type.
567 ///
568 /// If Ty is a scalable vector type, the scalable property will be set and
569 /// the runtime size will be a positive integer multiple of the base size.
570 ///
571 /// For example, returns 5 for i36 and 10 for x86_fp80.
573 TypeSize StoreSizeInBits = getTypeStoreSizeInBits(Ty);
574 return {StoreSizeInBits.getKnownMinValue() / 8,
575 StoreSizeInBits.isScalable()};
576 }
577
578 /// Returns the maximum number of bits that may be overwritten by
579 /// storing the specified type; always a multiple of 8.
580 ///
581 /// If Ty is a scalable vector type, the scalable property will be set and
582 /// the runtime size will be a positive integer multiple of the base size.
583 ///
584 /// For example, returns 40 for i36 and 80 for x86_fp80.
586 TypeSize BaseSize = getTypeSizeInBits(Ty);
587 uint64_t AlignedSizeInBits =
588 alignToPowerOf2(BaseSize.getKnownMinValue(), 8);
589 return {AlignedSizeInBits, BaseSize.isScalable()};
590 }
591
592 /// Returns true if no extra padding bits are needed when storing the
593 /// specified type.
594 ///
595 /// For example, returns false for i19 that has a 24-bit store size.
598 }
599
600 /// Returns the offset in bytes between successive objects of the
601 /// specified type, including alignment padding.
602 ///
603 /// If Ty is a scalable vector type, the scalable property will be set and
604 /// the runtime size will be a positive integer multiple of the base size.
605 ///
606 /// This is the amount that alloca reserves for this type. For example,
607 /// returns 12 or 16 for x86_fp80, depending on alignment.
609
610 /// Returns the offset in bits between successive objects of the
611 /// specified type, including alignment padding; always a multiple of 8.
612 ///
613 /// If Ty is a scalable vector type, the scalable property will be set and
614 /// the runtime size will be a positive integer multiple of the base size.
615 ///
616 /// This is the amount that alloca reserves for this type. For example,
617 /// returns 96 or 128 for x86_fp80, depending on alignment.
619 return 8 * getTypeAllocSize(Ty);
620 }
621
622 /// Returns the minimum ABI-required alignment for the specified type.
624
625 /// Helper function to return `Alignment` if it's set or the result of
626 /// `getABITypeAlign(Ty)`, in any case the result is a valid alignment.
628 Type *Ty) const {
629 return Alignment ? *Alignment : getABITypeAlign(Ty);
630 }
631
632 /// Returns the minimum ABI-required alignment for an integer type of
633 /// the specified bitwidth.
635 return getIntegerAlignment(BitWidth, /* abi_or_pref */ true);
636 }
637
638 /// Returns the preferred stack/global alignment for the specified
639 /// type.
640 ///
641 /// This is always at least as good as the ABI alignment.
643
644 /// Returns an integer type with size at least as big as that of a
645 /// pointer in the given address space.
647 unsigned AddressSpace = 0) const;
648
649 /// Returns an integer (vector of integer) type with size at least as
650 /// big as that of a pointer of the given pointer (vector of pointer) type.
652
653 /// Returns the smallest integer type with size at least as big as
654 /// Width bits.
656 unsigned Width = 0) const;
657
658 /// Returns the largest legal integer type, or null if none are set.
660 unsigned LargestSize = getLargestLegalIntTypeSizeInBits();
661 return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
662 }
663
664 /// Returns the size of largest legal integer type size, or 0 if none
665 /// are set.
667
668 /// Returns the type of a GEP index in \p AddressSpace.
669 /// If it was not specified explicitly, it will be the integer type of the
670 /// pointer width - IntPtrType.
672 unsigned AddressSpace) const;
673 /// Returns the type of an address in \p AddressSpace
677
678 /// Returns the type of a GEP index.
679 /// If it was not specified explicitly, it will be the integer type of the
680 /// pointer width - IntPtrType.
681 LLVM_ABI Type *getIndexType(Type *PtrTy) const;
682 /// Returns the type of an address in \p AddressSpace
683 Type *getAddressType(Type *PtrTy) const { return getIndexType(PtrTy); }
684
685 /// Returns the offset from the beginning of the type for the specified
686 /// indices.
687 ///
688 /// Note that this takes the element type, not the pointer type.
689 /// This is used to implement getelementptr.
690 LLVM_ABI int64_t getIndexedOffsetInType(Type *ElemTy,
691 ArrayRef<Value *> Indices) const;
692
693 /// Get GEP indices to access Offset inside ElemTy. ElemTy is updated to be
694 /// the result element type and Offset to be the residual offset.
696 APInt &Offset) const;
697
698 /// Get single GEP index to access Offset inside ElemTy. Returns std::nullopt
699 /// if index cannot be computed, e.g. because the type is not an aggregate.
700 /// ElemTy is updated to be the result element type and Offset to be the
701 /// residual offset.
702 LLVM_ABI std::optional<APInt> getGEPIndexForOffset(Type *&ElemTy,
703 APInt &Offset) const;
704
705 /// Returns a StructLayout object, indicating the alignment of the
706 /// struct, its size, and the offsets of its fields.
707 ///
708 /// Note that this information is lazily cached.
710
711 /// Returns the preferred alignment of the specified global.
712 ///
713 /// This includes an explicitly requested alignment (if the global has one).
715};
716
718 return reinterpret_cast<DataLayout *>(P);
719}
720
722 return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
723}
724
725/// Used to lazily calculate structure layout information for a target machine,
726/// based on the DataLayout structure.
727class StructLayout final : private TrailingObjects<StructLayout, TypeSize> {
728 friend TrailingObjects;
729
730 TypeSize StructSize;
731 Align StructAlignment;
732 unsigned IsPadded : 1;
733 unsigned NumElements : 31;
734
735public:
736 TypeSize getSizeInBytes() const { return StructSize; }
737
738 TypeSize getSizeInBits() const { return 8 * StructSize; }
739
740 Align getAlignment() const { return StructAlignment; }
741
742 /// Returns whether the struct has padding or not between its fields.
743 /// NB: Padding in nested element is not taken into account.
744 bool hasPadding() const { return IsPadded; }
745
746 /// Given a valid byte offset into the structure, returns the structure
747 /// index that contains it.
748 LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const;
749
753
755 return getTrailingObjects(NumElements);
756 }
757
758 TypeSize getElementOffset(unsigned Idx) const {
759 assert(Idx < NumElements && "Invalid element idx!");
760 return getMemberOffsets()[Idx];
761 }
762
763 TypeSize getElementOffsetInBits(unsigned Idx) const {
764 return getElementOffset(Idx) * 8;
765 }
766
767private:
768 friend class DataLayout; // Only DataLayout can create this class
769
770 StructLayout(StructType *ST, const DataLayout &DL);
771};
772
773// The implementation of this method is provided inline as it is particularly
774// well suited to constant folding when called on a specific Type subclass.
776 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
777 switch (Ty->getTypeID()) {
778 case Type::LabelTyID:
781 return TypeSize::getFixed(
782 getPointerSizeInBits(Ty->getPointerAddressSpace()));
783 case Type::ArrayTyID: {
784 ArrayType *ATy = cast<ArrayType>(Ty);
785 return ATy->getNumElements() *
787 }
788 case Type::StructTyID:
789 // Get the layout annotation... which is lazily created on demand.
792 return TypeSize::getFixed(Ty->getIntegerBitWidth());
793 case Type::HalfTyID:
794 case Type::BFloatTyID:
795 return TypeSize::getFixed(16);
796 case Type::FloatTyID:
797 return TypeSize::getFixed(32);
798 case Type::DoubleTyID:
799 return TypeSize::getFixed(64);
801 case Type::FP128TyID:
802 return TypeSize::getFixed(128);
804 return TypeSize::getFixed(8192);
805 // In memory objects this is always aligned to a higher boundary, but
806 // only 80 bits contain information.
808 return TypeSize::getFixed(80);
811 VectorType *VTy = cast<VectorType>(Ty);
812 auto EltCnt = VTy->getElementCount();
813 uint64_t MinBits = EltCnt.getKnownMinValue() *
815 return TypeSize(MinBits, EltCnt.isScalable());
816 }
817 case Type::TargetExtTyID: {
818 Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
819 return getTypeSizeInBits(LayoutTy);
820 }
821 default:
822 llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
823 }
824}
825
826} // end namespace llvm
827
828#endif // LLVM_IR_DATALAYOUT_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_ABI
Definition Compiler.h:213
This file defines the DenseSet and SmallDenseSet classes.
const uint64_t BitWidth
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This header defines support for implementing classes that have some trailing object (or arrays of obj...
static uint32_t getAlignment(const MCSectionCOFF &Sec)
Class for arbitrary precision integers.
Definition APInt.h:78
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Class to represent array types.
uint64_t getNumElements() const
Type * getElementType() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
unsigned getProgramAddressSpace() const
Definition DataLayout.h:267
bool typeSizeEqualsStoreSize(Type *Ty) const
Returns true if no extra padding bits are needed when storing the specified type.
Definition DataLayout.h:596
LLVM_ABI std::optional< unsigned > getNamedAddressSpace(StringRef Name) const
bool hasLinkerPrivateGlobalPrefix() const
Definition DataLayout.h:282
bool hasExternalState(unsigned AddrSpace) const
Returns whether this address space has external state (implies having a non-integral pointer represen...
Definition DataLayout.h:437
StringRef getLinkerPrivateGlobalPrefix() const
Definition DataLayout.h:284
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
bool isNonIntegralPointerType(Type *Ty) const
Definition DataLayout.h:473
@ 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.
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:215
bool isDefault() const
Test if the DataLayout was constructed from an empty string.
Definition DataLayout.h:231
Type * getAddressType(Type *PtrTy) const
Returns the type of an address in AddressSpace.
Definition DataLayout.h:683
TypeSize getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Definition DataLayout.h:585
LLVM_ABI unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:511
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU.
Definition DataLayout.h:240
unsigned getDefaultGlobalsAddressSpace() const
Definition DataLayout.h:268
FunctionPtrAlignType getFunctionPtrAlignType() const
Return the type of function pointer alignment.
Definition DataLayout.h:263
Align getABIIntegerTypeAlignment(unsigned BitWidth) const
Returns the minimum ABI-required alignment for an integer type of the specified bitwidth.
Definition DataLayout.h:634
IntegerType * getAddressType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of an address in AddressSpace.
Definition DataLayout.h:674
bool vectorsAreElementAligned() const
Whether vectors are element aligned, rather than naturally aligned.
Definition DataLayout.h:219
bool doNotMangleLeadingQuestionMark() const
Returns true if symbols with leading question marks should not receive IR mangling.
Definition DataLayout.h:278
LLVM_ABI unsigned getIndexSize(unsigned AS) const
The index size in bytes used for address calculation, rounded up to a whole number of bytes.
bool mustNotIntroduceIntToPtr(unsigned AddrSpace) const
Returns whether passes must avoid introducing inttoptr instructions for this address space (unless th...
Definition DataLayout.h:454
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.
bool hasUnstableRepresentation(unsigned AddrSpace) const
Returns whether this address space has an "unstable" pointer representation.
Definition DataLayout.h:421
bool mustNotIntroduceIntToPtr(Type *Ty) const
Definition DataLayout.h:483
unsigned getAddressSizeInBits(Type *Ty) const
The size in bits of an address for this type.
Definition DataLayout.h:531
bool mustNotIntroducePtrToInt(Type *Ty) const
Definition DataLayout.h:478
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.
unsigned getPointerTypeSize(Type *Ty) const
Definition DataLayout.h:535
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
bool isNonIntegralAddressSpace(unsigned AddrSpace) const
Returns whether this address space has a non-integral pointer representation, i.e.
Definition DataLayout.h:410
bool isIllegalInteger(uint64_t Width) const
Definition DataLayout.h:244
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
PointerType * getAllocaPtrType(LLVMContext &Ctx) const
Definition DataLayout.h:252
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
bool isBigEndian() const
Definition DataLayout.h:216
SmallVector< unsigned, 8 > getNonStandardAddressSpaces() const
Return the address spaces with special pointer semantics (such as being unstable or non-integral).
Definition DataLayout.h:384
MaybeAlign getStackAlignment() const
Returns the natural stack alignment, or MaybeAlign() if one wasn't specified.
Definition DataLayout.h:248
unsigned getAllocaAddrSpace() const
Definition DataLayout.h:250
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...
StringRef getInternalSymbolPrefix() const
Definition DataLayout.h:306
bool mustNotIntroducePtrToInt(unsigned AddrSpace) const
Returns whether passes must avoid introducing ptrtoint instructions for this address space (unless th...
Definition DataLayout.h:465
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.
bool hasExternalState(Type *Ty) const
Definition DataLayout.h:440
LLVM_ABI Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
bool fitsInLegalInteger(unsigned Width) const
Returns true if the specified type fits in a native integer type supported by the CPU.
Definition DataLayout.h:331
bool hasMicrosoftFastStdCallMangling() const
Definition DataLayout.h:272
bool hasUnstableRepresentation(Type *Ty) const
Definition DataLayout.h:424
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.
bool isNonIntegralPointerType(PointerType *PT) const
Definition DataLayout.h:469
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
Type * getLargestLegalIntType(LLVMContext &C) const
Returns the largest legal integer type, or null if none are set.
Definition DataLayout.h:659
MaybeAlign getFunctionPtrAlign() const
Returns the alignment of function pointers, which may or may not be related to the alignment of funct...
Definition DataLayout.h:259
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
bool operator!=(const DataLayout &Other) const
Definition DataLayout.h:208
DataLayout(const DataLayout &DL)
Definition DataLayout.h:201
TypeSize getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Definition DataLayout.h:618
char getGlobalPrefix() const
Definition DataLayout.h:290
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.
const std::string & getStringRepresentation() const
Returns the string representation of the DataLayout.
Definition DataLayout.h:226
unsigned getAddressSize(unsigned AS) const
The integral size of a pointer in a given address space in bytes, which is defined to be the same as ...
Definition DataLayout.h:380
Align getValueOrABITypeAlignment(MaybeAlign Alignment, Type *Ty) const
Helper function to return Alignment if it's set or the result of getABITypeAlign(Ty),...
Definition DataLayout.h:627
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.
Tagged union holding either a T or a Error.
Definition Error.h:485
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:298
Class to represent pointers.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
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
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
bool hasPadding() const
Returns whether the struct has padding or not between its fields.
Definition DataLayout.h:744
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
friend class DataLayout
Definition DataLayout.h:768
ArrayRef< TypeSize > getMemberOffsets() const
Definition DataLayout.h:754
TypeSize getSizeInBits() const
Definition DataLayout.h:738
TypeSize getElementOffsetInBits(unsigned Idx) const
Definition DataLayout.h:763
Align getAlignment() const
Definition DataLayout.h:740
Class to represent struct types.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
@ 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
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:300
LLVM Value Representation.
Definition Value.h:75
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
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
struct LLVMOpaqueTargetData * LLVMTargetDataRef
Definition Target.h:39
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition MathExtras.h:493
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:397
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:392
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
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