In libobjc/:
authornicola <nicola@138bc75d-0d04-0410-961f-82ee72b054a4>
Tue, 14 Sep 2010 10:23:37 +0000 (10:23 +0000)
committernicola <nicola@138bc75d-0d04-0410-961f-82ee72b054a4>
Tue, 14 Sep 2010 10:23:37 +0000 (10:23 +0000)
       Implemented objc_sync_enter() and objc_sync_exit(), which are
       required by @synchronized() to work.
       * objc-sync.c: New file.
       * objc/objc-sync.h: New file.
       * objc-private/objc-sync.h: New file.
       * init.c (__objc_exec_class): Call __objc_sync_init() during the
       Objective-C runtime startup.
       * Makefile.in: Added objc-sync.c and objc-sync.h.
       * configure.ac: Added GCC_CHECK_TLS.
       * acinclude.m4: Include ../config/enable.m4 and ../config/tls.m4.
       * configure: Regenerated.
       * config.h.in: Regenerated.

git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/trunk@164276 138bc75d-0d04-0410-961f-82ee72b054a4

libobjc/ChangeLog
libobjc/Makefile.in
libobjc/acinclude.m4
libobjc/config.h.in
libobjc/configure
libobjc/configure.ac
libobjc/init.c
libobjc/objc-private/objc-sync.h [new file with mode: 0644]
libobjc/objc-sync.c [new file with mode: 0644]
libobjc/objc/objc-sync.h [new file with mode: 0644]

index 39bcd16..9022c1b 100644 (file)
@@ -1,3 +1,18 @@
+2010-09-14  Nicola Pero  <nicola.pero@meta-innovation.com>
+
+       Implemented objc_sync_enter() and objc_sync_exit(), which are
+       required by @synchronized() to work.
+       * objc-sync.c: New file.
+       * objc/objc-sync.h: New file.
+       * objc-private/objc-sync.h: New file.
+       * init.c (__objc_exec_class): Call __objc_sync_init() during the
+       Objective-C runtime startup.
+       * Makefile.in: Added objc-sync.c and objc-sync.h.
+       * configure.ac: Added GCC_CHECK_TLS.
+       * acinclude.m4: Include ../config/enable.m4 and ../config/tls.m4.
+       * configure: Regenerated.
+       * config.h.in: Regenerated.
+       
 2010-09-12  Nicola Pero  <nicola.pero@meta-innovation.com>
 
        * Makefile.in (%_gc.lo): New pattern rules to build the
index e5116a9..78d5bb0 100644 (file)
@@ -111,6 +111,7 @@ INCLUDES = -I$(srcdir)/$(MULTISRCTOP)../gcc \
 OBJC_H = \
   objc.h \
   objc-exception.h \
+  objc-sync.h \
   \
   NXConstStr.h \
   Object.h \
@@ -159,6 +160,7 @@ C_SOURCE_FILES = \
    init.c \
    memory.c \
    nil_method.c \
+   objc-sync.c \
    objects.c \
    sarray.c \
    selector.c \
index 6a0bbc4..581a5f2 100644 (file)
@@ -1,4 +1,4 @@
-dnl Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2004
+dnl Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2010
 dnl Free Software Foundation, Inc.
 dnl This file is free software; the Free Software Foundation
 dnl gives unlimited permission to copy and/or distribute it,
@@ -11,6 +11,8 @@ dnl PARTICULAR PURPOSE.
 
 m4_include(../config/acx.m4)
 m4_include(../config/no-executables.m4)
+m4_include(../config/enable.m4)
+m4_include(../config/tls.m4)
 
 m4_include(../libtool.m4)
 dnl The lines below arrange for aclocal not to bring an installed
index 6cb1f77..d9c8172 100644 (file)
@@ -1,5 +1,8 @@
 /* config.h.in.  Generated from configure.ac by autoheader.  */
 
+/* Define to 1 if the target assembler supports thread-local storage. */
+#undef HAVE_CC_TLS
+
 /* Define to 1 if you have the <dlfcn.h> header file. */
 #undef HAVE_DLFCN_H
 
@@ -33,6 +36,9 @@
 /* Define to 1 if you have the <sys/types.h> header file. */
 #undef HAVE_SYS_TYPES_H
 
+/* Define to 1 if the target supports thread-local storage. */
+#undef HAVE_TLS
+
 /* Define to 1 if you have the <unistd.h> header file. */
 #undef HAVE_UNISTD_H
 
index 1dfcb31..ffa3a88 100755 (executable)
@@ -718,6 +718,7 @@ with_pic
 enable_fast_install
 with_gnu_ld
 enable_libtool_lock
+enable_tls
 enable_sjlj_exceptions
 '
       ac_precious_vars='build_alias
@@ -1351,6 +1352,7 @@ Optional Features:
   --enable-fast-install[=PKGS]
                           optimize for fast installation [default=yes]
   --disable-libtool-lock  avoid locking (might break parallel builds)
+  --enable-tls            Use thread-local storage [default=yes]
   --enable-sjlj-exceptions
                           force use of builtin_setjmp for exceptions
 
@@ -10566,7 +10568,7 @@ else
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
   lt_status=$lt_dlunknown
   cat > conftest.$ac_ext <<_LT_EOF
-#line 10569 "configure"
+#line 10571 "configure"
 #include "confdefs.h"
 
 #if HAVE_DLFCN_H
@@ -10672,7 +10674,7 @@ else
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
   lt_status=$lt_dlunknown
   cat > conftest.$ac_ext <<_LT_EOF
-#line 10675 "configure"
+#line 10677 "configure"
 #include "confdefs.h"
 
 #if HAVE_DLFCN_H
@@ -11232,6 +11234,215 @@ $as_echo "#define HAVE_GTHR_DEFAULT 1" >>confdefs.h
 
 fi
 
+# Check if we have thread-local storage
+
+
+   # Check whether --enable-tls was given.
+if test "${enable_tls+set}" = set; then :
+  enableval=$enable_tls;
+      case "$enableval" in
+       yes|no) ;;
+       *) as_fn_error "Argument to enable/disable tls must be yes or no" "$LINENO" 5 ;;
+      esac
+
+else
+  enable_tls=yes
+fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the target supports thread-local storage" >&5
+$as_echo_n "checking whether the target supports thread-local storage... " >&6; }
+if test "${gcc_cv_have_tls+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    if test "$cross_compiling" = yes; then :
+                if test x$gcc_no_link = xyes; then
+  as_fn_error "Link tests are not allowed after GCC_NO_EXECUTABLES." "$LINENO" 5
+fi
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+__thread int a; int b; int main() { return a = b; }
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  chktls_save_LDFLAGS="$LDFLAGS"
+                         case $host in
+           *-*-linux*)
+             LDFLAGS="-shared -Wl,--no-undefined $LDFLAGS"
+             ;;
+         esac
+         chktls_save_CFLAGS="$CFLAGS"
+         CFLAGS="-fPIC $CFLAGS"
+                 if test x$gcc_no_link = xyes; then
+  as_fn_error "Link tests are not allowed after GCC_NO_EXECUTABLES." "$LINENO" 5
+fi
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int f() { return 0; }
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  if test x$gcc_no_link = xyes; then
+  as_fn_error "Link tests are not allowed after GCC_NO_EXECUTABLES." "$LINENO" 5
+fi
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+__thread int a; int b; int f() { return a = b; }
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  gcc_cv_have_tls=yes
+else
+  gcc_cv_have_tls=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+else
+  gcc_cv_have_tls=yes
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+         CFLAGS="$chktls_save_CFLAGS"
+         LDFLAGS="$chktls_save_LDFLAGS"
+else
+  gcc_cv_have_tls=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+
+
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+__thread int a; int b; int main() { return a = b; }
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+                      chktls_save_LDFLAGS="$LDFLAGS"
+      LDFLAGS="-static $LDFLAGS"
+      if test x$gcc_no_link = xyes; then
+  as_fn_error "Link tests are not allowed after GCC_NO_EXECUTABLES." "$LINENO" 5
+fi
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int main() { return 0; }
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  if test "$cross_compiling" = yes; then :
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "cannot run test program while cross compiling
+See \`config.log' for more details." "$LINENO" 5; }
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+__thread int a; int b; int main() { return a = b; }
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  gcc_cv_have_tls=yes
+else
+  gcc_cv_have_tls=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+else
+  gcc_cv_have_tls=yes
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+      LDFLAGS="$chktls_save_LDFLAGS"
+      if test $gcc_cv_have_tls = yes; then
+                                               chktls_save_CFLAGS="$CFLAGS"
+       thread_CFLAGS=failed
+       for flag in '' '-pthread' '-lpthread'; do
+         CFLAGS="$flag $chktls_save_CFLAGS"
+         if test x$gcc_no_link = xyes; then
+  as_fn_error "Link tests are not allowed after GCC_NO_EXECUTABLES." "$LINENO" 5
+fi
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <pthread.h>
+               void *g(void *d) { return NULL; }
+int
+main ()
+{
+pthread_t t; pthread_create(&t,NULL,g,NULL);
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  thread_CFLAGS="$flag"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+         if test "X$thread_CFLAGS" != Xfailed; then
+           break
+         fi
+       done
+       CFLAGS="$chktls_save_CFLAGS"
+       if test "X$thread_CFLAGS" != Xfailed; then
+         CFLAGS="$thread_CFLAGS $chktls_save_CFLAGS"
+                                                 if test "$cross_compiling" = yes; then :
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "cannot run test program while cross compiling
+See \`config.log' for more details." "$LINENO" 5; }
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <pthread.h>
+               __thread int a;
+               static int *volatile a_in_other_thread;
+               static void *
+               thread_func (void *arg)
+               {
+                 a_in_other_thread = &a;
+                 return (void *)0;
+               }
+int
+main ()
+{
+pthread_t thread;
+               void *thread_retval;
+               int *volatile a_in_main_thread;
+               a_in_main_thread = &a;
+               if (pthread_create (&thread, (pthread_attr_t *)0,
+                                   thread_func, (void *)0))
+                 return 0;
+               if (pthread_join (thread, &thread_retval))
+                 return 0;
+               return (a_in_other_thread == a_in_main_thread);
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  gcc_cv_have_tls=yes
+else
+  gcc_cv_have_tls=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+         CFLAGS="$chktls_save_CFLAGS"
+       fi
+      fi
+else
+  gcc_cv_have_tls=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $gcc_cv_have_tls" >&5
+$as_echo "$gcc_cv_have_tls" >&6; }
+  if test "$enable_tls $gcc_cv_have_tls" = "yes yes"; then
+
+$as_echo "#define HAVE_TLS 1" >>confdefs.h
+
+  fi
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for exception model to use" >&5
 $as_echo_n "checking for exception model to use... " >&6; }
@@ -11246,7 +11457,7 @@ if test "${enable_sjlj_exceptions+set}" = set; then :
   enableval=$enable_sjlj_exceptions; :
 else
   cat > conftest.$ac_ext << EOF
-#line 11249 "configure"
+#line 11460 "configure"
 @interface Frob
 @end
 @implementation Frob
index 8820edc..ed532fa 100644 (file)
@@ -215,6 +215,8 @@ if test $target_thread_file != single; then
         [Define if the compiler has a thread header that is non single.])
 fi 
 
+# Check if we have thread-local storage
+GCC_CHECK_TLS
 
 AC_MSG_CHECKING([for exception model to use])
 AC_LANG_PUSH(C)
index de624cf..206b85b 100644 (file)
@@ -32,6 +32,7 @@ see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
 #include "objc/hash.h"
 #include "objc/objc-list.h" 
 #include "objc-private/runtime.h"
+#include "objc-private/objc-sync.h" /* For __objc_sync_init() */
 
 /* The version number of this runtime.  This must match the number 
    defined in gcc (objc-act.c).  */
@@ -550,6 +551,7 @@ __objc_exec_class (Module_t module)
       __objc_load_methods = objc_hash_new (128, 
                                           (hash_func_type)objc_hash_ptr,
                                           objc_compare_ptrs);
+      __objc_sync_init ();
       previous_constructors = 1;
     }
 
diff --git a/libobjc/objc-private/objc-sync.h b/libobjc/objc-private/objc-sync.h
new file mode 100644 (file)
index 0000000..e69d756
--- /dev/null
@@ -0,0 +1,41 @@
+/* GNU Objective C Runtime @synchronized implementation - Private functions
+   Copyright (C) 2010 Free Software Foundation, Inc.
+   Contributed by Nicola Pero <nicola.pero@meta-innovation.com>
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under the
+terms of the GNU General Public License as published by the Free Software
+Foundation; either version 3, or (at your option) any later version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+details.
+
+Under Section 7 of GPL version 3, you are granted additional
+permissions described in the GCC Runtime Library Exception, version
+3.1, as published by the Free Software Foundation.
+
+You should have received a copy of the GNU General Public License and
+a copy of the GCC Runtime Library Exception along with this program;
+see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
+<http://www.gnu.org/licenses/>.  */
+
+#ifndef __objc_private_objc_sync_INCLUDE_GNU
+#define __objc_private_objc_sync_INCLUDE_GNU
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* This function needs to be called at startup before @synchronized()
+   can be used.  */
+void
+__objc_sync_init (void);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* not __objc_private_objc_sync_INCLUDE_GNU */
diff --git a/libobjc/objc-sync.c b/libobjc/objc-sync.c
new file mode 100644 (file)
index 0000000..7f42115
--- /dev/null
@@ -0,0 +1,491 @@
+/* GNU Objective C Runtime @synchronized implementation
+   Copyright (C) 2010 Free Software Foundation, Inc.
+   Contributed by Nicola Pero <nicola.pero@meta-innovation.com>
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under the
+terms of the GNU General Public License as published by the Free Software
+Foundation; either version 3, or (at your option) any later version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+details.
+
+Under Section 7 of GPL version 3, you are granted additional
+permissions described in the GCC Runtime Library Exception, version
+3.1, as published by the Free Software Foundation.
+
+You should have received a copy of the GNU General Public License and
+a copy of the GCC Runtime Library Exception along with this program;
+see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
+<http://www.gnu.org/licenses/>.  */
+
+/*
+  This file implements objc_sync_enter() and objc_sync_exit(), the
+  two functions required to support @synchronized().
+
+  objc_sync_enter(object) needs to get a recursive lock associated
+  with 'object', and lock it.
+
+  objc_sync_exit(object) needs to get the recursive lock associated
+  with 'object', and unlock it.
+ */
+
+/* To avoid the overhead of continuously allocating and deallocating
+   locks, we implement a pool of locks.  When a lock is needed for an
+   object, we get a lock from the pool and associate it with the
+   object.
+   The lock pool need to be protected by its own lock (the
+   "protection" lock), which has to be locked then unlocked each time
+   objc_sync_enter() and objc_sync_exit() are called.  To reduce the
+   contention on the protection lock, instead of a single pool with a
+   single (global) protection lock we use a number of smaller pools,
+   each with its own pool protection lock.  To decide which lock pool
+   to use for each object, we compute a hash from the object pointer.
+   The implementation of each lock pool uses a linked list of all the
+   locks in the pool (both unlocked, and locked); this works in the
+   assumption that the number of locks concurrently required is very
+   low.  In practice, it seems that you rarely see more than a few
+   locks ever concurrently required.
+   A standard case is a thread acquiring a lock recursively, over and
+   over again: for example when most methods of a class are protected
+   by @synchronized(self) but they also call each other.  We use
+   thread-local storage to implement a cache and optimize this case.
+   The cache stores locks that the thread successfully acquired,
+   allowing objc_sync_enter() and objc_sync_exit() to locate a lock
+   which is already held by the current thread without having to use
+   any protection lock or synchronization mechanism.  It can so detect
+   recursive locks/unlocks, and transform them into no-ops that
+   require no actual locking or synchronization mechanisms at all.
+*/
+
+/* You can disable the thread-local cache (most likely to benchmark
+   the code with and without it) by compiling with
+   -DSYNC_CACHE_DISABLE, or commenting out the following line.
+ */
+/* #define SYNC_CACHE_DISABLE */
+
+/* If thread-local storage is not available, automatically disable the
+   cache.
+*/
+#ifndef HAVE_TLS
+# define SYNC_CACHE_DISABLE
+#endif
+
+#include "objc/objc-sync.h"         /* For objc_sync_enter(), objc_sync_exit() */
+#include "objc/objc-api.h"          /* For objc_malloc() */
+#include "objc/thr.h"               /* For objc_mutex_loc() and similar */
+#include "objc-private/objc-sync.h" /* For __objc_sync_init() */
+
+/* We have 32 pools of locks, each of them protected by its own
+   protection lock.  It's tempting to increase this number to reduce
+   contention; but in our tests it is high enough.
+ */
+#define SYNC_NUMBER_OF_POOLS 32
+
+/* Given an object, it determines which pool contains the associated
+   lock.
+ */
+#define SYNC_OBJECT_HASH(OBJECT) ((((size_t)OBJECT >> 8) ^ (size_t)OBJECT) & (SYNC_NUMBER_OF_POOLS - 1))
+
+/* The locks protecting each pool.  */
+static objc_mutex_t sync_pool_protection_locks[SYNC_NUMBER_OF_POOLS];
+
+/* The data structure (linked list) holding the locks.  */
+typedef struct lock_node
+{
+  /* Pointer to next entry on the list.  NULL indicates end of list.
+     You need to hold the appropriate sync_pool_protection_locks[N] to
+     read or write this variable.  */
+  struct lock_node *next;
+
+  /* The (recursive) lock.  Allocated when the node is created, and
+     always not-NULL, and unchangeable, after that.  */
+  objc_mutex_t lock;
+
+  /* This is how many times the objc_mutex_lock() has been called on
+     the lock (it is 0 when the lock is unused).  Used to track when
+     the lock is no longer associated with an object and can be reused
+     for another object.  It records "real" locks, potentially (but
+     not necessarily) by multiple threads.  You need to hold the
+     appropriate sync_pool_protection_locks[N] to read or write this
+     variable.  */
+  unsigned int usage_count;
+
+  /* The object that the lock is associated with.  This variable can
+     only be written when holding the sync_pool_protection_locks[N]
+     and when node->usage_count == 0, ie, the lock is not being used.
+     You can read this variable either when you hold the
+     sync_pool_protection_locks[N] or when you hold node->lock,
+     because in that case you know that node->usage_count can't get to
+     zero until you release the lock.  It is valid to have usage_count
+     == 0 and object != nil; in that case, the lock is not currently
+     being used, but is still currently associated with the object.
+   */
+  id object;
+
+  /* This is a counter reserved for use by the thread currently
+     holding the lock.  So, you need to hold node->lock to read or
+     write this variable.  It is normally 0, and if the cache is not
+     being used, it is kept at 0 (even if recursive locks are being
+     done; in that case, no difference is made between recursive and
+     non-recursive locks: they all increase usage_count, and call
+     objc_mutex_lock()).  When the cache is being used, a thread may
+     be able to find a lock that it already holds using the cache; in
+     that case, to perform additional locks/unlocks it can
+     increase/decrease the recursive_usage_count (which does not
+     require any synchronization with other threads, since it's
+     protected by the node->lock itself) instead of the usage_count
+     (which requires locking the pool protection lock).  And it can
+     skip the call to objc_mutex_lock/unlock too.
+   */
+  unsigned int recursive_usage_count;
+} *lock_node_ptr;
+
+
+/* The pools of locks.  Each of them is a linked list of lock_nodes.
+   In the list we keep both unlocked and locked nodes.
+ */
+static lock_node_ptr sync_pool_array[SYNC_NUMBER_OF_POOLS];
+
+#ifndef SYNC_CACHE_DISABLE
+/* We store a cache of locks acquired by each thread in thread-local
+   storage.
+*/
+static __thread lock_node_ptr *lock_cache = NULL;
+
+/* This is a conservative implementation that uses a static array of
+   fixed size as cache.  Because the cache is an array that we scan
+   linearly, the bigger it is, the slower it gets.  This does not
+   matter much at small sizes (eg, the overhead of checking 8 cache
+   slots instead of 4 is very small compared to the other overheads
+   involved such as function calls and lock/unlock operations), but at
+   large sizes it becomes important as obviously there is a size over
+   which using the cache backfires: the lookup is so slow that the
+   cache slows down the software instead of speeding it up.  In
+   practice, it seems that most threads use a small number of
+   concurrent locks, so we have a conservative implementation with a
+   fixed-size cache of 8 locks which gives a very predictable
+   behaviour.  If a thread locks lots of different locks, only the
+   first 8 get the speed benefits of the cache, but the cache remains
+   always small, fast and predictable.
+   SYNC_CACHE_SIZE is the size of the lock cache for each thread.
+ */
+#define SYNC_CACHE_SIZE 8
+#endif /* SYNC_CACHE_DISABLE */
+
+/* Called at startup by init.c.  */
+void
+__objc_sync_init (void)
+{
+  int i;
+
+  for (i = 0; i < SYNC_NUMBER_OF_POOLS; i++)
+    {
+      lock_node_ptr new_node;
+      
+      /* Create a protection lock for each pool.  */
+      sync_pool_protection_locks[i] = objc_mutex_allocate ();
+
+      /* Preallocate a lock per pool.  */
+      new_node = objc_malloc (sizeof (struct lock_node));
+      new_node->lock = objc_mutex_allocate ();
+      new_node->object = nil;
+      new_node->usage_count = 0;
+      new_node->recursive_usage_count = 0;
+      new_node->next = NULL;
+
+      sync_pool_array[i] = new_node;
+    }
+}  
+
+int
+objc_sync_enter (id object)
+{
+#ifndef SYNC_CACHE_DISABLE
+  int free_cache_slot;
+#endif
+  int hash;
+  lock_node_ptr node;
+  lock_node_ptr unused_node;
+
+  if (object == nil)
+    {
+      return OBJC_SYNC_SUCCESS;
+    }
+
+#ifndef SYNC_CACHE_DISABLE
+  if (lock_cache == NULL)
+    {
+      /* Note that this calloc only happen only once per thread, the
+        very first time a thread does a objc_sync_enter().
+       */
+      lock_cache = objc_calloc (SYNC_CACHE_SIZE, sizeof (lock_node_ptr));
+    }
+
+  /* Check the cache to see if we have a record of having already
+     locked the lock corresponding to this object.  While doing so,
+     keep track of the first free cache node in case we need it later.
+   */ 
+  node = NULL;
+  free_cache_slot = -1;
+
+  {
+    int i;
+    for (i = 0; i < SYNC_CACHE_SIZE; i++)
+      {
+       lock_node_ptr locked_node = lock_cache[i];
+       
+       if (locked_node == NULL)
+         {
+           if (free_cache_slot == -1)
+             {
+               free_cache_slot = i;
+             }
+         }
+       else if (locked_node->object == object)
+         {
+           node = locked_node;
+           break;
+         }
+      }
+  }
+
+  if (node != NULL)
+    {
+      /* We found the lock.  Increase recursive_usage_count, which is
+        protected by node->lock, which we already hold.
+       */
+      node->recursive_usage_count++;
+      
+      /* There is no need to actually lock anything, since we already
+        hold the lock.  Correspondingly, objc_sync_exit() will just
+        decrease recursive_usage_count and do nothing to unlock.
+       */
+      return OBJC_SYNC_SUCCESS;
+    }
+#endif /* SYNC_CACHE_DISABLE */
+
+  /* The following is the standard lookup for the lock in the standard
+     pool lock.  It requires a pool protection lock.
+   */
+  hash = SYNC_OBJECT_HASH(object);
+
+  /* Search for an existing lock for 'object'.  While searching, make
+     note of any unused lock if we find any.
+   */
+  unused_node = NULL;
+
+  objc_mutex_lock (sync_pool_protection_locks[hash]);
+
+  node = sync_pool_array[hash];
+
+  while (node != NULL)
+    {
+      if (node->object == object)
+       {
+         /* We found the lock.  */
+         node->usage_count++;
+         objc_mutex_unlock (sync_pool_protection_locks[hash]);
+
+#ifndef SYNC_CACHE_DISABLE
+         /* Put it in the cache.  */
+         if (free_cache_slot != -1)
+           {
+             lock_cache[free_cache_slot] = node;
+           }
+#endif
+
+         /* Lock it.  */
+         objc_mutex_lock (node->lock);
+
+         return OBJC_SYNC_SUCCESS;
+       }
+
+      if (unused_node == NULL  &&  node->usage_count == 0)
+       {
+         /* We found the first unused node.  Record it.  */
+         unused_node = node;
+       }
+      
+      node = node->next;
+    }
+
+  /* An existing lock for 'object' could not be found.  */
+  if (unused_node != NULL)
+    {
+      /* But we found a unused lock; use it.  */
+      unused_node->object = object;
+      unused_node->usage_count = 1;
+      unused_node->recursive_usage_count = 0;
+      objc_mutex_unlock (sync_pool_protection_locks[hash]);
+
+#ifndef SYNC_CACHE_DISABLE
+      if (free_cache_slot != -1)
+       {
+         lock_cache[free_cache_slot] = unused_node;
+       }
+#endif
+
+      objc_mutex_lock (unused_node->lock);
+
+      return OBJC_SYNC_SUCCESS;
+    }
+  else
+    {
+      /* There are no unused nodes; allocate a new node.  */
+      lock_node_ptr new_node;
+
+      /* Create the node.  */
+      new_node = objc_malloc (sizeof (struct lock_node));
+      new_node->lock = objc_mutex_allocate ();
+      new_node->object = object;
+      new_node->usage_count = 1;
+      new_node->recursive_usage_count = 0;
+
+      /* Attach it at the beginning of the pool.  */
+      new_node->next = sync_pool_array[hash];
+      sync_pool_array[hash] = new_node;
+      objc_mutex_unlock (sync_pool_protection_locks[hash]);
+
+#ifndef SYNC_CACHE_DISABLE
+      if (free_cache_slot != -1)
+       {
+         lock_cache[free_cache_slot] = new_node;
+       }
+#endif
+
+      objc_mutex_lock (new_node->lock);
+
+      return OBJC_SYNC_SUCCESS;
+    }
+}
+
+int
+objc_sync_exit (id object)
+{
+  int hash;
+  lock_node_ptr node;
+
+  if (object == nil)
+    {
+      return OBJC_SYNC_SUCCESS;
+    }
+  
+#ifndef SYNC_CACHE_DISABLE
+  if (lock_cache != NULL)
+    {
+      int i;
+    
+      /* Find the lock in the cache.  */
+      node = NULL;
+      for (i = 0; i < SYNC_CACHE_SIZE; i++)
+       {
+         lock_node_ptr locked_node = lock_cache[i];
+         
+         if (locked_node != NULL  &&  locked_node->object == object)
+           {
+             node = locked_node;
+             break;
+           }
+       }
+      /* Note that, if a node was found in the cache, the variable i
+        now holds the index where it was found, which will be used to
+        remove it from the cache.  */
+
+      if (node != NULL)
+       {
+         if (node->recursive_usage_count > 0)
+           {
+             node->recursive_usage_count--;
+             return OBJC_SYNC_SUCCESS;
+           }
+         else
+           {
+             /* We need to do a real unlock.  */
+             hash = SYNC_OBJECT_HASH(object);
+             
+             /* TODO: If we had atomic increase/decrease operations
+                with memory barriers, we could avoid the lock here!
+             */
+             objc_mutex_lock (sync_pool_protection_locks[hash]);
+             node->usage_count--;
+             /* Normally, we do not reset object to nil here.  We'll
+                leave the lock associated with that object, at zero
+                usage count.  This makes it slighly more efficient to
+                provide a lock for that object if (as likely)
+                requested again.  If the object is deallocated, we
+                don't care.  It will never match a new lock that is
+                requested, and the node will be reused at some point.
+
+                But, if garbage collection is enabled, leaving a
+                pointer to the object in memory might prevent the
+                object from being released.  In that case, we remove
+                it (TODO: maybe we should avoid using the garbage
+                collector at all ?  Nothing is ever deallocated in
+                this file).
+             */
+#if OBJC_WITH_GC
+             node->object = nil;
+#endif
+             objc_mutex_unlock (sync_pool_protection_locks[hash]);
+           
+             /* PS: Between objc_mutex_unlock
+                (sync_pool_protection_locks[hash]) and
+                objc_mutex_unlock (node->lock), the pool is unlocked
+                so other threads may allocate this same lock to
+                another object (!).  This is not a problem, but it is
+                curious.
+             */
+             objc_mutex_unlock (node->lock);
+             
+             /* Remove the node from the cache.  */
+             lock_cache[i] = NULL;
+             
+             return OBJC_SYNC_SUCCESS;
+           }
+       }
+    }
+#endif   
+
+  /* The cache either wasn't there, or didn't work (eg, we overflowed
+     it at some point and stopped recording new locks in the cache).
+     Proceed with a full search of the lock pool.  */
+  hash = SYNC_OBJECT_HASH(object);
+
+  objc_mutex_lock (sync_pool_protection_locks[hash]);
+
+  /* Search for an existing lock for 'object'.  */
+  node = sync_pool_array[hash];
+
+  while (node != NULL)
+    {
+      if (node->object == object)
+       {
+         /* We found the lock.  */
+         node->usage_count--;
+         objc_mutex_unlock (sync_pool_protection_locks[hash]);
+
+         objc_mutex_unlock (node->lock);
+
+         /* No need to remove the node from the cache, since it
+            wasn't found in the cache when we looked for it!
+          */
+
+         return OBJC_SYNC_SUCCESS;
+       }
+      
+      node = node->next;
+    }
+
+  objc_mutex_unlock (sync_pool_protection_locks[hash]);
+
+  /* A lock for 'object' to unlock could not be found (!!).  */
+  return OBJC_SYNC_NOT_OWNING_THREAD_ERROR;
+}
diff --git a/libobjc/objc/objc-sync.h b/libobjc/objc/objc-sync.h
new file mode 100644 (file)
index 0000000..fc8e930
--- /dev/null
@@ -0,0 +1,70 @@
+/* GNU Objective C Runtime @synchronized implementation
+   Copyright (C) 2010 Free Software Foundation, Inc.
+   Contributed by Nicola Pero <nicola.pero@meta-innovation.com>
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GCC is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+Under Section 7 of GPL version 3, you are granted additional
+permissions described in the GCC Runtime Library Exception, version
+3.1, as published by the Free Software Foundation.
+
+You should have received a copy of the GNU General Public License and
+a copy of the GCC Runtime Library Exception along with this program;
+see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
+<http://www.gnu.org/licenses/>.  */
+
+#ifndef __objc_sync_INCLUDE_GNU
+#define __objc_sync_INCLUDE_GNU
+
+#include "objc.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* These functions are automatically called by @synchronized().  */
+
+/* 'objc_sync_enter' is automatically called when entering a
+   @synchronized() block.  It locks the recursive lock associated with
+   'object'.  If 'object' is nil, it does nothing.  It returns
+   OBJC_SYNC_SUCCESS on success; see the enumeration below for error
+   values.
+   Note that you should not rely on the behaviour when 'object' is nil
+   because it could change.
+ */
+int objc_sync_enter (id object);
+
+/* 'objc_sync_exit' is automatically called when exiting from a
+   @synchronized() block.  It unlocks the recursive lock associated
+   with 'object'.  If 'object' is nil, it does nothing.  It returns
+   OBJC_SYNC_SUCCESS on success; see the enumeration below for error
+   values.
+ */
+int objc_sync_exit (id object);
+
+/* All the possible return values for objc_sync_enter() and
+   objc_sync_exit().
+ */
+enum {
+  OBJC_SYNC_SUCCESS = 0,
+  OBJC_SYNC_NOT_OWNING_THREAD_ERROR = -1,
+  OBJC_SYNC_TIMED_OUT = -2,
+  OBJC_SYNC_NOT_INITIALIZED = -3
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* not __objc_sync_INCLUDE_GNU */