Page 1 of 1

QEMU invalid opcode exception, only when compiled using -O2

Posted: Thu Mar 27, 2014 10:30 pm
by alaroldai
Hey guys, I've encountered an unexpected "Invalid Opcode" exception being raised in my kernel code, that only appears when:
  • running the code in QEMU (to be fair, I haven't actually tried any other emulators/hardware)
  • the code is compiled with -O2 or higher. If compiled with -O0 or -O1, no exception is raised.
Obviously clang is outputting some opcodes that qemu doesn't support, but I'm unsure as to how to work around this. I'd like to avoid compiling with a lower optimization level, if possible.

The relevant code seems fairly innocuous - it's just filling values in an array of bitmaps:

Code: Select all

for (uint32_t i = 0; i < kNumBitmapEntries; i++) {
    if (i > map_index) {
        bitmaps[i] = ~0;
    } else {
        bitmaps[i] = 0;
    }
}
Which is being translated into the following assembly:

Code: Select all

.LBB4_1:
	movd	%edx, %xmm4
	pshufd	$0, %xmm4, %xmm4
	movdqa	%xmm4, %xmm5
	paddd	%xmm1, %xmm5
	paddd	%xmm2, %xmm4
	pxor	%xmm3, %xmm5
	pcmpgtd	%xmm0, %xmm5
	pxor	%xmm3, %xmm4
	pcmpgtd	%xmm0, %xmm4
	movdqu	%xmm5, bitmaps(,%edx,4)
	movdqu	%xmm4, bitmaps+16(,%edx,4)
	addl	$8, %edx
	cmpl	$32768, %edx
	jne	.LBB4_1
Have any of you had trouble with unsupported opcodes in qemu before?

Re: QEMU invalid opcode exception, only when compiled using

Posted: Thu Mar 27, 2014 10:54 pm
by Brendan
Hi,

Which architecture is your compiler optimising for (e.g. is it optimising for "host 80x86 CPU that has SSE") and does the CPU emulated by Qemu have all the same features?
alaroldai wrote:Which is being translated into the following assembly:
That code expects SSE2.


Cheers,

Brendan

Re: QEMU invalid opcode exception, only when compiled using

Posted: Thu Mar 27, 2014 11:00 pm
by thepowersgang
Pretty easy, it's compiling into SSE code, but you haven't enabled SSE yet, hence you get an invalid opcode excepion. I'd suggest adding '-fno-sse' to the compile options (or whatever the option is, I forget atm)

(Partially ninja'd by Brendan)

Re: QEMU invalid opcode exception, only when compiled using

Posted: Thu Mar 27, 2014 11:58 pm
by alaroldai
Thanks, guys - I've added code to enable SSE if it's available, and it seems to work as expected.

Cheers!
Alastair