stack_space.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. #include "explorer/interpreter/stack_space.h"
  5. #include "common/check.h"
  6. #include "llvm/Support/Compiler.h"
  7. #include "llvm/Support/CrashRecoveryContext.h"
  8. namespace Carbon::Internal {
  9. static constexpr int64_t SufficientStack = 256 << 10;
  10. static constexpr int64_t DesiredStackSpace = 8 << 20;
  11. static LLVM_THREAD_LOCAL intptr_t bottom_of_stack = 0;
  12. // Returns the current bottom of stack.
  13. LLVM_NO_SANITIZE("address")
  14. LLVM_ATTRIBUTE_NOINLINE static auto GetStackPointer() -> intptr_t {
  15. #if __GNUC__ || __has_builtin(__builtin_frame_address)
  16. return reinterpret_cast<intptr_t>(__builtin_frame_address(0));
  17. #else
  18. char char_on_stack = 0;
  19. char* volatile ptr = &char_on_stack;
  20. return reinterpret_cast<intptr_t>(ptr);
  21. #endif
  22. }
  23. auto IsStackSpaceNearlyExhausted() -> bool {
  24. if (bottom_of_stack == 0) {
  25. // Not initialized on the thread; always start a new thread.
  26. return true;
  27. }
  28. return std::abs(GetStackPointer() - bottom_of_stack) >
  29. (DesiredStackSpace - SufficientStack);
  30. }
  31. auto RunWithExtraStackHelper(llvm::function_ref<void()> fn) -> void {
  32. llvm::CrashRecoveryContext context;
  33. context.RunSafelyOnThread(
  34. [&] {
  35. bottom_of_stack = GetStackPointer();
  36. fn();
  37. },
  38. DesiredStackSpace);
  39. }
  40. } // namespace Carbon::Internal