patch to suggest putc/fputs over printf("string") or printf("\n")

Ulrich Drepper drepper@cygnus.com
Mon Jan 11 14:05:00 GMT 1999


Jeffrey A Law <law@hurl.cygnus.com> writes:

> Simlarly if via attributes we can determine the string has no formatting
> chars, then we can make the transformation.

No, this is exactly the problem.  Via the attributes we can see the
format string and *suggest* optimizations.  But we cannot perform them
automatically since the string the compiler sees need not be the one
used at runtime.

	printf (gettext ("string with format"));

The compiler is able to see "string with format" as the format string
argument to printf and therefore could decide to use fputs.  But this
fails (note: a new case I found!) if the translation contains a format
element.  This can either be in one of the strange cases I've
mentioned before or simply like this

	gettext ("string with format") -> "some string with %%"

Now the program has a different behaviour after the "optimization".

If the compiler warns about this, the programmer will be able to
replace printf with fputs in the sources and the translator will
replace %% by %.  Note that the percent could stand for something else
but itself, e.g, in escape sequences to select character sets.

> Not getting an optimal solution from the start does not prevent us
> from working on these kinds of optimizations.  Sorry if you feel
> differently.

The point is not not getting an optimal solution from the start.
Optimizations like optimizing string operations can never be optimized
sufficently.  The compiler must always assume the worst case.

   cp = my_malloc (100);
   sprintf (cp, "foo");
   strcat (cp, "bar");

The compiler itself can never rewrite this to

   cp = my_malloc (100); 
   memcpy (mempcpy (cp, "foo", 3), "bar", 4);

since it cannot assume that there are no side-effects on buf.  There
are sequence points in this instructions sequence which cannot easily
be removed.

This means there is no "we will handle the other optimizations later".


So let's compromise: make the automatic code rewrite optional.  Let it
be automatically included for -O2 or -O3 or whatever.  But if
-Wwarn-constant-print (or however you want to call it) is given and in
the case gettext is used, print a warning instead of replacing the
code automatically.

-- 
---------------.      drepper at gnu.org  ,-.   1325 Chesapeake Terrace
Ulrich Drepper  \    ,-------------------'   \  Sunnyvale, CA 94089 USA
Cygnus Solutions `--' drepper at cygnus.com   `------------------------



More information about the Gcc-patches mailing list