2

I have found this little piece of C gem in the gcc torture tests suite, and more or less I understand it, except the lines marked with my comments ...

void __attribute__((noinline,noclone))
foo(int *p, float *q) { __asm__ volatile ("" : : : "memory"); } /// ??? 1

int main()
{
  if (sizeof (int) == sizeof (float))
    {
      int i;
      float f;
      int *p;
      /* Prevent i and f from being rewritten into SSA form. */
      foo (&i, &f);
      i = 0;
      f = 1.0;
      p = (int *)&f;
      __builtin_memcpy (&i, p, 4);     /// ??? 2
      if (*(float *)&i != 1.0)
        __builtin_abort ();
    }
  return 0;
}

So, question number 1:

What is this __asm__ volatile ("" : : : "memory"); ? Didn't see this syntax till now ...

Question number 2:

Since __builtin_memcpy feels to me as being a function where is this defined? The full source code compiles and runs as it is, (without any extra includes and libraries) so I'm dazed ... Is there a set of __builtin*** functions which are available via gcc, without using any library?

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167

2 Answers2

6

__asm__ volatile is a way to write your own inline asm code, and the volatile bit means that gcc can't delete it. Check this answer for links & details.
The function, then is written in asm, and the use of the (GCC specific attribute) noinline means that this code won't be inlined by the compiler. In case you're wondering.

__builtin_memcpy is a GCC built-in (obviously) version of the memcpy function. Sometimes, though, the regular, standard memcpy function will be used, or the other way around (memcpy can be "optimized" by gcc, and result in a __builtin_memcpy call).
The use of this is debatable, and writing code that targets specific compiler extensions isn't really a great idea, but given that this code is part of the gcc torture test suite, it makes sense to use the __buitlin*functions explicitly, as in some cases, they could well perform worse than the standard functions

Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
3

What is this asm volatile ("" : : : "memory"); ?

This baisically means that the assembly code will be executed where you expect it to execute. Compiler is informed not to reorder instructions around it.

From the wiki:

These barriers prevent a compiler from reordering instructions, they do not prevent reordering by CPU.

You may also find the details about this syntax Volatile ...?.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • for that syntax question, basicly it is inline assembler in C: http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html#s4 , this one having the impact you stated – Najzero Mar 03 '14 at 12:37