[fpc-devel] XML node dump feature
J. Gareth Moreton
gareth at moreton-family.com
Tue Jun 25 10:40:30 CEST 2019
Initially, F probably wouldn't be optimised because 'arg' is not
constant. However, if F were marked as inline (not pure) and its actual
parameter is a constant (say, 5, for the sake of argument), then there
is definitely potential for optimisation, since it would be expanded to
the following:
s := 0;
for i := 0 to 100 do
s := s + PureFunc(5);
Result := s;
In this case, PureFunc(5) would be replaced with its pre-calculated
result, and some node analysis could potentially replace the entire
for-loop with s := s + x, where x is equal to 101 * PureFunc(5), since
it's now dealing with simple numbers.
Now for the case where F is not pure or inline, it may take a bit more
thought in allowing the compiler to detect the mathematical equivalence
and replace the for-loop with s := s + 101 * PureFunc(arg), but it's
certainly doable. Going back to the original subject title, this is one
reason why I pushed to get the XML node dump feature implemented,
because it provides valuable research data for the development of such
optimisations. Such an optimisation may have to be -O4 though because
of a side-effect with range check errors - if the error is handled, s
might contain a different value to what is expected (e.g. if s was
initially $7FFFFFF0 and PureFunc(arg) = 1, then assuming s isn't written
to before the error is raised, it will still contain $7FFFFFF0 rather
than $7FFFFFFF that would occur if the for-loop ran a few times).
Long story short, it took me a brief moment to see how the optimisation
would work until I thought about it a bit more, but if PureFunc is
indeed pure, then that could certainly be a development goal.
Thank you very much for that!
Gareth aka. Kit
On 25/06/2019 09:19, denisgolovan wrote:
>> Can I have an example of "hoisting pure functions out of loops" that you
>> speak of?
> Sure.
> I mean something like following (completely artificial example):
>
> function PureFunc1: ...
> function F(arg: Integer): Integer;
> var s:Integer;
> begin
> s:=0;
> for i:=0 to 100 do
> s:=s+PureFunc(arg);
> Result:=s;
> end;
>
> Of course, the real value of pure functions for optimization oppotunities is some combination of generics and closures, but that's completely another story...
>
---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus
More information about the fpc-devel
mailing list