https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105676
--- Comment #3 from Jan Hubicka <hubicka at gcc dot gnu.org> ---
Such code is not that obviously safe.  It is possible that getval will get
inlined to some calls and not other within single function.  In that case the
calling function will read and modify cache variable and will assume that these
are not changed across uninlined calls to getval.

After inlinning GCC might see something like:

        if (cache == -1)
                cache = do_expensive_calculation();
        val = getval ();

So now the question is whether one can convince gcc to duplicate and re-order
the code into something like:

        if (cache == -1)
                val = getval ();
                cache = do_expensive_calculation();
        else
                val = getval ();

which technically is valid transformation given what GCC is given and would
result in duplicatd expensive calculation.  I am not sure how to make this
happen.

tracer pass may be convinced to do the duplication:

        if (cache == -1)
                cache = do_expensive_calculation();
                val = getval ();
        else
                val = getval ();

but I don't think we currently have transform that will reorder val = getval()
the way I need.  This does not promise we won't have in future.  For example it
would be good optimizations to swap calls here:
__attribute__ ((const)) test(int);
__attribute__ ((const)) test2(int);

int ret (int a, int e)
{
        int c = test2 (2);
        int b = test (1);
        return c + b/e;
}

since division is a long operation and would benefit from b being ready earlier
than c.  It is kind of defect of our scheduler that we don't seem to do that.

I will look at the confused warning.  We should not suggest pure when function
is already const and I tought we already check for that.

I think we may want extra attribute for such caching functions.  Internally GCC
should make difference between "I can remove repeated calls to this function"
and "this function have no side effects".

Reply via email to