Code optimization issue Xcode 7


I was in contact with Apple Developer Technical Support, and it was suggested that I send a question to this list.

I will post the complete conversation below, but to summarize.

I have a header file with this declaration:

protected: bool gravityFlipped_;
public: virtual bool getGravityFlipped(void) const { return gravityFlipped_; }
public: virtual void setGravityFlipped(bool val) { gravityFlipped_ = val; }

Everything works fine with optimization disabled -O0, but anything above that introduces issues. The getter seems to be changed in some way to the point where what it returns is garbage.

Simply copying the declaration and placing it somewhere else in the header fixes the problem. Removing the “virtual” tag, or adding a log in the getter/setter also fixes the problem.

I am out of ideas and any help you could provide would be great, thank you!



Below is the complete conversation with Apple DTS


It’s really hard to help much without a reproduction - also, trying to create a reduced example of the problem can often help you find the issue. So, if you want further advice, I’d suggest starting by ripping apart (a copy of) your program until you can’t remove anything else without losing the interesting/problematic behavior.

That said, generally behavior like this isn’t a bug in the compiler/optimizer, but a bug in the user code that’s relying on Undefined Behavior (null dereference, use after free, use after scope, array out of bounds, etc) and the optimizer just decided to optimize/break it differently today. So you could consider using tools around that (ASan, UBSan, etc) to help see if there are problems like that you might address first & see if they make the strange behavior go away.