Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[llvm][Support] thread_local threadid on Apple systems #87219

Merged
merged 1 commit into from
Apr 1, 2024

Conversation

Mogball
Copy link
Contributor

@Mogball Mogball commented Apr 1, 2024

I was profiling our compiler and noticed that llvm::get_threadid was at the top of the hotlist, taking up a surprising 5% (7 seconds) in the profile trace. It seems that computing this on MacOS systems is non-trivial, so cache the result in a thread_local.

Co-authored-by: Mehdi Amini joker.eph@gmail.com

I was profiling our compiler and noticed that `llvm::get_threadid` was
at the top of the hotlist, taking up a surprising 5% (7 seconds) in the
profile trace. It seems that computing this on MacOS systems is
non-trivial, so cache the result in a thread_local.
@llvmbot
Copy link
Collaborator

llvmbot commented Apr 1, 2024

@llvm/pr-subscribers-llvm-support

Author: Jeff Niu (Mogball)

Changes

I was profiling our compiler and noticed that llvm::get_threadid was at the top of the hotlist, taking up a surprising 5% (7 seconds) in the profile trace. It seems that computing this on MacOS systems is non-trivial, so cache the result in a thread_local.


Full diff: https://github.com/llvm/llvm-project/pull/87219.diff

1 Files Affected:

  • (modified) llvm/lib/Support/Unix/Threading.inc (+5-2)
diff --git a/llvm/lib/Support/Unix/Threading.inc b/llvm/lib/Support/Unix/Threading.inc
index 55e7dcfa4678cf..839c00c5ebbf96 100644
--- a/llvm/lib/Support/Unix/Threading.inc
+++ b/llvm/lib/Support/Unix/Threading.inc
@@ -115,8 +115,11 @@ uint64_t llvm::get_threadid() {
   // Calling "mach_thread_self()" bumps the reference count on the thread
   // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
   // count.
-  thread_port_t Self = mach_thread_self();
-  mach_port_deallocate(mach_task_self(), Self);
+  static thread_local thread_port_t Self = [] {
+    thread_port_t InitSelf = mach_thread_self();
+    mach_port_deallocate(mach_task_self(), Self);
+    return InitSelf;
+  }();
   return Self;
 #elif defined(__FreeBSD__)
   return uint64_t(pthread_getthreadid_np());

Copy link
Collaborator

@lattner lattner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice!

@joker-eph joker-eph merged commit f2f01f6 into llvm:main Apr 1, 2024
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants