1//===--- RunOnNewStack.cpp - Crash Recovery -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Support/ProgramStack.h"
10#include "llvm/Config/config.h"
11#include "llvm/Support/Compiler.h"
12
13#ifdef LLVM_ON_UNIX
14# include <sys/resource.h> // for getrlimit
15#endif
16
17#ifdef _MSC_VER
18# include <intrin.h> // for _AddressOfReturnAddress
19#endif
20
21#include "llvm/Support/thread.h"
22
23using namespace llvm;
24
25uintptr_t llvm::getStackPointer() {
26#if __GNUC__ || __has_builtin(__builtin_frame_address)
27 return (uintptr_t)__builtin_frame_address(0);
28#elif defined(_MSC_VER)
29 return (uintptr_t)_AddressOfReturnAddress();
30#else
31 volatile char CharOnStack = 0;
32 // The volatile store here is intended to escape the local variable, to
33 // prevent the compiler from optimizing CharOnStack into anything other
34 // than a char on the stack.
35 //
36 // Tested on: MSVC 2015 - 2019, GCC 4.9 - 9, Clang 3.2 - 9, ICC 13 - 19.
37 char *volatile Ptr = &CharOnStack;
38 return (uintptr_t)Ptr;
39#endif
40}
41
42unsigned llvm::getDefaultStackSize() {
43#ifdef LLVM_ON_UNIX
44 rlimit RL;
45 getrlimit(RLIMIT_STACK, rlimits: &RL);
46 return RL.rlim_cur;
47#else
48 // Clang recursively parses, instantiates templates, and evaluates constant
49 // expressions. We've found 8MiB to be a reasonable stack size given the way
50 // Clang works and the way C++ is commonly written.
51 return 8 << 20;
52#endif
53}
54
55void llvm::runOnNewStack(unsigned StackSize, function_ref<void()> Fn) {
56 llvm::thread Thread(
57 StackSize == 0 ? std::nullopt : std::optional<unsigned>(StackSize), Fn);
58 Thread.join();
59}
60