For llvm::sys::ThreadLocalImpl instead of malloc'ing the platform-specific
[oota-llvm.git] / lib / Support / ThreadLocal.cpp
1 //===- ThreadLocal.cpp - Thread Local Data ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the llvm::sys::ThreadLocal class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Config/config.h"
15 #include "llvm/Support/ThreadLocal.h"
16
17 //===----------------------------------------------------------------------===//
18 //=== WARNING: Implementation here must contain only TRULY operating system
19 //===          independent code.
20 //===----------------------------------------------------------------------===//
21
22 #if !defined(LLVM_ENABLE_THREADS) || LLVM_ENABLE_THREADS == 0
23 // Define all methods as no-ops if threading is explicitly disabled
24 namespace llvm {
25 using namespace sys;
26 ThreadLocalImpl::ThreadLocalImpl() { }
27 ThreadLocalImpl::~ThreadLocalImpl() { }
28 void ThreadLocalImpl::setInstance(const void* d) { data = const_cast<void*>(d);}
29 const void* ThreadLocalImpl::getInstance() { return data; }
30 void ThreadLocalImpl::removeInstance() { data = 0; }
31 }
32 #else
33
34 #if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_GETSPECIFIC)
35
36 #include <cassert>
37 #include <pthread.h>
38 #include <stdlib.h>
39
40 namespace llvm {
41 using namespace sys;
42
43 ThreadLocalImpl::ThreadLocalImpl() : data(0) {
44   typedef int SIZE_TOO_BIG[sizeof(pthread_key_t) <= sizeof(data) ? 1 : -1];
45   pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
46   int errorcode = pthread_key_create(key, NULL);
47   assert(errorcode == 0);
48   (void) errorcode;
49 }
50
51 ThreadLocalImpl::~ThreadLocalImpl() {
52   pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
53   int errorcode = pthread_key_delete(*key);
54   assert(errorcode == 0);
55   (void) errorcode;
56 }
57
58 void ThreadLocalImpl::setInstance(const void* d) {
59   pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
60   int errorcode = pthread_setspecific(*key, d);
61   assert(errorcode == 0);
62   (void) errorcode;
63 }
64
65 const void* ThreadLocalImpl::getInstance() {
66   pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
67   return pthread_getspecific(*key);
68 }
69
70 void ThreadLocalImpl::removeInstance() {
71   setInstance(0);
72 }
73
74 }
75
76 #elif defined(LLVM_ON_UNIX)
77 #include "Unix/ThreadLocal.inc"
78 #elif defined( LLVM_ON_WIN32)
79 #include "Windows/ThreadLocal.inc"
80 #else
81 #warning Neither LLVM_ON_UNIX nor LLVM_ON_WIN32 set in Support/ThreadLocal.cpp
82 #endif
83 #endif