Extend the sprintf optimization to also handle %d, %i and %u directives
whose argument is an INTEGER_CST that fits the type implied by the
length modifier.

New tests were created by Claude.

gcc/ChangeLog:

        * gimple-ssa-sprintf.cc (get_type_tree_for_integer): New,
        factored out from...
        (format_integer): ...here.
        (gimple_fold_builtin_sprintf): Handle %d, %i and %u.
        * tree.cc (build_string_from_int): New.
        * tree.h (build_string_from_int): Declare.

gcc/testsuite/ChangeLog:

        * gcc.dg/tree-ssa/builtin-sprintf-30.c: Add tests for
        integer constants.
        * gcc.dg/tree-ssa/builtin-sprintf-32.c: Ditto.

Signed-off-by: Filip Kastl <[email protected]>
Co-authored-by: Giuliano Belinassi <[email protected]>
Assisted-by: Claude Opus 5.5 <[email protected]>
---
 gcc/gimple-ssa-sprintf.cc                     | 165 ++++++++++++------
 .../gcc.dg/tree-ssa/builtin-sprintf-30.c      |  87 +++++++++
 .../gcc.dg/tree-ssa/builtin-sprintf-32.c      |  20 +++
 gcc/tree.cc                                   |  43 +++++
 gcc/tree.h                                    |   1 +
 5 files changed, 265 insertions(+), 51 deletions(-)

diff --git a/gcc/gimple-ssa-sprintf.cc b/gcc/gimple-ssa-sprintf.cc
index c4ec186a2ec..f2975fbd8ae 100644
--- a/gcc/gimple-ssa-sprintf.cc
+++ b/gcc/gimple-ssa-sprintf.cc
@@ -1239,6 +1239,67 @@ adjust_range_for_overflow (tree dirtype, tree *argmin, 
tree *argmax)
   return true;
 }
 
+/* Get the type of modifier for an integer specifier.  */
+static tree
+get_type_tree_for_integer (bool sign, const directive &dir)
+{
+  tree intmax_type_node;
+  tree uintmax_type_node;
+
+  tree dirtype;
+
+  /* Determine the expected type of the argument from the length
+     modifier.  */
+  switch (dir.modifier)
+    {
+    case FMT_LEN_none:
+      if (dir.specifier == 'p')
+       dirtype = ptr_type_node;
+      else
+       dirtype = sign ? integer_type_node : unsigned_type_node;
+      break;
+
+    case FMT_LEN_h:
+      dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
+      break;
+
+    case FMT_LEN_hh:
+      dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
+      break;
+
+    case FMT_LEN_l:
+      dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
+      break;
+
+    /* FIXME: L is used for doubles, not integers.  Handling this as long long
+       is potentially problematic and may depend of printf implementation.  */
+    case FMT_LEN_L:
+    case FMT_LEN_ll:
+      dirtype = (sign
+                ? long_long_integer_type_node
+                : long_long_unsigned_type_node);
+      break;
+
+    case FMT_LEN_z:
+      dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
+      break;
+
+    case FMT_LEN_t:
+      dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
+      break;
+
+    case FMT_LEN_j:
+      build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
+      dirtype = sign ? intmax_type_node : uintmax_type_node;
+      break;
+
+    default:
+      return NULL_TREE;
+    }
+
+  return dirtype;
+}
+
 /* Return a range representing the minimum and maximum number of bytes
    that the format directive DIR will output for any argument given
    the WIDTH and PRECISION (extracted from DIR).  This function is
@@ -1247,9 +1308,6 @@ adjust_range_for_overflow (tree dirtype, tree *argmin, 
tree *argmax)
 static fmtresult
 format_integer (const directive &dir, tree arg, pointer_query &ptr_qry)
 {
-  tree intmax_type_node;
-  tree uintmax_type_node;
-
   /* Base to format the number in.  */
   int base;
 
@@ -1293,54 +1351,9 @@ format_integer (const directive &dir, tree arg, 
pointer_query &ptr_qry)
   const unsigned adj = (sign | maybebase) + (base == 2 || base == 16);
 
   /* The type of the "formal" argument expected by the directive.  */
-  tree dirtype = NULL_TREE;
-
-  /* Determine the expected type of the argument from the length
-     modifier.  */
-  switch (dir.modifier)
-    {
-    case FMT_LEN_none:
-      if (dir.specifier == 'p')
-       dirtype = ptr_type_node;
-      else
-       dirtype = sign ? integer_type_node : unsigned_type_node;
-      break;
-
-    case FMT_LEN_h:
-      dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
-      break;
-
-    case FMT_LEN_hh:
-      dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
-      break;
-
-    case FMT_LEN_l:
-      dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
-      break;
-
-    case FMT_LEN_L:
-    case FMT_LEN_ll:
-      dirtype = (sign
-                ? long_long_integer_type_node
-                : long_long_unsigned_type_node);
-      break;
-
-    case FMT_LEN_z:
-      dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
-      break;
-
-    case FMT_LEN_t:
-      dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
-      break;
-
-    case FMT_LEN_j:
-      build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
-      dirtype = sign ? intmax_type_node : uintmax_type_node;
-      break;
-
-    default:
-      return fmtresult ();
-    }
+  tree dirtype = get_type_tree_for_integer (sign, dir);
+  if (dirtype == NULL_TREE)
+    return fmtresult ();
 
   /* The type of the argument to the directive, either deduced from
      the actual non-constant argument if one is known, or from
@@ -4394,6 +4407,9 @@ gimple_fold_builtin_sprintf (const call_info &info, 
gimple_stmt_iterator *gsi)
       if (dir.have_any_set_flag () == true)
        return false;
 
+      /* In case of integers, flags if it's signed.  */
+      bool sign = false;
+
       /* Computed length of the string.  */
       tree len = NULL_TREE;
 
@@ -4520,6 +4536,53 @@ gimple_fold_builtin_sprintf (const call_info &info, 
gimple_stmt_iterator *gsi)
                break;
              }
 
+           case 'd':
+           case 'i':
+             sign = true;
+             /* Fallthrough.  */
+
+           case 'u':
+             {
+               /* Don't crash on sprintf (str1, "%u").  */
+               if (!dir.arg)
+                 return false;
+
+               /* If user specified a precision then let's not optimize it.  */
+               if (dir.prec[1] >= 0)
+                 return false;
+
+               /* If the parameter to %d is not known in compile time, then do
+                  not optimize it.  */
+               if (TREE_CODE (dir.arg) != INTEGER_CST)
+                 return false;
+
+               tree dirtype = get_type_tree_for_integer (sign, dir);
+               if (dirtype == NULL_TREE)
+                 return false;
+
+               /* In case the value doesn't fit, give up.  */
+               if (!int_fits_type_p (dir.arg, dirtype))
+                 return false;
+
+               /* Build the string.  */
+               tree str = build_string_from_int (10, dir.arg);
+               tree addr_str = build1 (ADDR_EXPR,
+                                       build_pointer_type (TREE_TYPE (str)),
+                                       str);
+
+               /* Now TREE_STRING_LENGTH returns the SIZE of the string.  So
+                  subtract one so we have its LENGTH.  */
+               size_t str_len = TREE_STRING_LENGTH (str) - 1;
+
+               /* Emit the memcpy.  */
+               len = build_int_cst (sizetype, str_len);
+               gimple *repl = gimple_build_call (fn_memcpy, 3, last_head,
+                                                 addr_str, len);
+               gimple_seq_add_stmt_without_update (&stmts, repl);
+
+               break;
+             }
+
            default:
              /* Unsupported directive.  Abort.  */
              return false;
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c 
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
index d2bb80959b4..b35a6c0d951 100644
--- a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
@@ -183,6 +183,90 @@ test_s_unknown (void)
   T ("hel", "%.3s", vhello);
 }
 
+static void __attribute__ ((noipa))
+test_int (void)
+{
+  TV ("0", "%d", 0);
+  TV ("1", "%d", 1);
+  TV ("-1", "%d", -1);
+  TV ("-42", "%d", -42);
+  TV ("123456", "%i", 123456);
+  TV ("0", "%u", 0u);
+  TV ("7", "%u", 7u);
+
+  /* Precision of zero with a zero argument produces no output.  */
+  TV ("", "%.0d", 0);
+  TV ("", "%.0i", 0);
+  TV ("", "%.0u", 0u);
+  TV ("[]", "[%.0d]", 0);
+  TV ("5", "%.0d", 5);
+  TV ("-5", "%.0d", -5);
+
+  TV ("-128", "%hhd", -128);
+  TV ("127", "%hhd", 127);
+  TV ("255", "%hhu", 255);
+  TV ("-32768", "%hd", -32768);
+  TV ("65535", "%hu", 65535);
+
+  TV ("123", "%zu", (size_t) 123);
+  TV ("-123", "%td", (__PTRDIFF_TYPE__) -123);
+  TV ("-123", "%jd", (__INTMAX_TYPE__) -123);
+  TV ("123", "%ju", (__UINTMAX_TYPE__) 123);
+  TV ("-123", "%ld", -123L);
+  TV ("123", "%lu", 123LU);
+  TV ("-123", "%lld", -123LL);
+  TV ("123", "%llu", 123LLU);
+
+#if __INT_MAX__ == 2147483647
+  TV ("2147483647", "%d", __INT_MAX__);
+  TV ("-2147483648", "%d", -__INT_MAX__ - 1);
+  TV ("2147483647", "%u", (unsigned) __INT_MAX__);
+  TV ("2147483648", "%u", (unsigned) __INT_MAX__ + 1);
+  TV ("4294967295", "%u", -1u);
+  TV ("3000000000", "%u", 3000000000u);
+#endif
+
+#if __LONG_MAX__ == 9223372036854775807L
+  TV ("9223372036854775807", "%ld", __LONG_MAX__);
+  TV ("-9223372036854775808", "%ld", -__LONG_MAX__ - 1);
+  TV ("18446744073709551615", "%lu", -1LU);
+#elif __LONG_MAX__ == 2147483647L
+  TV ("2147483647", "%ld", __LONG_MAX__);
+  TV ("-2147483648", "%ld", -__LONG_MAX__ - 1);
+  TV ("4294967295", "%lu", -1LU);
+#endif
+
+#if __LONG_LONG_MAX__ == 9223372036854775807LL
+  TV ("9223372036854775807", "%lld", __LONG_LONG_MAX__);
+  TV ("-9223372036854775808", "%lld", -__LONG_LONG_MAX__ - 1);
+  TV ("18446744073709551615", "%llu", -1LLU);
+#endif
+}
+
+static void __attribute__ ((noipa))
+test_mixed (int c)
+{
+  const char *s2 = c ? "ab" : "abcd";
+
+  TV ("x=-7, s=abc, u=7.", "x=%d, s=%s, u=%u.", -7, "abc", 7u);
+  TV ("-7abc", "%d%s", -7, "abc");
+  TV ("abc-7", "%s%d", "abc", -7);
+  TV ("1 2 3", "%d %i %u", 1, 2, 3u);
+  TV ("123", "%d%d%d", 1, 2, 3);
+  TV ("he42", "%.2s%d", "hello", 42);
+  TV ("42he", "%d%.2s", 42, "hello");
+  TV ("[42:he]", "[%d:%.2s]", 42, "hello");
+
+  TV (c ? "ab-42" : "abcd-42", "%s%d", s2, -42);
+  TV (c ? "-42ab" : "-42abcd", "%d%s", -42, s2);
+  TV (c ? "<ab|1>" : "<abcd|1>", "<%s|%d>", s2, 1);
+
+  V ("hello-42", "%s%d", vhello, -42);
+  V ("-42hello", "%d%s", -42, vhello);
+  V ("-42hel", "%d%.3s", -42, vhello);
+  V ("hel-42", "%.3s%d", vhello, -42);
+}
+
 /* Directives the folding does not handle must still work.  */
 
 static void __attribute__ ((noipa))
@@ -261,6 +345,9 @@ main (void)
   test_s_range (vzero);
   test_s_range (vone);
   test_s_unknown ();
+  test_int ();
+  test_mixed (vzero);
+  test_mixed (vone);
   test_unhandled (3, 5);
   test_unknown_width (5);
 
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c 
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
index 9ae4cc74cb9..3a4dbf2a090 100644
--- a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
@@ -49,6 +49,26 @@ int f_s_range_ret (char *d, int c)
   return sprintf (d, "%s", c ? "ab" : "abcd");
 }
 
+void f_d (char *d)
+{
+  sprintf (d, "%d", -123);
+}
+
+void f_u (char *d)
+{
+  sprintf (d, "%u", 123u);
+}
+
+int f_d_ret (char *d)
+{
+  return sprintf (d, "%i", 123);
+}
+
+void f_mixed (char *d, const char *s)
+{
+  sprintf (d, "%d:%s:%u", -1, s, 2u);
+}
+
 /* { dg-final { scan-tree-dump-times "__builtin_strnlen" 1 "optimized" } } */
 
 /* Calls expected not to be folded because we don't support these formats so
diff --git a/gcc/tree.cc b/gcc/tree.cc
index 2e46b4bcdaa..7cc80444ccd 100644
--- a/gcc/tree.cc
+++ b/gcc/tree.cc
@@ -2637,6 +2637,49 @@ build_string (unsigned len, const char *str /*= NULL */)
   return s;
 }
 
+/* Given an INTEGER_CST, return a newly constructed STRING_CST node whose value
+   is the string representation of the argument.  */
+tree
+build_string_from_int (int base, tree num)
+{
+  gcc_assert (TREE_CODE (num) == INTEGER_CST);
+
+  char buf[WIDE_INT_PRINT_BUFFER_SIZE];
+  char *dest = buf;
+
+  wide_int value = wi::to_wide (num);
+  signop sign = TYPE_UNSIGNED (TREE_TYPE (num)) ? UNSIGNED : SIGNED;
+
+  switch (base)
+    {
+    case 10:
+      print_dec (value, dest, sign);
+      break;
+
+    /* If we wanted, we could support base 16 like this:
+    case 16:
+      print_hex (value, dest);
+      // Compensate for print_hex always prepending 0x
+      dest += strlen ("0x");
+      break;
+    */
+
+    default:
+      /* Only base 10 currently supported.  */
+      gcc_assert (false);
+    }
+
+  /* Create string tree node.  */
+  size_t size = strlen (dest) + 1;
+  tree string = build_string (size, dest);
+
+  /* Make sure it is an array type of SIZE elements.  */
+  tree const_char_type = build_qualified_type (char_type_node, 
TYPE_QUAL_CONST);
+  TREE_TYPE (string) = build_array_type_nelts (const_char_type, size);
+
+  return string;
+}
+
 /* Return a newly constructed COMPLEX_CST node whose value is
    specified by the real and imaginary parts REAL and IMAG.
    Both REAL and IMAG should be constant nodes.  TYPE, if specified,
diff --git a/gcc/tree.h b/gcc/tree.h
index 73c7d25a22c..c44b007fbcd 100644
--- a/gcc/tree.h
+++ b/gcc/tree.h
@@ -5047,6 +5047,7 @@ extern tree build_zero_cst (tree);
 extern tree build_replicated_int_cst (tree, unsigned, HOST_WIDE_INT);
 extern tree sign_mask_for (tree);
 extern tree build_string (unsigned, const char * = NULL);
+extern tree build_string_from_int (int base, tree);
 extern tree build_poly_int_cst (tree, const poly_wide_int_ref &);
 extern tree build_tree_list (tree, tree CXX_MEM_STAT_INFO);
 extern tree build_tree_list_vec (const vec<tree, va_gc> * CXX_MEM_STAT_INFO);
-- 
2.55.0

Reply via email to