This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Inline assembly for detecting int32 overflow on IA32 and AMD64
- From: Adam Warner <lists at consulting dot net dot nz>
- To: gcc-help at gcc dot gnu dot org
- Date: Thu, 20 Jan 2005 17:47:09 +1300
- Subject: Re: Inline assembly for detecting int32 overflow on IA32 and AMD64
- References: <pan.2005.01.18.04.06.12.280929@consulting.net.nz>
Thanks for the brilliant response Thorsten (via email, which I just
discovered).
A fixed solution is:
#include <stdint.h>
#include <stdio.h>
inline int32_t add(int32_t a, int32_t b) {
signed char overflow;
int32_t sum=a;
__asm__ __volatile__("add %[src], %[dest] \n\t" \
"seto %[overflow] \n"
: [dest] "+R" (sum), [overflow] "=m" (overflow)
: [src] "g" (b)
: "cc");
printf("sum is %i\n", sum);
if (overflow) printf("Overflow\n");
else printf("No Overflow\n");
return sum;
}
int main(void) {
add(0x7FFFFFFF, 0);
add(0x7FFFFFFF, 1);
return 0;
}
I made a number of mistakes:
1. The [dest] should be a read/write variable.
2. I clobbered the condition code (cc) so I should tell gcc this.
3. The condition code may change between assembly blocks so it has to be
written as a single block.
Many thanks Thorsten.
Thorsten used seto instead of branch on overflow because branch
mispredictions are usually expensive on modern CPUs.
Posting to gcc help can be a bit hit and miss. The NNTP version (via
news.individual.net) doesn't appear to propagate to the mailing list
(which I'm posting to via the news.gmane.org NNTP interface).
Regards,
Adam