[libc-commits] [libc] [libc] Add aligned_alloc (PR #96586)

Nick Desaulniers via libc-commits libc-commits at lists.llvm.org
Tue Jun 25 09:02:00 PDT 2024


================
@@ -261,6 +262,40 @@ class Block {
 
   constexpr Block(size_t prev_outer_size, size_t outer_size);
 
+  bool usable_space_is_aligned(size_t alignment) const {
+    return reinterpret_cast<uintptr_t>(usable_space()) % alignment == 0;
+  }
+
+  size_t extra_space_for_adjustment(size_t alignment) const {
+    if (usable_space_is_aligned(alignment))
+      return 0;
+
+    // We need to ensure we can always split this block into a "padding" block
+    // and the aligned block. To do this, we need enough extra space for at
+    // least one block.
+    //
+    // |block   |usable_space                          |
+    // |........|......................................|
+    //                            ^
+    //                            Alignment requirement
+    //
+    //
+    // |block   |space   |block   |usable_space        |
+    // |........|........|........|....................|
+    //                            ^
+    //                            Alignment requirement
+    //
+    uintptr_t start = reinterpret_cast<uintptr_t>(usable_space());
+    alignment = cpp::max(alignment, ALIGNMENT);
+    size_t adjustment = align_up(start + BLOCK_OVERHEAD, alignment) - start;
+    return adjustment;
----------------
nickdesaulniers wrote:

```suggestion
    return align_up(start + BLOCK_OVERHEAD, alignment) - start;
```

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


More information about the libc-commits mailing list