-2

What do I have to write in C to get the assembler to show the imul with one operand? For example:

imul  %ebp
phuclv
  • 37,963
  • 15
  • 156
  • 475
Elcazador
  • 11
  • 3
  • 2
    There's no rule that requires a compiler-writer to use a particular instruction. So there's no answer to your question beyond what might happen to work with a particular compiler at a particular version and release with specific options. So all in all not a useful question. – Gene Apr 03 '16 at 03:59
  • 2
    Possible duplicate of [x86 MUL Instruction from VS 2008/2010](http://stackoverflow.com/questions/4039378/x86-mul-instruction-from-vs-2008-2010) – Peter Cordes Apr 04 '16 at 00:26
  • same question for a different compiler, but has the same answer. – Peter Cordes Apr 04 '16 at 00:26

1 Answers1

4

If you want to write C code so that the compiler emits imul with one operand then the only way is to use widening signed multiplication, i.e. cast the operand(s) to a signed type twice the register length. Hence in 32-bit mode the following code will produce the expected output

long long multiply(int x, int y) {
    return (long long)x * y;
}

Because non-widening multiplication in 2's complement is the same for both signed and unsigned types, compilers will almost always use multi-operand imul as it's faster and more flexible.

In x86_64 compilers use multi-operand imul to produce 64-bit results even when the inputs were only 32-bits because they still typically have better latency and throughput than single-operand imul. As a result you'll also have to use a double-register-width (128-bit) type like above. Clang, ICC and GCC do support that via __int128, though.

The below snippet

__int128_t multiply(long long x, long long y) {
    return  (__int128_t)x * y;
}

will be compiled to

mov     rax, rdi
imul    rsi
ret

If you use MSVC then you can use _umul128 in 64-bit mode

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Your demo left out `-m32`, so gcc just uses a two-operand 64bit `imul`. Also, in posts where you aren't hitting the character limit, non-shortened godbolt links are preferable [to avoid any chance of link-rot](http://meta.stackoverflow.com/a/319594/224132) – Peter Cordes Apr 03 '16 at 22:40
  • @PeterCordes thanks. I put -m32 at first but then removed it to check the x86_64 code and forgot to include it again – phuclv Apr 04 '16 at 03:06