Assembly ADD Instruction
In x86-64 assembly language, the ADD
instruction is used to add two operands and store the result in a destination operand. ADD
is an arithmetic instruction, specifically used for addition operations.
The syntax for the ADD
instruction is shown below and requires two operands, a source and destination:
ADD <destination>, <source>
Here, destination
is the operand where the result will be stored, while source
is the operand that will be added to the destination.
Both the destination
and source
operands can be either registers or memory locations. In addition, the source operand may be an ‘immediate’ – a number used directly in the code.
For example, the following code adds the values in the rax
and rbx
registers and stores the result in the rax
register:
ADD rax, rbx
If we want to add an immediate to the value in a register, we can do this using the source operand. The following example will add 5 to the value in rax:
ADD rax, 5
Let’s see how ADD works using a more complete example:
MOV rax, 1 ; set rax to '1'
MOV rbx, 2 ; set rbx to '2'
ADD rax, rbx ; rax will now equal '3'
ADD rax, 5 ; rax will now equal '8'
In this example, we use the MOV instruction to set the rax register equal to 1 and rbx equal to 2.
One thing to keep in mind about the ADD instruction is that it does rewrite the value in the destination operand.
However, there are several tactics that we can use to prevent overwriting a value stored in a location that we will need later.
- If we only need to keep one value, we can simply switch the source and destination operands so that we are overwriting the one of our choosing.
- If we need to keep the values stored in both operands, we can simply copy one of the values to a third location (either in memory or a register) and then use that as the destination operand.
Preserving the Value of a Register While Using the ADD Instruction
In the following example, we want to retain the values of rax and rbx, so we use a third register (rcx) to function as the destination operand for the ADD instruction:
MOV rax, 1
MOV rbx, 2
MOV rcx, rax
ADD rcx, rbx ; rcx will now equal '3'
Note that this works because MOV produces a copy of the original value and does not change the value of rax. Following the execution of this code:
- rax will equal 1
- rbx will equal 2
- rcx will equal 3.
This strategy allows us to retain the ‘original’ values of rax and rbx, and it only cost us one additional instruction.