check_internal.h 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_CHECK_INTERNAL_H_
  5. #define CARBON_COMMON_CHECK_INTERNAL_H_
  6. #include "common/template_string.h"
  7. #include "llvm/Support/FormatVariadic.h"
  8. namespace Carbon::Internal {
  9. // Evaluates a condition in a CHECK. This diagnoses if the condition evaluates
  10. // to the constant `true` or `false`.
  11. [[clang::always_inline]] constexpr bool
  12. // Trailing GNU function attributes are incompatible with trailing return types.
  13. // Filed as https://github.com/llvm/llvm-project/issues/118697
  14. // NOLINTNEXTLINE(modernize-use-trailing-return-type)
  15. CheckCondition(bool condition)
  16. __attribute__((diagnose_if(condition,
  17. "CHECK condition is always true; replace with "
  18. "static_assert if this is intended",
  19. "error")))
  20. __attribute__((diagnose_if(!condition,
  21. "CHECK condition is always false; replace with "
  22. "CARBON_FATAL if this is intended",
  23. "error"))) {
  24. return condition;
  25. }
  26. // Implements the check failure message printing.
  27. //
  28. // This is out-of-line and will arrange to stop the program, print any debugging
  29. // information and this string. In `!NDEBUG` mode (`dbg` and `fastbuild`), check
  30. // failures can be made non-fatal by a build flag, so this is not `[[noreturn]]`
  31. // in that case.
  32. //
  33. // This API uses `const char*` C string arguments rather than `llvm::StringRef`
  34. // because we know that these are available as C strings and passing them that
  35. // way lets the code size of calling it be smaller: it only needs to materialize
  36. // a single pointer argument for each. The runtime cost of re-computing the size
  37. // should be minimal. The extra message however might not be compile-time
  38. // guaranteed to be a C string so we use a normal `StringRef` there.
  39. #ifdef NDEBUG
  40. [[noreturn]]
  41. #endif
  42. auto CheckFailImpl(const char* kind, const char* file, int line,
  43. const char* condition_str, llvm::StringRef extra_message)
  44. -> void;
  45. // Allow converting format values; the default behaviour is to just pass them
  46. // through.
  47. template <typename T>
  48. auto ConvertFormatValue(T&& t) -> T&& {
  49. return std::forward<T>(t);
  50. }
  51. // Convert enums to larger integers so that byte-sized enums are not confused
  52. // with being chars and printed as invalid (or nul-terminating) characters.
  53. // Scoped enums are explicitly converted to integers so they can be printed
  54. // without the user writing a cast.
  55. template <typename T>
  56. requires(std::is_enum_v<std::remove_reference_t<T>>)
  57. auto ConvertFormatValue(T&& t) -> auto {
  58. if constexpr (std::is_signed_v<
  59. std::underlying_type_t<std::remove_reference_t<T>>>) {
  60. return static_cast<int64_t>(t);
  61. } else {
  62. return static_cast<uint64_t>(t);
  63. }
  64. }
  65. // Prints a check failure, including rendering any user-provided message using
  66. // a format string.
  67. //
  68. // Most of the parameters are passed as compile-time template strings to avoid
  69. // runtime cost of parameter setup in optimized builds. Each of these are passed
  70. // along to the underlying implementation to include in the final printed
  71. // message.
  72. //
  73. // Any user-provided format string and values are directly passed to
  74. // `llvm::formatv` which handles all of the formatting of output.
  75. template <TemplateString Kind, TemplateString File, int Line,
  76. TemplateString ConditionStr, TemplateString FormatStr, typename... Ts>
  77. #ifdef NDEBUG
  78. [[noreturn]]
  79. #endif
  80. [[gnu::cold, clang::noinline]] auto CheckFail(Ts&&... values) -> void {
  81. if constexpr (llvm::StringRef(FormatStr).empty()) {
  82. // Skip the format string rendering if empty. Note that we don't skip it
  83. // even if there are no values as we want to have consistent handling of
  84. // `{}`s in the format string. This case is about when there is no message
  85. // at all, just the condition.
  86. CheckFailImpl(Kind.c_str(), File.c_str(), Line, ConditionStr.c_str(), "");
  87. } else {
  88. CheckFailImpl(Kind.c_str(), File.c_str(), Line, ConditionStr.c_str(),
  89. llvm::formatv(FormatStr.c_str(),
  90. ConvertFormatValue(std::forward<Ts>(values))...)
  91. .str());
  92. }
  93. }
  94. } // namespace Carbon::Internal
  95. // Evaluates the condition of a CHECK as a boolean value.
  96. //
  97. // This performs a contextual conversion to bool, diagnoses if the condition is
  98. // always true or always false, and returns its value.
  99. #define CARBON_INTERNAL_CHECK_CONDITION(cond) \
  100. (Carbon::Internal::CheckCondition(true && (cond)))
  101. // Implements check messages without any formatted values.
  102. //
  103. // Passes each of the provided components of the message to the template
  104. // parameters of the check failure printing function above, including an empty
  105. // string for the format string. Because there are multiple template arguments,
  106. // the entire call is wrapped in parentheses.
  107. #define CARBON_INTERNAL_CHECK_IMPL(kind, file, line, condition_str) \
  108. (Carbon::Internal::CheckFail<kind, file, line, condition_str, "">())
  109. // Implements check messages with a format string and potentially formatted
  110. // values.
  111. //
  112. // Each of the main components is passed as a template arguments, and then any
  113. // formatted values are passed as arguments. Because there are multiple template
  114. // arguments, the entire call is wrapped in parentheses.
  115. #define CARBON_INTERNAL_CHECK_IMPL_FORMAT(kind, file, line, condition_str, \
  116. format_str, ...) \
  117. (Carbon::Internal::CheckFail<kind, file, line, condition_str, format_str>( \
  118. __VA_ARGS__))
  119. // Implements the failure of a check.
  120. //
  121. // Collects all the metadata about the failure to be printed, such as source
  122. // location and stringified condition, and passes those, any format string and
  123. // formatted arguments to the correct implementation macro above.
  124. #define CARBON_INTERNAL_CHECK(condition, ...) \
  125. CARBON_INTERNAL_CHECK_IMPL##__VA_OPT__(_FORMAT)( \
  126. "CHECK", __FILE__, __LINE__, #condition __VA_OPT__(, ) __VA_ARGS__)
  127. // Implements the fatal macro.
  128. //
  129. // Similar to the check failure macro, but tags the message as a fatal one and
  130. // leaves the stringified condition empty.
  131. #define CARBON_INTERNAL_FATAL(...) \
  132. (CARBON_INTERNAL_CHECK_IMPL##__VA_OPT__(_FORMAT)( \
  133. "FATAL", __FILE__, __LINE__, "" __VA_OPT__(, ) __VA_ARGS__), \
  134. CARBON_INTERNAL_FATAL_NORETURN_SUFFIX())
  135. #ifdef NDEBUG
  136. // For `DCHECK` in optimized builds we have a dead check that we want to
  137. // potentially "use" arguments, but otherwise have the minimal overhead. We
  138. // avoid forming interesting format strings here so that we don't have to
  139. // repeatedly instantiate the `Check` function above. This format string would
  140. // be an error if actually used.
  141. #define CARBON_INTERNAL_DEAD_DCHECK(condition, ...) \
  142. CARBON_INTERNAL_DEAD_DCHECK_IMPL##__VA_OPT__(_FORMAT)(__VA_ARGS__)
  143. #define CARBON_INTERNAL_DEAD_DCHECK_IMPL() \
  144. Carbon::Internal::CheckFail<"", "", 0, "", "">()
  145. #define CARBON_INTERNAL_DEAD_DCHECK_IMPL_FORMAT(format_str, ...) \
  146. Carbon::Internal::CheckFail<"", "", 0, "", "">(__VA_ARGS__)
  147. // The CheckFail function itself is noreturn in NDEBUG.
  148. #define CARBON_INTERNAL_FATAL_NORETURN_SUFFIX() void()
  149. #else
  150. #define CARBON_INTERNAL_FATAL_NORETURN_SUFFIX() std::abort()
  151. #endif
  152. #endif // CARBON_COMMON_CHECK_INTERNAL_H_