OptimizedStructLayout.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. //===--- OptimizedStructLayout.cpp - Optimal data layout algorithm ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the performOptimizedStructLayout interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/OptimizedStructLayout.h"
  13. using namespace llvm;
  14. using Field = OptimizedStructLayoutField;
  15. #ifndef NDEBUG
  16. static void checkValidLayout(ArrayRef<Field> Fields, uint64_t Size,
  17. Align MaxAlign) {
  18. uint64_t LastEnd = 0;
  19. Align ComputedMaxAlign;
  20. for (auto &Field : Fields) {
  21. assert(Field.hasFixedOffset() &&
  22. "didn't assign a fixed offset to field");
  23. assert(isAligned(Field.Alignment, Field.Offset) &&
  24. "didn't assign a correctly-aligned offset to field");
  25. assert(Field.Offset >= LastEnd &&
  26. "didn't assign offsets in ascending order");
  27. LastEnd = Field.getEndOffset();
  28. assert(Field.Alignment <= MaxAlign &&
  29. "didn't compute MaxAlign correctly");
  30. ComputedMaxAlign = std::max(Field.Alignment, MaxAlign);
  31. }
  32. assert(LastEnd == Size && "didn't compute LastEnd correctly");
  33. assert(ComputedMaxAlign == MaxAlign && "didn't compute MaxAlign correctly");
  34. }
  35. #endif
  36. std::pair<uint64_t, Align>
  37. llvm::performOptimizedStructLayout(MutableArrayRef<Field> Fields) {
  38. #ifndef NDEBUG
  39. // Do some simple precondition checks.
  40. {
  41. bool InFixedPrefix = true;
  42. size_t LastEnd = 0;
  43. for (auto &Field : Fields) {
  44. assert(Field.Size > 0 && "field of zero size");
  45. if (Field.hasFixedOffset()) {
  46. assert(InFixedPrefix &&
  47. "fixed-offset fields are not a strict prefix of array");
  48. assert(LastEnd <= Field.Offset &&
  49. "fixed-offset fields overlap or are not in order");
  50. LastEnd = Field.getEndOffset();
  51. assert(LastEnd > Field.Offset &&
  52. "overflow in fixed-offset end offset");
  53. } else {
  54. InFixedPrefix = false;
  55. }
  56. }
  57. }
  58. #endif
  59. // Do an initial pass over the fields.
  60. Align MaxAlign;
  61. // Find the first flexible-offset field, tracking MaxAlign.
  62. auto FirstFlexible = Fields.begin(), E = Fields.end();
  63. while (FirstFlexible != E && FirstFlexible->hasFixedOffset()) {
  64. MaxAlign = std::max(MaxAlign, FirstFlexible->Alignment);
  65. ++FirstFlexible;
  66. }
  67. // If there are no flexible fields, we're done.
  68. if (FirstFlexible == E) {
  69. uint64_t Size = 0;
  70. if (!Fields.empty())
  71. Size = Fields.back().getEndOffset();
  72. #ifndef NDEBUG
  73. checkValidLayout(Fields, Size, MaxAlign);
  74. #endif
  75. return std::make_pair(Size, MaxAlign);
  76. }
  77. // Walk over the flexible-offset fields, tracking MaxAlign and
  78. // assigning them a unique number in order of their appearance.
  79. // We'll use this unique number in the comparison below so that
  80. // we can use array_pod_sort, which isn't stable. We won't use it
  81. // past that point.
  82. {
  83. uintptr_t UniqueNumber = 0;
  84. for (auto I = FirstFlexible; I != E; ++I) {
  85. I->Scratch = reinterpret_cast<void*>(UniqueNumber++);
  86. MaxAlign = std::max(MaxAlign, I->Alignment);
  87. }
  88. }
  89. // Sort the flexible elements in order of decreasing alignment,
  90. // then decreasing size, and then the original order as recorded
  91. // in Scratch. The decreasing-size aspect of this is only really
  92. // important if we get into the gap-filling stage below, but it
  93. // doesn't hurt here.
  94. array_pod_sort(FirstFlexible, E,
  95. [](const Field *lhs, const Field *rhs) -> int {
  96. // Decreasing alignment.
  97. if (lhs->Alignment != rhs->Alignment)
  98. return (lhs->Alignment < rhs->Alignment ? 1 : -1);
  99. // Decreasing size.
  100. if (lhs->Size != rhs->Size)
  101. return (lhs->Size < rhs->Size ? 1 : -1);
  102. // Original order.
  103. auto lhsNumber = reinterpret_cast<uintptr_t>(lhs->Scratch);
  104. auto rhsNumber = reinterpret_cast<uintptr_t>(rhs->Scratch);
  105. if (lhsNumber != rhsNumber)
  106. return (lhsNumber < rhsNumber ? -1 : 1);
  107. return 0;
  108. });
  109. // Do a quick check for whether that sort alone has given us a perfect
  110. // layout with no interior padding. This is very common: if the
  111. // fixed-layout fields have no interior padding, and they end at a
  112. // sufficiently-aligned offset for all the flexible-layout fields,
  113. // and the flexible-layout fields all have sizes that are multiples
  114. // of their alignment, then this will reliably trigger.
  115. {
  116. bool HasPadding = false;
  117. uint64_t LastEnd = 0;
  118. // Walk the fixed-offset fields.
  119. for (auto I = Fields.begin(); I != FirstFlexible; ++I) {
  120. assert(I->hasFixedOffset());
  121. if (LastEnd != I->Offset) {
  122. HasPadding = true;
  123. break;
  124. }
  125. LastEnd = I->getEndOffset();
  126. }
  127. // Walk the flexible-offset fields, optimistically assigning fixed
  128. // offsets. Note that we maintain a strict division between the
  129. // fixed-offset and flexible-offset fields, so if we end up
  130. // discovering padding later in this loop, we can just abandon this
  131. // work and we'll ignore the offsets we already assigned.
  132. if (!HasPadding) {
  133. for (auto I = FirstFlexible; I != E; ++I) {
  134. auto Offset = alignTo(LastEnd, I->Alignment);
  135. if (LastEnd != Offset) {
  136. HasPadding = true;
  137. break;
  138. }
  139. I->Offset = Offset;
  140. LastEnd = I->getEndOffset();
  141. }
  142. }
  143. // If we already have a perfect layout, we're done.
  144. if (!HasPadding) {
  145. #ifndef NDEBUG
  146. checkValidLayout(Fields, LastEnd, MaxAlign);
  147. #endif
  148. return std::make_pair(LastEnd, MaxAlign);
  149. }
  150. }
  151. // The algorithm sketch at this point is as follows.
  152. //
  153. // Consider the padding gaps between fixed-offset fields in ascending
  154. // order. Let LastEnd be the offset of the first byte following the
  155. // field before the gap, or 0 if the gap is at the beginning of the
  156. // structure. Find the "best" flexible-offset field according to the
  157. // criteria below. If no such field exists, proceed to the next gap.
  158. // Otherwise, add the field at the first properly-aligned offset for
  159. // that field that is >= LastEnd, then update LastEnd and repeat in
  160. // order to fill any remaining gap following that field.
  161. //
  162. // Next, let LastEnd to be the offset of the first byte following the
  163. // last fixed-offset field, or 0 if there are no fixed-offset fields.
  164. // While there are flexible-offset fields remaining, find the "best"
  165. // flexible-offset field according to the criteria below, add it at
  166. // the first properly-aligned offset for that field that is >= LastEnd,
  167. // and update LastEnd to the first byte following the field.
  168. //
  169. // The "best" field is chosen by the following criteria, considered
  170. // strictly in order:
  171. //
  172. // - When filling a gap betweeen fields, the field must fit.
  173. // - A field is preferred if it requires less padding following LastEnd.
  174. // - A field is preferred if it is more aligned.
  175. // - A field is preferred if it is larger.
  176. // - A field is preferred if it appeared earlier in the initial order.
  177. //
  178. // Minimizing leading padding is a greedy attempt to avoid padding
  179. // entirely. Preferring more-aligned fields is an attempt to eliminate
  180. // stricter constraints earlier, with the idea that weaker alignment
  181. // constraints may be resolvable with less padding elsewhere. These
  182. // These two rules are sufficient to ensure that we get the optimal
  183. // layout in the "C-style" case. Preferring larger fields tends to take
  184. // better advantage of large gaps and may be more likely to have a size
  185. // that's a multiple of a useful alignment. Preferring the initial
  186. // order may help somewhat with locality but is mostly just a way of
  187. // ensuring deterministic output.
  188. //
  189. // Note that this algorithm does not guarantee a minimal layout. Picking
  190. // a larger object greedily may leave a gap that cannot be filled as
  191. // efficiently. Unfortunately, solving this perfectly is an NP-complete
  192. // problem (by reduction from bin-packing: let B_i be the bin sizes and
  193. // O_j be the object sizes; add fixed-offset fields such that the gaps
  194. // between them have size B_i, and add flexible-offset fields with
  195. // alignment 1 and size O_j; if the layout size is equal to the end of
  196. // the last fixed-layout field, the objects fit in the bins; note that
  197. // this doesn't even require the complexity of alignment).
  198. // The implementation below is essentially just an optimized version of
  199. // scanning the list of remaining fields looking for the best, which
  200. // would be O(n^2). In the worst case, it doesn't improve on that.
  201. // However, in practice it'll just scan the array of alignment bins
  202. // and consider the first few elements from one or two bins. The
  203. // number of bins is bounded by a small constant: alignments are powers
  204. // of two that are vanishingly unlikely to be over 64 and fairly unlikely
  205. // to be over 8. And multiple elements only need to be considered when
  206. // filling a gap between fixed-offset fields, which doesn't happen very
  207. // often. We could use a data structure within bins that optimizes for
  208. // finding the best-sized match, but it would require allocating memory
  209. // and copying data, so it's unlikely to be worthwhile.
  210. // Start by organizing the flexible-offset fields into bins according to
  211. // their alignment. We expect a small enough number of bins that we
  212. // don't care about the asymptotic costs of walking this.
  213. struct AlignmentQueue {
  214. /// The minimum size of anything currently in this queue.
  215. uint64_t MinSize;
  216. /// The head of the queue. A singly-linked list. The order here should
  217. /// be consistent with the earlier sort, i.e. the elements should be
  218. /// monotonically descending in size and otherwise in the original order.
  219. ///
  220. /// We remove the queue from the array as soon as this is empty.
  221. OptimizedStructLayoutField *Head;
  222. /// The alignment requirement of the queue.
  223. Align Alignment;
  224. static Field *getNext(Field *Cur) {
  225. return static_cast<Field *>(Cur->Scratch);
  226. }
  227. };
  228. SmallVector<AlignmentQueue, 8> FlexibleFieldsByAlignment;
  229. for (auto I = FirstFlexible; I != E; ) {
  230. auto Head = I;
  231. auto Alignment = I->Alignment;
  232. uint64_t MinSize = I->Size;
  233. auto LastInQueue = I;
  234. for (++I; I != E && I->Alignment == Alignment; ++I) {
  235. LastInQueue->Scratch = I;
  236. LastInQueue = I;
  237. MinSize = std::min(MinSize, I->Size);
  238. }
  239. LastInQueue->Scratch = nullptr;
  240. FlexibleFieldsByAlignment.push_back({MinSize, Head, Alignment});
  241. }
  242. #ifndef NDEBUG
  243. // Verify that we set the queues up correctly.
  244. auto checkQueues = [&]{
  245. bool FirstQueue = true;
  246. Align LastQueueAlignment;
  247. for (auto &Queue : FlexibleFieldsByAlignment) {
  248. assert((FirstQueue || Queue.Alignment < LastQueueAlignment) &&
  249. "bins not in order of descending alignment");
  250. LastQueueAlignment = Queue.Alignment;
  251. FirstQueue = false;
  252. assert(Queue.Head && "queue was empty");
  253. uint64_t LastSize = ~(uint64_t)0;
  254. for (auto I = Queue.Head; I; I = Queue.getNext(I)) {
  255. assert(I->Alignment == Queue.Alignment && "bad field in queue");
  256. assert(I->Size <= LastSize && "queue not in descending size order");
  257. LastSize = I->Size;
  258. }
  259. }
  260. };
  261. checkQueues();
  262. #endif
  263. /// Helper function to remove a field from a queue.
  264. auto spliceFromQueue = [&](AlignmentQueue *Queue, Field *Last, Field *Cur) {
  265. assert(Last ? Queue->getNext(Last) == Cur : Queue->Head == Cur);
  266. // If we're removing Cur from a non-initial position, splice it out
  267. // of the linked list.
  268. if (Last) {
  269. Last->Scratch = Cur->Scratch;
  270. // If Cur was the last field in the list, we need to update MinSize.
  271. // We can just use the last field's size because the list is in
  272. // descending order of size.
  273. if (!Cur->Scratch)
  274. Queue->MinSize = Last->Size;
  275. // Otherwise, replace the head.
  276. } else {
  277. if (auto NewHead = Queue->getNext(Cur))
  278. Queue->Head = NewHead;
  279. // If we just emptied the queue, destroy its bin.
  280. else
  281. FlexibleFieldsByAlignment.erase(Queue);
  282. }
  283. };
  284. // Do layout into a local array. Doing this in-place on Fields is
  285. // not really feasible.
  286. SmallVector<Field, 16> Layout;
  287. Layout.reserve(Fields.size());
  288. // The offset that we're currently looking to insert at (or after).
  289. uint64_t LastEnd = 0;
  290. // Helper function to splice Cur out of the given queue and add it
  291. // to the layout at the given offset.
  292. auto addToLayout = [&](AlignmentQueue *Queue, Field *Last, Field *Cur,
  293. uint64_t Offset) -> bool {
  294. assert(Offset == alignTo(LastEnd, Cur->Alignment));
  295. // Splice out. This potentially invalidates Queue.
  296. spliceFromQueue(Queue, Last, Cur);
  297. // Add Cur to the layout.
  298. Layout.push_back(*Cur);
  299. Layout.back().Offset = Offset;
  300. LastEnd = Layout.back().getEndOffset();
  301. // Always return true so that we can be tail-called.
  302. return true;
  303. };
  304. // Helper function to try to find a field in the given queue that'll
  305. // fit starting at StartOffset but before EndOffset (if present).
  306. // Note that this never fails if EndOffset is not provided.
  307. auto tryAddFillerFromQueue = [&](AlignmentQueue *Queue,
  308. uint64_t StartOffset,
  309. Optional<uint64_t> EndOffset) -> bool {
  310. assert(Queue->Head);
  311. assert(StartOffset == alignTo(LastEnd, Queue->Alignment));
  312. assert(!EndOffset || StartOffset < *EndOffset);
  313. // Figure out the maximum size that a field can be, and ignore this
  314. // queue if there's nothing in it that small.
  315. auto MaxViableSize =
  316. (EndOffset ? *EndOffset - StartOffset : ~(uint64_t)0);
  317. if (Queue->MinSize > MaxViableSize) return false;
  318. // Find the matching field. Note that this should always find
  319. // something because of the MinSize check above.
  320. for (Field *Cur = Queue->Head, *Last = nullptr; true;
  321. Last = Cur, Cur = Queue->getNext(Cur)) {
  322. assert(Cur && "didn't find a match in queue despite its MinSize");
  323. if (Cur->Size <= MaxViableSize)
  324. return addToLayout(Queue, Last, Cur, StartOffset);
  325. }
  326. llvm_unreachable("didn't find a match in queue despite its MinSize");
  327. };
  328. // Helper function to find the "best" flexible-offset field according
  329. // to the criteria described above.
  330. auto tryAddBestField = [&](Optional<uint64_t> BeforeOffset) -> bool {
  331. assert(!BeforeOffset || LastEnd < *BeforeOffset);
  332. auto QueueB = FlexibleFieldsByAlignment.begin();
  333. auto QueueE = FlexibleFieldsByAlignment.end();
  334. // Start by looking for the most-aligned queue that doesn't need any
  335. // leading padding after LastEnd.
  336. auto FirstQueueToSearch = QueueB;
  337. for (; FirstQueueToSearch != QueueE; ++FirstQueueToSearch) {
  338. if (isAligned(FirstQueueToSearch->Alignment, LastEnd))
  339. break;
  340. }
  341. uint64_t Offset = LastEnd;
  342. while (true) {
  343. // Invariant: all of the queues in [FirstQueueToSearch, QueueE)
  344. // require the same initial padding offset.
  345. // Search those queues in descending order of alignment for a
  346. // satisfactory field.
  347. for (auto Queue = FirstQueueToSearch; Queue != QueueE; ++Queue) {
  348. if (tryAddFillerFromQueue(Queue, Offset, BeforeOffset))
  349. return true;
  350. }
  351. // Okay, we don't need to scan those again.
  352. QueueE = FirstQueueToSearch;
  353. // If we started from the first queue, we're done.
  354. if (FirstQueueToSearch == QueueB)
  355. return false;
  356. // Otherwise, scan backwards to find the most-aligned queue that
  357. // still has minimal leading padding after LastEnd. If that
  358. // minimal padding is already at or past the end point, we're done.
  359. --FirstQueueToSearch;
  360. Offset = alignTo(LastEnd, FirstQueueToSearch->Alignment);
  361. if (BeforeOffset && Offset >= *BeforeOffset)
  362. return false;
  363. while (FirstQueueToSearch != QueueB &&
  364. Offset == alignTo(LastEnd, FirstQueueToSearch[-1].Alignment))
  365. --FirstQueueToSearch;
  366. }
  367. };
  368. // Phase 1: fill the gaps between fixed-offset fields with the best
  369. // flexible-offset field that fits.
  370. for (auto I = Fields.begin(); I != FirstFlexible; ++I) {
  371. assert(LastEnd <= I->Offset);
  372. while (LastEnd != I->Offset) {
  373. if (!tryAddBestField(I->Offset))
  374. break;
  375. }
  376. Layout.push_back(*I);
  377. LastEnd = I->getEndOffset();
  378. }
  379. #ifndef NDEBUG
  380. checkQueues();
  381. #endif
  382. // Phase 2: repeatedly add the best flexible-offset field until
  383. // they're all gone.
  384. while (!FlexibleFieldsByAlignment.empty()) {
  385. bool Success = tryAddBestField(None);
  386. assert(Success && "didn't find a field with no fixed limit?");
  387. (void) Success;
  388. }
  389. // Copy the layout back into place.
  390. assert(Layout.size() == Fields.size());
  391. memcpy(Fields.data(), Layout.data(),
  392. Fields.size() * sizeof(OptimizedStructLayoutField));
  393. #ifndef NDEBUG
  394. // Make a final check that the layout is valid.
  395. checkValidLayout(Fields, LastEnd, MaxAlign);
  396. #endif
  397. return std::make_pair(LastEnd, MaxAlign);
  398. }