title: C/С++. Why could a simple integer addition on a volatile be translated to a different asm instruction on gcc and clang?
body: <p>I wrote a simple loop:</p>
  
  <pre><code>int volatile value = 0;
  
  void loop(int limit) {
    for (int i = 0; i &lt; limit; ++i) { 
        ++value;
    }
  }
  </code></pre>
  
  <p>I compiled this with gcc and clang(<code>-O3 -fno-unroll-loops</code>) and got different outputs. They differ in <code>++value</code> part:</p>
  
  <p><strong>clang:</strong></p>
  
  <pre><code>  add dword ptr [rip + value], 1 # ++value
    add edi, -1                    # --limit
    jne .LBB0_1                    # if limit &gt; 0 then continue looping
  </code></pre>
  
  <p><strong>gcc:</strong></p>
  
  <pre><code>  mov eax, DWORD PTR value[rip] # copy value to a register
    add edx, 1                    # ++i
    add eax, 1                    # increment a copy of value
    mov DWORD PTR value[rip], eax # store incremented copy to value, i. e. ++value
    cmp edi, edx                  # compare i &lt; limit
    jne .L3                       # if i &lt; limit then continue looping
  </code></pre>
  
  <p>C and C++ versions are same on each compiler(<a href="https://gcc.godbolt.org/z/5x5jGP" rel="nofollow noreferrer">https://gcc.godbolt.org/z/5x5jGP</a>)
  So my questions are:</p>
  
  <p>1) Is gcc doing something wrong? What is the point of copying the <code>value</code>?</p>
  
  <p>2) I have <a href="http://quick-bench.com/3p68ACK08i0BrqNlNMr8Ufpx0jk" rel="nofollow noreferrer">benchmarked</a> that code and for some reason the profiler shows that in gcc's version 73% of time is wasted on instruction <code>add edx, 1</code>, 13% on <code>mov DWORD PTR value[rip], eax</code> and 13% on <code>cmp edi, edx</code>. Am I interpreting this results wrong? Why other addition and move instructions take less than 1% of the time?</p>
  
  <p>3) Why can performance differ on gcc/clang in such a primitive code?</p>