LLVM 23.0.0git
Threading.inc
Go to the documentation of this file.
1//===- Windows/Threading.inc - Win32 Threading Implementation - -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides the Win32 specific implementation of Threading functions.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/Twine.h"
15#include "llvm/Support/thread.h"
16
18#include <process.h>
19
20#include <bitset>
21
22// Windows will at times define MemoryFence.
23#ifdef MemoryFence
24#undef MemoryFence
25#endif
26
27namespace llvm {
28HANDLE
29llvm_execute_on_thread_impl(unsigned(__stdcall *ThreadFunc)(void *), void *Arg,
30 std::optional<unsigned> StackSizeInBytes) {
31 HANDLE hThread = (HANDLE)::_beginthreadex(NULL, StackSizeInBytes.value_or(0),
32 ThreadFunc, Arg, 0, NULL);
33
34 if (!hThread)
35 ReportLastErrorFatal("_beginthreadex failed");
36
37 return hThread;
38}
39
40void llvm_thread_join_impl(HANDLE hThread) {
41 if (::WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED)
42 ReportLastErrorFatal("WaitForSingleObject failed");
43 if (::CloseHandle(hThread) == FALSE)
44 ReportLastErrorFatal("CloseHandle failed");
45}
46
47void llvm_thread_detach_impl(HANDLE hThread) {
48 if (::CloseHandle(hThread) == FALSE)
49 ReportLastErrorFatal("CloseHandle failed");
50}
51
52DWORD llvm_thread_get_id_impl(HANDLE hThread) { return ::GetThreadId(hThread); }
53
54DWORD llvm_thread_get_current_id_impl() { return ::GetCurrentThreadId(); }
55
56} // namespace llvm
57
58uint64_t llvm::get_threadid() { return uint64_t(::GetCurrentThreadId()); }
59
61
62#if defined(_MSC_VER)
63static void SetThreadName(DWORD Id, LPCSTR Name) {
64 constexpr DWORD MS_VC_EXCEPTION = 0x406D1388;
65
66#pragma pack(push, 8)
67 struct THREADNAME_INFO {
68 DWORD dwType; // Must be 0x1000.
69 LPCSTR szName; // Pointer to thread name
70 DWORD dwThreadId; // Thread ID (-1 == current thread)
71 DWORD dwFlags; // Reserved. Do not use.
72 };
73#pragma pack(pop)
74
75 THREADNAME_INFO info;
76 info.dwType = 0x1000;
77 info.szName = Name;
78 info.dwThreadId = Id;
79 info.dwFlags = 0;
80
81 __try {
82 ::RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR),
83 (ULONG_PTR *)&info);
84 } __except (EXCEPTION_EXECUTE_HANDLER) {
85 }
86}
87#endif
88
89void llvm::set_thread_name(const Twine &Name) {
90#if defined(_MSC_VER)
91 // Make sure the input is null terminated.
92 SmallString<64> Storage;
93 StringRef NameStr = Name.toNullTerminatedStringRef(Storage);
94 SetThreadName(::GetCurrentThreadId(), NameStr.data());
95#endif
96}
97
98void llvm::get_thread_name(SmallVectorImpl<char> &Name) {
99 // "Name" is not an inherent property of a thread on Windows. In fact, when
100 // you "set" the name, you are only firing a one-time message to a debugger
101 // which it interprets as a program setting its threads' name. We may be
102 // able to get fancy by creating a TLS entry when someone calls
103 // set_thread_name so that subsequent calls to get_thread_name return this
104 // value.
105 Name.clear();
106}
107
109llvm::set_thread_priority(ThreadPriority Priority) {
110#ifdef THREAD_POWER_THROTTLING_CURRENT_VERSION
111 HMODULE kernelM = llvm::sys::windows::loadSystemModuleSecure(L"kernel32.dll");
112 if (kernelM) {
113 // SetThreadInformation is only available on Windows 8 and later. Since we
114 // still support compilation on Windows 7, we load the function dynamically.
115 typedef BOOL(WINAPI * SetThreadInformation_t)(
116 HANDLE hThread, THREAD_INFORMATION_CLASS ThreadInformationClass,
117 _In_reads_bytes_(ThreadInformationSize) PVOID ThreadInformation,
118 ULONG ThreadInformationSize);
119 static const auto pfnSetThreadInformation =
120 (SetThreadInformation_t)::GetProcAddress(kernelM,
121 "SetThreadInformation");
122 if (pfnSetThreadInformation) {
123 auto setThreadInformation = [](ULONG ControlMaskAndStateMask) {
124 THREAD_POWER_THROTTLING_STATE state{};
125 state.Version = THREAD_POWER_THROTTLING_CURRENT_VERSION;
126 state.ControlMask = ControlMaskAndStateMask;
127 state.StateMask = ControlMaskAndStateMask;
128 return pfnSetThreadInformation(
129 ::GetCurrentThread(), ThreadPowerThrottling, &state, sizeof(state));
130 };
131
132 // Use EcoQoS for ThreadPriority::Background available (running on most
133 // efficent cores at the most efficient cpu frequency):
134 // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadinformation
135 // https://learn.microsoft.com/en-us/windows/win32/procthread/quality-of-service
136 setThreadInformation(Priority == ThreadPriority::Background
137 ? THREAD_POWER_THROTTLING_EXECUTION_SPEED
138 : 0);
139 }
140 }
141#endif
142
143 // https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-setthreadpriority
144 // Begin background processing mode. The system lowers the resource scheduling
145 // priorities of the thread so that it can perform background work without
146 // significantly affecting activity in the foreground.
147 // End background processing mode. The system restores the resource scheduling
148 // priorities of the thread as they were before the thread entered background
149 // processing mode.
150 //
151 // FIXME: consider THREAD_PRIORITY_BELOW_NORMAL for Low
152 return SetThreadPriority(GetCurrentThread(),
153 Priority != ThreadPriority::Default
154 ? THREAD_MODE_BACKGROUND_BEGIN
155 : THREAD_MODE_BACKGROUND_END)
156 ? SetThreadPriorityResult::SUCCESS
157 : SetThreadPriorityResult::FAILURE;
158}
159
160struct ProcessorGroup {
161 unsigned ID;
162 unsigned AllThreads;
163 unsigned UsableThreads;
164 unsigned ThreadsPerCore;
165 uint64_t Affinity;
166
167 unsigned useableCores() const {
168 return std::max(1U, UsableThreads / ThreadsPerCore);
169 }
170};
171
172template <typename F>
173static bool IterateProcInfo(LOGICAL_PROCESSOR_RELATIONSHIP Relationship, F Fn) {
174 DWORD Len = 0;
175 BOOL R = ::GetLogicalProcessorInformationEx(Relationship, NULL, &Len);
176 if (R || GetLastError() != ERROR_INSUFFICIENT_BUFFER)
177 return false;
178
179 auto *Info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)calloc(1, Len);
180 R = ::GetLogicalProcessorInformationEx(Relationship, Info, &Len);
181 if (R) {
182 auto *End =
183 (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)((uint8_t *)Info + Len);
184 for (auto *Curr = Info; Curr < End;
185 Curr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)((uint8_t *)Curr +
186 Curr->Size)) {
187 if (Curr->Relationship != Relationship)
188 continue;
189 Fn(Curr);
190 }
191 }
192 free(Info);
193 return true;
194}
195
196static std::optional<std::vector<USHORT>> getActiveGroups() {
197 USHORT Count = 0;
198 if (::GetProcessGroupAffinity(GetCurrentProcess(), &Count, nullptr))
199 return std::nullopt;
200
201 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
202 return std::nullopt;
203
204 std::vector<USHORT> Groups;
205 Groups.resize(Count);
206 if (!::GetProcessGroupAffinity(GetCurrentProcess(), &Count, Groups.data()))
207 return std::nullopt;
208
209 return Groups;
210}
211
212static llvm::ArrayRef<ProcessorGroup> getProcessorGroups() {
213 auto computeGroups = []() {
215
216 auto HandleGroup = [&](SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *ProcInfo) {
217 GROUP_RELATIONSHIP &El = ProcInfo->Group;
218 for (unsigned J = 0; J < El.ActiveGroupCount; ++J) {
219 ProcessorGroup G;
220 G.ID = Groups.size();
221 G.AllThreads = El.GroupInfo[J].MaximumProcessorCount;
222 G.UsableThreads = El.GroupInfo[J].ActiveProcessorCount;
223 assert(G.UsableThreads <= 64);
224 G.Affinity = El.GroupInfo[J].ActiveProcessorMask;
225 Groups.push_back(G);
226 }
227 };
228
229 if (!IterateProcInfo(RelationGroup, HandleGroup))
230 return std::vector<ProcessorGroup>();
231
232 auto HandleProc = [&](SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *ProcInfo) {
233 PROCESSOR_RELATIONSHIP &El = ProcInfo->Processor;
234 assert(El.GroupCount == 1);
235 unsigned NumHyperThreads = 1;
236 // If the flag is set, each core supports more than one hyper-thread.
237 if (El.Flags & LTP_PC_SMT)
238 NumHyperThreads = std::bitset<64>(El.GroupMask[0].Mask).count();
239 unsigned I = El.GroupMask[0].Group;
240 Groups[I].ThreadsPerCore = NumHyperThreads;
241 };
242
243 if (!IterateProcInfo(RelationProcessorCore, HandleProc))
244 return std::vector<ProcessorGroup>();
245
246 auto ActiveGroups = getActiveGroups();
247 if (!ActiveGroups)
248 return std::vector<ProcessorGroup>();
249
250 // If there's an affinity mask set, assume the user wants to constrain the
251 // current process to only a single CPU group. On Windows, it is not
252 // possible for affinity masks to cross CPU group boundaries.
253 DWORD_PTR ProcessAffinityMask = 0, SystemAffinityMask = 0;
254 if (::GetProcessAffinityMask(GetCurrentProcess(), &ProcessAffinityMask,
255 &SystemAffinityMask)) {
256
257 if (ProcessAffinityMask != SystemAffinityMask) {
258 if (llvm::RunningWindows11OrGreater() && ActiveGroups->size() > 1) {
259 // The process affinity mask is spurious, due to an OS bug, ignore it.
260 return std::vector<ProcessorGroup>(Groups.begin(), Groups.end());
261 }
262
263 assert(ActiveGroups->size() == 1 &&
264 "When an affinity mask is set, the process is expected to be "
265 "assigned to a single processor group!");
266
267 unsigned CurrentGroupID = (*ActiveGroups)[0];
268 ProcessorGroup NewG{Groups[CurrentGroupID]};
269 NewG.Affinity = ProcessAffinityMask;
270 NewG.UsableThreads = llvm::popcount(ProcessAffinityMask);
271 Groups.clear();
272 Groups.push_back(NewG);
273 }
274 }
275 return std::vector<ProcessorGroup>(Groups.begin(), Groups.end());
276 };
277 static auto Groups = computeGroups();
279}
280
281template <typename R, typename UnaryPredicate>
282static unsigned aggregate(R &&Range, UnaryPredicate P) {
283 unsigned I{};
284 for (const auto &It : Range)
285 I += P(It);
286 return I;
287}
288
290 static unsigned Cores =
291 aggregate(getProcessorGroups(), [](const ProcessorGroup &G) {
292 return G.UsableThreads / G.ThreadsPerCore;
293 });
294 return Cores;
295}
296
297static int computeHostNumHardwareThreads() {
298 static unsigned Threads =
299 aggregate(getProcessorGroups(),
300 [](const ProcessorGroup &G) { return G.UsableThreads; });
301 return Threads;
302}
303
304// Finds the proper CPU socket where a thread number should go. Returns
305// 'std::nullopt' if the thread shall remain on the actual CPU socket.
306std::optional<unsigned>
307llvm::ThreadPoolStrategy::compute_cpu_socket(unsigned ThreadPoolNum) const {
308 ArrayRef<ProcessorGroup> Groups = getProcessorGroups();
309 // Only one CPU socket in the system or process affinity was set, no need to
310 // move the thread(s) to another CPU socket.
311 if (Groups.size() <= 1)
312 return std::nullopt;
313
314 // We ask for less threads than there are hardware threads per CPU socket, no
315 // need to dispatch threads to other CPU sockets.
316 unsigned MaxThreadsPerSocket =
317 UseHyperThreads ? Groups[0].UsableThreads : Groups[0].useableCores();
318 if (compute_thread_count() <= MaxThreadsPerSocket)
319 return std::nullopt;
320
321 assert(ThreadPoolNum < compute_thread_count() &&
322 "The thread index is not within thread strategy's range!");
323
324 // Assumes the same number of hardware threads per CPU socket.
325 return (ThreadPoolNum * Groups.size()) / compute_thread_count();
326}
327
328// Assign the current thread to a more appropriate CPU socket or CPU group
330 unsigned ThreadPoolNum) const {
331
332 // After Windows 11 and Windows Server 2022, let the OS do the scheduling,
333 // since a process automatically gains access to all processor groups.
335 return;
336
337 std::optional<unsigned> Socket = compute_cpu_socket(ThreadPoolNum);
338 if (!Socket)
339 return;
340 ArrayRef<ProcessorGroup> Groups = getProcessorGroups();
341 GROUP_AFFINITY Affinity{};
342 Affinity.Group = Groups[*Socket].ID;
343 Affinity.Mask = Groups[*Socket].Affinity;
344 SetThreadGroupAffinity(GetCurrentThread(), &Affinity, nullptr);
345}
346
348 GROUP_AFFINITY Affinity{};
349 GetThreadGroupAffinity(GetCurrentThread(), &Affinity);
350
351 static unsigned All =
352 aggregate(getProcessorGroups(),
353 [](const ProcessorGroup &G) { return G.AllThreads; });
354
355 unsigned StartOffset =
356 aggregate(getProcessorGroups(), [&](const ProcessorGroup &G) {
357 return G.ID < Affinity.Group ? G.AllThreads : 0;
358 });
359
361 V.resize(All);
362 for (unsigned I = 0; I < sizeof(KAFFINITY) * 8; ++I) {
363 if ((Affinity.Mask >> I) & 1)
364 V.set(StartOffset + I);
365 }
366 return V;
367}
368
369unsigned llvm::get_cpus() { return getProcessorGroups().size(); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
This file defines the SmallString class.
static const X86InstrFMA3Group Groups[]
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_ABI void apply_thread_strategy(unsigned ThreadPoolNum) const
Assign the current thread to an ideal hardware CPU or NUMA node.
LLVM_ABI std::optional< unsigned > compute_cpu_socket(unsigned ThreadPoolNum) const
Finds the CPU socket where a thread should go.
LLVM_ABI unsigned compute_thread_count() const
Retrieves the max available threads for the current strategy.
Definition Threading.cpp:43
LLVM_ABI HMODULE loadSystemModuleSecure(LPCWSTR lpModuleName)
Retrieves the handle to a in-memory system module such as ntdll.dll, while ensuring we're not retriev...
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
void ReportLastErrorFatal(const char *Msg)
LLVM_ABI llvm::BitVector get_thread_affinity_mask()
Returns a mask that represents on which hardware thread, core, CPU, NUMA group, the calling thread ca...
Definition Threading.cpp:41
LLVM_ABI uint32_t get_max_thread_name_length()
Get the maximum length of a thread name on this platform.
Definition Threading.cpp:35
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:154
LLVM_ABI SetThreadPriorityResult set_thread_priority(ThreadPriority Priority)
LLVM_ABI unsigned get_cpus()
Returns how many physical CPUs or NUMA groups the system has.
LLVM_ABI bool RunningWindows11OrGreater()
Determines if the program is running on Windows 11 or Windows Server 2022.
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
LLVM_ABI void set_thread_name(const Twine &Name)
Set the name of the current thread.
Definition Threading.cpp:37
SetThreadPriorityResult
Definition Threading.h:285
LLVM_ABI void get_thread_name(SmallVectorImpl< char > &Name)
Get the name of the current thread.
Definition Threading.cpp:39
LLVM_ABI int get_physical_cores()
Returns how many physical cores (as opposed to logical cores returned from thread::hardware_concurren...
Definition Threading.cpp:49
LLVM_ABI uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
Definition Threading.cpp:33
ArrayRef(const T &OneElt) -> ArrayRef< T >