new helper class to provide more explicit management of static ctor/dtors.
[oota-llvm.git] / include / llvm / Support / ManagedStatic.h
1 //===-- llvm/Support/ManagedStatic.h - Static Global wrapper ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ManagedStatic class and the llvm_shutdown() function.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_SUPPORT_MANAGED_STATIC_H
15 #define LLVM_SUPPORT_MANAGED_STATIC_H
16
17 namespace llvm {
18
19 /// object_deleter - Helper method for ManagedStatic.
20 ///
21 template<class C>
22 void object_deleter(void *Ptr) {
23   delete (C*)Ptr;
24 }
25
26 /// ManagedStaticBase - Common base class for ManagedStatic instances.
27 class ManagedStaticBase {
28 protected:
29   // This should only be used as a static variable, which guarantees that this
30   // will be zero initialized.
31   mutable void *Ptr;
32   mutable void (*DeleterFn)(void*);
33   mutable const ManagedStaticBase *Next;
34   
35   void RegisterManagedStatic(void *ObjPtr, void (*deleter)(void*)) const;
36 public:
37   void destroy() const;
38 };
39
40 /// ManagedStatic - This transparently changes the behavior of global statics to
41 /// be lazily constructed on demand (good for reducing startup times of dynamic
42 /// libraries that link in LLVM components) and for making destruction be
43 /// explicit through the llvm_shutdown() function call.
44 ///
45 template<class C>
46 class ManagedStatic : public ManagedStaticBase {
47 public:
48   
49   // Accessors.
50   C &operator*() {
51     if (!Ptr) LazyInit();
52     return *static_cast<C*>(Ptr);
53   }
54   C *operator->() {
55     if (!Ptr) LazyInit();
56     return static_cast<C*>(Ptr);
57   }
58   const C &operator*() const {
59     if (!Ptr) LazyInit();
60     return *static_cast<C*>(Ptr);
61   }
62   const C *operator->() const {
63     if (!Ptr) LazyInit();
64     return static_cast<C*>(Ptr);
65   }
66   
67 public:
68   void LazyInit() const {
69     RegisterManagedStatic(new C(), object_deleter<C>);
70   }
71 };
72
73
74 /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
75 void llvm_shutdown();
76
77 }
78
79 #endif