2

I don't understand a lot of ASM. I recently ran across inline gcc asm which reads:

("rdtsc;movl %%eax,%0":"=m"(x)::"ax","dx")

It looks to me as though that puts the lower 32 bits of the counter in x, a 32-bit unsigned integer. What I don't understand is why would you clobber ax and dx. Is that for synchronization, or for some other reason? I've seen a lot of rdtsc examples but never any that clobber ax and dx.

Also, regarding rdtsc, I read here if you clobber memory then gcc won't reorder the instruction. Is that good advice and do you have any suggestions from preventing reordering of rdtsc instructions?

Thanks

Community
  • 1
  • 1
loop
  • 3,460
  • 5
  • 34
  • 57
  • From [Intel(R) 64 and IA-32 architectures Software Developer's Manual, Volumes 1, 2ABC and 3ABC, vol. 2B, page 4-296](http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-manual-325462.html): "RDTSC - Read Time-Stamp Counter" "Read time-stamp counter into EDX:EAX." – nrz Oct 31 '13 at 06:48
  • 1
    Side note: the output should be processed using constraint too, not with a `mov`. – Jester Oct 31 '13 at 10:22
  • @Jester what do you mean process with constraint? – loop Nov 01 '13 at 17:26
  • @nrz Yes I'm aware of that but why clobber ax,dx? Does that also clobber eax edx? – loop Nov 01 '13 at 17:27
  • 1
    You can delete the `mov` and the `ax` clobber and use `"=a" (x)` or even `"=A" (x)` with `x` being a 64 bit variable. – Jester Nov 01 '13 at 17:52
  • See Jester's advice. `ax` clobber and `mov` are not needed, use `"=a"(x)`. Also I think that `dx` clobber should be replaced with `edx` clobber, as `rdtsc` overwrites `edx:eax`, not only `dx` (`dx` is the low 16 bits part of 32-bit register `edx`). – nrz Nov 02 '13 at 20:07
  • This is just silly code; let gcc store to memory if it wants to, outside the asm statement. See [Get CPU cycle count?](//stackoverflow.com/a/51907627) (and @mysticial's answer there) for correct implementations. (And BTW, no `"=A"` would not be good. It doesn't mean `edx:eax` in 64-bit mode.) – Peter Cordes Aug 18 '18 at 15:50

1 Answers1

1

I'm not an inline asm expert, but, according to what is written here:

  1. The registers used internally by the inline program must be specified as clobber. The RDTSC instructions loads the counter into eax-edx pair, and these registers must be clobbered so that gcc doesn't uses them as caches. I have no idea why ax and dx is clobbered instead of eax and edx, but maybe this is due to my lacked experience with inline asm.

2. Memory must only be clobbered if it is modified unpredictably. Here, the modification address is mentioned explicitly, so that there is no need to clobber memory.

valplo
  • 693
  • 5
  • 13