http://gcc.gnu.org/bugzilla/show_bug.cgi?id=49467
Summary: Enhancement: Intrinsic to read CARRY and OVERFLOW flags (where applicable) Product: gcc Version: unknown Status: UNCONFIRMED Severity: enhancement Priority: P3 Component: c AssignedTo: unassig...@gcc.gnu.org ReportedBy: noloa...@gmail.com On hardware with fixed width registers, it is possible for an integer math operation to overflow/wrap/underflow. For example, when working with 32 bit unsigned integers, UINT_MAX + 1 will result in 0, while UINT_MAX + UINT_MAX = 4294967294 (ie, UINT_MAX -1). Similarly, -1 + INT_MIN = 2147483647. Due to the security implications of integer overflow, it would be great if GCC would provide an intrinsic for fetching relevant status flags. For signed integers on x86/x64 PCs, the flag of interest is OVERFLOW. For unsigned integers, the flag of interest is CARRY. Many [other] popular architectures, such as ARM processors, include similar flags (in the case of ARM, it is available in the Current Program Status Register (CPSR)). I envision one of two intrinsics. The first intrinsic would simply return the value of the flag (carry shown, overflow similar): uint32_t a, b; .... uint32_t r = a + b; unsigned int cy = __get_carry_flag(); A second version of the same would accept an lvaue: uint32_t a, b, r; unsigned int cy; r = a + b; __get_carry_flag(&cy); With carry/overflow in hand, a programmer would be enabled to perform safe math on data, without the need/overhead for a big integer package. For example: uint32_t r = a + b; unsigned int cy = __get_carry_flag(); if(cy) { fprintf(stderr, "Integer addition overflowed\n"); abort(); } A third system would include integer math handlers. Upon program startup, the process would register 'failed add', 'failed subtract', etc, handlers. A program could perform safe integer math as follows: uint32_t r = a + b; test_uadd_result(); An executing program which was not interested in carry/overflow handling would simply call the operation without the subsequent test: uint32_t r = a + b; // No test, who cares? Though this feature request was filed C, both C++ and Objective C would benefit from the intrinsic.