[fpc-devel] Const optimization is a serious bug

Alexander Klenin klenin at gmail.com
Tue Jul 5 08:55:44 CEST 2011


On Tue, Jul 5, 2011 at 14:02, Chad Berchek <ad100 at vobarian.com> wrote:
> We also have to remember that *probably almost nobody* remembers fixing a bug related to this.
> That's because most people who come up against this bug probably have no clue what is happening and only by making some other changes do they coincidentally "fix" it.
> I propose that for a problem like this you cannot rely on reported incidents to determine how frequent it is.

Yesterday I have initiated a review of the (Delphi) code in one
company I work for, to check for
this issue. So far, we have found two instances of procedures with
non-const string parameters
with the comment to the effect of "do not change to const, or the code
will break".
One of these instances is fairly recent, and the developer who made
the change did remember
that it cost him more than a work-day to fix -- and that was after the
crash report from the client.
The company is now considering outright ban on all const string parameters,
similar to already implemented ban in const interface parameters.

I really think FPC should do better than this.
See also:
http://stackoverflow.com/questions/5851584/are-const-string-parameters-thread-safe
http://chrisbensen.blogspot.com/2007/11/string-parameters-in-delphi.html?showComment=1196373240000#c7340129019635270394

Repeating my proposal from the bug-report
(http://bugs.freepascal.org/view.php?id=19605):
1) Introduce new optimization switch, e.g.  {$OPTIMIZATION CONSTNOREF},
preferably locally-scoped.
2) Include that switch in UNCERTAIN group and disable it by default
3) In certain specific cases, enable the optimization anyway if
it can be proved safe.
4) Enable this optimization *even for non-const parameters* in the same cases.

I hope the last two points can seriously reduce performance hit
(or even gain some improvements) without compromising correctness.
>From the top of my head, I can see following safe cases available
without cross-function analysis:
1) inlined procedures
2) leaf procedures
3) procedures where string parameters are not accessed after the first
call to another function

The last case, while sounding artificial, can be actually quite common
in the setters
for string properties:

procedure TMyObj.SetProp(AValue: String);
begin
  if FProp = AValue then exit;
  FProp := AValue;
  MyObjChanged;
end;

-- 
Alexander S. Klenin



More information about the fpc-devel mailing list