1 //===-- llvm/Support/ManagedStatic.h - Static Global wrapper ----*- C++ -*-===//
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 defines the ManagedStatic class and the llvm_shutdown() function.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_MANAGED_STATIC_H
15 #define LLVM_SUPPORT_MANAGED_STATIC_H
17 #include "llvm/System/Atomic.h"
18 #include "llvm/System/Threading.h"
22 /// object_creator - Helper method for ManagedStatic.
24 void* object_creator() {
28 /// object_deleter - Helper method for ManagedStatic.
31 void object_deleter(void *Ptr) {
35 /// ManagedStaticBase - Common base class for ManagedStatic instances.
36 class ManagedStaticBase {
38 // This should only be used as a static variable, which guarantees that this
39 // will be zero initialized.
41 mutable void (*DeleterFn)(void*);
42 mutable const ManagedStaticBase *Next;
44 void RegisterManagedStatic(void *(*creator)(), void (*deleter)(void*)) const;
46 /// isConstructed - Return true if this object has not been created yet.
47 bool isConstructed() const { return Ptr != 0; }
52 /// ManagedStatic - This transparently changes the behavior of global statics to
53 /// be lazily constructed on demand (good for reducing startup times of dynamic
54 /// libraries that link in LLVM components) and for making destruction be
55 /// explicit through the llvm_shutdown() function call.
58 class ManagedStatic : public ManagedStaticBase {
64 if (llvm_is_multithreaded()) sys::MemoryFence();
65 if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>);
67 return *static_cast<C*>(Ptr);
71 if (llvm_is_multithreaded()) sys::MemoryFence();
72 if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>);
74 return static_cast<C*>(Ptr);
76 const C &operator*() const {
78 if (llvm_is_multithreaded()) sys::MemoryFence();
79 if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>);
81 return *static_cast<C*>(Ptr);
83 const C *operator->() const {
85 if (llvm_is_multithreaded()) sys::MemoryFence();
86 if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>);
88 return static_cast<C*>(Ptr);
92 template<void (*CleanupFn)(void*)>
93 class ManagedCleanup : public ManagedStaticBase {
95 void Register() { RegisterManagedStatic(0, CleanupFn); }
98 /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
102 /// llvm_shutdown_obj - This is a simple helper class that calls
103 /// llvm_shutdown() when it is destroyed.
104 struct llvm_shutdown_obj {
105 llvm_shutdown_obj() { }
106 explicit llvm_shutdown_obj(bool multithreaded) {
107 if (multithreaded) llvm_start_multithreaded();
109 ~llvm_shutdown_obj() { llvm_shutdown(); }