[llvm] [APInt] remove getClearedMemory and improve slow initialization (PR #106945)

Princeton Ferro via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 3 10:08:55 PDT 2024


https://github.com/Prince781 updated https://github.com/llvm/llvm-project/pull/106945

>From 55df297e264bb52ff2ffff1a9fe0a8b270ee5f0a Mon Sep 17 00:00:00 2001
From: Princeton Ferro <pferro at nvidia.com>
Date: Sun, 1 Sep 2024 22:03:50 -0700
Subject: [PATCH] [APInt] avoid extra memset in initialization

The purpose is to save an extra memset in both cases:

1. When int64_t(val) < 0, zeroing out is redundant as the subsequent
   for-loop will initialize to val .. 0xFFFFF ..... Instead we should
   only create an uninitialized buffer, and transform the slow for-loop
   into a memset to initialize the higher words to 0xFF.
2. In the other case, first we create an uninitialized array (new
   int64_t[]) and then we zero it out with memset. But this can be
   combined in one operation with new int64_t[](), which
   default-initializes the array.
---
 llvm/lib/Support/APInt.cpp | 19 ++++++++++---------
 1 file changed, 10 insertions(+), 9 deletions(-)

diff --git a/llvm/lib/Support/APInt.cpp b/llvm/lib/Support/APInt.cpp
index fe22e9ba04b6f5..fa1ca03b0eb7c5 100644
--- a/llvm/lib/Support/APInt.cpp
+++ b/llvm/lib/Support/APInt.cpp
@@ -34,9 +34,7 @@ using namespace llvm;
 /// A utility function for allocating memory, checking for allocation failures,
 /// and ensuring the contents are zeroed.
 inline static uint64_t* getClearedMemory(unsigned numWords) {
-  uint64_t *result = new uint64_t[numWords];
-  memset(result, 0, numWords * sizeof(uint64_t));
-  return result;
+  return new uint64_t[numWords]();
 }
 
 /// A utility function for allocating memory and checking for allocation
@@ -74,12 +72,15 @@ inline static unsigned getDigit(char cdigit, uint8_t radix) {
 
 
 void APInt::initSlowCase(uint64_t val, bool isSigned) {
-  U.pVal = getClearedMemory(getNumWords());
-  U.pVal[0] = val;
-  if (isSigned && int64_t(val) < 0)
-    for (unsigned i = 1; i < getNumWords(); ++i)
-      U.pVal[i] = WORDTYPE_MAX;
-  clearUnusedBits();
+  if (isSigned && int64_t(val) < 0) {
+    U.pVal = getMemory(getNumWords());
+    U.pVal[0] = val;
+    memset(&U.pVal[1], 0xFF, APINT_WORD_SIZE * (getNumWords() - 1));
+    clearUnusedBits();
+  } else {
+    U.pVal = getClearedMemory(getNumWords());
+    U.pVal[0] = val;
+  }
 }
 
 void APInt::initSlowCase(const APInt& that) {



More information about the llvm-commits mailing list