1. The function gimple_fold_builtin_sprintf is only used in
gimple-ssa-sprintf.cc. Move it there and make it private.
2. Previously, gimple_fold_builtin_sprintf only handled cases where the
format string were a directiveless plain string or a single %s. Here
we expand this to be able to handle multiple directives within a single
format string, transforming each directive or plain string into calls
to memcpy and strlen/strnlen if its size is unknown in compilation time.
New tests were generated by Claude.
gcc/ChangeLog:
* gimple-fold.cc (gimple_fold_builtin_sprintf): Move to
gimple_fold_builtin_sprintf and make static.
* gimple-fold.h (gimple_fold_builtin_sprintf): Remove
declaration.
* gimple-ssa-sprintf.cc (directive::have_any_set_flag): New.
(directive::is_plain_format): New.
(directive::create_fmt): New.
(call_info::directives): New.
(format_plain): Forward declare.
(compute_format_length): Store the directives into info.
(gimple_fold_builtin_sprintf): Expand to handle multiple plain
strings %s directives.
(try_simplify_call): Pass info to gimple_fold_builtin_sprintf.
gcc/testsuite/ChangeLog:
* gcc.dg/tree-ssa/builtin-sprintf-30.c: New test.
* gcc.dg/tree-ssa/builtin-sprintf-31.c: New test.
* gcc.dg/tree-ssa/builtin-sprintf-32.c: New test.
Signed-off-by: Filip Kastl <[email protected]>
Co-authored-by: Giuliano Belinassi <[email protected]>
Assisted-by: Claude Opus 5.5 <[email protected]>
---
gcc/gimple-fold.cc | 130 ---------
gcc/gimple-fold.h | 1 -
gcc/gimple-ssa-sprintf.cc | 275 ++++++++++++++++-
.../gcc.dg/tree-ssa/builtin-sprintf-30.c | 276 ++++++++++++++++++
.../gcc.dg/tree-ssa/builtin-sprintf-31.c | 7 +
.../gcc.dg/tree-ssa/builtin-sprintf-32.c | 124 ++++++++
6 files changed, 681 insertions(+), 132 deletions(-)
create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-31.c
create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
diff --git a/gcc/gimple-fold.cc b/gcc/gimple-fold.cc
index 71dd8f1da74..7b0f827ac03 100644
--- a/gcc/gimple-fold.cc
+++ b/gcc/gimple-fold.cc
@@ -3633,136 +3633,6 @@ gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator
*gsi,
return true;
}
-/* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
- ORIG may be null if this is a 2-argument call. We don't attempt to
- simplify calls with more than 3 arguments.
-
- Return true if simplification was possible, otherwise false. */
-
-bool
-gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
-{
- gimple *stmt = gsi_stmt (*gsi);
-
- /* Verify the required arguments in the original call. We deal with two
- types of sprintf() calls: 'sprintf (str, fmt)' and
- 'sprintf (dest, "%s", orig)'. */
- if (gimple_call_num_args (stmt) > 3)
- return false;
-
- tree orig = NULL_TREE;
- if (gimple_call_num_args (stmt) == 3)
- orig = gimple_call_arg (stmt, 2);
-
- /* Check whether the format is a literal string constant. */
- tree fmt = gimple_call_arg (stmt, 1);
- const char *fmt_str = c_getstr (fmt);
- if (fmt_str == NULL)
- return false;
-
- tree dest = gimple_call_arg (stmt, 0);
-
- if (!init_target_chars ())
- return false;
-
- tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
- if (!fn || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
- return false;
-
- /* If the format doesn't contain % args or %%, use strcpy. */
- if (strchr (fmt_str, target_percent) == NULL)
- {
- /* Don't optimize sprintf (buf, "abc", ptr++). */
- if (orig)
- return false;
-
- /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
- 'format' is known to contain no % formats. */
- gimple_seq stmts = NULL;
- gimple *repl = gimple_build_call (fn, 2, dest, fmt);
-
- /* Propagate the NO_WARNING bit to avoid issuing the same
- warning more than once. */
- copy_warning (repl, stmt);
-
- gimple_seq_add_stmt_without_update (&stmts, repl);
- if (tree lhs = gimple_call_lhs (stmt))
- {
- repl = gimple_build_assign (lhs, build_int_cst (TREE_TYPE (lhs),
- strlen (fmt_str)));
- gimple_seq_add_stmt_without_update (&stmts, repl);
- gsi_replace_with_seq_vops (gsi, stmts);
- /* gsi now points at the assignment to the lhs, get a
- stmt iterator to the memcpy call.
- ??? We can't use gsi_for_stmt as that doesn't work when the
- CFG isn't built yet. */
- gimple_stmt_iterator gsi2 = *gsi;
- gsi_prev (&gsi2);
- fold_stmt (&gsi2);
- }
- else
- {
- gsi_replace_with_seq_vops (gsi, stmts);
- fold_stmt (gsi);
- }
- return true;
- }
-
- /* If the format is "%s", use strcpy if the result isn't used. */
- else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
- {
- /* Don't crash on sprintf (str1, "%s"). */
- if (!orig)
- return false;
-
- /* Don't fold calls with source arguments of invalid (nonpointer)
- types. */
- if (!POINTER_TYPE_P (TREE_TYPE (orig)))
- return false;
-
- tree orig_len = NULL_TREE;
- if (gimple_call_lhs (stmt))
- {
- orig_len = get_maxval_strlen (orig, SRK_STRLEN);
- if (!orig_len)
- return false;
- }
-
- /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
- gimple_seq stmts = NULL;
- gimple *repl = gimple_build_call (fn, 2, dest, orig);
-
- /* Propagate the NO_WARNING bit to avoid issuing the same
- warning more than once. */
- copy_warning (repl, stmt);
-
- gimple_seq_add_stmt_without_update (&stmts, repl);
- if (tree lhs = gimple_call_lhs (stmt))
- {
- if (!useless_type_conversion_p (TREE_TYPE (lhs),
- TREE_TYPE (orig_len)))
- orig_len = fold_convert (TREE_TYPE (lhs), orig_len);
- repl = gimple_build_assign (lhs, orig_len);
- gimple_seq_add_stmt_without_update (&stmts, repl);
- gsi_replace_with_seq_vops (gsi, stmts);
- /* gsi now points at the assignment to the lhs, get a
- stmt iterator to the memcpy call.
- ??? We can't use gsi_for_stmt as that doesn't work when the
- CFG isn't built yet. */
- gimple_stmt_iterator gsi2 = *gsi;
- gsi_prev (&gsi2);
- fold_stmt (&gsi2);
- }
- else
- {
- gsi_replace_with_seq_vops (gsi, stmts);
- fold_stmt (gsi);
- }
- return true;
- }
- return false;
-}
-
/* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
attempt to simplify calls with more than 4 arguments.
diff --git a/gcc/gimple-fold.h b/gcc/gimple-fold.h
index 2cb93087712..9a130ac0617 100644
--- a/gcc/gimple-fold.h
+++ b/gcc/gimple-fold.h
@@ -60,7 +60,6 @@ extern tree gimple_get_virt_method_for_vtable (HOST_WIDE_INT,
tree,
unsigned HOST_WIDE_INT,
bool *can_refer = NULL);
extern tree gimple_fold_indirect_ref (tree);
-extern bool gimple_fold_builtin_sprintf (gimple_stmt_iterator *);
extern bool gimple_fold_builtin_snprintf (gimple_stmt_iterator *);
extern bool arith_code_with_undefined_signed_overflow (tree_code);
extern bool gimple_needing_rewrite_undefined (gimple *, bool = false);
diff --git a/gcc/gimple-ssa-sprintf.cc b/gcc/gimple-ssa-sprintf.cc
index b4c1490ed88..c4ec186a2ec 100644
--- a/gcc/gimple-ssa-sprintf.cc
+++ b/gcc/gimple-ssa-sprintf.cc
@@ -555,6 +555,9 @@ get_int_range (tree, gimple *, HOST_WIDE_INT *,
HOST_WIDE_INT *,
bool, HOST_WIDE_INT, range_query *);
struct call_info;
+struct directive;
+
+static fmtresult format_plain (const directive &, tree, pointer_query &);
/* Description of a format directive. A directive is either a plain
string or a conversion specification that starts with '%'. */
@@ -628,6 +631,16 @@ struct directive
&= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
}
+ /* Check if there is any set flag. That means, if the bitfield is != 0. */
+ bool have_any_set_flag () const
+ {
+ unsigned reduce = 0;
+ for (size_t i = 0; i < ARRAY_SIZE (flags); i++)
+ reduce |= flags[i];
+
+ return reduce;
+ }
+
/* Set both bounds of the width range to VAL. */
void set_width (HOST_WIDE_INT val)
{
@@ -663,6 +676,27 @@ struct directive
&& (prec[1] < 0
|| (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
}
+
+ /* Check if the format string is the plain format one, that is without
+ any %. */
+ inline bool is_plain_format () const
+ {
+ return fmtfunc == format_plain;
+ }
+
+ /* Build a string literal representation of this directive and return a tree
+ node representing a pointer to it. */
+ inline tree to_string_literal () const
+ {
+ /* Duplicate string to make sure it is \0-terminated. */
+ char *dup = xstrndup (beg, len);
+
+ /* Create the string tree object. */
+ tree string = build_string_literal (len + 1, dup);
+
+ free (dup);
+ return string;
+ }
};
/* The result of a call to a formatted function. */
@@ -899,6 +933,9 @@ struct call_info
tree format;
const char *fmtstr;
+ /* Vector of stored directives. */
+ auto_vec<directive> directives;
+
/* The location of the format argument. */
location_t fmtloc;
@@ -4077,6 +4114,9 @@ compute_format_length (call_info &info, format_result
*res,
if (!format_directive (info, res, dir, ptr_qry))
return false;
+ /* Remember the directive. */
+ info.directives.safe_push (dir);
+
/* Return success when the directive is zero bytes long and it's
the last thing in the format string (i.e., it's the terminating
nul, which isn't really a directive but handling it as one makes
@@ -4294,6 +4334,239 @@ try_substitute_return_value (gimple_stmt_iterator *gsi,
return removed;
}
+/* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
+ ORIG may be null if this is a 2-argument call. We don't attempt to
+ simplify calls with more than 3 arguments.
+
+ Return true if simplification was possible, otherwise false. */
+
+static bool
+gimple_fold_builtin_sprintf (const call_info &info, gimple_stmt_iterator *gsi)
+{
+ gimple *stmt = gsi_stmt (*gsi);
+ tree dest = gimple_call_arg (stmt, 0);
+
+ if (!init_target_chars ())
+ return false;
+
+ tree fn_strlen = builtin_decl_implicit (BUILT_IN_STRLEN);
+ tree fn_memcpy = builtin_decl_implicit (BUILT_IN_MEMCPY);
+
+ /* This one may not be available, yet still we can optimize some calls even
+ if this is not present. */
+ tree fn_strnlen = builtin_decl_explicit (BUILT_IN_STRNLEN);
+
+ if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
+ return false;
+
+ if (!fn_strlen || !fn_memcpy)
+ return false;
+
+ /* Create a list of statements we will append into. */
+ gimple_seq stmts = NULL;
+
+ /* Create a temporary variable that will point to the beginning of the
+ output sprintf buffer. */
+ tree char_ptr_type = build_pointer_type (char_type_node);
+ tree head_var = create_tmp_var (char_ptr_type, "head");
+ tree last_head = make_ssa_name (head_var, NULL);
+
+ gassign *assign = gimple_build_assign (last_head, dest);
+
+ /* Append the assignment to the beginning of the list. */
+ gimple_seq_add_stmt_without_update (&stmts, assign);
+
+ /* Get the last directive, we can avoid emitting some statements for the last
+ one. */
+ const directive &last_dir = info.directives.last ();
+
+ /* Iterate on every found directive and "compile" into other, cheaper
+ functions if possible. */
+ for (const directive &dir : info.directives)
+ {
+ /* In case this string has a 'width' value, do not optimize because we
+ still not support it. */
+ if (dir.width[0] >= 0 && dir.width[1] > 0)
+ return false;
+
+ /* In case there is a special flag to it, do not optimize it because
+ we don't support it. */
+ if (dir.have_any_set_flag () == true)
+ return false;
+
+ /* Computed length of the string. */
+ tree len = NULL_TREE;
+
+ /* If the format doesn't contain % args or %%, use plain memcpy. */
+ if (dir.is_plain_format ())
+ {
+ tree literal = dir.to_string_literal ();
+
+ size_t dir_len = dir.len;
+
+ /* Create a tree node with the length of the string. */
+ len = build_int_cst (size_type_node, dir_len);
+
+ /* Convert sprintf (str, fmt) into memcpy (str, fmt, len) when
+ 'format' is known to contain no % formats. */
+ gimple *repl = gimple_build_call (fn_memcpy, 3, last_head, literal,
+ len);
+ gimple_seq_add_stmt_without_update (&stmts, repl);
+
+ /* Propagate the NO_WARNING bit to avoid issuing the same
+ warning more than once. */
+ copy_warning (repl, stmt);
+ }
+ else
+ {
+ /* Now handle the specifiers. */
+ switch (dir.specifier)
+ {
+ case 's':
+ {
+ /* Don't crash on sprintf (str1, "%s"). */
+ if (!dir.arg)
+ return false;
+
+ /* Don't fold calls with source arguments of invalid
+ (nonpointer) types. */
+ if (!POINTER_TYPE_P (TREE_TYPE (dir.arg)))
+ return false;
+
+ /* In case we have a precision, we need to take that into
+ account. */
+ if (dir.prec[1] == INT_MAX)
+ return false; /* Unknown precision, better be safe. */
+
+ /* In case the format for %s has any length specifier, then
+ quickly return. */
+ if (dir.modifier != FMT_LEN_none)
+ return false;
+
+ /* Check if we can find the length of the string in compilation
+ time. */
+ c_strlen_data lendata = { };
+ if (get_range_strlen (dir.arg, &lendata, /*eltsize=*/1)
+ && TREE_CODE (lendata.maxlen) == INTEGER_CST
+ && TREE_CODE (lendata.minlen) == INTEGER_CST
+ && tree_int_cst_equal (lendata.maxlen, lendata.minlen))
+ {
+ /* We can. */
+
+ /* When there is no precision indicated, prec is -1. */
+ HOST_WIDE_INT max = dir.prec[1] < 0 ? INT_MAX : dir.prec[1];
+
+ /* Clamp the string if the format says so. */
+ HOST_WIDE_INT clamped_len = tree_to_shwi (lendata.maxlen);
+ if (clamped_len > max)
+ clamped_len = max;
+
+ /* Now we want the minimum between the string length and
+ whatever was specified in the precision. */
+ tree min = build_int_cst (size_type_node, clamped_len);
+
+ /* Now we fold it to len. */
+ len = fold_convert (sizetype, min);
+ }
+ else
+ {
+ /* We can not. Create a call to strlen to find the length
+ of str2. */
+
+ gimple *strlencall;
+ if (dir.prec[1] >= 0)
+ {
+ /* We need strnlen for this. */
+ if (!fn_strnlen)
+ return false;
+
+ /* We have precision. Set a call to strnlen to account
+ for that. */
+ tree precision = build_int_cst (size_type_node,
+ dir.prec[1]);
+ strlencall = gimple_build_call (fn_strnlen, 2, dir.arg,
+ precision);
+ /* At a later pass we might find out that the string
+ length is actually computable in compilation time,
+ and this can issue a warning on strnlen. Hence
+ disable the warning. */
+ suppress_warning (strlencall, OPT_Warray_bounds_);
+ }
+ else
+ {
+ /* No precision. */
+ strlencall = gimple_build_call (fn_strlen, 1, dir.arg);
+ }
+
+ len = make_temp_ssa_name (size_type_node, NULL, "");
+ gimple_call_set_lhs (strlencall, len);
+ gimple_seq_add_stmt_without_update (&stmts, strlencall);
+ }
+
+ /* Convert sprintf (str1, "%s", str2) into
+ memcpy (str1, str2, len). */
+ gimple *repl = gimple_build_call (fn_memcpy, 3, last_head,
+ dir.arg, len);
+ gimple_seq_add_stmt_without_update (&stmts, repl);
+
+ /* Propagate the NO_WARNING bit to avoid issuing the same
+ warning more than once. */
+ copy_warning (repl, stmt);
+
+ /* In case the user provided us broken strings, make sure that
+ -Warray-bounds won't issue a new warning. */
+ suppress_warning (repl, OPT_Warray_bounds_);
+
+ break;
+ }
+
+ default:
+ /* Unsupported directive. Abort. */
+ return false;
+ }
+ }
+
+ /* Update the head pointer if necessary. */
+ if (&dir != &last_dir)
+ {
+ gcc_assert (len != NULL_TREE);
+ tree new_head = make_ssa_name (SSA_NAME_VAR (last_head), NULL);
+ gassign *update_head = gimple_build_assign (new_head,
+ POINTER_PLUS_EXPR,
+ last_head, len);
+ gimple_seq_add_stmt_without_update (&stmts, update_head);
+ last_head = new_head;
+ }
+ }
+
+ /* Compute the return value again. */
+ if (tree lhs = gimple_call_lhs (stmt))
+ {
+ tree len = make_temp_ssa_name (ptrdiff_type_node, NULL, "len");
+
+ /* The number of written bytes is the difference of whatever is in the
+ head pointer and the original buffer, buf - head. */
+ gassign *assign1 = gimple_build_assign (len, POINTER_DIFF_EXPR,
+ last_head, dest);
+
+ gimple_seq_add_stmt_without_update (&stmts, assign1);
+
+ /* Make sure we match the original return type of sprintf. */
+ if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (len)))
+ len = fold_convert (TREE_TYPE (lhs), len);
+
+ /* Replace the original call lhs. */
+ gassign *assign2 = gimple_build_assign (lhs, len);
+
+ gimple_seq_add_stmt_without_update (&stmts, assign2);
+ }
+
+ /* Fold the created list of stmts replacing the original call. */
+ gsi_replace_with_seq_vops (gsi, stmts);
+
+ return true;
+}
+
/* Try to simplify a s{,n}printf call described by INFO with result
RES by replacing it with a simpler and presumably more efficient
call (such as strcpy). */
@@ -4313,7 +4586,7 @@ try_simplify_call (gimple_stmt_iterator *gsi,
return gimple_fold_builtin_snprintf (gsi);
case BUILT_IN_SPRINTF:
- return gimple_fold_builtin_sprintf (gsi);
+ return gimple_fold_builtin_sprintf (info, gsi);
default:
;
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
new file mode 100644
index 00000000000..d2bb80959b4
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-30.c
@@ -0,0 +1,276 @@
+/* Verify that sprintf calls broken into sequences of memcpy calls produce
+ the same output and the same return value as the library sprintf.
+ -fno-printf-return-value prevents the return value from being replaced
+ by a constant computed by the sprintf pass so that the value computed
+ by the folded sequence is the one being checked.
+ { dg-do run }
+ { dg-options "-O2 -Wno-format -Wno-format-zero-length
-fno-printf-return-value" } */
+
+typedef __SIZE_TYPE__ size_t;
+
+#define sprintf(...) __builtin_sprintf (__VA_ARGS__)
+#define putchar(...) __builtin_putchar (__VA_ARGS__)
+#define puts(...) __builtin_puts (__VA_ARGS__)
+
+/* Larger than any output below. */
+#define BUFSIZE 80
+
+volatile int vzero = 0;
+volatile int vone = 1;
+
+const char *volatile vhello = "hello";
+const char *volatile vh = "h";
+const char *volatile vempty = "";
+
+unsigned nfails;
+
+static void __attribute__ ((noipa))
+print_buffer (int n, const char *buf)
+{
+ for (int i = 0; i < n; ++i)
+ if (buf[i] == '\0')
+ putchar('$');
+ else
+ putchar(buf[i]);
+ putchar('\n');
+}
+
+/* Check that BUF contains the string EXPECT and that the byte past its
+ terminating nul has not been clobbered. Unless N is negative, also
+ check that N, the value returned by sprintf, equals the length of
+ EXPECT. */
+
+static void __attribute__ ((noipa))
+check (int line, const char *buf, int n, const char *expect)
+{
+ size_t len = __builtin_strlen (expect);
+
+ if ((n >= 0 && (size_t) n != len)
+ || __builtin_memcmp (buf, expect, len + 1) != 0
+ || buf[len + 1] != 'X')
+ {
+ __builtin_printf ("line %i: sprintf returned %i, wrote \"%s\"; "
+ "expected %i, \"%s\"\n",
+ line, n, buf, (int) len, expect);
+ puts("Written buffer: ");
+ print_buffer(BUFSIZE, buf);
+ ++nfails;
+ }
+}
+
+/* Call sprintf and check both its output and its return value. */
+#define T(expect, ...) \
+ do { \
+ char buf[BUFSIZE]; \
+ __builtin_memset (buf, 'X', sizeof buf); \
+ buf[sizeof buf - 1] = '\0'; \
+ int n = sprintf (buf, __VA_ARGS__); \
+ check (__LINE__, buf, n, expect); \
+ } while (0)
+
+/* Call sprintf ignoring its return value and check its output. */
+#define V(expect, ...) \
+ do { \
+ char buf[BUFSIZE]; \
+ __builtin_memset (buf, 'X', sizeof buf); \
+ buf[sizeof buf - 1] = '\0'; \
+ sprintf (buf, __VA_ARGS__); \
+ check (__LINE__, buf, -1, expect); \
+ } while (0)
+
+/* Do both of the above. */
+#define TV(expect, ...) \
+ do { \
+ T (expect, __VA_ARGS__); \
+ V (expect, __VA_ARGS__); \
+ } while (0)
+
+static void __attribute__ ((noipa))
+test_plain (void)
+{
+ TV ("a", "a");
+ TV ("hello", "hello");
+ TV ("hello world", "hello world");
+ TV ("", "");
+}
+
+static void __attribute__ ((noipa))
+test_s_const (void)
+{
+ TV ("", "%s", "");
+ TV ("a", "%s", "a");
+ TV ("hello", "%s", "hello");
+ TV ("x", "%sx", "");
+ TV ("x", "x%s", "");
+ TV ("<abc>", "<%s>", "abc");
+ TV ("abc>", "%s>", "abc");
+ TV ("<abc", "<%s", "abc");
+ TV ("abcdef", "%s%s", "abc", "def");
+ TV ("a-b-c", "%s-%s-%s", "a", "b", "c");
+ TV ("abc", "%s%s%s", "", "abc", "");
+}
+
+static void __attribute__ ((noipa))
+test_s_const_prec (void)
+{
+ TV ("", "%.0s", "hello");
+ TV ("[]", "[%.0s]", "hello");
+ TV ("h", "%.1s", "hello");
+ TV ("he", "%.2s", "hello");
+ TV ("he!", "%.2s!", "hello");
+ TV ("!he", "!%.2s", "hello");
+ TV ("hello", "%.5s", "hello");
+ TV ("hello", "%.6s", "hello");
+ TV ("hello", "%.10s", "hello");
+ TV ("hello!", "%.10s!", "hello");
+ TV ("helworld", "%.3s%s", "hello", "world");
+ TV ("hellowor", "%s%.3s", "hello", "world");
+ TV ("helwor", "%.3s%.3s", "hello", "world");
+ TV ("he-wo", "%.2s-%.2s", "hello", "world");
+}
+
+/* Strings whose length is not constant but is bounded, so the return
+ value of sprintf is still known to be in range and the call can be
+ folded even when its result is used. */
+
+static void __attribute__ ((noipa))
+test_s_range (int c)
+{
+ const char *s2 = c ? "ab" : "abcd";
+ const char *s5 = c ? "ab" : "abcde";
+
+ TV (c ? "ab" : "abcd", "%s", s2);
+ TV (c ? "<ab>" : "<abcd>", "<%s>", s2);
+ TV (c ? "ab>" : "abcd>", "%s>", s2);
+ TV (c ? "<ab" : "<abcd", "<%s", s2);
+ TV (c ? "abab" : "abcdabcd", "%s%s", s2, s2);
+ TV (c ? "ab-ab" : "abcd-abcd", "%s-%s", s2, s2);
+
+ TV (c ? "ab" : "abc", "%.3s", s5);
+ TV (c ? "ab." : "abc.", "%.3s.", s5);
+ TV (c ? ".ab" : ".abc", ".%.3s", s5);
+ TV (c ? "abab" : "abcabcde", "%.3s%s", s5, s5);
+ TV (c ? "abab" : "abcdeabc", "%s%.3s", s5, s5);
+ TV ("", "%.0s", s5);
+ TV ("[]", "[%.0s]", s5);
+ TV (c ? "ab" : "abcde", "%.5s", s5);
+ TV (c ? "ab" : "abcde", "%.9s", s5);
+}
+
+/* Strings whose length is not known at all. The return value of these
+ calls cannot be folded, so only check the output. */
+
+static void __attribute__ ((noipa))
+test_s_unknown (void)
+{
+ V ("hello", "%s", vhello);
+ V ("", "%s", vempty);
+ V ("[hello]", "[%s]", vhello);
+ V ("hellohello", "%s%s", vhello, vhello);
+
+ V ("hel", "%.3s", vhello);
+ V ("h", "%.3s", vh);
+ V ("", "%.3s", vempty);
+ V ("", "%.0s", vhello);
+ V ("[hel]", "[%.3s]", vhello);
+ V ("hel!", "%.3s!", vhello);
+ V ("helhello", "%.3s%s", vhello, vhello);
+ V ("hellohel", "%s%.3s", vhello, vhello);
+ V ("hhello", "%.3s%s", vh, vhello);
+
+ /* The result is used but the call must still produce correct output. */
+ T ("hello", "%s", vhello);
+ T ("hel", "%.3s", vhello);
+}
+
+/* Directives the folding does not handle must still work. */
+
+static void __attribute__ ((noipa))
+test_unhandled (int i, int w)
+{
+ TV ("%", "%%");
+ TV ("100%", "100%%");
+ TV ("a", "%c", 'a');
+ TV ("ff", "%x", 255);
+ TV ("17", "%o", 15);
+ TV ("+5", "%+d", 5);
+ TV (" 5", "% d", 5);
+ TV (" ab", "%5s", "ab");
+ TV ("ab ", "%-5s", "ab");
+ TV ("00042", "%05d", 42);
+ TV ("007", "%.3d", 7);
+ TV ("hel", "%.*s", i, "hello");
+ TV (" ab", "%*s", 5, "ab");
+ TV (" ab", "%*s", w, "ab");
+ TV ("ab ", "%*s", -w, "ab");
+ TV ("[ ab]", "[%*s]", w, "ab");
+ TV (" 42", "%*d", w, 42);
+ TV (" he", "%*.2s", w, "hello");
+ TV ("3", "%d", i);
+ TV ("x3", "%s%d", "x", i);
+ TV ("3x", "%d%s", i, "x");
+}
+
+/* Same as above but with a destination of unknown size, so that the calls
+ are not rejected for possibly overflowing it. */
+
+static void __attribute__ ((noipa))
+sprintf_width_s (char *d, int w, const char *s)
+{
+ sprintf (d, "%*s", w, s);
+}
+
+static void __attribute__ ((noipa))
+sprintf_width_d (char *d, int w)
+{
+ sprintf (d, "%*d", w, 42);
+}
+
+static void __attribute__ ((noipa))
+sprintf_width_prec_s (char *d, int w, const char *s)
+{
+ sprintf (d, "[%*.2s]", w, s);
+}
+
+/* Call FUNC (BUF, ARGS...) and check its output. */
+#define F(expect, func, ...) \
+ do { \
+ char buf[BUFSIZE]; \
+ __builtin_memset (buf, 'X', sizeof buf); \
+ buf[sizeof buf - 1] = '\0'; \
+ func (buf, __VA_ARGS__); \
+ check (__LINE__, buf, -1, expect); \
+ } while (0)
+
+static void __attribute__ ((noipa))
+test_unknown_width (int w)
+{
+ F (" ab", sprintf_width_s, w, "ab");
+ F ("ab ", sprintf_width_s, -w, "ab");
+ F ("ab", sprintf_width_s, 0, "ab");
+ F (" 42", sprintf_width_d, w);
+ F ("[ he]", sprintf_width_prec_s, w, "hello");
+}
+
+int
+main (void)
+{
+ test_plain ();
+ test_s_const ();
+ test_s_const_prec ();
+ test_s_range (vzero);
+ test_s_range (vone);
+ test_s_unknown ();
+ test_unhandled (3, 5);
+ test_unknown_width (5);
+
+ /* Return failure rather than calling abort so that the output
+ describing the failures is flushed. */
+ if (nfails)
+ {
+ __builtin_printf ("%u failures\n", nfails);
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-31.c
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-31.c
new file mode 100644
index 00000000000..8ee9050d029
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-31.c
@@ -0,0 +1,7 @@
+/* Same as builtin-sprintf-30.c but with -fprintf-return-value enabled, so
+ that calls whose return value is known are folded into memcpy without
+ a left hand side.
+ { dg-do run }
+ { dg-options "-O2 -Wno-format -Wno-format-zero-length
-fprintf-return-value" } */
+
+#include "builtin-sprintf-30.c"
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
new file mode 100644
index 00000000000..9ae4cc74cb9
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/builtin-sprintf-32.c
@@ -0,0 +1,124 @@
+/* Verify which sprintf calls are folded into sequences of memcpy calls
+ and which are left alone.
+ { dg-do compile }
+ { dg-options "-O2 -Wno-format -fno-printf-return-value
-fdump-tree-optimized" } */
+
+typedef __SIZE_TYPE__ size_t;
+
+#define sprintf(...) __builtin_sprintf (__VA_ARGS__)
+
+/* Calls expected to be folded. */
+
+void f_plain (char *d)
+{
+ sprintf (d, "hello");
+}
+
+int f_plain_ret (char *d)
+{
+ return sprintf (d, "hello");
+}
+
+void f_s (char *d, const char *s)
+{
+ sprintf (d, "%s", s);
+}
+
+void f_s_plain (char *d, const char *s)
+{
+ sprintf (d, "<%s>", s);
+}
+
+void f_s_s (char *d, const char *s, const char *t)
+{
+ sprintf (d, "%s%s", s, t);
+}
+
+void f_s_prec (char *d, const char *s)
+{
+ sprintf (d, "%.3s", s);
+}
+
+void f_s_prec_const (char *d)
+{
+ sprintf (d, "%.3s", "hello");
+}
+
+int f_s_range_ret (char *d, int c)
+{
+ return sprintf (d, "%s", c ? "ab" : "abcd");
+}
+
+/* { dg-final { scan-tree-dump-times "__builtin_strnlen" 1 "optimized" } } */
+
+/* Calls expected not to be folded because we don't support these formats so
+ far. */
+
+void g_d_var (char *d, int i)
+{
+ sprintf (d, "%d", i);
+}
+
+void g_width (char *d, const char *s)
+{
+ sprintf (d, "%5s", s);
+}
+
+void g_width_star (char *d, int w, const char *s)
+{
+ sprintf (d, "%*s", w, s);
+}
+
+void g_prec_star (char *d, int p, const char *s)
+{
+ sprintf (d, "%.*s", p, s);
+}
+
+void g_flag_minus (char *d, const char *s)
+{
+ sprintf (d, "%-s", s);
+}
+
+void g_flag_plus (char *d)
+{
+ sprintf (d, "%+d", 1);
+}
+
+void g_flag_zero (char *d)
+{
+ sprintf (d, "%05d", 1);
+}
+
+void g_int_prec (char *d)
+{
+ sprintf (d, "%.3d", 1);
+}
+
+void g_x (char *d)
+{
+ sprintf (d, "%x", 255);
+}
+
+void g_c (char *d)
+{
+ sprintf (d, "%c", 'a');
+}
+
+void g_percent (char *d)
+{
+ sprintf (d, "100%%");
+}
+
+void g_mixed_var (char *d, const char *s, int i)
+{
+ sprintf (d, "%s%d", s, i);
+}
+
+/* The length of S is unknown and so is the return value. */
+
+int g_s_ret (char *d, const char *s)
+{
+ return sprintf (d, "%s", s);
+}
+
+/* { dg-final { scan-tree-dump-times "sprintf \\(" 13 "optimized" } } */
--
2.55.0