1 //===-- ManagedStatic.cpp - Static Global wrapper -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ManagedStatic class and llvm_shutdown().
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/ManagedStatic.h"
15 #include "llvm/Config/config.h"
16 #include "llvm/Support/Mutex.h"
17 #include "llvm/Support/MutexGuard.h"
18 #include "llvm/Support/Threading.h"
22 static const ManagedStaticBase
*StaticList
= nullptr;
23 static sys::Mutex
*ManagedStaticMutex
= nullptr;
24 static llvm::once_flag mutex_init_flag
;
26 static void initializeMutex() {
27 ManagedStaticMutex
= new sys::Mutex();
30 static sys::Mutex
* getManagedStaticMutex() {
31 llvm::call_once(mutex_init_flag
, initializeMutex
);
32 return ManagedStaticMutex
;
35 void ManagedStaticBase::RegisterManagedStatic(void *(*Creator
)(),
36 void (*Deleter
)(void*)) const {
38 if (llvm_is_multithreaded()) {
39 MutexGuard
Lock(*getManagedStaticMutex());
41 if (!Ptr
.load(std::memory_order_relaxed
)) {
42 void *Tmp
= Creator();
44 Ptr
.store(Tmp
, std::memory_order_release
);
47 // Add to list of managed statics.
52 assert(!Ptr
&& !DeleterFn
&& !Next
&&
53 "Partially initialized ManagedStatic!?");
57 // Add to list of managed statics.
63 void ManagedStaticBase::destroy() const {
64 assert(DeleterFn
&& "ManagedStatic not initialized correctly!");
65 assert(StaticList
== this &&
66 "Not destroyed in reverse order of construction?");
79 /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
80 void llvm::llvm_shutdown() {
81 MutexGuard
Lock(*getManagedStaticMutex());
84 StaticList
->destroy();