title: gcc Hangs trying to compile with -O2 optimisation
body: <p>I was trying to compile my project today, I have never had any trouble compiling this project before on multiple platforms, but trying on Mac OS X using g++ (4.2.1) in release mode (which uses the -O2 optimisation flag) caused the compilation to get stuck forever on the same file. Playing around with the code, I narrowed the problems down to essentially this code:</p>
  
  <pre><code>void MyClass::SendBigMessage()
  {
      int Offset = 0;
      PackByteArrayIntoMessage(SomeDataArray1, SomeDataArray1Size, Offset);
      PackByteArrayIntoMessage(SomeDataArray2, SomeDataArray2Size, Offset);
      // ...snip
      PackByteArrayIntoMessage(SomeDataArray9, SomeDataArray9Size, Offset);
      PackByteArrayIntoMessage(SomeDataArray10, SomeDataArray10Size, Offset);
  
      SendMessage(Message);
  }
  
  void MyClass::PackByteArrayIntoMessage(unsigned char *ByteArray, int Size, int &amp;Offset)
  {
      for(int i = 0; i &lt; Size; i++)
      {
          Message.SetByteAtOffset(ByteArray[i], Offset++);
      }
  }
  </code></pre>
  
  <p>Commenting out the body of the <code>PackByteArrayIntoMessage</code> means the file compiles without problem. Also, commenting out all of the calls to <code>PackByteArrayIntoMessage</code>, but leaving the body of the function commented in, means the file compiles without problem. When I start commenting in more calls to it, the compile time seems to get exponentially longer, until, with about 10 sequential calls to it, it seems to hang compiling the file forever.</p>
  
  <p>I guessed gcc was trying to do some clever optimisations, so I played around with the <code>PackByteArrayIntoMessage</code> until it started compiling again, this implementation worked fine:</p>
  
  <pre><code>void MyClass::PackByteArrayIntoMessage(unsigned char *ByteArray, int Size, int &amp;Offset)
  {
      for(int i = 0; i &lt; Size; i++)
      {
          Message.SetByteAtOffset(ByteArray[i], Offset + i);
      }
      Offset = Offset + Size;
  }
  </code></pre>
  
  <p>I can only assume this is a bug in gcc 4.2.1, as compiling with gcc 4.4.0 using -O2 on Linux works fine with no code modifications.</p>
  
  <p>So my question is, what exactly is the compiler trying to do that causes the hanging problem? I looked through the release notes of some gcc versions but I couldn't find anything referencing this particular issue. Also, is there a way to mark code segments to make sure they are not optimised?</p>