Re: Inline assembly for detecting int32 overflow on IA32 and AMD64

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux