DataLayout.h 25 KB

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