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 13#include "llvm/ADT/SmallString.h" 14#include "llvm/ADT/Twine.h" 15 16#include "WindowsSupport.h" 17#include <process.h> 18 19#include <bitset> 20 21// Windows will at times define MemoryFence. 22#ifdef MemoryFence 23#undef MemoryFence 24#endif 25 26static unsigned __stdcall threadFuncSync(void *Arg) { 27 SyncThreadInfo *TI = static_cast<SyncThreadInfo *>(Arg); 28 TI->UserFn(TI->UserData); 29 return 0; 30} 31 32static unsigned __stdcall threadFuncAsync(void *Arg) { 33 std::unique_ptr<AsyncThreadInfo> Info(static_cast<AsyncThreadInfo *>(Arg)); 34 (*Info)(); 35 return 0; 36} 37 38static void 39llvm_execute_on_thread_impl(unsigned (__stdcall *ThreadFunc)(void *), void *Arg, 40 llvm::Optional<unsigned> StackSizeInBytes, 41 JoiningPolicy JP) { 42 HANDLE hThread = (HANDLE)::_beginthreadex( 43 NULL, StackSizeInBytes.getValueOr(0), ThreadFunc, Arg, 0, NULL); 44 45 if (!hThread) { 46 ReportLastErrorFatal("_beginthreadex failed"); 47 } 48 49 if (JP == JoiningPolicy::Join) { 50 if (::WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED) { 51 ReportLastErrorFatal("WaitForSingleObject failed"); 52 } 53 } 54 if (::CloseHandle(hThread) == FALSE) { 55 ReportLastErrorFatal("CloseHandle failed"); 56 } 57} 58 59uint64_t llvm::get_threadid() { 60 return uint64_t(::GetCurrentThreadId()); 61} 62 63uint32_t llvm::get_max_thread_name_length() { return 0; } 64 65#if defined(_MSC_VER) 66static void SetThreadName(DWORD Id, LPCSTR Name) { 67 constexpr DWORD MS_VC_EXCEPTION = 0x406D1388; 68 69#pragma pack(push, 8) 70 struct THREADNAME_INFO { 71 DWORD dwType; // Must be 0x1000. 72 LPCSTR szName; // Pointer to thread name 73 DWORD dwThreadId; // Thread ID (-1 == current thread) 74 DWORD dwFlags; // Reserved. Do not use. 75 }; 76#pragma pack(pop) 77 78 THREADNAME_INFO info; 79 info.dwType = 0x1000; 80 info.szName = Name; 81 info.dwThreadId = Id; 82 info.dwFlags = 0; 83 84 __try { 85 ::RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), 86 (ULONG_PTR *)&info); 87 } 88 __except (EXCEPTION_EXECUTE_HANDLER) { 89 } 90} 91#endif 92 93void llvm::set_thread_name(const Twine &Name) { 94#if defined(_MSC_VER) 95 // Make sure the input is null terminated. 96 SmallString<64> Storage; 97 StringRef NameStr = Name.toNullTerminatedStringRef(Storage); 98 SetThreadName(::GetCurrentThreadId(), NameStr.data()); 99#endif 100} 101 102void llvm::get_thread_name(SmallVectorImpl<char> &Name) { 103 // "Name" is not an inherent property of a thread on Windows. In fact, when 104 // you "set" the name, you are only firing a one-time message to a debugger 105 // which it interprets as a program setting its threads' name. We may be 106 // able to get fancy by creating a TLS entry when someone calls 107 // set_thread_name so that subsequent calls to get_thread_name return this 108 // value. 109 Name.clear(); 110} 111 112SetThreadPriorityResult llvm::set_thread_priority(ThreadPriority Priority) { 113 // https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-setthreadpriority 114 // Begin background processing mode. The system lowers the resource scheduling 115 // priorities of the thread so that it can perform background work without 116 // significantly affecting activity in the foreground. 117 // End background processing mode. The system restores the resource scheduling 118 // priorities of the thread as they were before the thread entered background 119 // processing mode. 120 return SetThreadPriority(GetCurrentThread(), 121 Priority == ThreadPriority::Background 122 ? THREAD_MODE_BACKGROUND_BEGIN 123 : THREAD_MODE_BACKGROUND_END) 124 ? SetThreadPriorityResult::SUCCESS 125 : SetThreadPriorityResult::FAILURE; 126} 127 128struct ProcessorGroup { 129 unsigned ID; 130 unsigned AllThreads; 131 unsigned UsableThreads; 132 unsigned ThreadsPerCore; 133 uint64_t Affinity; 134}; 135 136template <typename F> 137static bool IterateProcInfo(LOGICAL_PROCESSOR_RELATIONSHIP Relationship, F Fn) { 138 DWORD Len = 0; 139 BOOL R = ::GetLogicalProcessorInformationEx(Relationship, NULL, &Len); 140 if (R || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { 141 return false; 142 } 143 auto *Info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)calloc(1, Len); 144 R = ::GetLogicalProcessorInformationEx(Relationship, Info, &Len); 145 if (R) { 146 auto *End = 147 (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)((uint8_t *)Info + Len); 148 for (auto *Curr = Info; Curr < End; 149 Curr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)((uint8_t *)Curr + 150 Curr->Size)) { 151 if (Curr->Relationship != Relationship) 152 continue; 153 Fn(Curr); 154 } 155 } 156 free(Info); 157 return true; 158} 159 160static ArrayRef<ProcessorGroup> getProcessorGroups() { 161 auto computeGroups = []() { 162 SmallVector<ProcessorGroup, 4> Groups; 163 164 auto HandleGroup = [&](SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *ProcInfo) { 165 GROUP_RELATIONSHIP &El = ProcInfo->Group; 166 for (unsigned J = 0; J < El.ActiveGroupCount; ++J) { 167 ProcessorGroup G; 168 G.ID = Groups.size(); 169 G.AllThreads = El.GroupInfo[J].MaximumProcessorCount; 170 G.UsableThreads = El.GroupInfo[J].ActiveProcessorCount; 171 assert(G.UsableThreads <= 64); 172 G.Affinity = El.GroupInfo[J].ActiveProcessorMask; 173 Groups.push_back(G); 174 } 175 }; 176 177 if (!IterateProcInfo(RelationGroup, HandleGroup)) 178 return std::vector<ProcessorGroup>(); 179 180 auto HandleProc = [&](SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *ProcInfo) { 181 PROCESSOR_RELATIONSHIP &El = ProcInfo->Processor; 182 assert(El.GroupCount == 1); 183 unsigned NumHyperThreads = 1; 184 // If the flag is set, each core supports more than one hyper-thread. 185 if (El.Flags & LTP_PC_SMT) 186 NumHyperThreads = std::bitset<64>(El.GroupMask[0].Mask).count(); 187 unsigned I = El.GroupMask[0].Group; 188 Groups[I].ThreadsPerCore = NumHyperThreads; 189 }; 190 191 if (!IterateProcInfo(RelationProcessorCore, HandleProc)) 192 return std::vector<ProcessorGroup>(); 193 194 // If there's an affinity mask set on one of the CPUs, then assume the user 195 // wants to constrain the current process to only a single CPU. 196 for (auto &G : Groups) { 197 if (G.UsableThreads != G.AllThreads) { 198 ProcessorGroup NewG{G}; 199 Groups.clear(); 200 Groups.push_back(NewG); 201 break; 202 } 203 } 204 205 return std::vector<ProcessorGroup>(Groups.begin(), Groups.end()); 206 }; 207 static auto Groups = computeGroups(); 208 return ArrayRef<ProcessorGroup>(Groups); 209} 210 211template <typename R, typename UnaryPredicate> 212static unsigned aggregate(R &&Range, UnaryPredicate P) { 213 unsigned I{}; 214 for (const auto &It : Range) 215 I += P(It); 216 return I; 217} 218 219// for sys::getHostNumPhysicalCores 220int computeHostNumPhysicalCores() { 221 static unsigned Cores = 222 aggregate(getProcessorGroups(), [](const ProcessorGroup &G) { 223 return G.UsableThreads / G.ThreadsPerCore; 224 }); 225 return Cores; 226} 227 228int computeHostNumHardwareThreads() { 229 static unsigned Threads = 230 aggregate(getProcessorGroups(), 231 [](const ProcessorGroup &G) { return G.UsableThreads; }); 232 return Threads; 233} 234 235// Assign the current thread to a more appropriate CPU socket or CPU group 236void llvm::ThreadPoolStrategy::apply_thread_strategy( 237 unsigned ThreadPoolNum) const { 238 ArrayRef<ProcessorGroup> Groups = getProcessorGroups(); 239 240 assert(ThreadPoolNum < compute_thread_count() && 241 "The thread index is not within thread strategy's range!"); 242 243 // In this mode, the ThreadNumber represents the core number, not the 244 // hyper-thread number. Assumes all NUMA groups have the same amount of 245 // hyper-threads. 246 if (!UseHyperThreads) 247 ThreadPoolNum *= Groups[0].ThreadsPerCore; 248 249 unsigned ThreadRangeStart = 0; 250 for (unsigned I = 0; I < Groups.size(); ++I) { 251 const ProcessorGroup &G = Groups[I]; 252 if (ThreadPoolNum >= ThreadRangeStart && 253 ThreadPoolNum < ThreadRangeStart + G.UsableThreads) { 254 255 GROUP_AFFINITY Affinity{}; 256 Affinity.Group = G.ID; 257 Affinity.Mask = G.Affinity; 258 SetThreadGroupAffinity(GetCurrentThread(), &Affinity, nullptr); 259 } 260 ThreadRangeStart += G.UsableThreads; 261 } 262} 263 264llvm::BitVector llvm::get_thread_affinity_mask() { 265 GROUP_AFFINITY Affinity{}; 266 GetThreadGroupAffinity(GetCurrentThread(), &Affinity); 267 268 static unsigned All = 269 aggregate(getProcessorGroups(), 270 [](const ProcessorGroup &G) { return G.AllThreads; }); 271 272 unsigned StartOffset = 273 aggregate(getProcessorGroups(), [&](const ProcessorGroup &G) { 274 return G.ID < Affinity.Group ? G.AllThreads : 0; 275 }); 276 277 llvm::BitVector V; 278 V.resize(All); 279 for (unsigned I = 0; I < sizeof(KAFFINITY) * 8; ++I) { 280 if ((Affinity.Mask >> I) & 1) 281 V.set(StartOffset + I); 282 } 283 return V; 284} 285 286unsigned llvm::get_cpus() { return getProcessorGroups().size(); } 287