title: Fastest way to swap alternate bytes on ARM Cortex M4 using gcc
body: <p>I need to swap alternate bytes in a buffer as quickly as possible in an embedded system using ARM Cortex M4 processor. I use gcc. The amount of data is variable but the max is a little over 2K. it doesn't matter if a few extra bytes are converted because I can use an over-sized buffer.</p>
  
  <p>I know that the ARM has the <code>REV16</code> instruction, which I can use to swap alternate bytes in a 32-bit word. What I don't know is:</p>
  
  <ol>
  <li><p>Is there a way of getting at this instruction in gcc without resorting to assembler? The <code>__builtin_bswap16</code> intrinsic appears to operate on 16-bit words only. Converting 4 bytes at a time will surely be faster than converting 2 bytes.</p></li>
  <li><p>Does the Cortex M4 have a reorder buffer and/or do register renaming? If not, what do I need to do to minimise pipeline stalls when I convert the dwords of the buffer in a partially-unrolled loop? </p></li>
  </ol>
  
  <p>For example, is this code efficient, where <code>REV16</code> is appropriately defined to resolve (1):</p>
  
  <pre><code>uint32_t *buf = ... ;
  size_t n = ... ;  // (number of bytes to convert + 15)/16
  for (size_t i = 0; i &lt; n; ++i)
  {
      uint32_t a = buf[0];
      uint32_t b = buf[1];
      uint32_t c = buf[2];
      uint32_t d = buf[3];
      REV16(a, a);
      REV16(b, b);
      REV16(c, c);
      REV16(d, d);
      buf[0] = a;
      buf[1] = b;
      buf[2] = c;
      buf[3] = d;
      buf += 4;
  }
  </code></pre>