Because __builtin_constant_p() is sometimes (ab)used as a static analyzer, the
documentation should give more details what is expected to work, and what you
should not use it for. (see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36359)

Here is my suggestion, please incorporate it into the gcc 4.4.0 documentation
if you consider it appropriate:
- __builtin_constant_p() can return 1 even if during the execution of the
program it never is a constant
     for example: the optimizer splits the case when a value is zero and
non-zero, and fully expands the zero case, considering the variable is zero.
This doesn't mean that during a real execution the value can ever be zero.
This can happen for example if the optimizer cannot "see" that a certain value
is impossible.

- __builtin_constant_p() is not a static analyzer, as it doesn't offer
soundness or completeness guarantees for the analysis it makes

- when you write optimized code for the __builtin_constant_p() == 1 case,
you should not treat invalid constant values as build time errors, instead you
should fall back to using the generic code at runtime (which should handle the
invalid cases anyway). The reason is because gcc may constant-propagate/expand
a value that may not be reached ever, because of the reasons described above.

   for example, instead of doing this:
     __builtin_constant_p(val) ? (VALID(val) ? OPTIMIZED(val) :
__build_error())
                               :  generic_case(val)
   Do this: 
     (__builtin_constant_p(val) && VALID(val)) ? OPTIMIZED(val) 
                                               : generic_case(val);


What happens if you don't take the above advice: anytime gcc's optimizer is
changed, your code may break


-- 
           Summary: documentation: improve documentation of
                    __builtin_constant_p()
           Product: gcc
           Version: 4.4.0
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P3
         Component: c
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: edwintorok at gmail dot com
 GCC build triplet: x86_64-linux-gnu
  GCC host triplet: x86_64-linux-gnu
GCC target triplet: x86_64-linux-gnu


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38296

Reply via email to