DataLayout.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. //===--------- llvm/DataLayout.h - Data size & alignment info ---*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines layout properties related to datatype size/offset/alignment
  11. // information. It uses lazy annotations to cache information about how
  12. // structure types are laid out and used.
  13. //
  14. // This structure should be created once, filled in if the defaults are not
  15. // correct and then passed around by const&. None of the members functions
  16. // require modification to the object.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_IR_DATALAYOUT_H
  20. #define LLVM_IR_DATALAYOUT_H
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Type.h"
  25. #include "llvm/Pass.h"
  26. #include "llvm/Support/DataTypes.h"
  27. // This needs to be outside of the namespace, to avoid conflict with llvm-c
  28. // decl.
  29. typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
  30. namespace llvm {
  31. class Value;
  32. class Type;
  33. class IntegerType;
  34. class StructType;
  35. class StructLayout;
  36. class Triple;
  37. class GlobalVariable;
  38. class LLVMContext;
  39. template<typename T>
  40. class ArrayRef;
  41. /// Enum used to categorize the alignment types stored by LayoutAlignElem
  42. enum AlignTypeEnum {
  43. INVALID_ALIGN = 0,
  44. INTEGER_ALIGN = 'i',
  45. VECTOR_ALIGN = 'v',
  46. FLOAT_ALIGN = 'f',
  47. AGGREGATE_ALIGN = 'a'
  48. };
  49. // FIXME: Currently the DataLayout string carries a "preferred alignment"
  50. // for types. As the DataLayout is module/global, this should likely be
  51. // sunk down to an FTTI element that is queried rather than a global
  52. // preference.
  53. /// \brief Layout alignment element.
  54. ///
  55. /// Stores the alignment data associated with a given alignment type (integer,
  56. /// vector, float) and type bit width.
  57. ///
  58. /// \note The unusual order of elements in the structure attempts to reduce
  59. /// padding and make the structure slightly more cache friendly.
  60. struct LayoutAlignElem {
  61. /// \brief Alignment type from \c AlignTypeEnum
  62. unsigned AlignType : 8;
  63. unsigned TypeBitWidth : 24;
  64. unsigned ABIAlign : 16;
  65. unsigned PrefAlign : 16;
  66. static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
  67. unsigned pref_align, uint32_t bit_width);
  68. bool operator==(const LayoutAlignElem &rhs) const;
  69. };
  70. /// \brief Layout pointer alignment element.
  71. ///
  72. /// Stores the alignment data associated with a given pointer and address space.
  73. ///
  74. /// \note The unusual order of elements in the structure attempts to reduce
  75. /// padding and make the structure slightly more cache friendly.
  76. struct PointerAlignElem {
  77. unsigned ABIAlign;
  78. unsigned PrefAlign;
  79. uint32_t TypeByteWidth;
  80. uint32_t AddressSpace;
  81. /// Initializer
  82. static PointerAlignElem get(uint32_t AddressSpace, unsigned ABIAlign,
  83. unsigned PrefAlign, uint32_t TypeByteWidth);
  84. bool operator==(const PointerAlignElem &rhs) const;
  85. };
  86. /// \brief A parsed version of the target data layout string in and methods for
  87. /// querying it.
  88. ///
  89. /// The target data layout string is specified *by the target* - a frontend
  90. /// generating LLVM IR is required to generate the right target data for the
  91. /// target being codegen'd to.
  92. class DataLayout {
  93. private:
  94. /// Defaults to false.
  95. bool BigEndian;
  96. unsigned StackNaturalAlign;
  97. enum ManglingModeT {
  98. MM_None,
  99. MM_ELF,
  100. MM_MachO,
  101. MM_WinCOFF,
  102. MM_WinCOFFX86,
  103. MM_Mips
  104. };
  105. ManglingModeT ManglingMode;
  106. SmallVector<unsigned char, 8> LegalIntWidths;
  107. /// \brief Primitive type alignment data.
  108. SmallVector<LayoutAlignElem, 16> Alignments;
  109. /// \brief The string representation used to create this DataLayout
  110. std::string StringRepresentation;
  111. typedef SmallVector<PointerAlignElem, 8> PointersTy;
  112. PointersTy Pointers;
  113. PointersTy::const_iterator
  114. findPointerLowerBound(uint32_t AddressSpace) const {
  115. return const_cast<DataLayout *>(this)->findPointerLowerBound(AddressSpace);
  116. }
  117. PointersTy::iterator findPointerLowerBound(uint32_t AddressSpace);
  118. /// This member is a signal that a requested alignment type and bit width were
  119. /// not found in the SmallVector.
  120. static const LayoutAlignElem InvalidAlignmentElem;
  121. /// This member is a signal that a requested pointer type and bit width were
  122. /// not found in the DenseSet.
  123. static const PointerAlignElem InvalidPointerElem;
  124. // The StructType -> StructLayout map.
  125. mutable void *LayoutMap;
  126. void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
  127. unsigned pref_align, uint32_t bit_width);
  128. unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
  129. bool ABIAlign, Type *Ty) const;
  130. void setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
  131. unsigned PrefAlign, uint32_t TypeByteWidth);
  132. /// Internal helper method that returns requested alignment for type.
  133. unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
  134. /// \brief Valid alignment predicate.
  135. ///
  136. /// Predicate that tests a LayoutAlignElem reference returned by get() against
  137. /// InvalidAlignmentElem.
  138. bool validAlignment(const LayoutAlignElem &align) const {
  139. return &align != &InvalidAlignmentElem;
  140. }
  141. /// \brief Valid pointer predicate.
  142. ///
  143. /// Predicate that tests a PointerAlignElem reference returned by get()
  144. /// against \c InvalidPointerElem.
  145. bool validPointer(const PointerAlignElem &align) const {
  146. return &align != &InvalidPointerElem;
  147. }
  148. /// Parses a target data specification string. Assert if the string is
  149. /// malformed.
  150. void parseSpecifier(StringRef LayoutDescription);
  151. // Free all internal data structures.
  152. void clear();
  153. public:
  154. /// Constructs a DataLayout from a specification string. See reset().
  155. explicit DataLayout(StringRef LayoutDescription) : LayoutMap(nullptr) {
  156. reset(LayoutDescription);
  157. }
  158. /// Initialize target data from properties stored in the module.
  159. explicit DataLayout(const Module *M);
  160. void init(const Module *M);
  161. DataLayout(const DataLayout &DL) : LayoutMap(nullptr) { *this = DL; }
  162. DataLayout &operator=(const DataLayout &DL) {
  163. clear();
  164. StringRepresentation = DL.StringRepresentation;
  165. BigEndian = DL.isBigEndian();
  166. StackNaturalAlign = DL.StackNaturalAlign;
  167. ManglingMode = DL.ManglingMode;
  168. LegalIntWidths = DL.LegalIntWidths;
  169. Alignments = DL.Alignments;
  170. Pointers = DL.Pointers;
  171. return *this;
  172. }
  173. bool operator==(const DataLayout &Other) const;
  174. bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
  175. ~DataLayout(); // Not virtual, do not subclass this class
  176. /// Parse a data layout string (with fallback to default values).
  177. void reset(StringRef LayoutDescription);
  178. /// Layout endianness...
  179. bool isLittleEndian() const { return !BigEndian; }
  180. bool isBigEndian() const { return BigEndian; }
  181. /// \brief Returns the string representation of the DataLayout.
  182. ///
  183. /// This representation is in the same format accepted by the string
  184. /// constructor above. This should not be used to compare two DataLayout as
  185. /// different string can represent the same layout.
  186. const std::string &getStringRepresentation() const {
  187. return StringRepresentation;
  188. }
  189. /// \brief Test if the DataLayout was constructed from an empty string.
  190. bool isDefault() const { return StringRepresentation.empty(); }
  191. /// \brief Returns true if the specified type is known to be a native integer
  192. /// type supported by the CPU.
  193. ///
  194. /// For example, i64 is not native on most 32-bit CPUs and i37 is not native
  195. /// on any known one. This returns false if the integer width is not legal.
  196. ///
  197. /// The width is specified in bits.
  198. bool isLegalInteger(unsigned Width) const {
  199. for (unsigned LegalIntWidth : LegalIntWidths)
  200. if (LegalIntWidth == Width)
  201. return true;
  202. return false;
  203. }
  204. bool isIllegalInteger(unsigned Width) const { return !isLegalInteger(Width); }
  205. /// Returns true if the given alignment exceeds the natural stack alignment.
  206. bool exceedsNaturalStackAlignment(unsigned Align) const {
  207. return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
  208. }
  209. unsigned getStackAlignment() const { return StackNaturalAlign; }
  210. bool hasMicrosoftFastStdCallMangling() const {
  211. return ManglingMode == MM_WinCOFFX86;
  212. }
  213. bool hasLinkerPrivateGlobalPrefix() const { return ManglingMode == MM_MachO; }
  214. const char *getLinkerPrivateGlobalPrefix() const {
  215. if (ManglingMode == MM_MachO)
  216. return "l";
  217. return "";
  218. }
  219. char getGlobalPrefix() const {
  220. switch (ManglingMode) {
  221. case MM_None:
  222. case MM_ELF:
  223. case MM_Mips:
  224. case MM_WinCOFF:
  225. return '\0';
  226. case MM_MachO:
  227. case MM_WinCOFFX86:
  228. return '_';
  229. }
  230. llvm_unreachable("invalid mangling mode");
  231. }
  232. const char *getPrivateGlobalPrefix() const {
  233. switch (ManglingMode) {
  234. case MM_None:
  235. return "";
  236. case MM_ELF:
  237. return ".L";
  238. case MM_Mips:
  239. return "$";
  240. case MM_MachO:
  241. case MM_WinCOFF:
  242. case MM_WinCOFFX86:
  243. return "L";
  244. }
  245. llvm_unreachable("invalid mangling mode");
  246. }
  247. static const char *getManglingComponent(const Triple &T);
  248. /// \brief Returns true if the specified type fits in a native integer type
  249. /// supported by the CPU.
  250. ///
  251. /// For example, if the CPU only supports i32 as a native integer type, then
  252. /// i27 fits in a legal integer type but i45 does not.
  253. bool fitsInLegalInteger(unsigned Width) const {
  254. for (unsigned LegalIntWidth : LegalIntWidths)
  255. if (Width <= LegalIntWidth)
  256. return true;
  257. return false;
  258. }
  259. /// Layout pointer alignment
  260. /// FIXME: The defaults need to be removed once all of
  261. /// the backends/clients are updated.
  262. unsigned getPointerABIAlignment(unsigned AS = 0) const;
  263. /// Return target's alignment for stack-based pointers
  264. /// FIXME: The defaults need to be removed once all of
  265. /// the backends/clients are updated.
  266. unsigned getPointerPrefAlignment(unsigned AS = 0) const;
  267. /// Layout pointer size
  268. /// FIXME: The defaults need to be removed once all of
  269. /// the backends/clients are updated.
  270. unsigned getPointerSize(unsigned AS = 0) const;
  271. /// Layout pointer size, in bits
  272. /// FIXME: The defaults need to be removed once all of
  273. /// the backends/clients are updated.
  274. unsigned getPointerSizeInBits(unsigned AS = 0) const {
  275. return getPointerSize(AS) * 8;
  276. }
  277. /// Layout pointer size, in bits, based on the type. If this function is
  278. /// called with a pointer type, then the type size of the pointer is returned.
  279. /// If this function is called with a vector of pointers, then the type size
  280. /// of the pointer is returned. This should only be called with a pointer or
  281. /// vector of pointers.
  282. unsigned getPointerTypeSizeInBits(Type *) const;
  283. unsigned getPointerTypeSize(Type *Ty) const {
  284. return getPointerTypeSizeInBits(Ty) / 8;
  285. }
  286. /// Size examples:
  287. ///
  288. /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
  289. /// ---- ---------- --------------- ---------------
  290. /// i1 1 8 8
  291. /// i8 8 8 8
  292. /// i19 19 24 32
  293. /// i32 32 32 32
  294. /// i100 100 104 128
  295. /// i128 128 128 128
  296. /// Float 32 32 32
  297. /// Double 64 64 64
  298. /// X86_FP80 80 80 96
  299. ///
  300. /// [*] The alloc size depends on the alignment, and thus on the target.
  301. /// These values are for x86-32 linux.
  302. /// \brief Returns the number of bits necessary to hold the specified type.
  303. ///
  304. /// For example, returns 36 for i36 and 80 for x86_fp80. The type passed must
  305. /// have a size (Type::isSized() must return true).
  306. uint64_t getTypeSizeInBits(Type *Ty) const;
  307. /// \brief Returns the maximum number of bytes that may be overwritten by
  308. /// storing the specified type.
  309. ///
  310. /// For example, returns 5 for i36 and 10 for x86_fp80.
  311. uint64_t getTypeStoreSize(Type *Ty) const {
  312. return (getTypeSizeInBits(Ty) + 7) / 8;
  313. }
  314. /// \brief Returns the maximum number of bits that may be overwritten by
  315. /// storing the specified type; always a multiple of 8.
  316. ///
  317. /// For example, returns 40 for i36 and 80 for x86_fp80.
  318. uint64_t getTypeStoreSizeInBits(Type *Ty) const {
  319. return 8 * getTypeStoreSize(Ty);
  320. }
  321. /// \brief Returns the offset in bytes between successive objects of the
  322. /// specified type, including alignment padding.
  323. ///
  324. /// This is the amount that alloca reserves for this type. For example,
  325. /// returns 12 or 16 for x86_fp80, depending on alignment.
  326. uint64_t getTypeAllocSize(Type *Ty) const {
  327. // Round up to the next alignment boundary.
  328. return RoundUpToAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
  329. }
  330. /// \brief Returns the offset in bits between successive objects of the
  331. /// specified type, including alignment padding; always a multiple of 8.
  332. ///
  333. /// This is the amount that alloca reserves for this type. For example,
  334. /// returns 96 or 128 for x86_fp80, depending on alignment.
  335. uint64_t getTypeAllocSizeInBits(Type *Ty) const {
  336. return 8 * getTypeAllocSize(Ty);
  337. }
  338. /// \brief Returns the minimum ABI-required alignment for the specified type.
  339. unsigned getABITypeAlignment(Type *Ty) const;
  340. /// \brief Returns the minimum ABI-required alignment for an integer type of
  341. /// the specified bitwidth.
  342. unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
  343. /// \brief Returns the preferred stack/global alignment for the specified
  344. /// type.
  345. ///
  346. /// This is always at least as good as the ABI alignment.
  347. unsigned getPrefTypeAlignment(Type *Ty) const;
  348. /// \brief Returns the preferred alignment for the specified type, returned as
  349. /// log2 of the value (a shift amount).
  350. unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
  351. /// \brief Returns an integer type with size at least as big as that of a
  352. /// pointer in the given address space.
  353. IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
  354. /// \brief Returns an integer (vector of integer) type with size at least as
  355. /// big as that of a pointer of the given pointer (vector of pointer) type.
  356. Type *getIntPtrType(Type *) const;
  357. /// \brief Returns the smallest integer type with size at least as big as
  358. /// Width bits.
  359. Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
  360. /// \brief Returns the largest legal integer type, or null if none are set.
  361. Type *getLargestLegalIntType(LLVMContext &C) const {
  362. unsigned LargestSize = getLargestLegalIntTypeSize();
  363. return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
  364. }
  365. /// \brief Returns the size of largest legal integer type size, or 0 if none
  366. /// are set.
  367. unsigned getLargestLegalIntTypeSize() const;
  368. /// \brief Returns the offset from the beginning of the type for the specified
  369. /// indices.
  370. ///
  371. /// This is used to implement getelementptr.
  372. uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
  373. /// \brief Returns a StructLayout object, indicating the alignment of the
  374. /// struct, its size, and the offsets of its fields.
  375. ///
  376. /// Note that this information is lazily cached.
  377. const StructLayout *getStructLayout(StructType *Ty) const;
  378. /// \brief Returns the preferred alignment of the specified global.
  379. ///
  380. /// This includes an explicitly requested alignment (if the global has one).
  381. unsigned getPreferredAlignment(const GlobalVariable *GV) const;
  382. /// \brief Returns the preferred alignment of the specified global, returned
  383. /// in log form.
  384. ///
  385. /// This includes an explicitly requested alignment (if the global has one).
  386. unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
  387. };
  388. inline DataLayout *unwrap(LLVMTargetDataRef P) {
  389. return reinterpret_cast<DataLayout *>(P);
  390. }
  391. inline LLVMTargetDataRef wrap(const DataLayout *P) {
  392. return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
  393. }
  394. /// Used to lazily calculate structure layout information for a target machine,
  395. /// based on the DataLayout structure.
  396. class StructLayout {
  397. uint64_t StructSize;
  398. unsigned StructAlignment;
  399. unsigned NumElements;
  400. uint64_t MemberOffsets[1]; // variable sized array!
  401. public:
  402. uint64_t getSizeInBytes() const { return StructSize; }
  403. uint64_t getSizeInBits() const { return 8 * StructSize; }
  404. unsigned getAlignment() const { return StructAlignment; }
  405. /// \brief Given a valid byte offset into the structure, returns the structure
  406. /// index that contains it.
  407. unsigned getElementContainingOffset(uint64_t Offset) const;
  408. uint64_t getElementOffset(unsigned Idx) const {
  409. assert(Idx < NumElements && "Invalid element idx!");
  410. return MemberOffsets[Idx];
  411. }
  412. uint64_t getElementOffsetInBits(unsigned Idx) const {
  413. return getElementOffset(Idx) * 8;
  414. }
  415. private:
  416. friend class DataLayout; // Only DataLayout can create this class
  417. StructLayout(StructType *ST, const DataLayout &DL);
  418. };
  419. // The implementation of this method is provided inline as it is particularly
  420. // well suited to constant folding when called on a specific Type subclass.
  421. inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
  422. assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
  423. switch (Ty->getTypeID()) {
  424. case Type::LabelTyID:
  425. return getPointerSizeInBits(0);
  426. case Type::PointerTyID:
  427. return getPointerSizeInBits(Ty->getPointerAddressSpace());
  428. case Type::ArrayTyID: {
  429. ArrayType *ATy = cast<ArrayType>(Ty);
  430. return ATy->getNumElements() *
  431. getTypeAllocSizeInBits(ATy->getElementType());
  432. }
  433. case Type::StructTyID:
  434. // Get the layout annotation... which is lazily created on demand.
  435. return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
  436. case Type::IntegerTyID:
  437. return Ty->getIntegerBitWidth();
  438. case Type::HalfTyID:
  439. return 16;
  440. case Type::FloatTyID:
  441. return 32;
  442. case Type::DoubleTyID:
  443. case Type::X86_MMXTyID:
  444. return 64;
  445. case Type::PPC_FP128TyID:
  446. case Type::FP128TyID:
  447. return 128;
  448. // In memory objects this is always aligned to a higher boundary, but
  449. // only 80 bits contain information.
  450. case Type::X86_FP80TyID:
  451. return 80;
  452. case Type::VectorTyID: {
  453. VectorType *VTy = cast<VectorType>(Ty);
  454. // HLSL Change Begins.
  455. // HLSL vector use aligned size.
  456. return VTy->getNumElements() * getTypeAllocSizeInBits(VTy->getElementType());
  457. // HLSL Change Ends.
  458. }
  459. default:
  460. llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
  461. }
  462. }
  463. } // End llvm namespace
  464. #endif