1 //===-- Implementation of crt for amdgpu ----------------------------------===// 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 "src/__support/GPU/utils.h" 10 #include "src/__support/RPC/rpc_client.h" 11 #include "src/stdlib/atexit.h" 12 #include "src/stdlib/exit.h" 13 14 extern "C" int main(int argc, char **argv, char **envp); 15 16 namespace __llvm_libc { 17 18 extern "C" uintptr_t __init_array_start[]; 19 extern "C" uintptr_t __init_array_end[]; 20 extern "C" uintptr_t __fini_array_start[]; 21 extern "C" uintptr_t __fini_array_end[]; 22 23 using InitCallback = void(int, char **, char **); 24 using FiniCallback = void(void); 25 26 static void call_init_array_callbacks(int argc, char **argv, char **env) { 27 size_t init_array_size = __init_array_end - __init_array_start; 28 for (size_t i = 0; i < init_array_size; ++i) 29 reinterpret_cast<InitCallback *>(__init_array_start[i])(argc, argv, env); 30 } 31 32 static void call_fini_array_callbacks() { 33 size_t fini_array_size = __fini_array_end - __fini_array_start; 34 for (size_t i = 0; i < fini_array_size; ++i) 35 reinterpret_cast<FiniCallback *>(__fini_array_start[i])(); 36 } 37 38 } // namespace __llvm_libc 39 40 extern "C" [[gnu::visibility("protected"), clang::amdgpu_kernel]] void 41 _begin(int argc, char **argv, char **env, void *rpc_shared_buffer) { 42 // We need to set up the RPC client first in case any of the constructors 43 // require it. 44 __llvm_libc::rpc::client.reset(__llvm_libc::rpc::DEFAULT_PORT_COUNT, 45 __llvm_libc::gpu::get_lane_size(), 46 rpc_shared_buffer); 47 48 // We want the fini array callbacks to be run after other atexit 49 // callbacks are run. So, we register them before running the init 50 // array callbacks as they can potentially register their own atexit 51 // callbacks. 52 __llvm_libc::atexit(&__llvm_libc::call_fini_array_callbacks); 53 __llvm_libc::call_init_array_callbacks(argc, argv, env); 54 } 55 56 extern "C" [[gnu::visibility("protected"), clang::amdgpu_kernel]] void 57 _start(int argc, char **argv, char **envp, int *ret) { 58 // Invoke the 'main' function with every active thread that the user launched 59 // the _start kernel with. 60 __atomic_fetch_or(ret, main(argc, argv, envp), __ATOMIC_RELAXED); 61 } 62 63 extern "C" [[gnu::visibility("protected"), clang::amdgpu_kernel]] void 64 _end(int retval) { 65 // Only a single thread should call `exit` here, the rest should gracefully 66 // return from the kernel. This is so only one thread calls the destructors 67 // registred with 'atexit' above. 68 __llvm_libc::exit(retval); 69 } 70