3.5.Arithmetic and Logical Operations
\(3.5.\)Arithmetic and Logical Operations
1.Load Effective Address
- The
leaq
instruction doesn't reference memory at all. Instead of reading from the designated location, it copies the effective address to the destination.
The instruction can be used to generate pointers for later
memory reference. For example, if register %rdx
represents \(x\), then
leaq 7(%rdx, %rdx, 4), %rdx
will set %rdx
to
\(5x+7\).
2.Unary & Binary Operations
Operations in the first group are unary operations:
The single operand serves as both source and destination.
This operand can be either a register or a memory location.
The second group consists of binary operations.
- The second operand is used as both a source and a destination, the first operand is another operand.
This syntax is reminiscent of the C assignment operators, such as
x -= y
.
- The first operand can be either an immediate value, a register, or a memory location. The second can be either a register or a memory location.
The operation:
xor %rcx %rcx
is simply to set
3.Shift operations
The shift amount is either an immediate value or a single-byte register
%cl
.In x86-64, if the data values are \(w\) bits, then its shift amount will be the low-order \(m\) bits of
%cl
, where \(2^m=w\). For example, when%cl
has value 0xFF, thensalb
would shift by 7, whilesalw
would shift by 15.
\(e.g.\)(Convert 64-bits into 32-bits)
\(solution:\)
- The
movl %esi %ecx
is worth noting. Because we only need 4 bytes of data, we can usemovl
operation to set the low-order 32 bits ofrcx
to%esi
while high-order 32 bits to 0. Since we only need the low-order 4 bytes, doing this implies that the high-order 4 bytes is meaningless, which makes code safer, more accurate and more readable.
4.Special Arithmetic Operations
\(a.\)"One-operand" multiply
The mulq
(unsigned) and imulq
(signed) can
also act as "one-operand" instructions to compute the full
128-bits product of 2 64-bits values.
One of the multiplicand is value in
%rax
, another is the operand.The product is stored in
%rdx
(high-order 64 bits) and%rax
(low-order 64 bits).
We will need to take two steps to store an oct word:
\(e.g.\)
\(b.\)Division
For a division,
%rdx
stores the remainder and%rax
stores the quotient.For most applications of 64-bit addition, the dividend is given as a 64-bit value. The bits of
%rdx
should then be set to either all zeros (unsigned arithmetic) or the sign bit of %rax (signed arithmetic).The former can be implemented by
movl $0 %reg
, this can set upper 8 bytes of diviend to 0.The latter can be implemented by
cqto
. It takes no operands, implicitly reads the sign bit from %rax and copies it across all of %rdx.
\(e.g.\)(Signed and Unsigned)