0

Im working on a large code base which is now being compiled using gcc11 O3. Behaviour in certain parts of the code differs from when it was being used with gcc9 O3. When i try to print out the affected portion, optimizations change and I'm unable to see the bug anymore. Are there any steps i can follow to find out the bugs of this type ?

EDIT:- Found the problem. As pointed out by Stefan in the comments, it was an undefined behaviour. Was being caused by strict-aliasing issues. But it is certainly very hard to figure out.

  • wdym by optimizations change? – Yamahari Jun 07 '22 at 07:41
  • When i print the variables related to the bug, the bug disappears. Had seen a similar case and that was solved by 0 initialization (print was doing it for me that's why the bug was disappearing). – therapyCarrots Jun 07 '22 at 07:43
  • 1
    Issues such as this typically suggest undefined behaviour somewhere in the code. What's the nature of the bug -- segfault? – G.M. Jun 07 '22 at 07:47
  • 2
    Maybe, if you haven't already, start with `-fsanitize=undefined,address` and valgrind. If you have multiple threads also `-fsanitize=thread`. If you have undefined behavior they might spot it. If they report anything, you should probably fix it. – user17732522 Jun 07 '22 at 07:48
  • @G.M. not a segfault but incorrect results. Although when i print the result it shows correct value. – therapyCarrots Jun 07 '22 at 07:50
  • 2
    Like G.M. said, that smells like undefined behavior. Bugs are never introduced by -O3 (except in case of a compiler bug). Correct code doesn't get incorrect by enabling optimizations – Stefan Riedel Jun 07 '22 at 08:14
  • 1
    Sounds like a Heisenbug – Jabberwocky Jun 07 '22 at 08:54
  • 1
    Could also be a race condition that used to "just get there in time", but now something slightly nudged the timings. But the prints slow it down just enough again. – Frodyne Jun 07 '22 at 09:16
  • O3 is also often slower. You should benchmark each compilation unit if using O3 makes things faster or slower. And if you really want to optimize then -fLTO with -O2 will do more for you. – Goswin von Brederlow Jun 07 '22 at 09:26
  • also watch out for bad library API design like here https://stackoverflow.com/questions/60849247/different-output-with-different-optimization-levels-in-gcc – Yamahari Jun 08 '22 at 12:43

0 Answers0