Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q39 #62

Closed
Anding opened this issue Mar 7, 2018 · 1 comment
Closed

Q39 #62

Anding opened this issue Mar 7, 2018 · 1 comment

Comments

@Anding
Copy link

Anding commented Mar 7, 2018

How do we multiply rax by 9 using exactly one instruction?

Would this be acceptable as an alternative?

IMUL rax, 9
@sayon
Copy link
Collaborator

sayon commented Mar 11, 2018

For a long time it was impossible to use IMUL with more than one operand. Now there is a form that to multiply a register in one command it:

IMUL r64, r/m64, imm32 (from Intel reference manual, volume 2)

So the alternative using imul is possible, but it will look like that:

imul rax, rax, 9

lea is still used by compilers to multiply to certain constants, because it is faster than imul

For example:

/* main.c */
int start( int c ) {
   return c * 9;
}

Compiling with optimizations on without linking with C standard lib (avoids cluttering the disassembly):

> gcc -O3 main.c -o main
> objdump -M intel-mnemonic -d main
main:     file format elf64-x86-64


Disassembly of section .text:

0000000000400150 <_start>:
  400150:	8d 04 ff             	lea    eax,[rdi+rdi*8]
  400153:	c3                   	ret    

A less optimized code can implement the same functionality by using e.g. shifts and adds, which is still faster than imul.

@Anding Anding closed this as completed Mar 17, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants