From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 11959 invoked by alias); 19 Nov 2012 11:28:00 -0000 Received: (qmail 11935 invoked by uid 48); 19 Nov 2012 11:27:42 -0000 From: "cosmos at claycon dot org" To: gcc-bugs@gcc.gnu.org Subject: [Bug c++/55393] New: gcc/g++ multiplies two unsigned integers using the IMULQ instruction Date: Mon, 19 Nov 2012 11:28:00 -0000 X-Bugzilla-Reason: CC X-Bugzilla-Type: new X-Bugzilla-Watch-Reason: None X-Bugzilla-Product: gcc X-Bugzilla-Component: c++ X-Bugzilla-Keywords: X-Bugzilla-Severity: normal X-Bugzilla-Who: cosmos at claycon dot org X-Bugzilla-Status: UNCONFIRMED X-Bugzilla-Priority: P3 X-Bugzilla-Assigned-To: unassigned at gcc dot gnu.org X-Bugzilla-Target-Milestone: --- X-Bugzilla-Changed-Fields: Message-ID: X-Bugzilla-URL: http://gcc.gnu.org/bugzilla/ Auto-Submitted: auto-generated Content-Type: text/plain; charset="UTF-8" MIME-Version: 1.0 Mailing-List: contact gcc-bugs-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-bugs-owner@gcc.gnu.org X-SW-Source: 2012-11/txt/msg01740.txt.bz2 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=55393 Bug #: 55393 Summary: gcc/g++ multiplies two unsigned integers using the IMULQ instruction Classification: Unclassified Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ AssignedTo: unassigned@gcc.gnu.org ReportedBy: cosmos@claycon.org g++ -Wall -Wextra -O2 -o mult mult.cpp g++ (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2) 64bit mult.cpp: #include void display( unsigned long int num, unsigned long int mult) { unsigned long int tmp = num * mult; std::cout << "mult " << mult << "\n num " << num << "\n tmp " << tmp << std::endl; if (tmp < num) std::cout << "overflow" << std::endl; } int main( int /* argc */, char ** /* argv */) { unsigned long int num = 999999999999999999; unsigned long int mult = 1024; display(num, mult); return 0; } Problem: "overflow" is not displayed as expected. Analysis: gcc generates an IMULQ instruction to calculate the value of tmp. The value of num has bit 63 set. Since IMULQ sees that argument as signed, it results in an incorrect number that happens to be greater than num. IMULQ will generate the wrong result when the result just fits into 64 bits too, even though the result would have been correct (with no overflow) had the proper instruction been used. Fix: Whenever the multiplication operands are both unsigned, gcc should generate an unsigned multiply instruction (MULQ in this case), unless it can prove that the result would fit into 63 bits.