[PATCH] D119177: [demangler] Fix buffer growth

Nathan Sidwell via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Thu Feb 10 04:48:55 PST 2022


urnathan updated this revision to Diff 407477.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119177/new/

https://reviews.llvm.org/D119177

Files:
  libcxxabi/src/demangle/Utility.h
  llvm/include/llvm/Demangle/Utility.h


Index: llvm/include/llvm/Demangle/Utility.h
===================================================================
--- llvm/include/llvm/Demangle/Utility.h
+++ llvm/include/llvm/Demangle/Utility.h
@@ -33,12 +33,14 @@
   size_t CurrentPosition = 0;
   size_t BufferCapacity = 0;
 
-  // Ensure there is at least n more positions in buffer.
+  // Ensure there are at least N more positions in the buffer.
   void grow(size_t N) {
-    if (N + CurrentPosition >= BufferCapacity) {
-      BufferCapacity *= 2;
-      if (BufferCapacity < N + CurrentPosition)
-        BufferCapacity = N + CurrentPosition;
+    size_t Need = N + CurrentPosition;
+    if (Need > BufferCapacity) {
+      // Avoid many reallocations during startup, with a bit of hysteresis.
+      constexpr size_t MinInitAlloc = 1024;
+      Need = std::max(Need, MinInitAlloc);
+      BufferCapacity = std::max(Need, BufferCapacity * 2);
       Buffer = static_cast<char *>(std::realloc(Buffer, BufferCapacity));
       if (Buffer == nullptr)
         std::terminate();
Index: libcxxabi/src/demangle/Utility.h
===================================================================
--- libcxxabi/src/demangle/Utility.h
+++ libcxxabi/src/demangle/Utility.h
@@ -33,12 +33,14 @@
   size_t CurrentPosition = 0;
   size_t BufferCapacity = 0;
 
-  // Ensure there is at least n more positions in buffer.
+  // Ensure there are at least N more positions in the buffer.
   void grow(size_t N) {
-    if (N + CurrentPosition >= BufferCapacity) {
-      BufferCapacity *= 2;
-      if (BufferCapacity < N + CurrentPosition)
-        BufferCapacity = N + CurrentPosition;
+    size_t Need = N + CurrentPosition;
+    if (Need > BufferCapacity) {
+      // Avoid many reallocations during startup, with a bit of hysteresis.
+      constexpr size_t MinInitAlloc = 1024;
+      Need = std::max(Need, MinInitAlloc);
+      BufferCapacity = std::max(Need, BufferCapacity * 2);
       Buffer = static_cast<char *>(std::realloc(Buffer, BufferCapacity));
       if (Buffer == nullptr)
         std::terminate();


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D119177.407477.patch
Type: text/x-patch
Size: 2050 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20220210/64710457/attachment.bin>


More information about the llvm-commits mailing list