D Compilers Disprove Fermat’s Last Theorem

deadalnix deadalnix at gmail.com
Thu May 20 22:31:14 UTC 2021


On Tuesday, 18 May 2021 at 07:17:50 UTC, Dukc wrote:
> On Monday, 17 May 2021 at 08:24:22 UTC, user1234 wrote:
>> intersting but dmd -O does not disprove.
>> Alos it's not about D, it's about backend optimizations, as 
>> expalined in the article.
>
> To be more accurate, dmd-compiled code enters infinite loop, 
> just as it should. Printing "fermat's theorem has not been 
> disproven" would be just as wrong as LDC behaviour.
>
> It's surprising how so many backends can have the same 
> optimizing bug even in 2021. Kudos for DMD doing the right 
> thing.

Believe it or not, it is not a bug, at least not in C++. Consider 
the transforms as follow.

1/ What's after the loop is unreachable, therefore it can be 
removed.
2/ An analysis of the function shows that it has no side effects.
3/ Now the function must return true, granted that it returns at 
all.
4/ At the call site, we got a function with no side effect that 
can only return true, therefore we can constant fold the call to 
true.

You will note that all the transformation are trivially correct, 
except 3, because we don't know if the function will return or 
not. This is where precise legalese of the language definition 
comes into play, as it turns out, in C++ - and C++ is by far the 
language people working on optimizer have focused the most - it 
is not mandatory to prove that the function will terminate.

In a way, it does make sense, because providing that the function 
will terminate is equivalent to proving the halting problem, or, 
in this specific case, Fermat's last theorem, which is not 
something reasonable to expect from the optimizer.

If the language asks you to prove this terminates, then the cost 
you pay is that many function that will terminate will not be 
optimized, because it is too difficult to prove it.


More information about the Digitalmars-d mailing list