title: Using AARCH64 assembly to write a memcpy
body: <p>How would one go about writing a function which would copy a given number of bytes from a given source to a given destination in AARCH64 assembly language? This would basically be like memcpy, but with some additional assumptions.</p>
  
  <ol>
  <li>The source and destination are aligned on 16 byte boundaries</li>
  <li>The memory regions do not overlap</li>
  <li>The count is a multiple of 16</li>
  <li>The instructions must fit within 80 bytes</li>
  </ol>
  
  <p>The best resource I have found so far is <a href="https://code.woboq.org/userspace/glibc/sysdeps/aarch64/memcpy.S.html" rel="nofollow noreferrer">this source code for memcpy</a>, but I don't understand which parts are relevant to the specific parameters I was given.</p>
  
  <p>EDIT: So far I've tried converting the following function in C into assembly.</p>
  
  <pre><code>void memcpy80(unsigned char* dest, unsigned char* sourc, unsigned long count)
  {
  unsigned char* end = sourc + count;
  while (sourc &lt; end)
      *(dest++) = *(sourc++)
  }
  </code></pre>
  
  <p>I then tried to boil that down into a version that fits the specification like so:</p>
  
  <pre><code>memcpy80:
      add x3, x1, x2
  loopstart:
      cmp x3, x1
      //how do I branch to loopend if x1 &gt; x3?
      add x0, x0, 1
      add x1, x1, 1
      ldr x4, [x1]
      str x4, [x0]
      b loopstart
  loopend:
      ret
  </code></pre>
  
  <p>What would be the instruction to use to branch to the end of the loop? And then what else would I need to change to comply with the spec?</p>
  
  <p>This would be optimized on 64-bit ARMv8-a architecture. There's nothing in the spec to say that smaller or larger sizes are more common. There are no benefits to having a code-size smaller than 80B, so going right up to the limit for the sake of greater efficiency would be ideal.</p>