Movatterモバイル変換


[0]ホーム

URL:


LLVM 20.0.0git
Parallel.h
Go to the documentation of this file.
1//===- llvm/Support/Parallel.h - Parallel algorithms ----------------------===//
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#ifndef LLVM_SUPPORT_PARALLEL_H
10#define LLVM_SUPPORT_PARALLEL_H
11
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/Config/llvm-config.h"
14#include "llvm/Support/Error.h"
15#include "llvm/Support/MathExtras.h"
16#include "llvm/Support/Threading.h"
17
18#include <algorithm>
19#include <condition_variable>
20#include <functional>
21#include <mutex>
22
23namespacellvm {
24
25namespaceparallel {
26
27// Strategy for the default executor used by the parallel routines provided by
28// this file. It defaults to using all hardware threads and should be
29// initialized before the first use of parallel routines.
30externThreadPoolStrategystrategy;
31
32#if LLVM_ENABLE_THREADS
33#define GET_THREAD_INDEX_IMPL \
34 if (parallel::strategy.ThreadsRequested == 1) \
35 return 0; \
36 assert((threadIndex != UINT_MAX) && \
37 "getThreadIndex() must be called from a thread created by " \
38 "ThreadPoolExecutor"); \
39 return threadIndex;
40
41#ifdef _WIN32
42// Direct access to thread_local variables from a different DLL isn't
43// possible with Windows Native TLS.
44unsignedgetThreadIndex();
45#else
46// Don't access this directly, use the getThreadIndex wrapper.
47externthread_localunsigned threadIndex;
48
49inlineunsignedgetThreadIndex() { GET_THREAD_INDEX_IMPL; }
50#endif
51
52size_tgetThreadCount();
53#else
54inlineunsignedgetThreadIndex() {return 0; }
55inlinesize_tgetThreadCount() {return 1; }
56#endif
57
58namespacedetail {
59classLatch {
60uint32_t Count;
61mutable std::mutexMutex;
62mutable std::condition_variable Cond;
63
64public:
65explicitLatch(uint32_t Count = 0) : Count(Count) {}
66~Latch() {
67// Ensure at least that sync() was called.
68assert(Count == 0);
69 }
70
71voidinc() {
72 std::lock_guard<std::mutex> lock(Mutex);
73 ++Count;
74 }
75
76voiddec() {
77 std::lock_guard<std::mutex> lock(Mutex);
78if (--Count == 0)
79Cond.notify_all();
80 }
81
82voidsync() const{
83 std::unique_lock<std::mutex> lock(Mutex);
84Cond.wait(lock, [&] {return Count == 0; });
85 }
86};
87}// namespace detail
88
89classTaskGroup {
90detail::Latch L;
91bool Parallel;
92
93public:
94TaskGroup();
95~TaskGroup();
96
97// Spawn a task, but does not wait for it to finish.
98// Tasks marked with \p Sequential will be executed
99// exactly in the order which they were spawned.
100voidspawn(std::function<void()> f);
101
102voidsync() const{ L.sync(); }
103
104boolisParallel() const{return Parallel; }
105};
106
107namespacedetail {
108
109#if LLVM_ENABLE_THREADS
110constptrdiff_t MinParallelSize = 1024;
111
112/// Inclusive median.
113template <class RandomAccessIterator,class Comparator>
114RandomAccessIterator medianOf3(RandomAccessIterator Start,
115 RandomAccessIteratorEnd,
116const Comparator &Comp) {
117 RandomAccessIterator Mid = Start + (std::distance(Start,End) / 2);
118return Comp(*Start, *(End - 1))
119 ? (Comp(*Mid, *(End - 1)) ? (Comp(*Start, *Mid) ? Mid : Start)
120 :End - 1)
121 : (Comp(*Mid, *Start) ? (Comp(*(End - 1), *Mid) ? Mid :End - 1)
122 : Start);
123}
124
125template <class RandomAccessIterator,class Comparator>
126void parallel_quick_sort(RandomAccessIterator Start, RandomAccessIteratorEnd,
127const Comparator &Comp, TaskGroup &TG,size_tDepth) {
128// Do a sequential sort for small inputs.
129if (std::distance(Start,End) < detail::MinParallelSize ||Depth == 0) {
130llvm::sort(Start,End, Comp);
131return;
132 }
133
134// Partition.
135auto Pivot = medianOf3(Start,End, Comp);
136// Move Pivot to End.
137std::swap(*(End - 1), *Pivot);
138 Pivot = std::partition(Start,End - 1, [&Comp,End](decltype(*Start) V) {
139return Comp(V, *(End - 1));
140 });
141// Move Pivot to middle of partition.
142std::swap(*Pivot, *(End - 1));
143
144// Recurse.
145 TG.spawn([=, &Comp, &TG] {
146 parallel_quick_sort(Start, Pivot, Comp, TG,Depth - 1);
147 });
148 parallel_quick_sort(Pivot + 1,End, Comp, TG,Depth - 1);
149}
150
151template <class RandomAccessIterator,class Comparator>
152void parallel_sort(RandomAccessIterator Start, RandomAccessIteratorEnd,
153const Comparator &Comp) {
154 TaskGroup TG;
155 parallel_quick_sort(Start,End, Comp, TG,
156llvm::Log2_64(std::distance(Start,End)) + 1);
157}
158
159// TaskGroup has a relatively high overhead, so we want to reduce
160// the number of spawn() calls. We'll create up to 1024 tasks here.
161// (Note that 1024 is an arbitrary number. This code probably needs
162// improving to take the number of available cores into account.)
163enum { MaxTasksPerGroup = 1024 };
164
165template <classIterTy,classResultTy,classReduceFuncTy,
166classTransformFuncTy>
167ResultTy parallel_transform_reduce(IterTy Begin, IterTyEnd, ResultTy Init,
168 ReduceFuncTy Reduce,
169 TransformFuncTy Transform) {
170// Limit the number of tasks to MaxTasksPerGroup to limit job scheduling
171// overhead on large inputs.
172size_t NumInputs = std::distance(Begin,End);
173if (NumInputs == 0)
174return std::move(Init);
175size_t NumTasks = std::min(static_cast<size_t>(MaxTasksPerGroup), NumInputs);
176 std::vector<ResultTy>Results(NumTasks, Init);
177 {
178// Each task processes either TaskSize or TaskSize+1 inputs. Any inputs
179// remaining after dividing them equally amongst tasks are distributed as
180// one extra input over the first tasks.
181 TaskGroup TG;
182size_t TaskSize = NumInputs / NumTasks;
183size_t RemainingInputs = NumInputs % NumTasks;
184 IterTy TBegin = Begin;
185for (size_t TaskId = 0; TaskId < NumTasks; ++TaskId) {
186 IterTy TEnd = TBegin + TaskSize + (TaskId < RemainingInputs ? 1 : 0);
187 TG.spawn([=, &Transform, &Reduce, &Results] {
188// Reduce the result of transformation eagerly within each task.
189 ResultTyR = Init;
190for (IterTy It = TBegin; It != TEnd; ++It)
191 R = Reduce(R, Transform(*It));
192Results[TaskId] =R;
193 });
194 TBegin = TEnd;
195 }
196assert(TBegin ==End);
197 }
198
199// Do a final reduction. There are at most 1024 tasks, so this only adds
200// constant single-threaded overhead for large inputs. Hopefully most
201// reductions are cheaper than the transformation.
202 ResultTy FinalResult = std::move(Results.front());
203for (ResultTy &PartialResult :
204MutableArrayRef(Results.data() + 1,Results.size() - 1))
205 FinalResult = Reduce(FinalResult, std::move(PartialResult));
206return std::move(FinalResult);
207}
208
209#endif
210
211}// namespace detail
212}// namespace parallel
213
214template <classRandomAccessIterator,
215classComparator = std::less<
216typename std::iterator_traits<RandomAccessIterator>::value_type>>
217voidparallelSort(RandomAccessIterator Start, RandomAccessIteratorEnd,
218const Comparator &Comp = Comparator()) {
219#if LLVM_ENABLE_THREADS
220if (parallel::strategy.ThreadsRequested != 1) {
221 parallel::detail::parallel_sort(Start,End, Comp);
222return;
223 }
224#endif
225llvm::sort(Start,End, Comp);
226}
227
228voidparallelFor(size_t Begin,size_tEnd, function_ref<void(size_t)> Fn);
229
230template <class IterTy,class FuncTy>
231voidparallelForEach(IterTy Begin, IterTyEnd, FuncTy Fn) {
232parallelFor(0,End - Begin, [&](size_tI) { Fn(Begin[I]); });
233}
234
235template <classIterTy,classResultTy,classReduceFuncTy,
236classTransformFuncTy>
237ResultTyparallelTransformReduce(IterTy Begin, IterTyEnd, ResultTyInit,
238 ReduceFuncTy Reduce,
239 TransformFuncTy Transform) {
240#if LLVM_ENABLE_THREADS
241if (parallel::strategy.ThreadsRequested != 1) {
242return parallel::detail::parallel_transform_reduce(Begin,End,Init, Reduce,
243 Transform);
244 }
245#endif
246for (IterTyI = Begin;I !=End; ++I)
247Init = Reduce(std::move(Init), Transform(*I));
248return std::move(Init);
249}
250
251// Range wrappers.
252template <classRangeTy,
253classComparator = std::less<decltype(*std::begin(RangeTy()))>>
254voidparallelSort(RangeTy &&R,const Comparator &Comp = Comparator()) {
255parallelSort(std::begin(R), std::end(R), Comp);
256}
257
258template <class RangeTy,class FuncTy>
259voidparallelForEach(RangeTy &&R, FuncTy Fn) {
260parallelForEach(std::begin(R), std::end(R), Fn);
261}
262
263template <classRangeTy,classResultTy,classReduceFuncTy,
264classTransformFuncTy>
265ResultTyparallelTransformReduce(RangeTy &&R, ResultTyInit,
266 ReduceFuncTy Reduce,
267 TransformFuncTy Transform) {
268returnparallelTransformReduce(std::begin(R), std::end(R),Init, Reduce,
269 Transform);
270}
271
272// Parallel for-each, but with error handling.
273template <class RangeTy,class FuncTy>
274ErrorparallelForEachError(RangeTy &&R, FuncTy Fn) {
275// The transform_reduce algorithm requires that the initial value be copyable.
276// Error objects are uncopyable. We only need to copy initial success values,
277// so work around this mismatch via the C API. The C API represents success
278// values with a null pointer. The joinErrors discards null values and joins
279// multiple errors into an ErrorList.
280returnunwrap(parallelTransformReduce(
281 std::begin(R), std::end(R),wrap(Error::success()),
282 [](LLVMErrorRef Lhs,LLVMErrorRef Rhs) {
283returnwrap(joinErrors(unwrap(Lhs),unwrap(Rhs)));
284 },
285 [&Fn](auto &&V) {returnwrap(Fn(V)); }));
286}
287
288}// namespace llvm
289
290#endif// LLVM_SUPPORT_PARALLEL_H
Results
Function Alias Analysis Results
Definition:AliasAnalysis.cpp:731
End
bool End
Definition:ELF_riscv.cpp:480
I
#define I(x, y, z)
Definition:MD5.cpp:58
MathExtras.h
Cond
const SmallVectorImpl< MachineOperand > & Cond
Definition:RISCVRedundantCopyElimination.cpp:75
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
STLExtras.h
This file contains some templates that are useful if you are working with the STL at all.
Threading.h
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition:Error.h:160
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition:Error.h:337
llvm::Init
Definition:Record.h:285
llvm::ThreadPoolStrategy
This tells how a thread pool will be used.
Definition:Threading.h:115
llvm::parallel::TaskGroup
Definition:Parallel.h:89
llvm::parallel::TaskGroup::sync
void sync() const
Definition:Parallel.h:102
llvm::parallel::TaskGroup::~TaskGroup
~TaskGroup()
Definition:Parallel.cpp:188
llvm::parallel::TaskGroup::TaskGroup
TaskGroup()
Definition:Parallel.cpp:181
llvm::parallel::TaskGroup::spawn
void spawn(std::function< void()> f)
Definition:Parallel.cpp:194
llvm::parallel::TaskGroup::isParallel
bool isParallel() const
Definition:Parallel.h:104
llvm::parallel::detail::Latch
Definition:Parallel.h:59
llvm::parallel::detail::Latch::inc
void inc()
Definition:Parallel.h:71
llvm::parallel::detail::Latch::dec
void dec()
Definition:Parallel.h:76
llvm::parallel::detail::Latch::sync
void sync() const
Definition:Parallel.h:82
llvm::parallel::detail::Latch::Latch
Latch(uint32_t Count=0)
Definition:Parallel.h:65
llvm::parallel::detail::Latch::~Latch
~Latch()
Definition:Parallel.h:66
llvm::sys::SmartMutex< false >
ptrdiff_t
uint32_t
LLVMErrorRef
struct LLVMOpaqueError * LLVMErrorRef
Opaque reference to an error instance.
Definition:Error.h:33
Error.h
detail
Definition:ClauseT.h:112
llvm::RISCVFenceField::R
@ R
Definition:RISCVBaseInfo.h:373
llvm::parallel::strategy
ThreadPoolStrategy strategy
Definition:Parallel.cpp:19
llvm::parallel::getThreadIndex
unsigned getThreadIndex()
Definition:Parallel.h:54
llvm::parallel::getThreadCount
size_t getThreadCount()
Definition:Parallel.h:55
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition:AddressRanges.h:18
llvm::Depth
@ Depth
Definition:SIMachineScheduler.h:36
llvm::Log2_64
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition:MathExtras.h:347
llvm::parallelSort
void parallelSort(RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition:Parallel.h:217
llvm::joinErrors
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition:Error.h:438
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition:STLExtras.h:1664
llvm::MutableArrayRef
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
llvm::unwrap
Attribute unwrap(LLVMAttributeRef Attr)
Definition:Attributes.h:335
llvm::wrap
LLVMAttributeRef wrap(Attribute Attr)
Definition:Attributes.h:330
llvm::parallelFor
void parallelFor(size_t Begin, size_t End, function_ref< void(size_t)> Fn)
Definition:Parallel.cpp:211
llvm::parallelTransformReduce
ResultTy parallelTransformReduce(IterTy Begin, IterTy End, ResultTy Init, ReduceFuncTy Reduce, TransformFuncTy Transform)
Definition:Parallel.h:237
llvm::parallelForEach
void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn)
Definition:Parallel.h:231
llvm::parallelForEachError
Error parallelForEachError(RangeTy &&R, FuncTy Fn)
Definition:Parallel.h:274
std::swap
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition:BitVector.h:860

Generated on Sun Jul 20 2025 07:34:56 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp