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