blob: 889289587bd0f389e63c57f0f4b37418e3d8e831 [file] [log] [blame]
Jeremy Gebben65975ed2021-10-29 11:16:10 -06001/* Copyright (c) 2015-2017, 2019-2022 The Khronos Group Inc.
2 * Copyright (c) 2015-2017, 2019-2022 Valve Corporation
3 * Copyright (c) 2015-2017, 2019-2022 LunarG, Inc.
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -06004 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -06005 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -06008 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -06009 * http://www.apache.org/licenses/LICENSE-2.0
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060010 *
Jon Ashburn3ebf1252016-04-19 11:30:31 -060011 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060016 *
Jon Ashburne922f712015-11-03 13:41:23 -070017 * Author: Mark Lobodzinski <mark@lunarg.com>
18 * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
Dave Houlton59a20702017-02-02 17:26:23 -070019 * Author: Dave Houlton <daveh@lunarg.com>
Mark Lobodzinski6eda00a2016-02-02 15:55:36 -070020 */
21
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060022#pragma once
John Zulauff05b3772019-04-03 18:04:23 -060023
24#include <cassert>
25#include <cstddef>
26#include <functional>
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060027#include <stdbool.h>
John Zulauf965d88d2018-04-12 15:47:26 -060028#include <string>
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -060029#include <vector>
Mark Lobodzinski44145db2020-08-11 08:01:47 -060030#include <iomanip>
John Zulauf2c2ccd42019-04-05 13:13:13 -060031#include "cast_utils.h"
Dave Houlton3c9fca72017-03-27 17:25:54 -060032#include "vk_format_utils.h"
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -060033#include "vk_layer_logging.h"
34
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -060035#ifndef WIN32
Mark Lobodzinski64318ba2017-01-26 13:34:13 -070036#include <strings.h> // For ffs()
Courtney Goeltzenleuchter3698c622015-10-27 11:23:21 -060037#else
Mark Lobodzinski64318ba2017-01-26 13:34:13 -070038#include <intrin.h> // For __lzcnt()
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -060039#endif
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060040
Petr Krausc3382e92019-12-14 00:41:30 +010041#define STRINGIFY(s) STRINGIFY_HELPER(s)
42#define STRINGIFY_HELPER(s) #s
43
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -060044#ifdef __cplusplus
John Zulauf1507ee42020-05-18 11:33:09 -060045static inline VkExtent3D CastTo3D(const VkExtent2D &d2) {
46 VkExtent3D d3 = {d2.width, d2.height, 1};
47 return d3;
48}
49
50static inline VkOffset3D CastTo3D(const VkOffset2D &d2) {
51 VkOffset3D d3 = {d2.x, d2.y, 0};
52 return d3;
53}
54
Mark Lobodzinski44145db2020-08-11 08:01:47 -060055// Convert integer API version to a string
56static inline std::string StringAPIVersion(uint32_t version) {
57 std::stringstream version_name;
58 uint32_t major = VK_VERSION_MAJOR(version);
59 uint32_t minor = VK_VERSION_MINOR(version);
60 uint32_t patch = VK_VERSION_PATCH(version);
61 version_name << major << "." << minor << "." << patch << " (0x" << std::setfill('0') << std::setw(8) << std::hex << version
62 << ")";
63 return version_name.str();
64}
65
John Zulauf965d88d2018-04-12 15:47:26 -060066// Traits objects to allow string_join to operate on collections of const char *
67template <typename String>
68struct StringJoinSizeTrait {
69 static size_t size(const String &str) { return str.size(); }
70};
71
72template <>
73struct StringJoinSizeTrait<const char *> {
74 static size_t size(const char *str) {
75 if (!str) return 0;
76 return strlen(str);
77 }
78};
79// Similar to perl/python join
80// * String must support size, reserve, append, and be default constructable
81// * StringCollection must support size, const forward iteration, and store
82// strings compatible with String::append
83// * Accessor trait can be set if default accessors (compatible with string
84// and const char *) don't support size(StringCollection::value_type &)
85//
86// Return type based on sep type
87template <typename String = std::string, typename StringCollection = std::vector<String>,
88 typename Accessor = StringJoinSizeTrait<typename StringCollection::value_type>>
89static inline String string_join(const String &sep, const StringCollection &strings) {
90 String joined;
91 const size_t count = strings.size();
92 if (!count) return joined;
93
94 // Prereserved storage, s.t. we will execute in linear time (avoids reallocation copies)
95 size_t reserve = (count - 1) * sep.size();
96 for (const auto &str : strings) {
97 reserve += Accessor::size(str); // abstracted to allow const char * type in StringCollection
98 }
99 joined.reserve(reserve + 1);
100
101 // Seps only occur *between* strings entries, so first is special
102 auto current = strings.cbegin();
103 joined.append(*current);
104 ++current;
105 for (; current != strings.cend(); ++current) {
106 joined.append(sep);
107 joined.append(*current);
108 }
109 return joined;
110}
111
112// Requires StringCollection::value_type has a const char * constructor and is compatible the string_join::String above
113template <typename StringCollection = std::vector<std::string>, typename SepString = std::string>
114static inline SepString string_join(const char *sep, const StringCollection &strings) {
115 return string_join<SepString, StringCollection>(SepString(sep), strings);
116}
117
Petr Kraus168417e2019-09-07 16:45:40 +0200118static inline std::string string_trim(const std::string &s) {
119 const char *whitespace = " \t\f\v\n\r";
120
121 const auto trimmed_beg = s.find_first_not_of(whitespace);
122 if (trimmed_beg == std::string::npos) return "";
123
124 const auto trimmed_end = s.find_last_not_of(whitespace);
125 assert(trimmed_end != std::string::npos && trimmed_beg <= trimmed_end);
126
127 return s.substr(trimmed_beg, trimmed_end - trimmed_beg + 1);
128}
129
John Zulaufdf851b12018-06-12 14:49:04 -0600130// Perl/Python style join operation for general types using stream semantics
131// Note: won't be as fast as string_join above, but simpler to use (and code)
132// Note: Modifiable reference doesn't match the google style but does match std style for stream handling and algorithms
133template <typename Stream, typename String, typename ForwardIt>
134Stream &stream_join(Stream &stream, const String &sep, ForwardIt first, ForwardIt last) {
135 if (first != last) {
136 stream << *first;
137 ++first;
138 while (first != last) {
139 stream << sep << *first;
140 ++first;
141 }
142 }
143 return stream;
144}
145
146// stream_join For whole collections with forward iterators
147template <typename Stream, typename String, typename Collection>
148Stream &stream_join(Stream &stream, const String &sep, const Collection &values) {
149 return stream_join(stream, sep, values.cbegin(), values.cend());
150}
151
Mark Lobodzinskic1b5b882018-06-25 14:54:04 -0600152typedef void *dispatch_key;
153static inline dispatch_key get_dispatch_key(const void *object) { return (dispatch_key) * (VkLayerDispatchTable **)object; }
154
155VK_LAYER_EXPORT VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func);
156VK_LAYER_EXPORT VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func);
157
Chris Mayer334e72f2018-11-29 14:25:41 +0100158static inline bool IsPowerOfTwo(unsigned x) { return x && !(x & (x - 1)); }
Chris Mayer9bc9d092018-11-12 12:29:10 +0100159
Aaron Hagan01370922021-11-12 19:22:50 -0500160static inline uint32_t MostSignificantBit(uint32_t mask) {
161 uint32_t highest_view_bit = 0;
162 for (uint32_t k = 0; k < 32; ++k) {
163 if (((mask >> k) & 1) != 0) {
164 highest_view_bit = k;
165 }
166 }
167 return highest_view_bit;
168}
169
sfricke-samsung8f658d42020-05-03 20:12:24 -0700170static inline uint32_t SampleCountSize(VkSampleCountFlagBits sample_count) {
171 uint32_t size = 0;
172 switch (sample_count) {
173 case VK_SAMPLE_COUNT_1_BIT:
174 size = 1;
175 break;
176 case VK_SAMPLE_COUNT_2_BIT:
177 size = 2;
178 break;
179 case VK_SAMPLE_COUNT_4_BIT:
180 size = 4;
181 break;
182 case VK_SAMPLE_COUNT_8_BIT:
183 size = 8;
184 break;
185 case VK_SAMPLE_COUNT_16_BIT:
186 size = 16;
187 break;
188 case VK_SAMPLE_COUNT_32_BIT:
189 size = 32;
190 break;
191 case VK_SAMPLE_COUNT_64_BIT:
192 size = 64;
193 break;
194 default:
195 size = 0;
196 }
197 return size;
198}
199
sfricke-samsungbd0e8052020-06-06 01:36:39 -0700200static inline bool IsIdentitySwizzle(VkComponentMapping components) {
201 // clang-format off
202 return (
203 ((components.r == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.r == VK_COMPONENT_SWIZZLE_R)) &&
204 ((components.g == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.g == VK_COMPONENT_SWIZZLE_G)) &&
205 ((components.b == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.b == VK_COMPONENT_SWIZZLE_B)) &&
206 ((components.a == VK_COMPONENT_SWIZZLE_IDENTITY) || (components.a == VK_COMPONENT_SWIZZLE_A))
207 );
208 // clang-format on
209}
210
sfricke-samsungdcb31412021-08-29 22:16:34 -0700211static inline VkDeviceSize GetIndexAlignment(VkIndexType indexType) {
212 switch (indexType) {
213 case VK_INDEX_TYPE_UINT16:
214 return 2;
215 case VK_INDEX_TYPE_UINT32:
216 return 4;
217 case VK_INDEX_TYPE_UINT8_EXT:
218 return 1;
219 default:
220 // Not a real index type. Express no alignment requirement here; we expect upper layer
221 // to have already picked up on the enum being nonsense.
222 return 1;
223 }
224}
225
sfricke-samsunge3086292021-11-18 23:02:35 -0800226static inline uint32_t GetPlaneIndex(VkImageAspectFlags aspect) {
227 // Returns an out of bounds index on error
228 switch (aspect) {
229 case VK_IMAGE_ASPECT_PLANE_0_BIT:
230 return 0;
231 break;
232 case VK_IMAGE_ASPECT_PLANE_1_BIT:
233 return 1;
234 break;
235 case VK_IMAGE_ASPECT_PLANE_2_BIT:
236 return 2;
237 break;
238 default:
239 // If more than one plane bit is set, return error condition
240 return FORMAT_MAX_PLANES;
241 break;
242 }
243}
244
sfricke-samsunged028b02021-09-06 23:14:51 -0700245// Perform a zero-tolerant modulo operation
246static inline VkDeviceSize SafeModulo(VkDeviceSize dividend, VkDeviceSize divisor) {
247 VkDeviceSize result = 0;
248 if (divisor != 0) {
249 result = dividend % divisor;
250 }
251 return result;
252}
253
254static inline VkDeviceSize SafeDivision(VkDeviceSize dividend, VkDeviceSize divisor) {
255 VkDeviceSize result = 0;
256 if (divisor != 0) {
257 result = dividend / divisor;
258 }
259 return result;
260}
261
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600262extern "C" {
263#endif
264
Jon Ashburnd883d812016-03-24 08:32:09 -0600265#define VK_LAYER_API_VERSION VK_MAKE_VERSION(1, 0, VK_HEADER_VERSION)
Mark Lobodzinskiadaac9d2016-01-08 11:07:56 -0700266
Mark Lobodzinskia9f33492016-01-11 14:17:05 -0700267typedef enum VkStringErrorFlagBits {
Jon Ashburn5484e0c2016-03-08 17:48:44 -0700268 VK_STRING_ERROR_NONE = 0x00000000,
269 VK_STRING_ERROR_LENGTH = 0x00000001,
270 VK_STRING_ERROR_BAD_DATA = 0x00000002,
Mark Lobodzinskia9f33492016-01-11 14:17:05 -0700271} VkStringErrorFlagBits;
272typedef VkFlags VkStringErrorFlags;
Mark Lobodzinski1ed594e2016-02-03 09:57:14 -0700273
Petr Kraus4ed81e32019-09-02 23:41:19 +0200274VK_LAYER_EXPORT void layer_debug_report_actions(debug_report_data *report_data, const VkAllocationCallbacks *pAllocator,
275 const char *layer_identifier);
Mark Young6ba8abe2017-11-09 10:37:04 -0700276
Petr Kraus4ed81e32019-09-02 23:41:19 +0200277VK_LAYER_EXPORT void layer_debug_messenger_actions(debug_report_data *report_data, const VkAllocationCallbacks *pAllocator,
278 const char *layer_identifier);
Mark Lobodzinski1079e1b2016-03-15 14:21:59 -0600279
Mike Stroyana551bc02016-09-28 09:42:28 -0600280VK_LAYER_EXPORT VkStringErrorFlags vk_string_validate(const int max_length, const char *char_array);
Mark Lobodzinskia0555012018-08-15 16:43:49 -0600281VK_LAYER_EXPORT bool white_list(const char *item, const std::set<std::string> &whitelist);
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600282
Jon Ashburn5484e0c2016-03-08 17:48:44 -0700283static inline int u_ffs(int val) {
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600284#ifdef WIN32
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700285 unsigned long bit_pos = 0;
Mike Stroyandebb9842016-01-07 10:05:21 -0700286 if (_BitScanForward(&bit_pos, val) != 0) {
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700287 bit_pos += 1;
288 }
289 return bit_pos;
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600290#else
Mark Lobodzinski5ddf6c32015-12-16 17:47:28 -0700291 return ffs(val);
Courtney Goeltzenleuchterd2635502015-10-21 17:08:06 -0600292#endif
293}
Mark Lobodzinski6f2274e2015-09-22 09:33:21 -0600294
295#ifdef __cplusplus
296}
297#endif
Jeff Bolz89b9a502019-08-20 08:58:51 -0500298
Jeremy Gebben32811462021-09-20 12:54:20 -0600299#ifdef __cplusplus
Jeremy Gebbena7c3a352021-09-20 12:54:20 -0600300// clang sets _MSC_VER to 1800 and _MSC_FULL_VER to 180000000, but we only want to clean up after MSVC.
301#if defined(_MSC_FULL_VER) && !defined(__clang__)
Bruce Dawson5fab7f82020-06-09 16:23:07 -0700302// Minimum Visual Studio 2015 Update 2, or libc++ with C++17
Jeremy Gebbena7c3a352021-09-20 12:54:20 -0600303// But, before Visual Studio 2017 version 15.7, __cplusplus is not set
304// correctly. See:
305// https://docs.microsoft.com/en-us/cpp/build/reference/zc-cplusplus?view=msvc-160
306// Also, according to commit e2a6c442cb1e4, SDKs older than NTDDI_WIN10_RS2 do not
307// support shared_mutex.
308#if _MSC_FULL_VER >= 190023918 && NTDDI_VERSION > NTDDI_WIN10_RS2 && (!defined(_LIBCPP_VERSION) || __cplusplus >= 201703)
Jeremy Gebben32811462021-09-20 12:54:20 -0600309#define VVL_USE_SHARED_MUTEX 1
310#endif
311#elif __cplusplus >= 201703
312#define VVL_USE_SHARED_MUTEX 1
Jeremy Gebben7891d762021-10-11 17:17:58 -0600313#elif __cplusplus >= 201402
314#define VVL_USE_SHARED_TIMED_MUTEX 1
Jeremy Gebben32811462021-09-20 12:54:20 -0600315#endif
316
Jeremy Gebben7891d762021-10-11 17:17:58 -0600317#if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
Jeff Bolz89b9a502019-08-20 08:58:51 -0500318#include <shared_mutex>
319#endif
320
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500321class ReadWriteLock {
322 private:
Jeremy Gebben32811462021-09-20 12:54:20 -0600323#if defined(VVL_USE_SHARED_MUTEX)
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600324 typedef std::shared_mutex Lock;
Jeremy Gebben7891d762021-10-11 17:17:58 -0600325#elif defined(VVL_USE_SHARED_TIMED_MUTEX)
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600326 typedef std::shared_timed_mutex Lock;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500327#else
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600328 typedef std::mutex Lock;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500329#endif
330
331 public:
332 void lock() { m_lock.lock(); }
333 bool try_lock() { return m_lock.try_lock(); }
334 void unlock() { m_lock.unlock(); }
Jeremy Gebben7891d762021-10-11 17:17:58 -0600335#if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500336 void lock_shared() { m_lock.lock_shared(); }
337 bool try_lock_shared() { return m_lock.try_lock_shared(); }
338 void unlock_shared() { m_lock.unlock_shared(); }
339#else
340 void lock_shared() { lock(); }
341 bool try_lock_shared() { return try_lock(); }
342 void unlock_shared() { unlock(); }
343#endif
344 private:
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600345 Lock m_lock;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500346};
347
Jeremy Gebben7891d762021-10-11 17:17:58 -0600348#if defined(VVL_USE_SHARED_MUTEX) || defined(VVL_USE_SHARED_TIMED_MUTEX)
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600349typedef std::shared_lock<ReadWriteLock> ReadLockGuard;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500350#else
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600351typedef std::unique_lock<ReadWriteLock> ReadLockGuard;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500352#endif
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600353typedef std::unique_lock<ReadWriteLock> WriteLockGuard;
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500354
Jeff Bolz89b9a502019-08-20 08:58:51 -0500355// Limited concurrent_unordered_map that supports internally-synchronized
356// insert/erase/access. Splits locking across N buckets and uses shared_mutex
357// for read/write locking. Iterators are not supported. The following
358// operations are supported:
359//
360// insert_or_assign: Insert a new element or update an existing element.
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500361// insert: Insert a new element and return whether it was inserted.
Jeff Bolz89b9a502019-08-20 08:58:51 -0500362// erase: Remove an element.
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500363// contains: Returns true if the key is in the map.
Jeff Bolz89b9a502019-08-20 08:58:51 -0500364// find: Returns != end() if found, value is in ret->second.
365// pop: Erases and returns the erased value if found.
366//
367// find/end: find returns a vaguely iterator-like type that can be compared to
368// end and can use iter->second to retrieve the reference. This is to ease porting
369// for existing code that combines the existence check and lookup in a single
370// operation (and thus a single lock). i.e.:
371//
372// auto iter = map.find(key);
373// if (iter != map.end()) {
374// T t = iter->second;
375// ...
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500376//
377// snapshot: Return an array of elements (key, value pairs) that satisfy an optional
378// predicate. This can be used as a substitute for iterators in exceptional cases.
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700379template <typename Key, typename T, int BUCKETSLOG2 = 2, typename Hash = layer_data::hash<Key>>
Jeff Bolz89b9a502019-08-20 08:58:51 -0500380class vl_concurrent_unordered_map {
Petr Kraus4ed81e32019-09-02 23:41:19 +0200381 public:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500382 void insert_or_assign(const Key &key, const T &value) {
383 uint32_t h = ConcurrentMapHashObject(key);
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600384 WriteLockGuard lock(locks[h].lock);
Jeff Bolz89b9a502019-08-20 08:58:51 -0500385 maps[h][key] = value;
386 }
387
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500388 bool insert(const Key &key, const T &value) {
389 uint32_t h = ConcurrentMapHashObject(key);
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600390 WriteLockGuard lock(locks[h].lock);
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700391 auto ret = maps[h].emplace(key, value);
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500392 return ret.second;
393 }
394
Jeff Bolz89b9a502019-08-20 08:58:51 -0500395 // returns size_type
396 size_t erase(const Key &key) {
397 uint32_t h = ConcurrentMapHashObject(key);
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600398 WriteLockGuard lock(locks[h].lock);
Jeff Bolz89b9a502019-08-20 08:58:51 -0500399 return maps[h].erase(key);
400 }
401
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500402 bool contains(const Key &key) const {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500403 uint32_t h = ConcurrentMapHashObject(key);
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600404 ReadLockGuard lock(locks[h].lock);
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500405 return maps[h].count(key) != 0;
406 }
407
Jeff Bolz89b9a502019-08-20 08:58:51 -0500408 // type returned by find() and end().
409 class FindResult {
Petr Kraus4ed81e32019-09-02 23:41:19 +0200410 public:
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500411 FindResult(bool a, T b) : result(a, std::move(b)) {}
Jeff Bolz89b9a502019-08-20 08:58:51 -0500412
413 // == and != only support comparing against end()
414 bool operator==(const FindResult &other) const {
415 if (result.first == false && other.result.first == false) {
416 return true;
417 }
418 return false;
419 }
420 bool operator!=(const FindResult &other) const { return !(*this == other); }
421
422 // Make -> act kind of like an iterator.
423 std::pair<bool, T> *operator->() { return &result; }
424 const std::pair<bool, T> *operator->() const { return &result; }
425
Petr Kraus4ed81e32019-09-02 23:41:19 +0200426 private:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500427 // (found, reference to element)
428 std::pair<bool, T> result;
429 };
430
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500431 // find()/end() return a FindResult containing a copy of the value. For end(),
432 // return a default value.
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500433 FindResult end() const { return FindResult(false, T()); }
Jeff Bolz89b9a502019-08-20 08:58:51 -0500434
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500435 FindResult find(const Key &key) const {
Jeff Bolz89b9a502019-08-20 08:58:51 -0500436 uint32_t h = ConcurrentMapHashObject(key);
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600437 ReadLockGuard lock(locks[h].lock);
Jeff Bolz89b9a502019-08-20 08:58:51 -0500438
439 auto itr = maps[h].find(key);
440 bool found = itr != maps[h].end();
441
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500442 if (found) {
443 return FindResult(true, itr->second);
444 } else {
445 return end();
446 }
Jeff Bolz89b9a502019-08-20 08:58:51 -0500447 }
448
449 FindResult pop(const Key &key) {
450 uint32_t h = ConcurrentMapHashObject(key);
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600451 WriteLockGuard lock(locks[h].lock);
Jeff Bolz89b9a502019-08-20 08:58:51 -0500452
453 auto itr = maps[h].find(key);
454 bool found = itr != maps[h].end();
455
456 if (found) {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500457 auto ret = std::move(FindResult(true, itr->second));
Jeff Bolz89b9a502019-08-20 08:58:51 -0500458 maps[h].erase(itr);
459 return ret;
460 } else {
461 return end();
462 }
463 }
464
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500465 std::vector<std::pair<const Key, T>> snapshot(std::function<bool(T)> f = nullptr) const {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500466 std::vector<std::pair<const Key, T>> ret;
467 for (int h = 0; h < BUCKETS; ++h) {
Jeremy Gebben2e5b41b2021-10-11 16:41:49 -0600468 ReadLockGuard lock(locks[h].lock);
John Zulauf79f06582021-02-27 18:38:39 -0700469 for (const auto &j : maps[h]) {
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500470 if (!f || f(j.second)) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700471 ret.emplace_back(j.first, j.second);
Jeff Bolzfd3bb242019-08-22 06:10:49 -0500472 }
473 }
474 }
475 return ret;
476 }
477
Jeremy Gebben65975ed2021-10-29 11:16:10 -0600478 void clear() {
479 for (int h = 0; h < BUCKETS; ++h) {
Jeremy Gebbene406ff12022-01-07 10:34:40 -0700480 WriteLockGuard lock(locks[h].lock);
Jeremy Gebben65975ed2021-10-29 11:16:10 -0600481 maps[h].clear();
482 }
483 }
484
485 size_t size() const {
486 size_t result = 0;
487 for (int h = 0; h < BUCKETS; ++h) {
488 ReadLockGuard lock(locks[h].lock);
489 result += maps[h].size();
490 }
491 return result;
492 }
493
494 bool empty() const {
495 bool result = 0;
496 for (int h = 0; h < BUCKETS; ++h) {
497 ReadLockGuard lock(locks[h].lock);
498 result |= maps[h].empty();
499 }
500 return result;
501 }
502
Petr Kraus4ed81e32019-09-02 23:41:19 +0200503 private:
Jeff Bolz89b9a502019-08-20 08:58:51 -0500504 static const int BUCKETS = (1 << BUCKETSLOG2);
Jeff Bolz89b9a502019-08-20 08:58:51 -0500505
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700506 layer_data::unordered_map<Key, T, Hash> maps[BUCKETS];
Jeff Bolz89b9a502019-08-20 08:58:51 -0500507 struct {
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500508 mutable ReadWriteLock lock;
Jeff Bolz89b9a502019-08-20 08:58:51 -0500509 // Put each lock on its own cache line to avoid false cache line sharing.
Jeff Bolzcaeccc72019-10-15 15:35:26 -0500510 char padding[(-int(sizeof(ReadWriteLock))) & 63];
Jeff Bolz89b9a502019-08-20 08:58:51 -0500511 } locks[BUCKETS];
512
513 uint32_t ConcurrentMapHashObject(const Key &object) const {
514 uint64_t u64 = (uint64_t)(uintptr_t)object;
515 uint32_t hash = (uint32_t)(u64 >> 32) + (uint32_t)u64;
516 hash ^= (hash >> BUCKETSLOG2) ^ (hash >> (2 * BUCKETSLOG2));
517 hash &= (BUCKETS - 1);
518 return hash;
519 }
520};
Jeremy Gebben32811462021-09-20 12:54:20 -0600521#endif