assert.h 4.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <cstdlib>
  6. #include "common/common_funcs.h"
  7. #include "common/logging/log.h"
  8. // For asserts we'd like to keep all the junk executed when an assert happens away from the
  9. // important code in the function. One way of doing this is to put all the relevant code inside a
  10. // lambda and force the compiler to not inline it. Unfortunately, MSVC seems to have no syntax to
  11. // specify __declspec on lambda functions, so what we do instead is define a noinline wrapper
  12. // template that calls the lambda. This seems to generate an extra instruction at the call-site
  13. // compared to the ideal implementation (which wouldn't support ASSERT_MSG parameters), but is good
  14. // enough for our purposes.
  15. template <typename Fn>
  16. #if defined(_MSC_VER)
  17. [[msvc::noinline, noreturn]]
  18. #elif defined(__GNUC__)
  19. [[gnu::cold, gnu::noinline, noreturn]]
  20. #endif
  21. static void
  22. assert_noinline_call(const Fn& fn) {
  23. fn();
  24. Crash();
  25. exit(1); // Keeps GCC's mouth shut about this actually returning
  26. }
  27. #define ASSERT(_a_) \
  28. do \
  29. if (!(_a_)) { \
  30. assert_noinline_call([] { LOG_CRITICAL(Debug, "Assertion Failed!"); }); \
  31. } \
  32. while (0)
  33. #define ASSERT_MSG(_a_, ...) \
  34. do \
  35. if (!(_a_)) { \
  36. assert_noinline_call([&] { LOG_CRITICAL(Debug, "Assertion Failed!\n" __VA_ARGS__); }); \
  37. } \
  38. while (0)
  39. #define UNREACHABLE() assert_noinline_call([] { LOG_CRITICAL(Debug, "Unreachable code!"); })
  40. #define UNREACHABLE_MSG(...) \
  41. assert_noinline_call([&] { LOG_CRITICAL(Debug, "Unreachable code!\n" __VA_ARGS__); })
  42. #ifdef _DEBUG
  43. #define DEBUG_ASSERT(_a_) ASSERT(_a_)
  44. #define DEBUG_ASSERT_MSG(_a_, ...) ASSERT_MSG(_a_, __VA_ARGS__)
  45. #else // not debug
  46. #define DEBUG_ASSERT(_a_)
  47. #define DEBUG_ASSERT_MSG(_a_, _desc_, ...)
  48. #endif
  49. #define UNIMPLEMENTED() ASSERT_MSG(false, "Unimplemented code!")
  50. #define UNIMPLEMENTED_MSG(...) ASSERT_MSG(false, __VA_ARGS__)
  51. #define UNIMPLEMENTED_IF(cond) ASSERT_MSG(!(cond), "Unimplemented code!")
  52. #define UNIMPLEMENTED_IF_MSG(cond, ...) ASSERT_MSG(!(cond), __VA_ARGS__)
  53. // If the assert is ignored, execute _b_
  54. #define ASSERT_OR_EXECUTE(_a_, _b_) \
  55. do { \
  56. ASSERT(_a_); \
  57. if (!(_a_)) { \
  58. _b_ \
  59. } \
  60. } while (0)
  61. // If the assert is ignored, execute _b_
  62. #define ASSERT_OR_EXECUTE_MSG(_a_, _b_, ...) \
  63. do { \
  64. ASSERT_MSG(_a_, __VA_ARGS__); \
  65. if (!(_a_)) { \
  66. _b_ \
  67. } \
  68. } while (0)