[fpc-devel] Optimization breaks check for overridden function / Is there a better way to check?
Sven Barth
pascaldragon at googlemail.com
Tue Oct 21 00:18:01 CEST 2025
Martin Frb via fpc-devel <fpc-devel at lists.freepascal.org> schrieb am Mo.,
20. Okt. 2025, 22:29:
> On 17/10/2025 21:15, Sven Barth via fpc-devel wrote:
> >> What is the best way to check if a virtual function in a base class
> >> has been overridden by a class that inherits the base class?
> >>
> >> In LCL TPrinter.pas the following check is used:
> >>
> >>
> >> procedure TPrinter.NewPage;
> >> begin
> >> Inc(fPageNumber);
> >> if TMethod(@Self.DoNewPage).Code = Pointer(@TPrinter.DoNewPage) then
> >> begin
> >> ..
> >> end
> >> ..
> >> end
> >>
> >> We have run across an optimization problem with the TCocoaPrinter
> >> class and that TPrinter code.
> >>
> >> TCocoaPrinter = class(TPrinter)
> >>
> >> with no override of DeNewPage
> >
> > David's problem is *not* due to a corruction or a bug, but due to an
> > optimization that FPC performs that leads to different behavior,
> > namely changing virtual methods that are empty to EmptyMethod to
> > reduce the number of duplicate (empty) methods in the binary.
>
> I am trying to figure out under which circumstances this would happen?
> TPrinter = class...
> procedure DoNewPage; virtual;
>
> And the check really only makes sense for virtual methods. Well (in
> generics that differs, but for non virtual, both classes are known at
> compiletime).
>
> So if it is a virtual method:
>
> If the compiler optimizes @TPrinter.DoNewPage to EmptyMethod, then it
> would put that into the class definition?
> So that is into the VMT?
> And there is only one VMT?
> And self is a pointer (to pointer) to that one VMT?
>
> So then how can one be replaced, but the other not?
>
If one is compiled with -O3, but the other is compiled with -O2. The VMT is
created for each type, so even if a method isn't overridden it can be
replaced in one VMT, but not in the other.
In this case I suspect the LCL and thus TPrinter is compiled with -O2 and
the custom code with -O3.
Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20251021/3bf13ddb/attachment.htm>
More information about the fpc-devel
mailing list