assume.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_SYSTEM_ASSUME_H_
  11. #define RTC_BASE_SYSTEM_ASSUME_H_
  12. // Possibly evaluate `p`, promising the compiler that the result is true; the
  13. // compiler is allowed (but not required) to use this information when
  14. // optimizing the code. USE WITH CAUTION! If you promise the compiler things
  15. // that aren't true, it will build a broken binary for you.
  16. //
  17. // As a simple example, the compiler is allowed to transform this
  18. //
  19. // RTC_ASSUME(x == 4);
  20. // return x;
  21. //
  22. // into this
  23. //
  24. // return 4;
  25. //
  26. // It is even allowed to propagate the assumption "backwards in time", if it can
  27. // prove that it must have held at some earlier time. For example, the compiler
  28. // is allowed to transform this
  29. //
  30. // int Add(int x, int y) {
  31. // if (x == 17)
  32. // y += 1;
  33. // RTC_ASSUME(x != 17);
  34. // return x + y;
  35. // }
  36. //
  37. // into this
  38. //
  39. // int Add(int x, int y) {
  40. // return x + y;
  41. // }
  42. //
  43. // since if `x` isn't 17 on the third line of the function body, the test of `x
  44. // == 17` on the first line must fail since nothing can modify the local
  45. // variable `x` in between.
  46. //
  47. // The intended use is to allow the compiler to optimize better. For example,
  48. // here we allow the compiler to omit an instruction that ensures correct
  49. // rounding of negative arguments:
  50. //
  51. // int DivBy2(int x) {
  52. // RTC_ASSUME(x >= 0);
  53. // return x / 2;
  54. // }
  55. //
  56. // and here we allow the compiler to possibly omit a null check:
  57. //
  58. // void Delete(int* p) {
  59. // RTC_ASSUME(p != nullptr);
  60. // delete p;
  61. // }
  62. //
  63. // clang-format off
  64. #if defined(__GNUC__)
  65. #define RTC_ASSUME(p) do { if (!(p)) __builtin_unreachable(); } while (0)
  66. #else
  67. #define RTC_ASSUME(p) do {} while (0)
  68. #endif
  69. // clang-format on
  70. #endif // RTC_BASE_SYSTEM_ASSUME_H_