http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48837
Summary: Wrong optimization of recursive function calls Product: gcc Version: 4.6.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization AssignedTo: unassig...@gcc.gnu.org ReportedBy: perso...@e-maxx.ru Created attachment 24153 --> http://gcc.gnu.org/bugzilla/attachment.cgi?id=24153 The example program - it should output "ans = 1", but outputs "ans = 0" in -O2 The program attached outputs "global ans = 1" if compiled without optimizations, and "global ans = 0" with -O2 set. Moreover, if we insert debug-output into the recursive function, it becomes working right: //cout << "query = " << ans << endl; // ^^^^^ UNCOMMENT THIS LINE TO MAKE THE PROGRAM WORK OK If we uncomment the line, the program outputs "global ans = 1" both with -O2 and without it. Unfortunately, I couldn't make the test program very simple - optimizer works OK on simple programs, but when we have a complex recursion calls - it starts making wrong code. To make you understand it better - there are some additional debug-outputs. For example, the right program flow results in the following output: call auxillary (t[9], 123): auxillary = 1 call auxillary (t[5], 123): auxillary = 0 global ans = 1 When we compile with -O2, the output becomes: call auxillary (t[9], 123): auxillary = 1 call auxillary (t[5], 123): auxillary = 0 global ans = 0 (note that from code we can see that query() returns sum of all recursive answers - then how can it return 0, if one auxillary() returned 1???)