[bigint] Small bug caused by clang/llvm optimizations
Zachary Kurmas <kurmasz at gvsu.edu>
Thu May 8 07:16:44 PDT 2014
Your bigint library has a bug when compiled on a mac using the -O2 flag with Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn). In particular, Line 115 of BigInteger::convertToSignedPrimitive()
X x = -X(b);
doesn’t behave as expected when compiled at the -O2 level.
Compile the attached C++ sample on a mac using clang/llvm to see exactly what goes wrong.
I fixed this bug and added 64-bit tests. You will find the fixes/improvements here: https://github.com/kurmasz/bigint
Zack Kurmas
--
Zachary Kurmas
Assistant Professor of Computer Science
Grand Valley State University
http://www.cis.gvsu.edu/~kurmasz
——
#include <iostream>
template<class Out> Out negate(unsigned long in) {
// This line casts an unsigned long to a signed long.
// 2^63 as an unsigned long is 0x8000000000000000
// Casting 2^63 from unsigned long to signed long should
// produce -2^63 (which is also 0x8000000000000000).
// The twos complement of -2^63 just happens to be -2^63,
// so, (long)(2^63) should always be -2^63, correct?
// This code works as expected when compiled with gcc 4.4.7; but,
// when compiled on a mac with -O2 using LLVM 5.1 / clang-503.0.40,
// it produces the wrong answer. (The source of the problem is
// clearly visible in the generated assembly code.)
Out out = -Out(in);
if (out > 0) {
std::cout << "Oops!" << std::endl;
} else {
std::cout << "Correct." << std::endl;
}
return out;
}
int main() {
unsigned long in = 9223372036854775808UL;
std::cout << "Attempt 3: " << std::endl;
negate<long>(in);
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mattmccutchen.net/mailman/archives/bigint/attachments/20140508/30019b29/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: bug_take3.cpp
Type: application/octet-stream
Size: 991 bytes
Desc: bug_take3.cpp
URL: <http://mattmccutchen.net/mailman/archives/bigint/attachments/20140508/30019b29/attachment.obj>
More information about the bigint
mailing list