| 1 | //===----------------------------------------------------------------------===// |
| 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 | #include "lld/Common/Parallel.h" |
| 10 | #include "llvm/Support/Parallel.h" |
| 11 | #include <algorithm> |
| 12 | #include <atomic> |
| 13 | |
| 14 | using namespace llvm; |
| 15 | |
| 16 | void lld::parallelForSharded(size_t numShards, size_t end, |
| 17 | function_ref<void(size_t, size_t)> fn) { |
| 18 | std::atomic<size_t> next = 0; |
| 19 | auto work = [&](size_t shard) { |
| 20 | for (size_t i; (i = next.fetch_add(i: 1, m: std::memory_order_relaxed)) < end;) |
| 21 | fn(shard, i); |
| 22 | }; |
| 23 | // Run shard 0 on the calling thread. |
| 24 | parallel::TaskGroup tg; |
| 25 | for (size_t shard = 1, e = std::min(a: numShards, b: end); shard < e; ++shard) |
| 26 | tg.spawn(f: [&, shard] { work(shard); }); |
| 27 | work(0); |
| 28 | } |
| 29 | |
| 30 | void lld::parallelForFineGrained(size_t end, function_ref<void(size_t)> fn) { |
| 31 | parallelForSharded(numShards: parallel::getThreadCount(), end, |
| 32 | fn: [&](size_t, size_t i) { fn(i); }); |
| 33 | } |
| 34 | |