A new #FreePascal lesson, thanks to #CompilerExplorer. Incrementing a number by ...

@thelastpsion@oldbytes.space

A new #FreePascal lesson, thanks to #CompilerExplorer.

Incrementing a number by an ordinal can be done in a few ways in Free Pascal, but they result in a different number of lines of x86_64 assembly.

Let's say we want to increment i by 1.

PASCAL:
i := i + 1; // ... and ...
i += 1; // produce identical assembly

ASSEMBLY:
movl -16(%rbp),%eax
leal 1(%eax),%eax
movl %eax,-16(%rbp)

However...

PASCAL:
Inc(i);

ASSEMBLY:
addl $1,-16(%rbp)

Granted, this might be before any optimisation takes place, but it's still very interesting to see!

I hadn't realised before today that Inc() will work with numbers other than one. So...

PASCAL:
Inc(i, 2);

ASSEMBLY:
addl $2,-16(%rbp)

It will also work with variables.

Let's say we want to increment i by AInt, an incoming argument.

PASCAL:
i := i + AInt; // ... and ...
i += AInt; // produce identical assembly

ASSEMBLY:
movl -16(%rbp),%eax
movl -8(%rbp),%edx
leal (%eax,%edx),%eax
movl %eax,-16(%rbp)

However...

PASCAL:
Inc(i, AInt);

ASSEMBLY:
movl -8(%rbp),%eax
addl %eax,-16(%rbp)