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