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