Bug in iPhone Box2D when disabling Thumb

I have found a strange problem when using Box2D on the iPhone. For reference, I am using the version that adds in b2EdgeShapes. The program runs fine with the Thumb instruction set, although a little bit slow. When I switch to ARM, the contacts between polygons and edge shapes stop working properly. As a test, I switched the b2EdgeShapes to b2Polygons using convex decomposition, and the problem persists. Basically, rectangular objects sitting on my terrain start shaking around and eventually smash all the way through the terrain.

Using the -mno-thumb compiler flag for each file rather than a global "Compile for Thumb" project setting, I have isolated the problem to the source file b2ContactSolver.cpp. I am really surprised that anything in that source file could really be dependent on the instruction set.

Random Notes:
The only change I made in Box2D when porting to the iPhone was in b2Math.h. I put in the std::isfinite line because finite did not appear to be defined.
Code:
/// This function is used to ensure that a floating point number is
/// not a NaN or infinity.
inline bool b2IsValid(float32 x)
{
#ifdef _MSC_VER
   return _finite(x) != 0;
#else
//   return finite(x) != 0;
   return std::isfinite(x)!=0;
#endif
}

Could there be some functions in files like b2Math.h that are used in b2ContactSolver.cpp, and no other source files? Also, I see definition checks like TARGET_FLOAT32_IS_FIXED and _MSC_VER in b2Math.h and wonder if any definitions depend on the instruction set (i.e. Thumb vs. ARM).

Edit:
This should totally have gone in the bug forum. Sorry about that.
What optimization mode are you using? I've noticed problems with Box2d when using O3 opts...
ewjordan wrote:
What optimization mode are you using? I've noticed problems with Box2d when using O3 opts...

This is a great observation. I have been using O2, and after a lot of experimenting it seems like reducing the optimization level of b2Contact.cpp and b2ContactSolver.cpp to O1 removes the problem. I can actually bump up the project wide optimization to O3 if I keep those two files at O1. The issue now is whether lowering the optimization level of those two files is worth enabling ARM for b2ContactSolver.cpp. Which optimization level do you typically compile Box2d with?

I did some reading on optimization levels and it looks like with O2 and O3, you can run into problems where variables are loaded into registers and are not updated later on, unless the variable is declared to be volatile. I have no idea which variables should be declared volatile in Box2d, but my guess would be that this is the reason for incorrect behavior with the higher optimization levels.

Here is a link to short introduction to the volatile keyword and optimizations:
http://www.linuxdevices.com/articles/AT5980346182.html
Quite strange...I tend to use -Os optimization, mainly because it at least seems to work and produce fairly fast code. I haven't done extensive Box2d testing at this level, so I'm not positive that it works fully.

Erin, do you have any idea what might be going on here? I wouldn't think anything in Box2d would require volatile declarations, but you may know better than I would...I was always under the impression that volatile was only necessary when you were doing "weird" things that involved asynchronous updating of variables, which seems to be confirmed by the link that Robert posted.

I'd love to track this down, and figure out where the bug is so we can either fix it or report it - it only seems to show up on the iPhone, so it may be an ARM gcc bug or something like that, or possibly a bad interaction with the iPhone OS...
I tried playing around with the volatile keyword, and started declaring sections of variables in b2ContactSolver.cpp volatile, and actually stumbled on some promising results. When three specific variables in the b2ContactSolver constructor are declared volatile, the problem seems to vanish.

Considering my lack of experience with volatile, I highly doubt I have located the core of the problem, but it at least seems to prevent the optimizer from doing its faulty optimization. I can actually compile the whole project with Thumb turned off and O3 enabled without any visible problems. I will probably only use O2 though, because I'm not sure if O3 is necessary or helpful.

Code:
   // If we have two points, then prepare the block solver.
   if (cc->pointCount == 2)
   {
      b2ContactConstraintPoint* ccp1 = cc->points + 0;
      b2ContactConstraintPoint* ccp2 = cc->points + 1;
      
      float32 invMass1 = b1->m_invMass;
      float32 invI1 = b1->m_invI;
      float32 invMass2 = b2->m_invMass;
      float32 invI2 = b2->m_invI;
      float32 rn11 = b2Cross(ccp1->r1, normal);
      float32 rn12 = b2Cross(ccp1->r2, normal);
      float32 rn21 = b2Cross(ccp2->r1, normal);
      float32 rn22 = b2Cross(ccp2->r2, normal);

      volatile float32 k11 = invMass1 + invMass2 + invI1 * rn11 * rn11 + invI2 * rn12 * rn12;
      volatile float32 k22 = invMass1 + invMass2 + invI1 * rn21 * rn21 + invI2 * rn22 * rn22;
      volatile float32 k12 = invMass1 + invMass2 + invI1 * rn11 * rn21 + invI2 * rn12 * rn22;
      
      // Ensure a reasonable condition number.
      const float32 k_maxConditionNumber = 100.0f;
      if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12))
      {
         // K is safe to invert.
         cc->K.col1.Set(k11, k12);
         cc->K.col2.Set(k12, k22);
         cc->normalMass = cc->K.GetInverse();
      }
      else
      {
         // The constraints are redundant, just use one.
         // TODO_ERIN use deepest?
         cc->pointCount = 1;
      }
   }

I see no reason why these specific variables require volatile. They aren't even changed after being declared. I suspect this simply tricks the optimizer into skipping the bad optimization. ewjordan, I would be curious if declaring these lines volatile removes the problems you observed with O3.
Box2D shouldn't require volatile anywhere because it is single threaded.
Erin Catto wrote:
Box2D shouldn't require volatile anywhere because it is single threaded.

Yup, that's what I assumed.

You may be right, robert, and what's really happening is that the volatile marker is slightly changing the optimization path taken, rather than actually solving anything. This seems more and more like an ARM gcc bug the more I think about it.

I haven't had a chance to check my example (it's not compiling at the moment), but I will at some point soon. Unfortunately I have no idea how we might boil this one down to a simple bug report...perhaps we can just submit the whole thing to Apple and let them sort it out, as Box2d has already been used in several iPhone games and if it's exposing some bug in the compiler they'd have some interest in working it out. Then again, if it's a gcc thing it's not really Apple's fault, so... I don't know, though, I'm a bit hesitant to report it directly to the gcc devs without knowing a bit more about it or at least being able to reproduce it on another ARM device.
Well, I'm just happy I can use Box2D with the optimizer, and will stick with the volatile hack until I hear of some other way of doing it. Thanks for the help!
Porting to iphone myself.

O3 is definately the fastest, along with disabled thumb. The problem here is, with O3 you need to always initialize your variables fully.

This is because the fastest, smallest flag actually uses a local stack, and doesn't assume that new variables will be null.

By making sure all variables are nulled to begin with, you will avoid bugs with O3. Its all about making sure that new vars are not pointing to some garbage, but to null. If you make it null, it will work fine.

I think Box2D is a little lazy in places and doesn't always initialise variables with null or a value and this is why it breaks. I pulled this info off Apple site someplace, can't remember where.

O3 is significantly faster (for me though).

Original thread: https://box2d.org/forum/viewtopic.php?t=2688