Skip to content

Commit 8655d3d

Browse files
committed
Adding SDL_Assume macro to give hint to the optimiser
with a given condition generating less instructions.
1 parent c29629a commit 8655d3d

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

include/SDL_assert.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,18 @@ assert can have unique static variables associated with it.
6969
#define SDL_TriggerBreakpoint()
7070
#endif
7171

72+
#if defined(_MSC_VER) && (_MSC_VER > 1400)
73+
#define SDL_Assume(cond) __assume(cond)
74+
#elif _SDL_HAS_BUILTIN(__builtin_assume)
75+
#define SDL_Assume(cond) __builtin_assume(cond)
76+
#elif defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 4))
77+
#define SDL_Assume(cond) do { \
78+
(__builtin_expect(!(cond), 0) ? __builtin_unreachable() : (void)0); \
79+
} while (0)
80+
#else
81+
#define SDL_Assume(cond)
82+
#endif
83+
7284
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 supports __func__ as a standard. */
7385
# define SDL_FUNCTION __func__
7486
#elif ((defined(__GNUC__) && (__GNUC__ >= 2)) || defined(_MSC_VER) || defined (__WATCOMC__))

test/testplatform.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
*/
1212

1313
#include <stdio.h>
14+
#include <time.h>
1415

1516
#include "SDL.h"
1617

@@ -442,6 +443,19 @@ TestAssertions(SDL_bool verbose)
442443
return (0);
443444
}
444445

446+
int
447+
TestAssume(SDL_bool verbose)
448+
{
449+
int max, count, i;
450+
451+
max = 16;
452+
srand(time(0));
453+
count = rand() % max;
454+
SDL_Assume(count <= max);
455+
for (i = 0; i < count; i ++);
456+
return (0);
457+
}
458+
445459
int
446460
main(int argc, char *argv[])
447461
{
@@ -463,6 +477,7 @@ main(int argc, char *argv[])
463477
status += Test64Bit(verbose);
464478
status += TestCPUInfo(verbose);
465479
status += TestAssertions(verbose);
480+
status += TestAssume(verbose);
466481

467482
return status;
468483
}

0 commit comments

Comments
 (0)