[fpc-devel] Object/Pointer Swap Intrinsic
J. Gareth Moreton
gareth at moreton-family.com
Wed Dec 11 07:26:02 CET 2019
Hi everyone,
I was wondering... is there an intrinsic in Free Pascal that swaps the
pointers stored in two object or pointer variables? That is... something
like "procedure SwapAddresses(var Obj1: TObject; var Obj2: TObject);" so
after it is called, Obj2 now points to Obj1 and vice versa? Under
x86-64, for example, it can be implemented as (Intel notation):
XOR RCX, RDX
XOR RDX, RCX
XOR RCX, RDX
Or just
XCHG RCX, RDX
Both methods take just 3 cycles to perform (faster than transferring the
object data by several orders of magnitude, plus the pointers don't get
dereferenced). But equivalent Pascal code that typecasts the objects or
pointers into PtrUint and then uses the xor operator may not be portable
(e.g. on platforms that don't have pointers and treat objects differently).
I ask this because I've noticed a slightly clever speed-up in parts of
the peephole optimiser where "TmpUsedRegs" contains exactly the
information required to be stored in "UsedRegs" (usually because
"UpdateUsedRegs(TmpUsedRegs, tai(p.Next))" was called and then p was
freed, hence any required call to "UpdateUsedRegs(tai(p.Next))" will
reproduce the same register usage. By simply swapping the pointers
between UsedRegs and TmpUsedRegs, I can immediately treat the contents
of TmpUsedRegs as the live data and repurpose UsedRegs as the new
temporary register tracking. Calls to TransferUsedRegs and
RestoreUsedRegs are slow.
Gareth aka. Kit
More information about the fpc-devel
mailing list