r/cpp • u/aregtech • 0m ago
GCC -O3 deletes a whole function: 3rd GCC bug in my project, still in trunk
I develop areg-sdk, a mid-size C++ framework. My unit tests started crashing and hanging. After a long hunt (sanitizers helped a lot), the cause turned out to be GCC, not my code.
The bug in short: with -O3, GCC wrongly decides that a virtual function call can never happen, so it deletes the code that leads to it.
How it looks:
- A class inherits from two base classes.
- You call a virtual function through the second base.
- Inside that function, another virtual function is called.
Schematically:
struct Base : Out, Cur { ... }; // Cur is the SECOND base
struct Buf : Base { ... };
What the code says:
test()
├─ to_begin() // Cur method
│ └─ set_pos() // virtual, through 2nd base -> Buf::set_pos
│ └─ is_open() // virtual -> Buf::is_open
└─ printf("test: ...")
What GCC -O3 builds:
test() { } // EMPTY -> crash-O2 works. Clang -O3 works. GCC 13 through trunk all fail with -O3.
- Try it yourself (50 lines): Compiler Explorer
- Full analysis, repro and results per compiler: gist
- Workaround: add
-fno-ipa-cp-clone - Bug report: Started, but long way for approval by GCC team
This is the third GCC bug I've hit in this project. The first two were already fixed in GCC 15. This one isn't.
It made me think: C++ gets a lot of new features every 3 years, but a feature or optimization that breaks valid code isn't a real feature. I'd take more stable compilers over more features.
What compiler bugs have you hit and how you work around them? Ideas for a better workaround than -fno-ipa-cp-clone are welcome and highly appreciated.