Skip to content

Commit 3f5c0a4

Browse files
committed
c/maxminclamp.h: Optimize MAX and MIN macros for assignments to the same variable.
1 parent 0bdd419 commit 3f5c0a4

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

c/maxminclamp.h

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,17 @@
2020
#define STATIC_ASSERT_TYPES_COMPATIBLE(x,y, msg) ((void) (&x == &y))
2121
#endif
2222

23+
/**
24+
25+
The macros are optimized for the pattern x = MAX(x,y) and x = MIN(x,y), so
26+
that when x == y, it will generate x = x instead of x = y, and the compiler
27+
will optimize the assignment out.
28+
29+
*/
2330
#if (defined(__GNUC__) && __GNUC__ >= 3) || defined(__clang__)
24-
#define __cmp_op_MIN <
25-
#define __cmp_op_MAX >
26-
#define __cmp(op, x, y) ((x) __cmp_op_##op (y) ? (x) : (y))
31+
#define __cmp_op_MAX <
32+
#define __cmp_op_MIN >
33+
#define __cmp(op, x, y) ((x) __cmp_op_##op (y) ? (y) : (x))
2734
#define __careful_cmp(op, x, y) __extension__({ \
2835
__auto_type _x__ = (x); \
2936
__auto_type _y__ = (y); \
@@ -47,8 +54,8 @@
4754
_x__ <= _xmin__ ? _xmin__ : _x__ >= _xmax__ ? _xmax__ : _x__; })
4855

4956
#else
50-
#define MAX(x,y) ((x) > (y) ? (x) : (y))
51-
#define MIN(x,y) ((x) < (y) ? (x) : (y))
57+
#define MAX(x,y) ((x) < (y) ? (y) : (x))
58+
#define MIN(x,y) ((x) > (y) ? (y) : (x))
5259
#define CLAMP(x, xmin, xmax) (MAX((xim), (MIN((x), (xmax)))))
5360
#endif
5461

0 commit comments

Comments
 (0)