title: How effective is compiler common subexpression elimination?
body: <p>I need to compute some fairly long expressions that contain common subexpressions. For example, consider the following two expressions:</p>
  
  <pre><code>double dfdx1 = 2 * (-x2 + x1 - sin(b2)*n34 + cos(b2)*sin(c2)*n24 - cos(b2)*cos(c2)*n14 + sin(b1)*m34 - cos(b1)*sin(c1)*m24 + cos(b1)*cos(c1)*m14);
  
  double dfdx2 = -2 * (-x2 + x1 - sin(b2)*n34 + cos(b2)*sin(c2)*n24 - cos(b2)*cos(c2)*n14 + sin(b1)*m34 - cos(b1)*sin(c1)*m24 + cos(b1)*cos(c1)*m14);
  </code></pre>
  
  <p>Aside from eliminating all the trigonometric functions, one obvious elimination is <code>dfdx2 = -dfdx1</code>. The question is whether the compiler will recognise this. I found that using MATLAB's MuPad <code>generate::optimize()</code> function does not, which rather surprised me.</p>
  
  <p>More generally, will the compiler recognise that <code>f2 = -f1</code> in the example below:</p>
  
  <pre><code>double f1 = a*a + b*b - c*a - c*b;
  double f2 = c*a + c*b - a*a - b*b;
  </code></pre>
  
  <p>Or will it just eliminate the terms <code>a*a</code>, <code>b*b</code>, <code>c*a</code> and <code>c*b</code>?</p>
  
  <p>I am using the MSVC compiler, but I guess that they all do pretty much the same thing.</p>