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