[cfe-commits] [PATCH] PR12290: introducing overflow builtins

Xi Wang xi.wang at gmail.com
Wed Apr 11 03:26:45 PDT 2012


Ping?  Please take a look.  Thanks.

There was some related discussion about overflow builtins from GCC, FYI.

	http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48580

I also created a higher-level library on top of these builtins for demonstration.

	https://github.com/xiw/libo

Basically it provides the following functions (macros/wrappers).

	bool overflow_add(type *, type, type);
	bool overflow_sub(type *, type, type);
	bool overflow_mul(type *, type, type);
	bool overflow_div(type *, type, type);

You even can use them with GCC (or Clang without overflow builtins).  Their implementations (in assembly) are generated automatically via Clang, except for overflow_div(), which doesn't depend on overflow builtins.

- xi
-------------- next part --------------
A non-text attachment was scrubbed...
Name: overflow.patch
Type: application/octet-stream
Size: 11632 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20120411/e85a4abb/attachment.obj>
-------------- next part --------------

On Apr 4, 2012, at 8:18 PM, Xi Wang wrote:

> Hi,
> 
> Attached is a patch that adds arithmetic with overflow builtins to Clang.  Please review.  Thanks.
> 
> Arithmetic with overflow builtins are used to perform arithmetic operations with overflow detection.
> 
> Syntax:
> 
> bool __builtin_add_with_overflow(type *ptr, type a, type b);
> bool __builtin_sub_with_overflow(type *ptr, type a, type b);
> bool __builtin_mul_with_overflow(type *ptr, type a, type b);
> 
> Example of Use:
> 
> void *malloc_array(size_t n, size_t size) {
>  size_t bytes;
>  if (__builtin_mul_with_overflow(&bytes, n, size))
>    return NULL;
>  return malloc(bytes);
> }
> 
> Description:
> 
> __builtin_op_with_overflow(ptr, a, b) stores the result of a op b in ptr, and returns true if an overflow occurred during the arithmetic operation. Note that type is inferred from *ptr. These builtins help developers write more efficient and correct code by avoiding ad hoc overflow checks.
> 
> Query for this feature with __has_builtin(__builtin_op_with_overflow).
> 
> - xi
> <overflow.patch>



More information about the cfe-commits mailing list