DataLayout.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/DataLayout.h - Data size & alignment info -----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines layout properties related to datatype size/offset/alignment
  15. // information. It uses lazy annotations to cache information about how
  16. // structure types are laid out and used.
  17. //
  18. // This structure should be created once, filled in if the defaults are not
  19. // correct and then passed around by const&. None of the members functions
  20. // require modification to the object.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #ifndef LLVM_IR_DATALAYOUT_H
  24. #define LLVM_IR_DATALAYOUT_H
  25. #include "llvm/ADT/APInt.h"
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/StringRef.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/Type.h"
  32. #include "llvm/Support/Alignment.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Support/Compiler.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/MathExtras.h"
  37. #include "llvm/Support/TrailingObjects.h"
  38. #include "llvm/Support/TypeSize.h"
  39. #include <cassert>
  40. #include <cstdint>
  41. #include <string>
  42. // This needs to be outside of the namespace, to avoid conflict with llvm-c
  43. // decl.
  44. using LLVMTargetDataRef = struct LLVMOpaqueTargetData *;
  45. namespace llvm {
  46. class GlobalVariable;
  47. class LLVMContext;
  48. class Module;
  49. class StructLayout;
  50. class Triple;
  51. class Value;
  52. /// Enum used to categorize the alignment types stored by LayoutAlignElem
  53. enum AlignTypeEnum {
  54. INVALID_ALIGN = 0,
  55. INTEGER_ALIGN = 'i',
  56. VECTOR_ALIGN = 'v',
  57. FLOAT_ALIGN = 'f',
  58. AGGREGATE_ALIGN = 'a'
  59. };
  60. // FIXME: Currently the DataLayout string carries a "preferred alignment"
  61. // for types. As the DataLayout is module/global, this should likely be
  62. // sunk down to an FTTI element that is queried rather than a global
  63. // preference.
  64. /// Layout alignment element.
  65. ///
  66. /// Stores the alignment data associated with a given alignment type (integer,
  67. /// vector, float) and type bit width.
  68. ///
  69. /// \note The unusual order of elements in the structure attempts to reduce
  70. /// padding and make the structure slightly more cache friendly.
  71. struct LayoutAlignElem {
  72. /// Alignment type from \c AlignTypeEnum
  73. unsigned AlignType : 8;
  74. unsigned TypeBitWidth : 24;
  75. Align ABIAlign;
  76. Align PrefAlign;
  77. static LayoutAlignElem get(AlignTypeEnum align_type, Align abi_align,
  78. Align pref_align, uint32_t bit_width);
  79. bool operator==(const LayoutAlignElem &rhs) const;
  80. };
  81. /// Layout pointer alignment element.
  82. ///
  83. /// Stores the alignment data associated with a given pointer and address space.
  84. ///
  85. /// \note The unusual order of elements in the structure attempts to reduce
  86. /// padding and make the structure slightly more cache friendly.
  87. struct PointerAlignElem {
  88. Align ABIAlign;
  89. Align PrefAlign;
  90. uint32_t TypeBitWidth;
  91. uint32_t AddressSpace;
  92. uint32_t IndexBitWidth;
  93. /// Initializer
  94. static PointerAlignElem getInBits(uint32_t AddressSpace, Align ABIAlign,
  95. Align PrefAlign, uint32_t TypeBitWidth,
  96. uint32_t IndexBitWidth);
  97. bool operator==(const PointerAlignElem &rhs) const;
  98. };
  99. /// A parsed version of the target data layout string in and methods for
  100. /// querying it.
  101. ///
  102. /// The target data layout string is specified *by the target* - a frontend
  103. /// generating LLVM IR is required to generate the right target data for the
  104. /// target being codegen'd to.
  105. class DataLayout {
  106. public:
  107. enum class FunctionPtrAlignType {
  108. /// The function pointer alignment is independent of the function alignment.
  109. Independent,
  110. /// The function pointer alignment is a multiple of the function alignment.
  111. MultipleOfFunctionAlign,
  112. };
  113. private:
  114. /// Defaults to false.
  115. bool BigEndian;
  116. unsigned AllocaAddrSpace;
  117. MaybeAlign StackNaturalAlign;
  118. unsigned ProgramAddrSpace;
  119. unsigned DefaultGlobalsAddrSpace;
  120. MaybeAlign FunctionPtrAlign;
  121. FunctionPtrAlignType TheFunctionPtrAlignType;
  122. enum ManglingModeT {
  123. MM_None,
  124. MM_ELF,
  125. MM_MachO,
  126. MM_WinCOFF,
  127. MM_WinCOFFX86,
  128. MM_GOFF,
  129. MM_Mips,
  130. MM_XCOFF
  131. };
  132. ManglingModeT ManglingMode;
  133. SmallVector<unsigned char, 8> LegalIntWidths;
  134. /// Primitive type alignment data. This is sorted by type and bit
  135. /// width during construction.
  136. using AlignmentsTy = SmallVector<LayoutAlignElem, 16>;
  137. AlignmentsTy Alignments;
  138. AlignmentsTy::const_iterator
  139. findAlignmentLowerBound(AlignTypeEnum AlignType, uint32_t BitWidth) const {
  140. return const_cast<DataLayout *>(this)->findAlignmentLowerBound(AlignType,
  141. BitWidth);
  142. }
  143. AlignmentsTy::iterator
  144. findAlignmentLowerBound(AlignTypeEnum AlignType, uint32_t BitWidth);
  145. /// The string representation used to create this DataLayout
  146. std::string StringRepresentation;
  147. using PointersTy = SmallVector<PointerAlignElem, 8>;
  148. PointersTy Pointers;
  149. const PointerAlignElem &getPointerAlignElem(uint32_t AddressSpace) const;
  150. // The StructType -> StructLayout map.
  151. mutable void *LayoutMap = nullptr;
  152. /// Pointers in these address spaces are non-integral, and don't have a
  153. /// well-defined bitwise representation.
  154. SmallVector<unsigned, 8> NonIntegralAddressSpaces;
  155. /// Attempts to set the alignment of the given type. Returns an error
  156. /// description on failure.
  157. Error setAlignment(AlignTypeEnum align_type, Align abi_align,
  158. Align pref_align, uint32_t bit_width);
  159. /// Attempts to set the alignment of a pointer in the given address space.
  160. /// Returns an error description on failure.
  161. Error setPointerAlignmentInBits(uint32_t AddrSpace, Align ABIAlign,
  162. Align PrefAlign, uint32_t TypeBitWidth,
  163. uint32_t IndexBitWidth);
  164. /// Internal helper to get alignment for integer of given bitwidth.
  165. Align getIntegerAlignment(uint32_t BitWidth, bool abi_or_pref) const;
  166. /// Internal helper method that returns requested alignment for type.
  167. Align getAlignment(Type *Ty, bool abi_or_pref) const;
  168. /// Attempts to parse a target data specification string and reports an error
  169. /// if the string is malformed.
  170. Error parseSpecifier(StringRef Desc);
  171. // Free all internal data structures.
  172. void clear();
  173. public:
  174. /// Constructs a DataLayout from a specification string. See reset().
  175. explicit DataLayout(StringRef LayoutDescription) {
  176. reset(LayoutDescription);
  177. }
  178. /// Initialize target data from properties stored in the module.
  179. explicit DataLayout(const Module *M);
  180. DataLayout(const DataLayout &DL) { *this = DL; }
  181. ~DataLayout(); // Not virtual, do not subclass this class
  182. DataLayout &operator=(const DataLayout &DL) {
  183. clear();
  184. StringRepresentation = DL.StringRepresentation;
  185. BigEndian = DL.isBigEndian();
  186. AllocaAddrSpace = DL.AllocaAddrSpace;
  187. StackNaturalAlign = DL.StackNaturalAlign;
  188. FunctionPtrAlign = DL.FunctionPtrAlign;
  189. TheFunctionPtrAlignType = DL.TheFunctionPtrAlignType;
  190. ProgramAddrSpace = DL.ProgramAddrSpace;
  191. DefaultGlobalsAddrSpace = DL.DefaultGlobalsAddrSpace;
  192. ManglingMode = DL.ManglingMode;
  193. LegalIntWidths = DL.LegalIntWidths;
  194. Alignments = DL.Alignments;
  195. Pointers = DL.Pointers;
  196. NonIntegralAddressSpaces = DL.NonIntegralAddressSpaces;
  197. return *this;
  198. }
  199. bool operator==(const DataLayout &Other) const;
  200. bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
  201. void init(const Module *M);
  202. /// Parse a data layout string (with fallback to default values).
  203. void reset(StringRef LayoutDescription);
  204. /// Parse a data layout string and return the layout. Return an error
  205. /// description on failure.
  206. static Expected<DataLayout> parse(StringRef LayoutDescription);
  207. /// Layout endianness...
  208. bool isLittleEndian() const { return !BigEndian; }
  209. bool isBigEndian() const { return BigEndian; }
  210. /// Returns the string representation of the DataLayout.
  211. ///
  212. /// This representation is in the same format accepted by the string
  213. /// constructor above. This should not be used to compare two DataLayout as
  214. /// different string can represent the same layout.
  215. const std::string &getStringRepresentation() const {
  216. return StringRepresentation;
  217. }
  218. /// Test if the DataLayout was constructed from an empty string.
  219. bool isDefault() const { return StringRepresentation.empty(); }
  220. /// Returns true if the specified type is known to be a native integer
  221. /// type supported by the CPU.
  222. ///
  223. /// For example, i64 is not native on most 32-bit CPUs and i37 is not native
  224. /// on any known one. This returns false if the integer width is not legal.
  225. ///
  226. /// The width is specified in bits.
  227. bool isLegalInteger(uint64_t Width) const {
  228. return llvm::is_contained(LegalIntWidths, Width);
  229. }
  230. bool isIllegalInteger(uint64_t Width) const { return !isLegalInteger(Width); }
  231. /// Returns true if the given alignment exceeds the natural stack alignment.
  232. bool exceedsNaturalStackAlignment(Align Alignment) const {
  233. return StackNaturalAlign && (Alignment > *StackNaturalAlign);
  234. }
  235. Align getStackAlignment() const {
  236. assert(StackNaturalAlign && "StackNaturalAlign must be defined");
  237. return *StackNaturalAlign;
  238. }
  239. unsigned getAllocaAddrSpace() const { return AllocaAddrSpace; }
  240. /// Returns the alignment of function pointers, which may or may not be
  241. /// related to the alignment of functions.
  242. /// \see getFunctionPtrAlignType
  243. MaybeAlign getFunctionPtrAlign() const { return FunctionPtrAlign; }
  244. /// Return the type of function pointer alignment.
  245. /// \see getFunctionPtrAlign
  246. FunctionPtrAlignType getFunctionPtrAlignType() const {
  247. return TheFunctionPtrAlignType;
  248. }
  249. unsigned getProgramAddressSpace() const { return ProgramAddrSpace; }
  250. unsigned getDefaultGlobalsAddressSpace() const {
  251. return DefaultGlobalsAddrSpace;
  252. }
  253. bool hasMicrosoftFastStdCallMangling() const {
  254. return ManglingMode == MM_WinCOFFX86;
  255. }
  256. /// Returns true if symbols with leading question marks should not receive IR
  257. /// mangling. True for Windows mangling modes.
  258. bool doNotMangleLeadingQuestionMark() const {
  259. return ManglingMode == MM_WinCOFF || ManglingMode == MM_WinCOFFX86;
  260. }
  261. bool hasLinkerPrivateGlobalPrefix() const { return ManglingMode == MM_MachO; }
  262. StringRef getLinkerPrivateGlobalPrefix() const {
  263. if (ManglingMode == MM_MachO)
  264. return "l";
  265. return "";
  266. }
  267. char getGlobalPrefix() const {
  268. switch (ManglingMode) {
  269. case MM_None:
  270. case MM_ELF:
  271. case MM_GOFF:
  272. case MM_Mips:
  273. case MM_WinCOFF:
  274. case MM_XCOFF:
  275. return '\0';
  276. case MM_MachO:
  277. case MM_WinCOFFX86:
  278. return '_';
  279. }
  280. llvm_unreachable("invalid mangling mode");
  281. }
  282. StringRef getPrivateGlobalPrefix() const {
  283. switch (ManglingMode) {
  284. case MM_None:
  285. return "";
  286. case MM_ELF:
  287. case MM_WinCOFF:
  288. return ".L";
  289. case MM_GOFF:
  290. return "@";
  291. case MM_Mips:
  292. return "$";
  293. case MM_MachO:
  294. case MM_WinCOFFX86:
  295. return "L";
  296. case MM_XCOFF:
  297. return "L..";
  298. }
  299. llvm_unreachable("invalid mangling mode");
  300. }
  301. static const char *getManglingComponent(const Triple &T);
  302. /// Returns true if the specified type fits in a native integer type
  303. /// supported by the CPU.
  304. ///
  305. /// For example, if the CPU only supports i32 as a native integer type, then
  306. /// i27 fits in a legal integer type but i45 does not.
  307. bool fitsInLegalInteger(unsigned Width) const {
  308. for (unsigned LegalIntWidth : LegalIntWidths)
  309. if (Width <= LegalIntWidth)
  310. return true;
  311. return false;
  312. }
  313. /// Layout pointer alignment
  314. Align getPointerABIAlignment(unsigned AS) const;
  315. /// Return target's alignment for stack-based pointers
  316. /// FIXME: The defaults need to be removed once all of
  317. /// the backends/clients are updated.
  318. Align getPointerPrefAlignment(unsigned AS = 0) const;
  319. /// Layout pointer size in bytes, rounded up to a whole
  320. /// number of bytes.
  321. /// FIXME: The defaults need to be removed once all of
  322. /// the backends/clients are updated.
  323. unsigned getPointerSize(unsigned AS = 0) const;
  324. /// Returns the maximum index size over all address spaces.
  325. unsigned getMaxIndexSize() const;
  326. // Index size in bytes used for address calculation,
  327. /// rounded up to a whole number of bytes.
  328. unsigned getIndexSize(unsigned AS) const;
  329. /// Return the address spaces containing non-integral pointers. Pointers in
  330. /// this address space don't have a well-defined bitwise representation.
  331. ArrayRef<unsigned> getNonIntegralAddressSpaces() const {
  332. return NonIntegralAddressSpaces;
  333. }
  334. bool isNonIntegralAddressSpace(unsigned AddrSpace) const {
  335. ArrayRef<unsigned> NonIntegralSpaces = getNonIntegralAddressSpaces();
  336. return is_contained(NonIntegralSpaces, AddrSpace);
  337. }
  338. bool isNonIntegralPointerType(PointerType *PT) const {
  339. return isNonIntegralAddressSpace(PT->getAddressSpace());
  340. }
  341. bool isNonIntegralPointerType(Type *Ty) const {
  342. auto *PTy = dyn_cast<PointerType>(Ty);
  343. return PTy && isNonIntegralPointerType(PTy);
  344. }
  345. /// Layout pointer size, in bits
  346. /// FIXME: The defaults need to be removed once all of
  347. /// the backends/clients are updated.
  348. unsigned getPointerSizeInBits(unsigned AS = 0) const {
  349. return getPointerAlignElem(AS).TypeBitWidth;
  350. }
  351. /// Returns the maximum index size over all address spaces.
  352. unsigned getMaxIndexSizeInBits() const {
  353. return getMaxIndexSize() * 8;
  354. }
  355. /// Size in bits of index used for address calculation in getelementptr.
  356. unsigned getIndexSizeInBits(unsigned AS) const {
  357. return getPointerAlignElem(AS).IndexBitWidth;
  358. }
  359. /// Layout pointer size, in bits, based on the type. If this function is
  360. /// called with a pointer type, then the type size of the pointer is returned.
  361. /// If this function is called with a vector of pointers, then the type size
  362. /// of the pointer is returned. This should only be called with a pointer or
  363. /// vector of pointers.
  364. unsigned getPointerTypeSizeInBits(Type *) const;
  365. /// Layout size of the index used in GEP calculation.
  366. /// The function should be called with pointer or vector of pointers type.
  367. unsigned getIndexTypeSizeInBits(Type *Ty) const;
  368. unsigned getPointerTypeSize(Type *Ty) const {
  369. return getPointerTypeSizeInBits(Ty) / 8;
  370. }
  371. /// Size examples:
  372. ///
  373. /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
  374. /// ---- ---------- --------------- ---------------
  375. /// i1 1 8 8
  376. /// i8 8 8 8
  377. /// i19 19 24 32
  378. /// i32 32 32 32
  379. /// i100 100 104 128
  380. /// i128 128 128 128
  381. /// Float 32 32 32
  382. /// Double 64 64 64
  383. /// X86_FP80 80 80 96
  384. ///
  385. /// [*] The alloc size depends on the alignment, and thus on the target.
  386. /// These values are for x86-32 linux.
  387. /// Returns the number of bits necessary to hold the specified type.
  388. ///
  389. /// If Ty is a scalable vector type, the scalable property will be set and
  390. /// the runtime size will be a positive integer multiple of the base size.
  391. ///
  392. /// For example, returns 36 for i36 and 80 for x86_fp80. The type passed must
  393. /// have a size (Type::isSized() must return true).
  394. TypeSize getTypeSizeInBits(Type *Ty) const;
  395. /// Returns the maximum number of bytes that may be overwritten by
  396. /// storing the specified type.
  397. ///
  398. /// If Ty is a scalable vector type, the scalable property will be set and
  399. /// the runtime size will be a positive integer multiple of the base size.
  400. ///
  401. /// For example, returns 5 for i36 and 10 for x86_fp80.
  402. TypeSize getTypeStoreSize(Type *Ty) const {
  403. TypeSize BaseSize = getTypeSizeInBits(Ty);
  404. return {divideCeil(BaseSize.getKnownMinValue(), 8), BaseSize.isScalable()};
  405. }
  406. /// Returns the maximum number of bits that may be overwritten by
  407. /// storing the specified type; always a multiple of 8.
  408. ///
  409. /// If Ty is a scalable vector type, the scalable property will be set and
  410. /// the runtime size will be a positive integer multiple of the base size.
  411. ///
  412. /// For example, returns 40 for i36 and 80 for x86_fp80.
  413. TypeSize getTypeStoreSizeInBits(Type *Ty) const {
  414. return 8 * getTypeStoreSize(Ty);
  415. }
  416. /// Returns true if no extra padding bits are needed when storing the
  417. /// specified type.
  418. ///
  419. /// For example, returns false for i19 that has a 24-bit store size.
  420. bool typeSizeEqualsStoreSize(Type *Ty) const {
  421. return getTypeSizeInBits(Ty) == getTypeStoreSizeInBits(Ty);
  422. }
  423. /// Returns the offset in bytes between successive objects of the
  424. /// specified type, including alignment padding.
  425. ///
  426. /// If Ty is a scalable vector type, the scalable property will be set and
  427. /// the runtime size will be a positive integer multiple of the base size.
  428. ///
  429. /// This is the amount that alloca reserves for this type. For example,
  430. /// returns 12 or 16 for x86_fp80, depending on alignment.
  431. TypeSize getTypeAllocSize(Type *Ty) const {
  432. // Round up to the next alignment boundary.
  433. return alignTo(getTypeStoreSize(Ty), getABITypeAlign(Ty).value());
  434. }
  435. /// Returns the offset in bits between successive objects of the
  436. /// specified type, including alignment padding; always a multiple of 8.
  437. ///
  438. /// If Ty is a scalable vector type, the scalable property will be set and
  439. /// the runtime size will be a positive integer multiple of the base size.
  440. ///
  441. /// This is the amount that alloca reserves for this type. For example,
  442. /// returns 96 or 128 for x86_fp80, depending on alignment.
  443. TypeSize getTypeAllocSizeInBits(Type *Ty) const {
  444. return 8 * getTypeAllocSize(Ty);
  445. }
  446. /// Returns the minimum ABI-required alignment for the specified type.
  447. /// FIXME: Deprecate this function once migration to Align is over.
  448. LLVM_DEPRECATED("use getABITypeAlign instead", "getABITypeAlign")
  449. uint64_t getABITypeAlignment(Type *Ty) const;
  450. /// Returns the minimum ABI-required alignment for the specified type.
  451. Align getABITypeAlign(Type *Ty) const;
  452. /// Helper function to return `Alignment` if it's set or the result of
  453. /// `getABITypeAlignment(Ty)`, in any case the result is a valid alignment.
  454. inline Align getValueOrABITypeAlignment(MaybeAlign Alignment,
  455. Type *Ty) const {
  456. return Alignment ? *Alignment : getABITypeAlign(Ty);
  457. }
  458. /// Returns the minimum ABI-required alignment for an integer type of
  459. /// the specified bitwidth.
  460. Align getABIIntegerTypeAlignment(unsigned BitWidth) const {
  461. return getIntegerAlignment(BitWidth, /* abi_or_pref */ true);
  462. }
  463. /// Returns the preferred stack/global alignment for the specified
  464. /// type.
  465. ///
  466. /// This is always at least as good as the ABI alignment.
  467. /// FIXME: Deprecate this function once migration to Align is over.
  468. LLVM_DEPRECATED("use getPrefTypeAlign instead", "getPrefTypeAlign")
  469. uint64_t getPrefTypeAlignment(Type *Ty) const;
  470. /// Returns the preferred stack/global alignment for the specified
  471. /// type.
  472. ///
  473. /// This is always at least as good as the ABI alignment.
  474. Align getPrefTypeAlign(Type *Ty) const;
  475. /// Returns an integer type with size at least as big as that of a
  476. /// pointer in the given address space.
  477. IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
  478. /// Returns an integer (vector of integer) type with size at least as
  479. /// big as that of a pointer of the given pointer (vector of pointer) type.
  480. Type *getIntPtrType(Type *) const;
  481. /// Returns the smallest integer type with size at least as big as
  482. /// Width bits.
  483. Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
  484. /// Returns the largest legal integer type, or null if none are set.
  485. Type *getLargestLegalIntType(LLVMContext &C) const {
  486. unsigned LargestSize = getLargestLegalIntTypeSizeInBits();
  487. return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
  488. }
  489. /// Returns the size of largest legal integer type size, or 0 if none
  490. /// are set.
  491. unsigned getLargestLegalIntTypeSizeInBits() const;
  492. /// Returns the type of a GEP index.
  493. /// If it was not specified explicitly, it will be the integer type of the
  494. /// pointer width - IntPtrType.
  495. Type *getIndexType(Type *PtrTy) const;
  496. /// Returns the offset from the beginning of the type for the specified
  497. /// indices.
  498. ///
  499. /// Note that this takes the element type, not the pointer type.
  500. /// This is used to implement getelementptr.
  501. int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef<Value *> Indices) const;
  502. /// Get GEP indices to access Offset inside ElemTy. ElemTy is updated to be
  503. /// the result element type and Offset to be the residual offset.
  504. SmallVector<APInt> getGEPIndicesForOffset(Type *&ElemTy, APInt &Offset) const;
  505. /// Get single GEP index to access Offset inside ElemTy. Returns std::nullopt
  506. /// if index cannot be computed, e.g. because the type is not an aggregate.
  507. /// ElemTy is updated to be the result element type and Offset to be the
  508. /// residual offset.
  509. std::optional<APInt> getGEPIndexForOffset(Type *&ElemTy, APInt &Offset) const;
  510. /// Returns a StructLayout object, indicating the alignment of the
  511. /// struct, its size, and the offsets of its fields.
  512. ///
  513. /// Note that this information is lazily cached.
  514. const StructLayout *getStructLayout(StructType *Ty) const;
  515. /// Returns the preferred alignment of the specified global.
  516. ///
  517. /// This includes an explicitly requested alignment (if the global has one).
  518. Align getPreferredAlign(const GlobalVariable *GV) const;
  519. };
  520. inline DataLayout *unwrap(LLVMTargetDataRef P) {
  521. return reinterpret_cast<DataLayout *>(P);
  522. }
  523. inline LLVMTargetDataRef wrap(const DataLayout *P) {
  524. return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
  525. }
  526. /// Used to lazily calculate structure layout information for a target machine,
  527. /// based on the DataLayout structure.
  528. class StructLayout final : public TrailingObjects<StructLayout, uint64_t> {
  529. uint64_t StructSize;
  530. Align StructAlignment;
  531. unsigned IsPadded : 1;
  532. unsigned NumElements : 31;
  533. public:
  534. uint64_t getSizeInBytes() const { return StructSize; }
  535. uint64_t getSizeInBits() const { return 8 * StructSize; }
  536. Align getAlignment() const { return StructAlignment; }
  537. /// Returns whether the struct has padding or not between its fields.
  538. /// NB: Padding in nested element is not taken into account.
  539. bool hasPadding() const { return IsPadded; }
  540. /// Given a valid byte offset into the structure, returns the structure
  541. /// index that contains it.
  542. unsigned getElementContainingOffset(uint64_t Offset) const;
  543. MutableArrayRef<uint64_t> getMemberOffsets() {
  544. return llvm::MutableArrayRef(getTrailingObjects<uint64_t>(),
  545. NumElements);
  546. }
  547. ArrayRef<uint64_t> getMemberOffsets() const {
  548. return llvm::ArrayRef(getTrailingObjects<uint64_t>(), NumElements);
  549. }
  550. uint64_t getElementOffset(unsigned Idx) const {
  551. assert(Idx < NumElements && "Invalid element idx!");
  552. return getMemberOffsets()[Idx];
  553. }
  554. uint64_t getElementOffsetInBits(unsigned Idx) const {
  555. return getElementOffset(Idx) * 8;
  556. }
  557. private:
  558. friend class DataLayout; // Only DataLayout can create this class
  559. StructLayout(StructType *ST, const DataLayout &DL);
  560. size_t numTrailingObjects(OverloadToken<uint64_t>) const {
  561. return NumElements;
  562. }
  563. };
  564. // The implementation of this method is provided inline as it is particularly
  565. // well suited to constant folding when called on a specific Type subclass.
  566. inline TypeSize DataLayout::getTypeSizeInBits(Type *Ty) const {
  567. assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
  568. switch (Ty->getTypeID()) {
  569. case Type::LabelTyID:
  570. return TypeSize::Fixed(getPointerSizeInBits(0));
  571. case Type::PointerTyID:
  572. return TypeSize::Fixed(getPointerSizeInBits(Ty->getPointerAddressSpace()));
  573. case Type::ArrayTyID: {
  574. ArrayType *ATy = cast<ArrayType>(Ty);
  575. return ATy->getNumElements() *
  576. getTypeAllocSizeInBits(ATy->getElementType());
  577. }
  578. case Type::StructTyID:
  579. // Get the layout annotation... which is lazily created on demand.
  580. return TypeSize::Fixed(
  581. getStructLayout(cast<StructType>(Ty))->getSizeInBits());
  582. case Type::IntegerTyID:
  583. return TypeSize::Fixed(Ty->getIntegerBitWidth());
  584. case Type::HalfTyID:
  585. case Type::BFloatTyID:
  586. return TypeSize::Fixed(16);
  587. case Type::FloatTyID:
  588. return TypeSize::Fixed(32);
  589. case Type::DoubleTyID:
  590. case Type::X86_MMXTyID:
  591. return TypeSize::Fixed(64);
  592. case Type::PPC_FP128TyID:
  593. case Type::FP128TyID:
  594. return TypeSize::Fixed(128);
  595. case Type::X86_AMXTyID:
  596. return TypeSize::Fixed(8192);
  597. // In memory objects this is always aligned to a higher boundary, but
  598. // only 80 bits contain information.
  599. case Type::X86_FP80TyID:
  600. return TypeSize::Fixed(80);
  601. case Type::FixedVectorTyID:
  602. case Type::ScalableVectorTyID: {
  603. VectorType *VTy = cast<VectorType>(Ty);
  604. auto EltCnt = VTy->getElementCount();
  605. uint64_t MinBits = EltCnt.getKnownMinValue() *
  606. getTypeSizeInBits(VTy->getElementType()).getFixedValue();
  607. return TypeSize(MinBits, EltCnt.isScalable());
  608. }
  609. case Type::TargetExtTyID: {
  610. Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
  611. return getTypeSizeInBits(LayoutTy);
  612. }
  613. default:
  614. llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
  615. }
  616. }
  617. } // end namespace llvm
  618. #endif // LLVM_IR_DATALAYOUT_H
  619. #ifdef __GNUC__
  620. #pragma GCC diagnostic pop
  621. #endif