DataLayout.h 25 KB

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