LLVM 24.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"
15#include "llvm/Support/Error.h"
18
19#include <algorithm>
20#include <atomic>
21#include <condition_variable>
22#include <functional>
23#include <mutex>
24
25namespace llvm {
26
27namespace parallel {
28
29// Strategy for the default executor used by the parallel routines provided by
30// this file. It defaults to using all hardware threads and should be
31// initialized before the first use of parallel routines.
33
34#if LLVM_ENABLE_THREADS
36#else
37inline size_t getThreadCount() { return 1; }
38#endif
39
40namespace detail {
41class Latch {
42 std::atomic<uint32_t> Count;
43 mutable std::mutex Mutex;
44 mutable std::condition_variable Cond;
45
46public:
47 explicit Latch(uint32_t Count = 0) : Count(Count) {}
48 ~Latch() { assert(Count.load(std::memory_order_relaxed) == 0); }
49
50 void inc() { Count.fetch_add(1, std::memory_order_relaxed); }
51
52 // dec() must hold Mutex so that sync() cannot observe Count==0 and
53 // destroy the Latch while dec() is still running.
54 void dec() {
55 std::lock_guard<std::mutex> lock(Mutex);
56 // fetch_sub returns the previous value; == 1 means Count is now 0.
57 if (Count.fetch_sub(1, std::memory_order_acq_rel) == 1)
58 Cond.notify_all();
59 }
60
61 uint32_t getCount() const { return Count.load(std::memory_order_acquire); }
62
63 void sync() const {
64 std::unique_lock<std::mutex> lock(Mutex);
65 Cond.wait(lock, [&] { return Count.load(std::memory_order_relaxed) == 0; });
66 }
67};
68} // namespace detail
69
70class TaskGroup {
72 bool Parallel;
73
74public:
77
78 // Spawn a task, but does not wait for it to finish.
79 LLVM_ABI void spawn(std::function<void()> f);
80
81 bool isParallel() const { return Parallel; }
82};
83
84namespace detail {
85
86#if LLVM_ENABLE_THREADS
87const ptrdiff_t MinParallelSize = 1024;
88
89/// Inclusive median.
90template <class RandomAccessIterator, class Comparator>
91RandomAccessIterator medianOf3(RandomAccessIterator Start,
92 RandomAccessIterator End,
93 const Comparator &Comp) {
94 RandomAccessIterator Mid = Start + (std::distance(Start, End) / 2);
95 return Comp(*Start, *(End - 1))
96 ? (Comp(*Mid, *(End - 1)) ? (Comp(*Start, *Mid) ? Mid : Start)
97 : End - 1)
98 : (Comp(*Mid, *Start) ? (Comp(*(End - 1), *Mid) ? Mid : End - 1)
99 : Start);
100}
101
102template <class RandomAccessIterator, class Comparator>
103void parallel_quick_sort(RandomAccessIterator Start, RandomAccessIterator End,
104 const Comparator &Comp, TaskGroup &TG, size_t Depth) {
105 // Do a sequential sort for small inputs.
106 if (std::distance(Start, End) < detail::MinParallelSize || Depth == 0) {
107 llvm::sort(Start, End, Comp);
108 return;
109 }
110
111 // Partition.
112 auto Pivot = medianOf3(Start, End, Comp);
113 // Move Pivot to End.
114 std::swap(*(End - 1), *Pivot);
115 Pivot = std::partition(Start, End - 1, [&Comp, End](decltype(*Start) V) {
116 return Comp(V, *(End - 1));
117 });
118 // Move Pivot to middle of partition.
119 std::swap(*Pivot, *(End - 1));
120
121 // Recurse.
122 TG.spawn([=, &Comp, &TG] {
123 parallel_quick_sort(Start, Pivot, Comp, TG, Depth - 1);
124 });
125 parallel_quick_sort(Pivot + 1, End, Comp, TG, Depth - 1);
126}
127
128template <class RandomAccessIterator, class Comparator>
129void parallel_sort(RandomAccessIterator Start, RandomAccessIterator End,
130 const Comparator &Comp) {
131 TaskGroup TG;
132 parallel_quick_sort(Start, End, Comp, TG,
133 llvm::Log2_64(std::distance(Start, End)) + 1);
134}
135
136// TaskGroup has a relatively high overhead, so we want to reduce
137// the number of spawn() calls. We'll create up to 1024 tasks here.
138// (Note that 1024 is an arbitrary number. This code probably needs
139// improving to take the number of available cores into account.)
140enum { MaxTasksPerGroup = 1024 };
141
142template <class IterTy, class ResultTy, class ReduceFuncTy,
143 class TransformFuncTy>
144ResultTy parallel_transform_reduce(IterTy Begin, IterTy End, ResultTy Init,
145 ReduceFuncTy Reduce,
146 TransformFuncTy Transform) {
147 // Limit the number of tasks to MaxTasksPerGroup to limit job scheduling
148 // overhead on large inputs.
149 size_t NumInputs = std::distance(Begin, End);
150 if (NumInputs == 0)
151 return std::move(Init);
152 size_t NumTasks = std::min(static_cast<size_t>(MaxTasksPerGroup), NumInputs);
153 std::vector<ResultTy> Results(NumTasks, Init);
154 {
155 // Each task processes either TaskSize or TaskSize+1 inputs. Any inputs
156 // remaining after dividing them equally amongst tasks are distributed as
157 // one extra input over the first tasks.
158 TaskGroup TG;
159 size_t TaskSize = NumInputs / NumTasks;
160 size_t RemainingInputs = NumInputs % NumTasks;
161 IterTy TBegin = Begin;
162 for (size_t TaskId = 0; TaskId < NumTasks; ++TaskId) {
163 IterTy TEnd = TBegin + TaskSize + (TaskId < RemainingInputs ? 1 : 0);
164 TG.spawn([=, &Transform, &Reduce, &Results] {
165 // Reduce the result of transformation eagerly within each task.
166 ResultTy R = Init;
167 for (IterTy It = TBegin; It != TEnd; ++It)
168 R = Reduce(R, Transform(*It));
169 Results[TaskId] = R;
170 });
171 TBegin = TEnd;
172 }
173 assert(TBegin == End);
174 }
175
176 // Do a final reduction. There are at most 1024 tasks, so this only adds
177 // constant single-threaded overhead for large inputs. Hopefully most
178 // reductions are cheaper than the transformation.
179 ResultTy FinalResult = std::move(Results.front());
180 for (ResultTy &PartialResult :
181 MutableArrayRef(Results.data() + 1, Results.size() - 1))
182 FinalResult = Reduce(FinalResult, std::move(PartialResult));
183 return std::move(FinalResult);
184}
185
186#endif
187
188} // namespace detail
189} // namespace parallel
190
191template <class RandomAccessIterator,
192 class Comparator = std::less<
193 typename std::iterator_traits<RandomAccessIterator>::value_type>>
194void parallelSort(RandomAccessIterator Start, RandomAccessIterator End,
195 const Comparator &Comp = Comparator()) {
196#if LLVM_ENABLE_THREADS
197 if (parallel::strategy.ThreadsRequested != 1) {
198 parallel::detail::parallel_sort(Start, End, Comp);
199 return;
200 }
201#endif
202 llvm::sort(Start, End, Comp);
203}
204
205LLVM_ABI void parallelFor(size_t Begin, size_t End,
206 function_ref<void(size_t)> Fn);
207
208template <class IterTy, class FuncTy>
209void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn) {
210 parallelFor(0, End - Begin, [&](size_t I) { Fn(Begin[I]); });
211}
212
213template <class IterTy, class ResultTy, class ReduceFuncTy,
214 class TransformFuncTy>
215ResultTy parallelTransformReduce(IterTy Begin, IterTy End, ResultTy Init,
216 ReduceFuncTy Reduce,
217 TransformFuncTy Transform) {
218#if LLVM_ENABLE_THREADS
219 if (parallel::strategy.ThreadsRequested != 1) {
220 return parallel::detail::parallel_transform_reduce(Begin, End, Init, Reduce,
221 Transform);
222 }
223#endif
224 for (IterTy I = Begin; I != End; ++I)
225 Init = Reduce(std::move(Init), Transform(*I));
226 return std::move(Init);
227}
228
229// Range wrappers.
230template <class RangeTy,
231 class Comparator = std::less<decltype(*std::begin(RangeTy()))>>
232void parallelSort(RangeTy &&R, const Comparator &Comp = Comparator()) {
233 parallelSort(std::begin(R), std::end(R), Comp);
234}
235
236template <class RangeTy, class FuncTy>
237void parallelForEach(RangeTy &&R, FuncTy Fn) {
238 parallelForEach(std::begin(R), std::end(R), Fn);
239}
240
241template <class RangeTy, class ResultTy, class ReduceFuncTy,
242 class TransformFuncTy>
243ResultTy parallelTransformReduce(RangeTy &&R, ResultTy Init,
244 ReduceFuncTy Reduce,
245 TransformFuncTy Transform) {
246 return parallelTransformReduce(std::begin(R), std::end(R), Init, Reduce,
247 Transform);
248}
249
250// Parallel for-each, but with error handling.
251template <class RangeTy, class FuncTy>
252Error parallelForEachError(RangeTy &&R, FuncTy Fn) {
253 // The transform_reduce algorithm requires that the initial value be copyable.
254 // Error objects are uncopyable. We only need to copy initial success values,
255 // so work around this mismatch via the C API. The C API represents success
256 // values with a null pointer. The joinErrors discards null values and joins
257 // multiple errors into an ErrorList.
259 std::begin(R), std::end(R), wrap(Error::success()),
260 [](LLVMErrorRef Lhs, LLVMErrorRef Rhs) {
261 return wrap(joinErrors(unwrap(Lhs), unwrap(Rhs)));
262 },
263 [&Fn](auto &&V) { return wrap(Fn(V)); }));
264}
265
266} // namespace llvm
267
268#endif // LLVM_SUPPORT_PARALLEL_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis Results
#define LLVM_ABI
Definition Compiler.h:215
#define I(x, y, z)
Definition MD5.cpp:57
This file contains some templates that are useful if you are working with the STL at all.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
This tells how a thread pool will be used.
Definition Threading.h:115
LLVM_ABI void spawn(std::function< void()> f)
Definition Parallel.cpp:244
bool isParallel() const
Definition Parallel.h:81
Latch(uint32_t Count=0)
Definition Parallel.h:47
uint32_t getCount() const
Definition Parallel.h:61
struct LLVMOpaqueError * LLVMErrorRef
Opaque reference to an error instance.
Definition Error.h:34
LLVM_ABI ThreadPoolStrategy strategy
Definition Parallel.cpp:27
size_t getThreadCount()
Definition Parallel.h:37
This is an optimization pass for GlobalISel generic memory operations.
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:338
void parallelSort(RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition Parallel.h:194
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:397
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:392
LLVM_ABI void parallelFor(size_t Begin, size_t End, function_ref< void(size_t)> Fn)
Definition Parallel.cpp:255
ResultTy parallelTransformReduce(IterTy Begin, IterTy End, ResultTy Init, ReduceFuncTy Reduce, TransformFuncTy Transform)
Definition Parallel.h:215
void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn)
Definition Parallel.h:209
Error parallelForEachError(RangeTy &&R, FuncTy Fn)
Definition Parallel.h:252
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880