title: gcc and cpu_relax, smb_mb, etc.?
body: <p>I've been reading on compiler optimizations vs CPU optimizations, and <code>volatile</code> vs memory barriers.</p>
  
  <p>One thing which isn't clear to me is that my current understanding is that CPU optimizations and compiler optimizations are orthogonal. I.e. can occur independently of each other.</p>
  
  <p>However, the article <a href="https://www.kernel.org/doc/html/v4.12/process/volatile-considered-harmful.html" rel="noreferrer">volatile considered harmful</a> makes the point that <code>volatile</code> should not be used. Linus's <a href="http://yarchive.net/comp/linux/memory_barriers.html" rel="noreferrer">post</a> makes similar claims. The main reasoning, IIUC, is that marking a variable as <code>volatile</code> disables <em>all</em> compiler optimizations when accessing that variable (i.e. even if they are not harmful), while still not providing protection against memory reorderings. Essentially, the main point is that it's not the <em>data</em> that should be handled with care, but rather a particular <em>access pattern</em> needs to be handled with care.</p>
  
  <p>Now, the <a href="https://www.kernel.org/doc/html/v4.12/process/volatile-considered-harmful.html" rel="noreferrer">volatile considered harmful</a> article gives the following example of a busy loop waiting for a flag:</p>
  
  <pre><code>while (my_variable != what_i_want) {}
  </code></pre>
  
  <p>and makes the point that the compiler can optimize the access to <code>my_variable</code> so that it only occurs once and not in a loop. The solution, so the article claims, is the following:</p>
  
  <pre><code>while (my_variable != what_i_want)
      cpu_relax();
  </code></pre>
  
  <p>It is said that <code>cpu_relax</code> acts as a <strong>compiler barrier</strong> (earlier versions of the article said that it's a <strong>memory barrier</strong>).</p>
  
  <p>I have several gaps here:</p>
  
  <p>1) Is the implication that gcc has special knowledge of the <code>cpu_relax</code> call, and that it translates to a hint to both the compiler <em>and</em> the CPU?</p>
  
  <p>2) Is the same true for other instructions such as <code>smb_mb()</code> and the likes?</p>
  
  <p>3) How does that work, given that <code>cpu_relax</code> is essentially defined as a C macro? If I manually expand <code>cpu_relax</code> will gcc still respect it as a compiler barrier? How can I know which calls are respected by gcc?</p>
  
  <p>4) What is the scope of <code>cpu_relax</code> as far as gcc is concerned? In other words, what's the scope of reads that cannot be optimized by gcc when it sees the <code>cpu_relax</code> instruction? From the CPU's perspective, the scope is wide (memory barriers place a mark in the read or write buffer). I would guess gcc uses a smaller scope - perhaps the C scope?</p>