title: Android. ART for loop optimization bug. Simple java function with unexpected result
body: <p><strong>EDIT:</strong>
  After many hours of testing I can say that this is a <strong>serious bug</strong> of the ART Android Runtime with for loops.</p>
  
  <p>Yesterday I found a glitch in our game, and when debugging the code found that a very simple java function was getting unexpected results (depending on the Android version of the device).
  This is the java code:</p>
  
  <pre><code>// Simple function to count items of a 6 rows pyramid (1+2+3+4+5+6)
  private int getSum ()
  {
      int sum=0, x=0;
      for (int i=0; i&lt;6; i++) { x++; sum+=x; }
      return sum;   // always should return 21
  }
  </code></pre>
  
  <p>To test it just add this line of code to your existing Android project in the OnCreate function:</p>
  
  <pre><code>    Log.d("@@@ Test", "getSum=" + getSum());
  </code></pre>
  
  <p>If your Android is <strike>5.1.1 or</strike> 6.0.x it will show 15 (ERROR result), if it's a previous Android version it will return 21 (OK result).</p>
  
  <p>Please, can someone do this simple test. I'm getting mad about this.</p>
  
  <p>If you debug step-by-step the code then it returns the correct value (21). If you try to trace the code it also returns 21 value.
  Example:</p>
  
  <pre><code>private int getSum2 ()
  {
      int sum=0, x=0;
      for (int i=0; i&lt;6; i++) { x++; Log.d ("@@@ Test","x="+x); sum+=x; }
      return sum;   // always should return 21
  }
  </code></pre>
  
  <p>getSum2 works ok always (just adding a Log.d).</p>
  
  <p>What I'm missing? This is driving me nuts.
  I'm not using proguard.
  I think this can be an optimization related bug of the ART runtime. </p>
  
  <p>Thanks in advance.</p>
  
  <p>David.</p>