DataLayout.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. //===-- DataLayout.cpp - Data size & alignment routines --------------------==//
  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.
  12. //
  13. // This structure should be created once, filled in if the defaults are not
  14. // correct and then passed around by const&. None of the members functions
  15. // require modification to the object.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/DataLayout.h"
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/Constants.h"
  21. #include "llvm/DerivedTypes.h"
  22. #include "llvm/Module.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/GetElementPtrTypeIterator.h"
  25. #include "llvm/Support/ManagedStatic.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/Mutex.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <algorithm>
  30. #include <cstdlib>
  31. using namespace llvm;
  32. // Handle the Pass registration stuff necessary to use DataLayout's.
  33. // Register the default SparcV9 implementation...
  34. INITIALIZE_PASS(DataLayout, "datalayout", "Data Layout", false, true)
  35. char DataLayout::ID = 0;
  36. //===----------------------------------------------------------------------===//
  37. // Support for StructLayout
  38. //===----------------------------------------------------------------------===//
  39. StructLayout::StructLayout(StructType *ST, const DataLayout &TD) {
  40. assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
  41. StructAlignment = 0;
  42. StructSize = 0;
  43. NumElements = ST->getNumElements();
  44. // Loop over each of the elements, placing them in memory.
  45. for (unsigned i = 0, e = NumElements; i != e; ++i) {
  46. Type *Ty = ST->getElementType(i);
  47. unsigned TyAlign = ST->isPacked() ? 1 : TD.getABITypeAlignment(Ty);
  48. // Add padding if necessary to align the data element properly.
  49. if ((StructSize & (TyAlign-1)) != 0)
  50. StructSize = DataLayout::RoundUpAlignment(StructSize, TyAlign);
  51. // Keep track of maximum alignment constraint.
  52. StructAlignment = std::max(TyAlign, StructAlignment);
  53. MemberOffsets[i] = StructSize;
  54. StructSize += TD.getTypeAllocSize(Ty); // Consume space for this data item
  55. }
  56. // Empty structures have alignment of 1 byte.
  57. if (StructAlignment == 0) StructAlignment = 1;
  58. // Add padding to the end of the struct so that it could be put in an array
  59. // and all array elements would be aligned correctly.
  60. if ((StructSize & (StructAlignment-1)) != 0)
  61. StructSize = DataLayout::RoundUpAlignment(StructSize, StructAlignment);
  62. }
  63. /// getElementContainingOffset - Given a valid offset into the structure,
  64. /// return the structure index that contains it.
  65. unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
  66. const uint64_t *SI =
  67. std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
  68. assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
  69. --SI;
  70. assert(*SI <= Offset && "upper_bound didn't work");
  71. assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
  72. (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
  73. "Upper bound didn't work!");
  74. // Multiple fields can have the same offset if any of them are zero sized.
  75. // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
  76. // at the i32 element, because it is the last element at that offset. This is
  77. // the right one to return, because anything after it will have a higher
  78. // offset, implying that this element is non-empty.
  79. return SI-&MemberOffsets[0];
  80. }
  81. //===----------------------------------------------------------------------===//
  82. // LayoutAlignElem, LayoutAlign support
  83. //===----------------------------------------------------------------------===//
  84. LayoutAlignElem
  85. LayoutAlignElem::get(AlignTypeEnum align_type, unsigned abi_align,
  86. unsigned pref_align, uint32_t bit_width) {
  87. assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
  88. LayoutAlignElem retval;
  89. retval.AlignType = align_type;
  90. retval.ABIAlign = abi_align;
  91. retval.PrefAlign = pref_align;
  92. retval.TypeBitWidth = bit_width;
  93. return retval;
  94. }
  95. bool
  96. LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
  97. return (AlignType == rhs.AlignType
  98. && ABIAlign == rhs.ABIAlign
  99. && PrefAlign == rhs.PrefAlign
  100. && TypeBitWidth == rhs.TypeBitWidth);
  101. }
  102. const LayoutAlignElem
  103. DataLayout::InvalidAlignmentElem = LayoutAlignElem::get(INVALID_ALIGN, 0, 0, 0);
  104. //===----------------------------------------------------------------------===//
  105. // PointerAlignElem, PointerAlign support
  106. //===----------------------------------------------------------------------===//
  107. PointerAlignElem
  108. PointerAlignElem::get(uint32_t addr_space, unsigned abi_align,
  109. unsigned pref_align, uint32_t bit_width) {
  110. assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
  111. PointerAlignElem retval;
  112. retval.AddressSpace = addr_space;
  113. retval.ABIAlign = abi_align;
  114. retval.PrefAlign = pref_align;
  115. retval.TypeBitWidth = bit_width;
  116. return retval;
  117. }
  118. bool
  119. PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
  120. return (ABIAlign == rhs.ABIAlign
  121. && AddressSpace == rhs.AddressSpace
  122. && PrefAlign == rhs.PrefAlign
  123. && TypeBitWidth == rhs.TypeBitWidth);
  124. }
  125. const PointerAlignElem
  126. DataLayout::InvalidPointerElem = PointerAlignElem::get(~0U, 0U, 0U, 0U);
  127. //===----------------------------------------------------------------------===//
  128. // DataLayout Class Implementation
  129. //===----------------------------------------------------------------------===//
  130. void DataLayout::init(StringRef Desc) {
  131. initializeDataLayoutPass(*PassRegistry::getPassRegistry());
  132. LayoutMap = 0;
  133. LittleEndian = false;
  134. StackNaturalAlign = 0;
  135. // Default alignments
  136. setAlignment(INTEGER_ALIGN, 1, 1, 1); // i1
  137. setAlignment(INTEGER_ALIGN, 1, 1, 8); // i8
  138. setAlignment(INTEGER_ALIGN, 2, 2, 16); // i16
  139. setAlignment(INTEGER_ALIGN, 4, 4, 32); // i32
  140. setAlignment(INTEGER_ALIGN, 4, 8, 64); // i64
  141. setAlignment(FLOAT_ALIGN, 2, 2, 16); // half
  142. setAlignment(FLOAT_ALIGN, 4, 4, 32); // float
  143. setAlignment(FLOAT_ALIGN, 8, 8, 64); // double
  144. setAlignment(FLOAT_ALIGN, 16, 16, 128); // ppcf128, quad, ...
  145. setAlignment(VECTOR_ALIGN, 8, 8, 64); // v2i32, v1i64, ...
  146. setAlignment(VECTOR_ALIGN, 16, 16, 128); // v16i8, v8i16, v4i32, ...
  147. setAlignment(AGGREGATE_ALIGN, 0, 8, 0); // struct
  148. setPointerAlignment(0, 8, 8, 8);
  149. parseSpecifier(Desc);
  150. }
  151. /// Checked version of split, to ensure mandatory subparts.
  152. static std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
  153. assert(!Str.empty() && "parse error, string can't be empty here");
  154. std::pair<StringRef, StringRef> Split = Str.split(Separator);
  155. assert((!Split.second.empty() || Split.first == Str) &&
  156. "a trailing separator is not allowed");
  157. return Split;
  158. }
  159. /// Get an unsinged integer, including error checks.
  160. static unsigned getInt(StringRef R) {
  161. unsigned Result;
  162. bool error = R.getAsInteger(10, Result); (void)error;
  163. assert(!error && "not a number, or does not fit in an unsigned int");
  164. return Result;
  165. }
  166. /// Convert bits into bytes. Assert if not a byte width multiple.
  167. static unsigned inBytes(unsigned Bits) {
  168. assert(Bits % 8 == 0 && "number of bits must be a byte width multiple");
  169. return Bits / 8;
  170. }
  171. void DataLayout::parseSpecifier(StringRef Desc) {
  172. while (!Desc.empty()) {
  173. // Split at '-'.
  174. std::pair<StringRef, StringRef> Split = split(Desc, '-');
  175. Desc = Split.second;
  176. // Split at ':'.
  177. Split = split(Split.first, ':');
  178. // Aliases used below.
  179. StringRef &Tok = Split.first; // Current token.
  180. StringRef &Rest = Split.second; // The rest of the string.
  181. char Specifier = Tok.front();
  182. Tok = Tok.substr(1);
  183. switch (Specifier) {
  184. case 'E':
  185. LittleEndian = false;
  186. break;
  187. case 'e':
  188. LittleEndian = true;
  189. break;
  190. case 'p': {
  191. // Address space.
  192. unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
  193. assert(AddrSpace < 1 << 24 &&
  194. "Invalid address space, must be a 24bit integer");
  195. // Size.
  196. Split = split(Rest, ':');
  197. unsigned PointerMemSize = inBytes(getInt(Tok));
  198. // ABI alignment.
  199. Split = split(Rest, ':');
  200. unsigned PointerABIAlign = inBytes(getInt(Tok));
  201. // Preferred alignment.
  202. unsigned PointerPrefAlign = PointerABIAlign;
  203. if (!Rest.empty()) {
  204. Split = split(Rest, ':');
  205. PointerPrefAlign = inBytes(getInt(Tok));
  206. }
  207. setPointerAlignment(AddrSpace, PointerABIAlign, PointerPrefAlign,
  208. PointerMemSize);
  209. break;
  210. }
  211. case 'i':
  212. case 'v':
  213. case 'f':
  214. case 'a':
  215. case 's': {
  216. AlignTypeEnum AlignType;
  217. switch (Specifier) {
  218. default:
  219. case 'i': AlignType = INTEGER_ALIGN; break;
  220. case 'v': AlignType = VECTOR_ALIGN; break;
  221. case 'f': AlignType = FLOAT_ALIGN; break;
  222. case 'a': AlignType = AGGREGATE_ALIGN; break;
  223. case 's': AlignType = STACK_ALIGN; break;
  224. }
  225. // Bit size.
  226. unsigned Size = Tok.empty() ? 0 : getInt(Tok);
  227. // ABI alignment.
  228. Split = split(Rest, ':');
  229. unsigned ABIAlign = inBytes(getInt(Tok));
  230. // Preferred alignment.
  231. unsigned PrefAlign = ABIAlign;
  232. if (!Rest.empty()) {
  233. Split = split(Rest, ':');
  234. PrefAlign = inBytes(getInt(Tok));
  235. }
  236. setAlignment(AlignType, ABIAlign, PrefAlign, Size);
  237. break;
  238. }
  239. case 'n': // Native integer types.
  240. for (;;) {
  241. unsigned Width = getInt(Tok);
  242. assert(Width != 0 && "width must be non-zero");
  243. LegalIntWidths.push_back(Width);
  244. if (Rest.empty())
  245. break;
  246. Split = split(Rest, ':');
  247. }
  248. break;
  249. case 'S': { // Stack natural alignment.
  250. StackNaturalAlign = inBytes(getInt(Tok));
  251. break;
  252. }
  253. default:
  254. llvm_unreachable("Unknown specifier in datalayout string");
  255. break;
  256. }
  257. }
  258. }
  259. /// Default ctor.
  260. ///
  261. /// @note This has to exist, because this is a pass, but it should never be
  262. /// used.
  263. DataLayout::DataLayout() : ImmutablePass(ID) {
  264. report_fatal_error("Bad DataLayout ctor used. "
  265. "Tool did not specify a DataLayout to use?");
  266. }
  267. DataLayout::DataLayout(const Module *M)
  268. : ImmutablePass(ID) {
  269. init(M->getDataLayout());
  270. }
  271. void
  272. DataLayout::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
  273. unsigned pref_align, uint32_t bit_width) {
  274. assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
  275. assert(pref_align < (1 << 16) && "Alignment doesn't fit in bitfield");
  276. assert(bit_width < (1 << 24) && "Bit width doesn't fit in bitfield");
  277. for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
  278. if (Alignments[i].AlignType == (unsigned)align_type &&
  279. Alignments[i].TypeBitWidth == bit_width) {
  280. // Update the abi, preferred alignments.
  281. Alignments[i].ABIAlign = abi_align;
  282. Alignments[i].PrefAlign = pref_align;
  283. return;
  284. }
  285. }
  286. Alignments.push_back(LayoutAlignElem::get(align_type, abi_align,
  287. pref_align, bit_width));
  288. }
  289. void
  290. DataLayout::setPointerAlignment(uint32_t addr_space, unsigned abi_align,
  291. unsigned pref_align, uint32_t bit_width) {
  292. assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
  293. DenseMap<unsigned,PointerAlignElem>::iterator val = Pointers.find(addr_space);
  294. if (val == Pointers.end()) {
  295. Pointers[addr_space] = PointerAlignElem::get(addr_space,
  296. abi_align, pref_align, bit_width);
  297. } else {
  298. val->second.ABIAlign = abi_align;
  299. val->second.PrefAlign = pref_align;
  300. val->second.TypeBitWidth = bit_width;
  301. }
  302. }
  303. /// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
  304. /// preferred if ABIInfo = false) the layout wants for the specified datatype.
  305. unsigned DataLayout::getAlignmentInfo(AlignTypeEnum AlignType,
  306. uint32_t BitWidth, bool ABIInfo,
  307. Type *Ty) const {
  308. // Check to see if we have an exact match and remember the best match we see.
  309. int BestMatchIdx = -1;
  310. int LargestInt = -1;
  311. for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
  312. if (Alignments[i].AlignType == (unsigned)AlignType &&
  313. Alignments[i].TypeBitWidth == BitWidth)
  314. return ABIInfo ? Alignments[i].ABIAlign : Alignments[i].PrefAlign;
  315. // The best match so far depends on what we're looking for.
  316. if (AlignType == INTEGER_ALIGN &&
  317. Alignments[i].AlignType == INTEGER_ALIGN) {
  318. // The "best match" for integers is the smallest size that is larger than
  319. // the BitWidth requested.
  320. if (Alignments[i].TypeBitWidth > BitWidth && (BestMatchIdx == -1 ||
  321. Alignments[i].TypeBitWidth < Alignments[BestMatchIdx].TypeBitWidth))
  322. BestMatchIdx = i;
  323. // However, if there isn't one that's larger, then we must use the
  324. // largest one we have (see below)
  325. if (LargestInt == -1 ||
  326. Alignments[i].TypeBitWidth > Alignments[LargestInt].TypeBitWidth)
  327. LargestInt = i;
  328. }
  329. }
  330. // Okay, we didn't find an exact solution. Fall back here depending on what
  331. // is being looked for.
  332. if (BestMatchIdx == -1) {
  333. // If we didn't find an integer alignment, fall back on most conservative.
  334. if (AlignType == INTEGER_ALIGN) {
  335. BestMatchIdx = LargestInt;
  336. } else {
  337. assert(AlignType == VECTOR_ALIGN && "Unknown alignment type!");
  338. // By default, use natural alignment for vector types. This is consistent
  339. // with what clang and llvm-gcc do.
  340. unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
  341. Align *= cast<VectorType>(Ty)->getNumElements();
  342. // If the alignment is not a power of 2, round up to the next power of 2.
  343. // This happens for non-power-of-2 length vectors.
  344. if (Align & (Align-1))
  345. Align = NextPowerOf2(Align);
  346. return Align;
  347. }
  348. }
  349. // Since we got a "best match" index, just return it.
  350. return ABIInfo ? Alignments[BestMatchIdx].ABIAlign
  351. : Alignments[BestMatchIdx].PrefAlign;
  352. }
  353. namespace {
  354. class StructLayoutMap {
  355. typedef DenseMap<StructType*, StructLayout*> LayoutInfoTy;
  356. LayoutInfoTy LayoutInfo;
  357. public:
  358. virtual ~StructLayoutMap() {
  359. // Remove any layouts.
  360. for (LayoutInfoTy::iterator I = LayoutInfo.begin(), E = LayoutInfo.end();
  361. I != E; ++I) {
  362. StructLayout *Value = I->second;
  363. Value->~StructLayout();
  364. free(Value);
  365. }
  366. }
  367. StructLayout *&operator[](StructType *STy) {
  368. return LayoutInfo[STy];
  369. }
  370. // for debugging...
  371. virtual void dump() const {}
  372. };
  373. } // end anonymous namespace
  374. DataLayout::~DataLayout() {
  375. delete static_cast<StructLayoutMap*>(LayoutMap);
  376. }
  377. const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
  378. if (!LayoutMap)
  379. LayoutMap = new StructLayoutMap();
  380. StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
  381. StructLayout *&SL = (*STM)[Ty];
  382. if (SL) return SL;
  383. // Otherwise, create the struct layout. Because it is variable length, we
  384. // malloc it, then use placement new.
  385. int NumElts = Ty->getNumElements();
  386. StructLayout *L =
  387. (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
  388. // Set SL before calling StructLayout's ctor. The ctor could cause other
  389. // entries to be added to TheMap, invalidating our reference.
  390. SL = L;
  391. new (L) StructLayout(Ty, *this);
  392. return L;
  393. }
  394. std::string DataLayout::getStringRepresentation() const {
  395. std::string Result;
  396. raw_string_ostream OS(Result);
  397. OS << (LittleEndian ? "e" : "E");
  398. SmallVector<unsigned, 8> addrSpaces;
  399. // Lets get all of the known address spaces and sort them
  400. // into increasing order so that we can emit the string
  401. // in a cleaner format.
  402. for (DenseMap<unsigned, PointerAlignElem>::const_iterator
  403. pib = Pointers.begin(), pie = Pointers.end();
  404. pib != pie; ++pib) {
  405. addrSpaces.push_back(pib->first);
  406. }
  407. std::sort(addrSpaces.begin(), addrSpaces.end());
  408. for (SmallVector<unsigned, 8>::iterator asb = addrSpaces.begin(),
  409. ase = addrSpaces.end(); asb != ase; ++asb) {
  410. const PointerAlignElem &PI = Pointers.find(*asb)->second;
  411. OS << "-p";
  412. if (PI.AddressSpace) {
  413. OS << PI.AddressSpace;
  414. }
  415. OS << ":" << PI.TypeBitWidth*8 << ':' << PI.ABIAlign*8
  416. << ':' << PI.PrefAlign*8;
  417. }
  418. OS << "-S" << StackNaturalAlign*8;
  419. for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
  420. const LayoutAlignElem &AI = Alignments[i];
  421. OS << '-' << (char)AI.AlignType << AI.TypeBitWidth << ':'
  422. << AI.ABIAlign*8 << ':' << AI.PrefAlign*8;
  423. }
  424. if (!LegalIntWidths.empty()) {
  425. OS << "-n" << (unsigned)LegalIntWidths[0];
  426. for (unsigned i = 1, e = LegalIntWidths.size(); i != e; ++i)
  427. OS << ':' << (unsigned)LegalIntWidths[i];
  428. }
  429. return OS.str();
  430. }
  431. uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
  432. assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
  433. switch (Ty->getTypeID()) {
  434. case Type::LabelTyID:
  435. return getPointerSizeInBits(0);
  436. case Type::PointerTyID: {
  437. unsigned AS = dyn_cast<PointerType>(Ty)->getAddressSpace();
  438. return getPointerSizeInBits(AS);
  439. }
  440. case Type::ArrayTyID: {
  441. ArrayType *ATy = cast<ArrayType>(Ty);
  442. return getTypeAllocSizeInBits(ATy->getElementType())*ATy->getNumElements();
  443. }
  444. case Type::StructTyID:
  445. // Get the layout annotation... which is lazily created on demand.
  446. return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
  447. case Type::IntegerTyID:
  448. return cast<IntegerType>(Ty)->getBitWidth();
  449. case Type::HalfTyID:
  450. return 16;
  451. case Type::FloatTyID:
  452. return 32;
  453. case Type::DoubleTyID:
  454. case Type::X86_MMXTyID:
  455. return 64;
  456. case Type::PPC_FP128TyID:
  457. case Type::FP128TyID:
  458. return 128;
  459. // In memory objects this is always aligned to a higher boundary, but
  460. // only 80 bits contain information.
  461. case Type::X86_FP80TyID:
  462. return 80;
  463. case Type::VectorTyID: {
  464. VectorType *VTy = cast<VectorType>(Ty);
  465. return VTy->getNumElements()*getTypeSizeInBits(VTy->getElementType());
  466. }
  467. default:
  468. llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
  469. }
  470. }
  471. /*!
  472. \param abi_or_pref Flag that determines which alignment is returned. true
  473. returns the ABI alignment, false returns the preferred alignment.
  474. \param Ty The underlying type for which alignment is determined.
  475. Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
  476. == false) for the requested type \a Ty.
  477. */
  478. unsigned DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
  479. int AlignType = -1;
  480. assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
  481. switch (Ty->getTypeID()) {
  482. // Early escape for the non-numeric types.
  483. case Type::LabelTyID:
  484. return (abi_or_pref
  485. ? getPointerABIAlignment(0)
  486. : getPointerPrefAlignment(0));
  487. case Type::PointerTyID: {
  488. unsigned AS = dyn_cast<PointerType>(Ty)->getAddressSpace();
  489. return (abi_or_pref
  490. ? getPointerABIAlignment(AS)
  491. : getPointerPrefAlignment(AS));
  492. }
  493. case Type::ArrayTyID:
  494. return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
  495. case Type::StructTyID: {
  496. // Packed structure types always have an ABI alignment of one.
  497. if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
  498. return 1;
  499. // Get the layout annotation... which is lazily created on demand.
  500. const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
  501. unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
  502. return std::max(Align, Layout->getAlignment());
  503. }
  504. case Type::IntegerTyID:
  505. AlignType = INTEGER_ALIGN;
  506. break;
  507. case Type::HalfTyID:
  508. case Type::FloatTyID:
  509. case Type::DoubleTyID:
  510. // PPC_FP128TyID and FP128TyID have different data contents, but the
  511. // same size and alignment, so they look the same here.
  512. case Type::PPC_FP128TyID:
  513. case Type::FP128TyID:
  514. case Type::X86_FP80TyID:
  515. AlignType = FLOAT_ALIGN;
  516. break;
  517. case Type::X86_MMXTyID:
  518. case Type::VectorTyID:
  519. AlignType = VECTOR_ALIGN;
  520. break;
  521. default:
  522. llvm_unreachable("Bad type for getAlignment!!!");
  523. }
  524. return getAlignmentInfo((AlignTypeEnum)AlignType, getTypeSizeInBits(Ty),
  525. abi_or_pref, Ty);
  526. }
  527. unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
  528. return getAlignment(Ty, true);
  529. }
  530. /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
  531. /// an integer type of the specified bitwidth.
  532. unsigned DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
  533. return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, 0);
  534. }
  535. unsigned DataLayout::getCallFrameTypeAlignment(Type *Ty) const {
  536. for (unsigned i = 0, e = Alignments.size(); i != e; ++i)
  537. if (Alignments[i].AlignType == STACK_ALIGN)
  538. return Alignments[i].ABIAlign;
  539. return getABITypeAlignment(Ty);
  540. }
  541. unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
  542. return getAlignment(Ty, false);
  543. }
  544. unsigned DataLayout::getPreferredTypeAlignmentShift(Type *Ty) const {
  545. unsigned Align = getPrefTypeAlignment(Ty);
  546. assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
  547. return Log2_32(Align);
  548. }
  549. /// getIntPtrType - Return an integer type with size at least as big as that
  550. /// of a pointer in the given address space.
  551. IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
  552. unsigned AddressSpace) const {
  553. return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
  554. }
  555. /// getIntPtrType - Return an integer (vector of integer) type with size at
  556. /// least as big as that of a pointer of the given pointer (vector of pointer)
  557. /// type.
  558. Type *DataLayout::getIntPtrType(Type *Ty) const {
  559. assert(Ty->isPtrOrPtrVectorTy() &&
  560. "Expected a pointer or pointer vector type.");
  561. unsigned NumBits = getTypeSizeInBits(Ty->getScalarType());
  562. IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
  563. if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
  564. return VectorType::get(IntTy, VecTy->getNumElements());
  565. return IntTy;
  566. }
  567. uint64_t DataLayout::getIndexedOffset(Type *ptrTy,
  568. ArrayRef<Value *> Indices) const {
  569. Type *Ty = ptrTy;
  570. assert(Ty->isPointerTy() && "Illegal argument for getIndexedOffset()");
  571. uint64_t Result = 0;
  572. generic_gep_type_iterator<Value* const*>
  573. TI = gep_type_begin(ptrTy, Indices);
  574. for (unsigned CurIDX = 0, EndIDX = Indices.size(); CurIDX != EndIDX;
  575. ++CurIDX, ++TI) {
  576. if (StructType *STy = dyn_cast<StructType>(*TI)) {
  577. assert(Indices[CurIDX]->getType() ==
  578. Type::getInt32Ty(ptrTy->getContext()) &&
  579. "Illegal struct idx");
  580. unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
  581. // Get structure layout information...
  582. const StructLayout *Layout = getStructLayout(STy);
  583. // Add in the offset, as calculated by the structure layout info...
  584. Result += Layout->getElementOffset(FieldNo);
  585. // Update Ty to refer to current element
  586. Ty = STy->getElementType(FieldNo);
  587. } else {
  588. // Update Ty to refer to current element
  589. Ty = cast<SequentialType>(Ty)->getElementType();
  590. // Get the array index and the size of each array element.
  591. if (int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue())
  592. Result += (uint64_t)arrayIdx * getTypeAllocSize(Ty);
  593. }
  594. }
  595. return Result;
  596. }
  597. /// getPreferredAlignment - Return the preferred alignment of the specified
  598. /// global. This includes an explicitly requested alignment (if the global
  599. /// has one).
  600. unsigned DataLayout::getPreferredAlignment(const GlobalVariable *GV) const {
  601. Type *ElemType = GV->getType()->getElementType();
  602. unsigned Alignment = getPrefTypeAlignment(ElemType);
  603. unsigned GVAlignment = GV->getAlignment();
  604. if (GVAlignment >= Alignment) {
  605. Alignment = GVAlignment;
  606. } else if (GVAlignment != 0) {
  607. Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
  608. }
  609. if (GV->hasInitializer() && GVAlignment == 0) {
  610. if (Alignment < 16) {
  611. // If the global is not external, see if it is large. If so, give it a
  612. // larger alignment.
  613. if (getTypeSizeInBits(ElemType) > 128)
  614. Alignment = 16; // 16-byte alignment.
  615. }
  616. }
  617. return Alignment;
  618. }
  619. /// getPreferredAlignmentLog - Return the preferred alignment of the
  620. /// specified global, returned in log form. This includes an explicitly
  621. /// requested alignment (if the global has one).
  622. unsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
  623. return Log2_32(getPreferredAlignment(GV));
  624. }