[libc-commits] [libc] [libc][malloc] Align blocks to max_align_t. (PR #100279)

via libc-commits libc-commits at lists.llvm.org
Tue Jul 23 16:29:50 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Daniel Thornburgh (mysterymath)

<details>
<summary>Changes</summary>

Since there are two offsets from block start to usable area, this ensures that the usable area is maximally aligned, so long as the offset type size is no less than half the max alignment. This is true on at least typical 32-bit and 64-bit targets.

Previously, there was a roughly 50-50 chance a given block's usable area would be misaligned for a malloc on a 32-bit system. The half that were misaligned would require at least one block of additional padding, costing 12 bytes. With this change, the only cost is 0-4 bytes at the beginning of the heap to reach an initial 8-byte alignment.

---
Full diff: https://github.com/llvm/llvm-project/pull/100279.diff


1 Files Affected:

- (modified) libc/src/__support/block.h (+6-3) 


``````````diff
diff --git a/libc/src/__support/block.h b/libc/src/__support/block.h
index af3ce181f1c99..86cb4bd7ad582 100644
--- a/libc/src/__support/block.h
+++ b/libc/src/__support/block.h
@@ -102,9 +102,12 @@ using cpp::optional;
 ///                       types can address more memory, but consume greater
 ///                       overhead.
 /// @tparam   kAlign      Sets the overall alignment for blocks. Minimum is
-///                       `alignof(OffsetType)` (the default). Larger values
-///                       cause greater overhead.
-template <typename OffsetType = uintptr_t, size_t kAlign = alignof(OffsetType)>
+///                       `alignof(OffsetType)`, but the default is max_align_t,
+///                       since the usable space will then already be
+///                       aligned to max_align_t if the size of OffsetType is no
+///                       less than half of max_align_t. Larger values cause
+///                       greater overhead.
+template <typename OffsetType = uintptr_t, size_t kAlign = alignof(max_align_t)>
 class Block {
   // Masks for the contents of the next_ field.
   static constexpr size_t USED_MASK = 1 << 0;

``````````

</details>


https://github.com/llvm/llvm-project/pull/100279


More information about the libc-commits mailing list