What exactly does opt-level do?

I'm currently using a C++ library with bindings generated with bindgen. After creating Rust structs that correspond to C++ classes, I consistently get segfaults from a pthread_mutex_lock used inside the C++ class. However, I found that compiling with cargo opt-level set to 0 or 1 seems to get rid of the segfault while 2 or 3 result in consistent errors. What exactly does opt-level affect that can potentially influence this issue?

The C and C++ languages have a concept of "Undefined Behaviour", commonly known as "UB". Which basically means you have to follow all the C/C++ language rules in your code otherwise the results will be completely undefined.

A simple example:

int* a_pointer;
int b = *a_pointer;    

Here the pointer is not initialised. Dereferencing it to get b is undefined behaviour. It's not that you can get a random result, it's that anything could happen, segfaults etc. Including the fact that your code might happen to work as expected, thus hiding the problem.

Other examples are indexing arrays out of bounds, integer overflow, race conditions between threads, thousands of others.

Now, because that behaviour is undefined a compiler is free to assume you never write code that does such things and can use that fact to optimise you code very well.

BUT, if you do happen to trigger undefined behaviour in your code then those optimisations may cause the program to behave differently than when optimisations are turned off.

In short, something in your program is triggering undefined behaviour. A bug. Because the behaviour is undefined it can be different with and without optimisations applied.

As to exactly which optimisation is showing up your undefined behaviour, there are so many optimisations that it could be a major task to find out which one does it.

I suggest you try debugging your code by using the analysers,

https://news.ycombinator.com/item?id=19937460

The sanitizers instrument and analyse your code as it runs. Thus hopefully catching memory use errors, data races, undefined behaviour etc.

4 Likes

See compiler developer Chandler Carruth discussing Undefined Behaviour and compiler optimisations here:

"Garbage In, Garbage Out: Arguing about Undefined Behavior...":

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.