dune-common  2.11
assume.hh
Go to the documentation of this file.
1 // -*- tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 // vi: set ts=8 sw=2 et sts=2:
3 // SPDX-FileCopyrightInfo: Copyright © DUNE Project contributors, see file LICENSE.md in module root
4 // SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception
5 #ifndef DUNE_COMMON_STD_ASSUME_HH
6 #define DUNE_COMMON_STD_ASSUME_HH
7 
26 // If the C++ standard attribute assume is available
27 #ifdef __has_cpp_attribute
28  #if __has_cpp_attribute(assume) >= 202207L
29  #define DUNE_ASSUME(...) [[assume(__VA_ARGS__)]]
30  #endif
31 #endif
32 
33 // if compiler intrinsics/attributes for assumptions are available
34 #ifndef DUNE_ASSUME
35  #if defined(__clang__) && defined(__has_builtin)
36  #if __has_builtin(__builtin_assume)
37  #define DUNE_ASSUME(...) __builtin_assume(__VA_ARGS__)
38  #endif
39  #elif defined(_MSC_VER)
40  #define DUNE_ASSUME(...) __assume(__VA_ARGS__)
41  #elif defined(__GNUC__)
42  #if __GNUC__ >= 13
43  #define DUNE_ASSUME(...) __attribute__((__assume__(__VA_ARGS__)))
44  #endif
45  #endif
46 #endif
47 
48 // if we are in release mode, use undefined behavior as a way to enforce an assumption
49 #if !defined(DUNE_ASSUME) && defined(NDEBUG)
50  #include <utility>
51  #if __cpp_lib_unreachable >= 202202L
52  #define DUNE_ASSUME(...) do { if (!bool(__VA_ARGS__)) ::std::unreachable(); } while(0)
53  #elif defined(__GNUC__)
54  #define DUNE_ASSUME(...) do { if (!bool(__VA_ARGS__)) __builtin_unreachable(); } while(0)
55  #elif defined(__has_builtin)
56  #if __has_builtin(__builtin_unreachable)
57  #define DUNE_ASSUME(...) do { if (!bool(__VA_ARGS__)) __builtin_unreachable(); } while(0)
58  #endif
59  #else
60  #include <cstdlib>
61  #define DUNE_ASSUME(...) do { if (!bool(__VA_ARGS__)) std::abort(); } while(0)
62  #endif
63 #endif
64 
65 // in debug mode and if not defined before, use the assert macro
66 #ifndef DUNE_ASSUME
67  #include <cassert>
68  #define DUNE_ASSUME(...) assert(bool(__VA_ARGS__))
69 #endif
70 
71 #endif // DUNE_COMMON_STD_ASSUME_HH