I tried to speed up an arbitrary-precision decimal record by replacing its dynamic-array field with a pointer to a reference-counted block, managed through Initialize, Finalize, AddRef and Copy. A micro-benchmark showed 8 ns per operation against 39 ns for the dynamic-array record, because the RTTI-driven fpc_initialize, fpc_finalize and fpc_copy calls disappear. The change compiled, but the test suite hung and returned wrong numbers. The cause is that the compiler does not call the operators as the wiki describes.
Environment: FPC 3.2.4 (rc2 build), aarch64, macOS. The results are the same at -O- and -O3. I have not tried other targets or trunk.
Faults (I counted references in a global array, so nothing touches freed memory):
1. Record without Copy: B := A does not call AddRef. The count stays at 1 and reaches -1 after both variables are finalized (a double free). The wiki says AddRef is called after the bitwise copy on assignment.
2. Record without Copy: A := Default(T) does not call Finalize on the old value of A (leak).
3. Record without Copy: B := A does not call Finalize on the old value of B (leak).
4. Record with all four operators: GA := MakeC(6), where GA is a variable of the main program block and MakeC returns a record through Result, leaves the count at 2 instead of 1. The temporary is not finalized after Copy. The same statement with a local variable in a procedure is correct.
Without Copy you get faults 1 to 3, and with Copy you get fault 4, so I found no operator set that works correctly.
Cases that work as documented: variable-to-variable assignment with Copy, a function that does Result := X, by-value parameters without Copy, and release at scope exit.
The test case is one stand-alone file using only the RTL. It prints ok or FAIL for each case, and on my machine it prints eight FAIL lines and exits with code 1. A fixed compiler should print ok on every line.
The full write-up, with the code and its output, is at
https://github.com/lscoughlin/TBigDecimal/blob/main/doc/management-operators.md. The test case file is
https://github.com/lscoughlin/TBigDecimal/blob/main/tests/fpcbugs/ManagementOperators.lpr.
I also found the open report
https://gitlab.com/freepascal.org/fpc/source/-/issues/40392 (double Finalize with nested functions, FPC 3.3.1). The symptom is different, and I do not know whether it shares a cause with these four.
Questions:
- Has anyone seen the same on other targets or on trunk?
- Is fault 1 (no AddRef on assignment without Copy) intended behavior?