From b053e90d5db4e9fe844d1dd1203792197873d51f Mon Sep 17 00:00:00 2001
From: Tomas Kalibera <tomas.kalibera@gmail.com>
Date: Mon, 16 May 2022 06:43:09 -0400
Subject: [PATCH] c-family: Let stdio.h override built in printf format
 [PR95130,PR92292]

Mingw32 targets use ms_printf format for printf, but mingw-w64 when
configured for UCRT uses gnu_format (via stdio.h).  GCC checks both formats,
which means that one gets a warning twice if the format string violates both
formats:

  printf("Hello %lu\n", (long long unsigned) x);

Fixed by disabling the built in format in case there are additional ones.

This fixes also prevents issues if the print formats disagree.  In the past
it was the case when printing 64-bit integers, but GCC ms_printf format since
c51f1e7427e6a5ae2a6d82b5a790df77a3adc99 supports %llu.

gcc/c-family/ChangeLog:

	PR c/95130
	PR c/92292

	* c-format.cc (check_function_format): For builtin functions with a
	  built in format and at least one more, do not check the first one.
---
 gcc/c-family/c-format.cc | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)

diff --git a/gcc/c-family/c-format.cc b/gcc/c-family/c-format.cc
index 01adea4ff41..613b7c827bb 100644
--- a/gcc/c-family/c-format.cc
+++ b/gcc/c-family/c-format.cc
@@ -1173,9 +1173,10 @@ void
 check_function_format (const_tree fn, tree attrs, int nargs,
 		       tree *argarray, vec<location_t> *arglocs)
 {
-  tree a;
+  tree a, aa;
 
   tree atname = get_identifier ("format");
+  bool skipped_default_format = false;
 
   /* See if this function has any format attributes.  */
   for (a = attrs; a; a = TREE_CHAIN (a))
@@ -1186,6 +1187,32 @@ check_function_format (const_tree fn, tree attrs, int nargs,
 	  function_format_info info;
 	  decode_format_attr (fn, atname, TREE_VALUE (a), &info,
 			      /*validated=*/true);
+
+	  /* Mingw32 targets have traditionally used ms_printf format for the
+	     printf function, and this format is built in GCC. But nowadays,
+	     if mingw-w64 is configured to target UCRT, the printf function
+	     uses the gnu_printf format (specified in the stdio.h header). This
+	     causes GCC to check both formats, which means that GCC would
+	     warn twice about the same issue when both formats are violated,
+	     e.g. for %lu used to print long long unsigned.
+
+	     Hence, if there are multiple format specifiers, we skip the first
+	     one. See PR 95130 (but note that GCC ms_printf already supports
+	     %llu) and PR 92292.  */
+
+	  if (!skipped_default_format && fn && TREE_CODE (fn) == FUNCTION_DECL)
+	    {
+	      for(aa = TREE_CHAIN (a); aa; aa = TREE_CHAIN (aa))
+		if (is_attribute_p ("format", get_attribute_name (aa))
+		    && fndecl_built_in_p (fn, BUILT_IN_NORMAL))
+		  {
+		    skipped_default_format = true;
+		    break;
+		  }
+	      if (skipped_default_format)
+		continue;
+	    }
+
 	  if (warn_format)
 	    {
 	      /* FIXME: Rewrite all the internal functions in this file
-- 
2.38.1

