xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/DataLayout.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
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/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/Support/Alignment.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/TrailingObjects.h"
35 #include "llvm/Support/TypeSize.h"
36 #include <cassert>
37 #include <cstdint>
38 #include <string>
39 
40 // This needs to be outside of the namespace, to avoid conflict with llvm-c
41 // decl.
42 using LLVMTargetDataRef = struct LLVMOpaqueTargetData *;
43 
44 namespace llvm {
45 
46 class GlobalVariable;
47 class LLVMContext;
48 class StructLayout;
49 class Triple;
50 class Value;
51 
52 // FIXME: Currently the DataLayout string carries a "preferred alignment"
53 // for types. As the DataLayout is module/global, this should likely be
54 // sunk down to an FTTI element that is queried rather than a global
55 // preference.
56 
57 /// A parsed version of the target data layout string in and methods for
58 /// querying it.
59 ///
60 /// The target data layout string is specified *by the target* - a frontend
61 /// generating LLVM IR is required to generate the right target data for the
62 /// target being codegen'd to.
63 class DataLayout {
64 public:
65   /// Primitive type specification.
66   struct PrimitiveSpec {
67     uint32_t BitWidth;
68     Align ABIAlign;
69     Align PrefAlign;
70 
71     LLVM_ABI bool operator==(const PrimitiveSpec &Other) const;
72   };
73 
74   /// Pointer type specification.
75   struct PointerSpec {
76     uint32_t AddrSpace;
77     uint32_t BitWidth;
78     Align ABIAlign;
79     Align PrefAlign;
80     uint32_t IndexBitWidth;
81     /// Pointers in this address space don't have a well-defined bitwise
82     /// representation (e.g. may be relocated by a copying garbage collector).
83     /// Additionally, they may also be non-integral (i.e. containing additional
84     /// metadata such as bounds information/permissions).
85     bool IsNonIntegral;
86     LLVM_ABI bool operator==(const PointerSpec &Other) const;
87   };
88 
89   enum class FunctionPtrAlignType {
90     /// The function pointer alignment is independent of the function alignment.
91     Independent,
92     /// The function pointer alignment is a multiple of the function alignment.
93     MultipleOfFunctionAlign,
94   };
95 
96 private:
97   bool BigEndian = false;
98 
99   unsigned AllocaAddrSpace = 0;
100   unsigned ProgramAddrSpace = 0;
101   unsigned DefaultGlobalsAddrSpace = 0;
102 
103   MaybeAlign StackNaturalAlign;
104   MaybeAlign FunctionPtrAlign;
105   FunctionPtrAlignType TheFunctionPtrAlignType =
106       FunctionPtrAlignType::Independent;
107 
108   enum ManglingModeT {
109     MM_None,
110     MM_ELF,
111     MM_MachO,
112     MM_WinCOFF,
113     MM_WinCOFFX86,
114     MM_GOFF,
115     MM_Mips,
116     MM_XCOFF
117   };
118   ManglingModeT ManglingMode = MM_None;
119 
120   // FIXME: `unsigned char` truncates the value parsed by `parseSpecifier`.
121   SmallVector<unsigned char, 8> LegalIntWidths;
122 
123   /// Primitive type specifications. Sorted and uniqued by type bit width.
124   SmallVector<PrimitiveSpec, 6> IntSpecs;
125   SmallVector<PrimitiveSpec, 4> FloatSpecs;
126   SmallVector<PrimitiveSpec, 10> VectorSpecs;
127 
128   /// Pointer type specifications. Sorted and uniqued by address space number.
129   SmallVector<PointerSpec, 8> PointerSpecs;
130 
131   /// The string representation used to create this DataLayout
132   std::string StringRepresentation;
133 
134   /// Struct type ABI and preferred alignments. The default spec is "a:8:64".
135   Align StructABIAlignment = Align::Constant<1>();
136   Align StructPrefAlignment = Align::Constant<8>();
137 
138   // The StructType -> StructLayout map.
139   mutable void *LayoutMap = nullptr;
140 
141   /// Sets or updates the specification for the given primitive type.
142   void setPrimitiveSpec(char Specifier, uint32_t BitWidth, Align ABIAlign,
143                         Align PrefAlign);
144 
145   /// Searches for a pointer specification that matches the given address space.
146   /// Returns the default address space specification if not found.
147   LLVM_ABI const PointerSpec &getPointerSpec(uint32_t AddrSpace) const;
148 
149   /// Sets or updates the specification for pointer in the given address space.
150   void setPointerSpec(uint32_t AddrSpace, uint32_t BitWidth, Align ABIAlign,
151                       Align PrefAlign, uint32_t IndexBitWidth,
152                       bool IsNonIntegral);
153 
154   /// Internal helper to get alignment for integer of given bitwidth.
155   LLVM_ABI Align getIntegerAlignment(uint32_t BitWidth, bool abi_or_pref) const;
156 
157   /// Internal helper method that returns requested alignment for type.
158   Align getAlignment(Type *Ty, bool abi_or_pref) const;
159 
160   /// Attempts to parse primitive specification ('i', 'f', or 'v').
161   Error parsePrimitiveSpec(StringRef Spec);
162 
163   /// Attempts to parse aggregate specification ('a').
164   Error parseAggregateSpec(StringRef Spec);
165 
166   /// Attempts to parse pointer specification ('p').
167   Error parsePointerSpec(StringRef Spec);
168 
169   /// Attempts to parse a single specification.
170   Error parseSpecification(StringRef Spec,
171                            SmallVectorImpl<unsigned> &NonIntegralAddressSpaces);
172 
173   /// Attempts to parse a data layout string.
174   Error parseLayoutString(StringRef LayoutString);
175 
176 public:
177   /// Constructs a DataLayout with default values.
178   LLVM_ABI DataLayout();
179 
180   /// Constructs a DataLayout from a specification string.
181   /// WARNING: Aborts execution if the string is malformed. Use parse() instead.
182   LLVM_ABI explicit DataLayout(StringRef LayoutString);
183 
DataLayout(const DataLayout & DL)184   DataLayout(const DataLayout &DL) { *this = DL; }
185 
186   LLVM_ABI ~DataLayout(); // Not virtual, do not subclass this class
187 
188   LLVM_ABI DataLayout &operator=(const DataLayout &Other);
189 
190   LLVM_ABI bool operator==(const DataLayout &Other) const;
191   bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
192 
193   /// Parse a data layout string and return the layout. Return an error
194   /// description on failure.
195   LLVM_ABI static Expected<DataLayout> parse(StringRef LayoutString);
196 
197   /// Layout endianness...
isLittleEndian()198   bool isLittleEndian() const { return !BigEndian; }
isBigEndian()199   bool isBigEndian() const { return BigEndian; }
200 
201   /// Returns the string representation of the DataLayout.
202   ///
203   /// This representation is in the same format accepted by the string
204   /// constructor above. This should not be used to compare two DataLayout as
205   /// different string can represent the same layout.
getStringRepresentation()206   const std::string &getStringRepresentation() const {
207     return StringRepresentation;
208   }
209 
210   /// Test if the DataLayout was constructed from an empty string.
isDefault()211   bool isDefault() const { return StringRepresentation.empty(); }
212 
213   /// Returns true if the specified type is known to be a native integer
214   /// type supported by the CPU.
215   ///
216   /// For example, i64 is not native on most 32-bit CPUs and i37 is not native
217   /// on any known one. This returns false if the integer width is not legal.
218   ///
219   /// The width is specified in bits.
isLegalInteger(uint64_t Width)220   bool isLegalInteger(uint64_t Width) const {
221     return llvm::is_contained(LegalIntWidths, Width);
222   }
223 
isIllegalInteger(uint64_t Width)224   bool isIllegalInteger(uint64_t Width) const { return !isLegalInteger(Width); }
225 
226   /// Returns the natural stack alignment, or MaybeAlign() if one wasn't
227   /// specified.
getStackAlignment()228   MaybeAlign getStackAlignment() const { return StackNaturalAlign; }
229 
getAllocaAddrSpace()230   unsigned getAllocaAddrSpace() const { return AllocaAddrSpace; }
231 
getAllocaPtrType(LLVMContext & Ctx)232   PointerType *getAllocaPtrType(LLVMContext &Ctx) const {
233     return PointerType::get(Ctx, AllocaAddrSpace);
234   }
235 
236   /// Returns the alignment of function pointers, which may or may not be
237   /// related to the alignment of functions.
238   /// \see getFunctionPtrAlignType
getFunctionPtrAlign()239   MaybeAlign getFunctionPtrAlign() const { return FunctionPtrAlign; }
240 
241   /// Return the type of function pointer alignment.
242   /// \see getFunctionPtrAlign
getFunctionPtrAlignType()243   FunctionPtrAlignType getFunctionPtrAlignType() const {
244     return TheFunctionPtrAlignType;
245   }
246 
getProgramAddressSpace()247   unsigned getProgramAddressSpace() const { return ProgramAddrSpace; }
getDefaultGlobalsAddressSpace()248   unsigned getDefaultGlobalsAddressSpace() const {
249     return DefaultGlobalsAddrSpace;
250   }
251 
hasMicrosoftFastStdCallMangling()252   bool hasMicrosoftFastStdCallMangling() const {
253     return ManglingMode == MM_WinCOFFX86;
254   }
255 
256   /// Returns true if symbols with leading question marks should not receive IR
257   /// mangling. True for Windows mangling modes.
doNotMangleLeadingQuestionMark()258   bool doNotMangleLeadingQuestionMark() const {
259     return ManglingMode == MM_WinCOFF || ManglingMode == MM_WinCOFFX86;
260   }
261 
hasLinkerPrivateGlobalPrefix()262   bool hasLinkerPrivateGlobalPrefix() const { return ManglingMode == MM_MachO; }
263 
getLinkerPrivateGlobalPrefix()264   StringRef getLinkerPrivateGlobalPrefix() const {
265     if (ManglingMode == MM_MachO)
266       return "l";
267     return "";
268   }
269 
getGlobalPrefix()270   char getGlobalPrefix() const {
271     switch (ManglingMode) {
272     case MM_None:
273     case MM_ELF:
274     case MM_GOFF:
275     case MM_Mips:
276     case MM_WinCOFF:
277     case MM_XCOFF:
278       return '\0';
279     case MM_MachO:
280     case MM_WinCOFFX86:
281       return '_';
282     }
283     llvm_unreachable("invalid mangling mode");
284   }
285 
getPrivateGlobalPrefix()286   StringRef getPrivateGlobalPrefix() const {
287     switch (ManglingMode) {
288     case MM_None:
289       return "";
290     case MM_ELF:
291     case MM_WinCOFF:
292       return ".L";
293     case MM_GOFF:
294       return "L#";
295     case MM_Mips:
296       return "$";
297     case MM_MachO:
298     case MM_WinCOFFX86:
299       return "L";
300     case MM_XCOFF:
301       return "L..";
302     }
303     llvm_unreachable("invalid mangling mode");
304   }
305 
306   LLVM_ABI static const char *getManglingComponent(const Triple &T);
307 
308   /// Returns true if the specified type fits in a native integer type
309   /// supported by the CPU.
310   ///
311   /// For example, if the CPU only supports i32 as a native integer type, then
312   /// i27 fits in a legal integer type but i45 does not.
fitsInLegalInteger(unsigned Width)313   bool fitsInLegalInteger(unsigned Width) const {
314     for (unsigned LegalIntWidth : LegalIntWidths)
315       if (Width <= LegalIntWidth)
316         return true;
317     return false;
318   }
319 
320   /// Layout pointer alignment
321   LLVM_ABI Align getPointerABIAlignment(unsigned AS) const;
322 
323   /// Return target's alignment for stack-based pointers
324   /// FIXME: The defaults need to be removed once all of
325   /// the backends/clients are updated.
326   LLVM_ABI Align getPointerPrefAlignment(unsigned AS = 0) const;
327 
328   /// The pointer representation size in bytes, rounded up to a whole number of
329   /// bytes. The difference between this function and getAddressSize() is that
330   /// this one returns the size of the entire pointer representation (including
331   /// metadata bits for fat pointers) and the latter only returns the number of
332   /// address bits.
333   /// \sa DataLayout::getAddressSizeInBits
334   /// FIXME: The defaults need to be removed once all of
335   /// the backends/clients are updated.
336   LLVM_ABI unsigned getPointerSize(unsigned AS = 0) const;
337 
338   /// The index size in bytes used for address calculation, rounded up to a
339   /// whole number of bytes. This not only defines the size used in
340   /// getelementptr operations, but also the size of addresses in this \p AS.
341   /// For example, a 64-bit CHERI-enabled target has 128-bit pointers of which
342   /// only 64 are used to represent the address and the remaining ones are used
343   /// for metadata such as bounds and access permissions. In this case
344   /// getPointerSize() returns 16, but getIndexSize() returns 8.
345   /// To help with code understanding, the alias getAddressSize() can be used
346   /// instead of getIndexSize() to clarify that an address width is needed.
347   LLVM_ABI unsigned getIndexSize(unsigned AS) const;
348 
349   /// The integral size of a pointer in a given address space in bytes, which
350   /// is defined to be the same as getIndexSize(). This exists as a separate
351   /// function to make it clearer when reading code that the size of an address
352   /// is being requested. While targets exist where index size and the
353   /// underlying address width are not identical (e.g. AMDGPU fat pointers with
354   /// 48-bit addresses and 32-bit offsets indexing), there is currently no need
355   /// to differentiate these properties in LLVM.
356   /// \sa DataLayout::getIndexSize
357   /// \sa DataLayout::getAddressSizeInBits
getAddressSize(unsigned AS)358   unsigned getAddressSize(unsigned AS) const { return getIndexSize(AS); }
359 
360   /// Return the address spaces containing non-integral pointers.  Pointers in
361   /// this address space don't have a well-defined bitwise representation.
getNonIntegralAddressSpaces()362   SmallVector<unsigned, 8> getNonIntegralAddressSpaces() const {
363     SmallVector<unsigned, 8> AddrSpaces;
364     for (const PointerSpec &PS : PointerSpecs) {
365       if (PS.IsNonIntegral)
366         AddrSpaces.push_back(PS.AddrSpace);
367     }
368     return AddrSpaces;
369   }
370 
isNonIntegralAddressSpace(unsigned AddrSpace)371   bool isNonIntegralAddressSpace(unsigned AddrSpace) const {
372     return getPointerSpec(AddrSpace).IsNonIntegral;
373   }
374 
isNonIntegralPointerType(PointerType * PT)375   bool isNonIntegralPointerType(PointerType *PT) const {
376     return isNonIntegralAddressSpace(PT->getAddressSpace());
377   }
378 
isNonIntegralPointerType(Type * Ty)379   bool isNonIntegralPointerType(Type *Ty) const {
380     auto *PTy = dyn_cast<PointerType>(Ty);
381     return PTy && isNonIntegralPointerType(PTy);
382   }
383 
384   /// The size in bits of the pointer representation in a given address space.
385   /// This is not necessarily the same as the integer address of a pointer (e.g.
386   /// for fat pointers).
387   /// \sa DataLayout::getAddressSizeInBits()
388   /// FIXME: The defaults need to be removed once all of
389   /// the backends/clients are updated.
390   unsigned getPointerSizeInBits(unsigned AS = 0) const {
391     return getPointerSpec(AS).BitWidth;
392   }
393 
394   /// The size in bits of indices used for address calculation in getelementptr
395   /// and for addresses in the given AS. See getIndexSize() for more
396   /// information.
397   /// \sa DataLayout::getAddressSizeInBits()
getIndexSizeInBits(unsigned AS)398   unsigned getIndexSizeInBits(unsigned AS) const {
399     return getPointerSpec(AS).IndexBitWidth;
400   }
401 
402   /// The size in bits of an address in for the given AS. This is defined to
403   /// return the same value as getIndexSizeInBits() since there is currently no
404   /// target that requires these two properties to have different values. See
405   /// getIndexSize() for more information.
406   /// \sa DataLayout::getIndexSizeInBits()
getAddressSizeInBits(unsigned AS)407   unsigned getAddressSizeInBits(unsigned AS) const {
408     return getIndexSizeInBits(AS);
409   }
410 
411   /// The pointer representation size in bits for this type. If this function is
412   /// called with a pointer type, then the type size of the pointer is returned.
413   /// If this function is called with a vector of pointers, then the type size
414   /// of the pointer is returned.  This should only be called with a pointer or
415   /// vector of pointers.
416   LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const;
417 
418   /// The size in bits of the index used in GEP calculation for this type.
419   /// The function should be called with pointer or vector of pointers type.
420   /// This is defined to return the same value as getAddressSizeInBits(),
421   /// but separate functions exist for code clarity.
422   LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const;
423 
424   /// The size in bits of an address for this type.
425   /// This is defined to return the same value as getIndexTypeSizeInBits(),
426   /// but separate functions exist for code clarity.
getAddressSizeInBits(Type * Ty)427   unsigned getAddressSizeInBits(Type *Ty) const {
428     return getIndexTypeSizeInBits(Ty);
429   }
430 
getPointerTypeSize(Type * Ty)431   unsigned getPointerTypeSize(Type *Ty) const {
432     return getPointerTypeSizeInBits(Ty) / 8;
433   }
434 
435   /// Size examples:
436   ///
437   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
438   /// ----        ----------  ---------------  ---------------
439   ///  i1            1           8                8
440   ///  i8            8           8                8
441   ///  i19          19          24               32
442   ///  i32          32          32               32
443   ///  i100        100         104              128
444   ///  i128        128         128              128
445   ///  Float        32          32               32
446   ///  Double       64          64               64
447   ///  X86_FP80     80          80               96
448   ///
449   /// [*] The alloc size depends on the alignment, and thus on the target.
450   ///     These values are for x86-32 linux.
451 
452   /// Returns the number of bits necessary to hold the specified type.
453   ///
454   /// If Ty is a scalable vector type, the scalable property will be set and
455   /// the runtime size will be a positive integer multiple of the base size.
456   ///
457   /// For example, returns 36 for i36 and 80 for x86_fp80. The type passed must
458   /// have a size (Type::isSized() must return true).
459   TypeSize getTypeSizeInBits(Type *Ty) const;
460 
461   /// Returns the maximum number of bytes that may be overwritten by
462   /// storing the specified type.
463   ///
464   /// If Ty is a scalable vector type, the scalable property will be set and
465   /// the runtime size will be a positive integer multiple of the base size.
466   ///
467   /// For example, returns 5 for i36 and 10 for x86_fp80.
getTypeStoreSize(Type * Ty)468   TypeSize getTypeStoreSize(Type *Ty) const {
469     TypeSize StoreSizeInBits = getTypeStoreSizeInBits(Ty);
470     return {StoreSizeInBits.getKnownMinValue() / 8,
471             StoreSizeInBits.isScalable()};
472   }
473 
474   /// Returns the maximum number of bits that may be overwritten by
475   /// storing the specified type; always a multiple of 8.
476   ///
477   /// If Ty is a scalable vector type, the scalable property will be set and
478   /// the runtime size will be a positive integer multiple of the base size.
479   ///
480   /// For example, returns 40 for i36 and 80 for x86_fp80.
getTypeStoreSizeInBits(Type * Ty)481   TypeSize getTypeStoreSizeInBits(Type *Ty) const {
482     TypeSize BaseSize = getTypeSizeInBits(Ty);
483     uint64_t AlignedSizeInBits =
484         alignToPowerOf2(BaseSize.getKnownMinValue(), 8);
485     return {AlignedSizeInBits, BaseSize.isScalable()};
486   }
487 
488   /// Returns true if no extra padding bits are needed when storing the
489   /// specified type.
490   ///
491   /// For example, returns false for i19 that has a 24-bit store size.
typeSizeEqualsStoreSize(Type * Ty)492   bool typeSizeEqualsStoreSize(Type *Ty) const {
493     return getTypeSizeInBits(Ty) == getTypeStoreSizeInBits(Ty);
494   }
495 
496   /// Returns the offset in bytes between successive objects of the
497   /// specified type, including alignment padding.
498   ///
499   /// If Ty is a scalable vector type, the scalable property will be set and
500   /// the runtime size will be a positive integer multiple of the base size.
501   ///
502   /// This is the amount that alloca reserves for this type. For example,
503   /// returns 12 or 16 for x86_fp80, depending on alignment.
getTypeAllocSize(Type * Ty)504   TypeSize getTypeAllocSize(Type *Ty) const {
505     // Round up to the next alignment boundary.
506     return alignTo(getTypeStoreSize(Ty), getABITypeAlign(Ty).value());
507   }
508 
509   /// Returns the offset in bits between successive objects of the
510   /// specified type, including alignment padding; always a multiple of 8.
511   ///
512   /// If Ty is a scalable vector type, the scalable property will be set and
513   /// the runtime size will be a positive integer multiple of the base size.
514   ///
515   /// This is the amount that alloca reserves for this type. For example,
516   /// returns 96 or 128 for x86_fp80, depending on alignment.
getTypeAllocSizeInBits(Type * Ty)517   TypeSize getTypeAllocSizeInBits(Type *Ty) const {
518     return 8 * getTypeAllocSize(Ty);
519   }
520 
521   /// Returns the minimum ABI-required alignment for the specified type.
522   LLVM_ABI Align getABITypeAlign(Type *Ty) const;
523 
524   /// Helper function to return `Alignment` if it's set or the result of
525   /// `getABITypeAlign(Ty)`, in any case the result is a valid alignment.
getValueOrABITypeAlignment(MaybeAlign Alignment,Type * Ty)526   inline Align getValueOrABITypeAlignment(MaybeAlign Alignment,
527                                           Type *Ty) const {
528     return Alignment ? *Alignment : getABITypeAlign(Ty);
529   }
530 
531   /// Returns the minimum ABI-required alignment for an integer type of
532   /// the specified bitwidth.
getABIIntegerTypeAlignment(unsigned BitWidth)533   Align getABIIntegerTypeAlignment(unsigned BitWidth) const {
534     return getIntegerAlignment(BitWidth, /* abi_or_pref */ true);
535   }
536 
537   /// Returns the preferred stack/global alignment for the specified
538   /// type.
539   ///
540   /// This is always at least as good as the ABI alignment.
541   LLVM_ABI Align getPrefTypeAlign(Type *Ty) const;
542 
543   /// Returns an integer type with size at least as big as that of a
544   /// pointer in the given address space.
545   LLVM_ABI IntegerType *getIntPtrType(LLVMContext &C,
546                                       unsigned AddressSpace = 0) const;
547 
548   /// Returns an integer (vector of integer) type with size at least as
549   /// big as that of a pointer of the given pointer (vector of pointer) type.
550   LLVM_ABI Type *getIntPtrType(Type *) const;
551 
552   /// Returns the smallest integer type with size at least as big as
553   /// Width bits.
554   LLVM_ABI Type *getSmallestLegalIntType(LLVMContext &C,
555                                          unsigned Width = 0) const;
556 
557   /// Returns the largest legal integer type, or null if none are set.
getLargestLegalIntType(LLVMContext & C)558   Type *getLargestLegalIntType(LLVMContext &C) const {
559     unsigned LargestSize = getLargestLegalIntTypeSizeInBits();
560     return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
561   }
562 
563   /// Returns the size of largest legal integer type size, or 0 if none
564   /// are set.
565   LLVM_ABI unsigned getLargestLegalIntTypeSizeInBits() const;
566 
567   /// Returns the type of a GEP index in \p AddressSpace.
568   /// If it was not specified explicitly, it will be the integer type of the
569   /// pointer width - IntPtrType.
570   LLVM_ABI IntegerType *getIndexType(LLVMContext &C,
571                                      unsigned AddressSpace) const;
572   /// Returns the type of an address in \p AddressSpace
getAddressType(LLVMContext & C,unsigned AddressSpace)573   IntegerType *getAddressType(LLVMContext &C, unsigned AddressSpace) const {
574     return getIndexType(C, AddressSpace);
575   }
576 
577   /// Returns the type of a GEP index.
578   /// If it was not specified explicitly, it will be the integer type of the
579   /// pointer width - IntPtrType.
580   LLVM_ABI Type *getIndexType(Type *PtrTy) const;
581   /// Returns the type of an address in \p AddressSpace
getAddressType(Type * PtrTy)582   Type *getAddressType(Type *PtrTy) const { return getIndexType(PtrTy); }
583 
584   /// Returns the offset from the beginning of the type for the specified
585   /// indices.
586   ///
587   /// Note that this takes the element type, not the pointer type.
588   /// This is used to implement getelementptr.
589   LLVM_ABI int64_t getIndexedOffsetInType(Type *ElemTy,
590                                           ArrayRef<Value *> Indices) const;
591 
592   /// Get GEP indices to access Offset inside ElemTy. ElemTy is updated to be
593   /// the result element type and Offset to be the residual offset.
594   LLVM_ABI SmallVector<APInt> getGEPIndicesForOffset(Type *&ElemTy,
595                                                      APInt &Offset) const;
596 
597   /// Get single GEP index to access Offset inside ElemTy. Returns std::nullopt
598   /// if index cannot be computed, e.g. because the type is not an aggregate.
599   /// ElemTy is updated to be the result element type and Offset to be the
600   /// residual offset.
601   LLVM_ABI std::optional<APInt> getGEPIndexForOffset(Type *&ElemTy,
602                                                      APInt &Offset) const;
603 
604   /// Returns a StructLayout object, indicating the alignment of the
605   /// struct, its size, and the offsets of its fields.
606   ///
607   /// Note that this information is lazily cached.
608   LLVM_ABI const StructLayout *getStructLayout(StructType *Ty) const;
609 
610   /// Returns the preferred alignment of the specified global.
611   ///
612   /// This includes an explicitly requested alignment (if the global has one).
613   LLVM_ABI Align getPreferredAlign(const GlobalVariable *GV) const;
614 };
615 
unwrap(LLVMTargetDataRef P)616 inline DataLayout *unwrap(LLVMTargetDataRef P) {
617   return reinterpret_cast<DataLayout *>(P);
618 }
619 
wrap(const DataLayout * P)620 inline LLVMTargetDataRef wrap(const DataLayout *P) {
621   return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
622 }
623 
624 /// Used to lazily calculate structure layout information for a target machine,
625 /// based on the DataLayout structure.
626 class StructLayout final : private TrailingObjects<StructLayout, TypeSize> {
627   friend TrailingObjects;
628 
629   TypeSize StructSize;
630   Align StructAlignment;
631   unsigned IsPadded : 1;
632   unsigned NumElements : 31;
633 
634 public:
getSizeInBytes()635   TypeSize getSizeInBytes() const { return StructSize; }
636 
getSizeInBits()637   TypeSize getSizeInBits() const { return 8 * StructSize; }
638 
getAlignment()639   Align getAlignment() const { return StructAlignment; }
640 
641   /// Returns whether the struct has padding or not between its fields.
642   /// NB: Padding in nested element is not taken into account.
hasPadding()643   bool hasPadding() const { return IsPadded; }
644 
645   /// Given a valid byte offset into the structure, returns the structure
646   /// index that contains it.
647   LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const;
648 
getMemberOffsets()649   MutableArrayRef<TypeSize> getMemberOffsets() {
650     return getTrailingObjects(NumElements);
651   }
652 
getMemberOffsets()653   ArrayRef<TypeSize> getMemberOffsets() const {
654     return getTrailingObjects(NumElements);
655   }
656 
getElementOffset(unsigned Idx)657   TypeSize getElementOffset(unsigned Idx) const {
658     assert(Idx < NumElements && "Invalid element idx!");
659     return getMemberOffsets()[Idx];
660   }
661 
getElementOffsetInBits(unsigned Idx)662   TypeSize getElementOffsetInBits(unsigned Idx) const {
663     return getElementOffset(Idx) * 8;
664   }
665 
666 private:
667   friend class DataLayout; // Only DataLayout can create this class
668 
669   StructLayout(StructType *ST, const DataLayout &DL);
670 };
671 
672 // The implementation of this method is provided inline as it is particularly
673 // well suited to constant folding when called on a specific Type subclass.
getTypeSizeInBits(Type * Ty)674 inline TypeSize DataLayout::getTypeSizeInBits(Type *Ty) const {
675   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
676   switch (Ty->getTypeID()) {
677   case Type::LabelTyID:
678     return TypeSize::getFixed(getPointerSizeInBits(0));
679   case Type::PointerTyID:
680     return TypeSize::getFixed(
681         getPointerSizeInBits(Ty->getPointerAddressSpace()));
682   case Type::ArrayTyID: {
683     ArrayType *ATy = cast<ArrayType>(Ty);
684     return ATy->getNumElements() *
685            getTypeAllocSizeInBits(ATy->getElementType());
686   }
687   case Type::StructTyID:
688     // Get the layout annotation... which is lazily created on demand.
689     return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
690   case Type::IntegerTyID:
691     return TypeSize::getFixed(Ty->getIntegerBitWidth());
692   case Type::HalfTyID:
693   case Type::BFloatTyID:
694     return TypeSize::getFixed(16);
695   case Type::FloatTyID:
696     return TypeSize::getFixed(32);
697   case Type::DoubleTyID:
698     return TypeSize::getFixed(64);
699   case Type::PPC_FP128TyID:
700   case Type::FP128TyID:
701     return TypeSize::getFixed(128);
702   case Type::X86_AMXTyID:
703     return TypeSize::getFixed(8192);
704   // In memory objects this is always aligned to a higher boundary, but
705   // only 80 bits contain information.
706   case Type::X86_FP80TyID:
707     return TypeSize::getFixed(80);
708   case Type::FixedVectorTyID:
709   case Type::ScalableVectorTyID: {
710     VectorType *VTy = cast<VectorType>(Ty);
711     auto EltCnt = VTy->getElementCount();
712     uint64_t MinBits = EltCnt.getKnownMinValue() *
713                        getTypeSizeInBits(VTy->getElementType()).getFixedValue();
714     return TypeSize(MinBits, EltCnt.isScalable());
715   }
716   case Type::TargetExtTyID: {
717     Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
718     return getTypeSizeInBits(LayoutTy);
719   }
720   default:
721     llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
722   }
723 }
724 
725 } // end namespace llvm
726 
727 #endif // LLVM_IR_DATALAYOUT_H
728