[issue38249] Optimize out Py_UNREACHABLE in the release mode

Serhiy Storchaka report at bugs.python.org
Mon Sep 23 14:48:25 EDT 2019


Serhiy Storchaka <storchaka+cpython at gmail.com> added the comment:

> What does __builtin_unreachable()? Does it nothing? Call abort()?

It is more than does nothing. It gives a hint to the compiler, so it can optimize out checks that lead to this code. For example, in

    switch (k) {
    case 0: ...
    case 1: ...
    case 2: ...
    case 3: ...
    default: __builtin_unreachable();
    }

the compiler can remove the check that k is in the range from 0 to 3 and use direct jump table. Or it can keep tests for k == 0, k == 1, k == 2 and remove the test for k == 3.

Py_UNREACHABLE() replaces assert(0), but additionally silences compiler warning about unreachable code. It was the purpose of introducing Py_UNREACHABLE() (see issue14656).

> For me, it's not an issue with the compiler, but more about handling corner cases. Py_UNREACHABLE() is used in cases which "should not occur" but can technically occur if you pass invalid data, or in "very unlikely case".

It is bad if Py_UNREACHABLE() is now used in both cases: for assert(0) and for abort(). Using Py_UNREACHABLE() for "very unlikely case" is technically incorrect. Raise an exception or call Py_FatalError() in that case.

We need to fix incorrect uses of Py_UNREACHABLE() or add Py_TRUE_UNREACHABLE() for true unreachable code.

> Here it's unclear to me if this case can be reached or not.

This is an infinite loop without "break". What can be the doubts?

> _PyLong_Format() calls Py_UNREACHABLE() if base is not in (2, 8, 16).

There is assert(base == 2 || base == 8 || base == 16) above in the code. Technically it is a bug. _PyLong_Format() can be used from public PyNumber_ToBase(). Either PyNumber_ToBase() or _PyLong_Format() should check that the base is 2, 8, 10 or 16, and raise an exception otherwise, but not abort the program.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38249>
_______________________________________


More information about the Python-bugs-list mailing list