1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 
3 /*
4  * Helpers for Xen self-tests of basic logic, including confirming that
5  * examples which should be calculated by the compiler are.
6  */
7 #ifndef XEN_SELF_TESTS_H
8 #define XEN_SELF_TESTS_H
9 
10 #include <xen/lib.h>
11 
12 /*
13  * Check that fn(val) can be calculated by the compiler, and that it gives the
14  * expected answer.
15  *
16  * N.B. fn is intentionally not bracketed to allow us to test function-like
17  * macros too.
18  */
19 #define COMPILE_CHECK(fn, val, res)                                     \
20     do {                                                                \
21         typeof(fn(val)) real = fn(val);                                 \
22                                                                         \
23         if ( !__builtin_constant_p(real) )                              \
24             BUILD_ERROR("'" STR(fn(val)) "' not compile-time constant"); \
25         else if ( real != (res) )                                       \
26             BUILD_ERROR("Compile time check '" STR(fn(val) == res) "' failed"); \
27     } while ( 0 )
28 
29 /*
30  * Check that Xen's runtime logic for fn(val) gives the expected answer.  This
31  * requires using HIDE() to prevent the optimiser from collapsing the logic
32  * into a constant.
33  *
34  * N.B. fn is intentionally not bracketed to allow us to test function-like
35  * macros too.
36  */
37 #define RUNTIME_CHECK(fn, val, res)                     \
38     do {                                                \
39         typeof(fn(val)) real = fn(HIDE(val));           \
40                                                         \
41         if ( real != (res) )                            \
42             panic("%s: %s(%s) expected %u, got %u\n",   \
43                   __func__, #fn, #val, real, res);      \
44     } while ( 0 )
45 
46 /*
47  * Perform compile-time and runtime checks for fn(val) == res.
48  */
49 #define CHECK(fn, val, res)                     \
50     do {                                        \
51         COMPILE_CHECK(fn, val, res);            \
52         RUNTIME_CHECK(fn, val, res);            \
53     } while ( 0 )
54 
55 #endif /* XEN_SELF_TESTS_H */
56