https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103176

--- Comment #5 from Eric Gallager <egallager at gcc dot gnu.org> ---
(In reply to Martin Sebor from comment #4) 
> Adding the following just before the definition of the string o prevents the
> warning.  Another alternative is to make both length and the loop control
> variable unsigned (making variables that represent sizes unsigned and
> keeping them that is a good practice since it communicates that constraint
> to the compiler).
> 
>               if (length < 0)
>                 __builtin_unreachable ();
> 
> In general, unless the compiler can prove that some expression won't reach a
> value that's invalid in some context, it can substitute the value for it in
> the process of optimizing surrounding code, which can then lead to the
> invalid code materializing even if it's not actually in the original source
> and even if the emitted invalid object code isn't reachable.  GCC warnings
> that are designed to look for this invalid code then trigger on it. 
> Resolving these warnings can often help GCC generate better object code (the
> __builtin_unreachable() trick isn't necessarily always the best way; it's
> only appropriate if the precondition is in the source and GCC loses track of
> it).  Long story short, there is nothing for us to do to.

I wonder if it'd be possible to get the warning to emit a note saying "note:
make this variable unsigned to avoid this warning" or something? It'd be
helpful if the compiler could communicate how to fix warnings like this to the
user so they don't get confused and end up having to file bug reports to find
out what's going on...

(...or maybe add a more general purpose "-Wsuggest-types" flag that suggests
changing the types of variables based on common heuristics such as the one
expressed here? e.g. making sizes unsigned, or possibly using VRP to suggest
the smallest type that can contain all values that the variable can be proved
to ever possibly hold... see for example bug 78798 where I called it
"-Wsuggest-bool")

Reply via email to