Loading...
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
 * Copyright (c) 2023 Apple Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef Algorithm_h
#define Algorithm_h

#include <atomic>
#include <algorithm>
#include <optional>
#include <span>

#include <dispatch/dispatch.h>

#include "Array.h"

// A global switch to force all uses of `dispatchApply` to run sequentially instead of in parallel.
// This is useful for debugging parallel algorithms.
extern bool gSerializeDispatchApply;

template<typename T, typename Fn>
void dispatchApply(T&& container, Fn fn);

constexpr uint64_t defaultMapChunkSize = 0x2000;

// mapReduce() is a generalized way to process the entire set of elements in parallel.
// It uses a map-reduce style algorithm where the entire set of elements is broken up into
// subranges (by default 8192 elements per subrange). In parallel, the subranges are passed
// to the 'map' callback along with a T object.  The map callback should process the range
// of elements and update the results in the T object. Once all elements have been processed,
// the 'reduce' callback is called with the full set of T objects. It should then combine
// all the information from the Ts.
//
// Note: since many map callbacks are in flight at the same time, each should only store any
// state information in the T object, and not in captured variables.
//
template<typename ElementTy, typename ChunkTy>
inline void mapReduce(std::span<ElementTy> elements, size_t elementsPerChunk,
                      void (^map)(size_t, ChunkTy&, std::span<ElementTy>),
                      void (^reduce)(std::span<ChunkTy>)=nullptr)
{
    if ( elements.empty() )
        return;

    // map:
    // divvy up all elements into chunks
    // construct a T object for each chunk
    // call map(elements range) on each MAP object for a subrange of elements
    const size_t chunkCount     = (elements.size() + (elementsPerChunk - 1)) / elementsPerChunk;
    const size_t lastChunkIndex = chunkCount - 1;

    // rdar://130080127 (Inputs with lots of potential duplicate functions may exhaust available stack space)
    std::unique_ptr<ChunkTy[]> chunksHeapStorage;
    ChunkTy*                   chunks = nullptr;
    constexpr size_t MaxStackAllocaSize = 1 << 17; // limit at 128kb
    if ( (sizeof(ChunkTy) * chunkCount) <= MaxStackAllocaSize ) {
        void* space = alloca(sizeof(ChunkTy) * chunkCount);
        chunks = new (space) ChunkTy[chunkCount];
    } else {
        chunksHeapStorage = std::make_unique<ChunkTy[]>(chunkCount);
        chunks = chunksHeapStorage.get();
    }

    dispatchApply(std::span(chunks, chunkCount), ^(size_t i, ChunkTy& chunk) {
        if ( i == lastChunkIndex )
            map(i, chunk, elements.subspan(i * elementsPerChunk)); // Run the last chunk with whatever is left over
        else
            map(i, chunk, elements.subspan(i * elementsPerChunk, elementsPerChunk));
    });

    // reduce:
    if ( reduce )
        reduce(std::span<ChunkTy>(chunks, chunkCount));
}

template<typename ElementTy, typename Fn>
inline void dispatchForEach(std::span<ElementTy> elements, size_t elementsPerChunk, Fn fn)
{
    if ( elements.empty() )
        return;

    // divvy up all elements into chunks
    // call fn on each subrange of elements
    const size_t chunkCount     = (elements.size() + (elementsPerChunk - 1)) / elementsPerChunk;
    const size_t lastChunkIndex = chunkCount - 1;
    dispatchApply(chunkCount, [elements, elementsPerChunk, lastChunkIndex, fn](size_t chunkIndex) {
        std::span<ElementTy> chunkElements;
        if ( chunkIndex == lastChunkIndex )
            chunkElements = elements.subspan(chunkIndex * elementsPerChunk); // Run the last chunk with whatever is left over
        else
            chunkElements = elements.subspan(chunkIndex * elementsPerChunk, elementsPerChunk);

        size_t chunkStart = chunkIndex * elementsPerChunk;
        for ( size_t i = 0; i < chunkElements.size(); ++i ) {
            fn(chunkStart + i, chunkElements[i]);
        }
    });
}

template<typename ElementTy, typename Fn>
inline void dispatchForEach(std::span<ElementTy> elements, Fn fn)
{
    dispatchForEach(elements, defaultMapChunkSize, fn);
}

template<typename ElementTy, typename ChunkTy>
inline void mapReduce(std::span<ElementTy> elements, void (^map)(size_t, ChunkTy&, std::span<ElementTy>),
                      void (^reduce)(std::span<ChunkTy>)=nullptr)
{
    mapReduce(elements, defaultMapChunkSize, map, reduce);
}

#if 0
// Unused.  Leaving it here in case we want to use it for something in future.
template<typename ElementTy, typename ChunkTy>
inline void mapImmediateReduce(std::span<ElementTy> elements, size_t elementsPerChunk,
                               void (^map)(size_t, ChunkTy&, std::span<ElementTy>),
                               void (^reduce)(ChunkTy&))
{
    if ( elements.empty() )
        return;

    // map:
    // divvy up all elements into chunks
    // construct a T object for each chunk
    // call map(elements range) on each MAP object for a subrange of elements
    const size_t chunkCount     = (elements.size() + (elementsPerChunk - 1)) / elementsPerChunk;
    const size_t lastChunkIndex = chunkCount - 1;
    ChunkTy      chunksStorage[chunkCount];
    ChunkTy*     chunks = chunksStorage; // work around clang bug

    // Chunks are applied (reduced) immediately when they are the next chunk in order
    // We'll have a state per chunk and use atomics to compare them
    // When a chunk is ready, it will be atomically swapped to the ready state
    std::atomic_bool chunksStateStorage[chunkCount];
    std::atomic_bool* chunksState = chunksStateStorage; // work around clang bug
    for ( uint32_t i = 0; i != chunkCount; ++i )
        chunksStateStorage[i].store(false, std::memory_order_relaxed);

    // Chunk[0] is the next chunk we should apply
    chunksStateStorage[0].store(true, std::memory_order_relaxed);

    dispatchApply(std::span(chunks, chunkCount), ^(size_t i, ChunkTy& chunk) {
        if ( i == lastChunkIndex )
            map(i, chunk, elements.subspan(i * elementsPerChunk)); // Run the last chunk with whatever is left over
        else
            map(i, chunk, elements.subspan(i * elementsPerChunk, elementsPerChunk));

        // Our chunk now has data.  So we want to transition to the ready to be reduced state
        // If we have already been marked as the next chunk to be reduced, then we can immediately reduce now
        // If we are in the unset state, then just move to the ready state, and some other thread will do the reduce
        bool expected = false;
        if ( chunksState[i].compare_exchange_strong(expected, true) ) {
            // Our chunk wasn't next to be reduced, but we've at least marked it as ready
            // Some other thread will run reduce on it.
        } else {
            // This chunk is the next chunk, so we are going to reduce it
            size_t chunkIndex = i;
            while ( true ) {
                reduce(chunks[chunkIndex]);

                // Stop if we are out of chunks
                if ( ++chunkIndex == chunkCount )
                    break;

                // Try set the next chunk as being next to be reduced, from the false state
                // In that succeeds, then we are done here, and some other thread
                // will see the nextChunk state and handle it
                expected = false;
                if ( chunksState[chunkIndex].compare_exchange_strong(expected, true) ) {
                    break;
                }
            }
        }
    });
}
#endif

template<typename T, typename Fn>
inline void dispatchApply(T&& container, Fn fn)
{
    if constexpr ( std::is_convertible_v<T, size_t> ) {
        size_t count = container;
        if ( (count <= 1) || gSerializeDispatchApply ) {
            for ( size_t i = 0; i < count; ++i )
                fn(i);
        } else {
            dispatch_apply(count, DISPATCH_APPLY_AUTO, ^(size_t i) {
                fn(i);
            });
        }
    } else {
        if ( (container.size() <= 1) || gSerializeDispatchApply ) {
            for ( size_t i = 0; i < container.size(); ++i )
                fn(i, container[i]);
        } else {
            dispatch_apply(container.size(), DISPATCH_APPLY_AUTO, ^(size_t i) {
                fn(i, container[i]);
            });
        }
    }
}

template<typename ValTy>
inline void mergeVectorChunks(std::vector<ValTy>& outVec, std::span<std::vector<ValTy>> chunks)
{
    size_t totalSize = 0;
    for ( auto& chunk : chunks ) {
        totalSize += chunk.size();
    }
    if ( totalSize == 0 ) return;

    outVec.reserve(outVec.size() + totalSize);
    for ( auto& chunk : chunks ) {
        if ( !chunk.empty() )
            outVec.insert(outVec.end(), chunk.begin(), chunk.end());
    }
}

template<typename ValTy>
inline void mergeVectorChunks(std::vector<ValTy>& outVec, std::vector<ValTy>* chunks, size_t numChunks, size_t stride)
{
    size_t totalSize = 0;
    for ( size_t i = 0; i < numChunks; ++i ) {
        std::vector<ValTy>* chunk = (std::vector<ValTy>*)((uint8_t*)chunks + i * stride);
        totalSize += chunk->size();
    }
    if ( totalSize == 0 ) return;

    outVec.reserve(outVec.size() + totalSize);
    for ( size_t i = 0; i < numChunks; ++i ) {
        std::vector<ValTy>& chunk = *(std::vector<ValTy>*)((uint8_t*)chunks + i * stride);
        if ( !chunk.empty() )
            outVec.insert(outVec.end(), chunk.begin(), chunk.end());
    }
}

namespace details
{

// Rturns a pair of iterators of the sorted range or std::nullopt if there are less than two
// elements. Result iterators and input iterators form two sub-arrays at
// [begin, result.first] and [result.second, end] that need to be sorted by calling
// `quicksortPartTasks` recursively or with other algorithm.
template <typename It, typename Comp>
inline std::optional<std::pair<It, It>> quicksortPartTasks(It begin, It end, Comp comp) {
    size_t size = std::distance(begin, end);
    if ( size < 2 ) return std::nullopt;

    const auto pivot = *(begin + size / 2);
    auto low = begin - 1;
    auto high = end;

    while (true) {
        do {
            ++low;
        } while (comp(*low, pivot));

        do {
            --high;
        } while (comp(pivot, *high));

        if (low >= high) {
            return std::make_pair(low, high + 1);
        }

        std::swap(*low, *high);
    }
}

constexpr size_t serialThreshold = 4096;
}

inline bool shouldUseParallelSort(size_t size) { return size > details::serialThreshold; }

// NOTE: This implementation is suitable only for large ranges and when the comparison
// is expensive, e.g. strings, so that it can be done in parallel. When sorting a simple
// vector of integers the overhead of concurrency and simple quicksort implementation
// will be slower than std::sort.
//
// Parallel sort algorithm based on divide-and-conquer and quicksort algorithm.
// Regular quicksort algorithm could be written recursively as:
// quicksort(It begin, It end)
//  if ( distance(begin, end) < 2 ) return
//  auto pivot = partition(begin, end)
//  quicksort(begin, pivot)
//  quicksort(pivot + 1, end)
//
// This parallel implementation works in the same principle, but instead of
// serial recursive execution the subranges created by pivot partition
// are gathered into a worklist and processed in parallel. e.g.:
// 1. [begin, end] range is partitioned (sequentially) to create
//    two sub ranges [begin, pivot], [pivot + 1, end]
// 2. the 2 subranges are added to the worklist array
//    and then both will be partitioned concurrently to create
//    4 subranges
// 3. then the 4 subranges will create 8 new subranges etc.
// 4. this will be repeated until the number of elements in a subrange
//    exceed the details::serialThreshold limit, once the subrange
//    is smaller than the threshold it will be sorted with std::sort
//    and that will finish the recursion
template <typename It, typename Comp>
void parallelSort(It begin, It end, Comp comp)
{
    {
        size_t size = std::distance(begin, end);
        if ( size < 2 ) return;
        if ( !shouldUseParallelSort(size) ) {
            std::sort(begin, end, comp);
            return;
        }
    }

    auto startPair = details::quicksortPartTasks(begin, end, comp);
    if ( !startPair ) return;

    using TaskTy = std::pair<It, It>;
    STACK_ALLOC_OVERFLOW_SAFE_ARRAY(TaskTy, nextTasks, 1024);
    STACK_ALLOC_OVERFLOW_SAFE_ARRAY(TaskTy, currentTasks, 1024);
    auto* nextTasksPtr = &nextTasks;

    currentTasks.push_back(std::make_pair(begin, startPair->first));
    currentTasks.push_back(std::make_pair(startPair->second, end));

    do {
        nextTasks.resize(currentTasks.count() * 2);

        std::atomic_size_t nextTasksCount = 0;
        auto* nextTasksCountPtr = &nextTasksCount;

        auto doTask = ^(size_t i) {
            auto curTask = currentTasks[i];

            auto pair = details::quicksortPartTasks(curTask.first, curTask.second, comp);
            if ( pair ) {
                auto firstSize = std::distance(curTask.first, pair->first);
                auto secondSize = std::distance(pair->second, curTask.second);

                bool serialFirst = !shouldUseParallelSort(firstSize);
                bool serialSecond = !shouldUseParallelSort(secondSize);

                if ( serialFirst || serialSecond ) {
                    if ( serialFirst ) {
                        std::sort(curTask.first, pair->first, comp);
                    } else {
                        auto idx = nextTasksCountPtr->fetch_add(1, std::memory_order::relaxed);
                        (*nextTasksPtr)[idx] = std::make_pair(curTask.first, pair->first);
                    }

                    if ( serialSecond ) {
                        std::sort(pair->second, curTask.second, comp);
                    } else {
                        auto idx = nextTasksCountPtr->fetch_add(1, std::memory_order::relaxed);
                        (*nextTasksPtr)[idx] = std::make_pair(pair->second, curTask.second);
                    }
                } else {
                    auto idx = nextTasksCountPtr->fetch_add(2, std::memory_order::relaxed);
                    (*nextTasksPtr)[idx] = std::make_pair(curTask.first, pair->first);
                    (*nextTasksPtr)[idx + 1] = std::make_pair(pair->second, curTask.second);
                }
            }
        };
        if ( currentTasks.count() == 1 ) {
            doTask(0);
        } else {
            dispatch_apply(currentTasks.count(), DISPATCH_APPLY_AUTO, ^(size_t i) {
                doTask(i);
            });
        }

        nextTasks.resize(nextTasksCount);
        {
            currentTasks.clear();
            auto tmp = std::move(currentTasks);
            currentTasks = std::move(nextTasks);
            nextTasks = std::move(tmp);
        }
    } while ( !currentTasks.empty() );
}


template <typename It>
void parallelSort(It begin, It end)
{
    parallelSort(begin, end, std::less<std::remove_reference_t<decltype(*begin)>>{});
}

template <typename Container, typename Comp>
void parallelSort(Container& c, Comp comp)
{
    parallelSort(c.begin(), c.end(), comp);
}

template <typename Container>
void parallelSort(Container& c)
{
    parallelSort(c, std::less<std::remove_reference_t<decltype(*c.begin())>>{});
}

#endif /* Algorithm_h */