blob: 387837ccb90edc572cec6b3757e1fbde2d046360 [file] [log] [blame]
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001/* Copyright (c) 2019-2022 The Khronos Group Inc.
2 * Copyright (c) 2019-2022 Valve Corporation
3 * Copyright (c) 2019-2022 LunarG, Inc.
John Zulauf9cb530d2019-09-30 14:14:10 -06004 *
5 * 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
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * 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.
16 *
17 * Author: John Zulauf <jzulauf@lunarg.com>
John Zulaufab7756b2020-12-29 16:10:16 -070018 * Author: Locke Lin <locke@lunarg.com>
19 * Author: Jeremy Gebben <jeremyg@lunarg.com>
John Zulauf9cb530d2019-09-30 14:14:10 -060020 */
21
22#include <limits>
23#include <vector>
locke-lunarg296a3c92020-03-25 01:04:29 -060024#include <memory>
25#include <bitset>
John Zulauf9cb530d2019-09-30 14:14:10 -060026#include "synchronization_validation.h"
Jeremy Gebben5f585ae2021-02-02 09:03:06 -070027#include "sync_utils.h"
John Zulauf9cb530d2019-09-30 14:14:10 -060028
John Zulaufea943c52022-02-22 11:05:17 -070029// Utilities to DRY up Get... calls
30template <typename Map, typename Key = typename Map::key_type, typename RetVal = layer_data::optional<typename Map::mapped_type>>
31RetVal GetMappedOptional(const Map &map, const Key &key) {
32 RetVal ret_val;
33 auto it = map.find(key);
34 if (it != map.cend()) {
35 ret_val.emplace(it->second);
36 }
37 return ret_val;
38}
39template <typename Map, typename Fn>
40typename Map::mapped_type GetMapped(const Map &map, const typename Map::key_type &key, Fn &&default_factory) {
41 auto value = GetMappedOptional(map, key);
42 return (value) ? *value : default_factory();
43}
44
45template <typename Map, typename Fn>
John Zulauf397e68b2022-04-19 11:44:07 -060046typename Map::mapped_type GetMappedInsert(Map &map, const typename Map::key_type &key, Fn &&emplace_factory) {
John Zulaufea943c52022-02-22 11:05:17 -070047 auto value = GetMappedOptional(map, key);
48 if (value) {
49 return *value;
50 }
John Zulauf397e68b2022-04-19 11:44:07 -060051 auto insert_it = map.emplace(std::make_pair(key, emplace_factory()));
John Zulaufea943c52022-02-22 11:05:17 -070052 assert(insert_it.second);
53
54 return insert_it.first->second;
55}
56
57template <typename Map, typename Key = typename Map::key_type, typename Mapped = typename Map::mapped_type,
58 typename Value = typename Mapped::element_type>
59Value *GetMappedPlainFromShared(const Map &map, const Key &key) {
60 auto value = GetMappedOptional<Map, Key>(map, key);
61 if (value) return value->get();
62 return nullptr;
63}
64
Jeremy Gebben6fbf8242021-06-21 09:14:46 -060065static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.Binding(); }
John Zulauf264cce02021-02-05 14:40:47 -070066
John Zulauf29d00532021-03-04 13:28:54 -070067static bool SimpleBinding(const IMAGE_STATE &image_state) {
Jeremy Gebben62c3bf42021-07-21 15:38:24 -060068 bool simple =
Jeremy Gebben82e11d52021-07-26 09:19:37 -060069 SimpleBinding(static_cast<const BINDABLE &>(image_state)) || image_state.IsSwapchainImage() || image_state.bind_swapchain;
John Zulauf29d00532021-03-04 13:28:54 -070070
71 // If it's not simple we must have an encoder.
72 assert(!simple || image_state.fragment_encoder.get());
73 return simple;
74}
75
John Zulauf4fa68462021-04-26 21:04:22 -060076static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
77static const std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
John Zulauf43cc7462020-12-03 12:33:12 -070078 AccessAddressType::kLinear, AccessAddressType::kIdealized};
79
John Zulaufd5115702021-01-18 12:34:33 -070080static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
John Zulauf264cce02021-02-05 14:40:47 -070081static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) {
82 return SimpleBinding(image) ? AccessContext::ImageAddressType(image) : AccessAddressType::kIdealized;
83}
John Zulaufd5115702021-01-18 12:34:33 -070084
John Zulauf9cb530d2019-09-30 14:14:10 -060085static const char *string_SyncHazardVUID(SyncHazard hazard) {
86 switch (hazard) {
87 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070088 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060089 break;
90 case SyncHazard::READ_AFTER_WRITE:
John Zulauf451e8c22022-09-01 14:14:00 -060091 return "SYNC-HAZARD-READ-AFTER-WRITE";
John Zulauf9cb530d2019-09-30 14:14:10 -060092 break;
93 case SyncHazard::WRITE_AFTER_READ:
John Zulauf451e8c22022-09-01 14:14:00 -060094 return "SYNC-HAZARD-WRITE-AFTER-READ";
John Zulauf9cb530d2019-09-30 14:14:10 -060095 break;
96 case SyncHazard::WRITE_AFTER_WRITE:
John Zulauf451e8c22022-09-01 14:14:00 -060097 return "SYNC-HAZARD-WRITE-AFTER-WRITE";
John Zulauf9cb530d2019-09-30 14:14:10 -060098 break;
John Zulauf2f952d22020-02-10 11:34:51 -070099 case SyncHazard::READ_RACING_WRITE:
100 return "SYNC-HAZARD-READ-RACING-WRITE";
101 break;
102 case SyncHazard::WRITE_RACING_WRITE:
103 return "SYNC-HAZARD-WRITE-RACING-WRITE";
104 break;
105 case SyncHazard::WRITE_RACING_READ:
106 return "SYNC-HAZARD-WRITE-RACING-READ";
107 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600108 default:
109 assert(0);
110 }
111 return "SYNC-HAZARD-INVALID";
112}
113
John Zulauf59e25072020-07-17 10:55:21 -0600114static bool IsHazardVsRead(SyncHazard hazard) {
115 switch (hazard) {
116 case SyncHazard::NONE:
117 return false;
118 break;
119 case SyncHazard::READ_AFTER_WRITE:
120 return false;
121 break;
122 case SyncHazard::WRITE_AFTER_READ:
123 return true;
124 break;
125 case SyncHazard::WRITE_AFTER_WRITE:
126 return false;
127 break;
128 case SyncHazard::READ_RACING_WRITE:
129 return false;
130 break;
131 case SyncHazard::WRITE_RACING_WRITE:
132 return false;
133 break;
134 case SyncHazard::WRITE_RACING_READ:
135 return true;
136 break;
137 default:
138 assert(0);
139 }
140 return false;
141}
142
John Zulauf9cb530d2019-09-30 14:14:10 -0600143static const char *string_SyncHazard(SyncHazard hazard) {
144 switch (hazard) {
145 case SyncHazard::NONE:
146 return "NONR";
147 break;
148 case SyncHazard::READ_AFTER_WRITE:
149 return "READ_AFTER_WRITE";
150 break;
151 case SyncHazard::WRITE_AFTER_READ:
152 return "WRITE_AFTER_READ";
153 break;
154 case SyncHazard::WRITE_AFTER_WRITE:
155 return "WRITE_AFTER_WRITE";
156 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700157 case SyncHazard::READ_RACING_WRITE:
158 return "READ_RACING_WRITE";
159 break;
160 case SyncHazard::WRITE_RACING_WRITE:
161 return "WRITE_RACING_WRITE";
162 break;
163 case SyncHazard::WRITE_RACING_READ:
164 return "WRITE_RACING_READ";
165 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600166 default:
167 assert(0);
168 }
169 return "INVALID HAZARD";
170}
171
John Zulauf37ceaed2020-07-03 16:18:15 -0600172static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
173 // Return the info for the first bit found
174 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700175 for (size_t i = 0; i < flags.size(); i++) {
176 if (flags.test(i)) {
177 info = &syncStageAccessInfoByStageAccessIndex[i];
178 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600179 }
180 }
181 return info;
182}
183
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700184static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600185 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700186 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600187 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700188 } else {
189 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
190 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
191 if ((flags & info.stage_access_bit).any()) {
192 if (!out_str.empty()) {
193 out_str.append(sep);
194 }
195 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600196 }
John Zulauf59e25072020-07-17 10:55:21 -0600197 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700198 if (out_str.length() == 0) {
199 out_str.append("Unhandled SyncStageAccess");
200 }
John Zulauf59e25072020-07-17 10:55:21 -0600201 }
202 return out_str;
203}
204
John Zulauf397e68b2022-04-19 11:44:07 -0600205std::ostream &operator<<(std::ostream &out, const ResourceUsageRecord &record) {
206 out << "command: " << CommandTypeString(record.command);
207 out << ", seq_no: " << record.seq_num;
208 if (record.sub_command != 0) {
209 out << ", subcmd: " << record.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700210 }
John Zulauf397e68b2022-04-19 11:44:07 -0600211 return out;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700212}
John Zulauf397e68b2022-04-19 11:44:07 -0600213
John Zulauf4fa68462021-04-26 21:04:22 -0600214static std::string string_UsageIndex(SyncStageAccessIndex usage_index) {
215 const char *stage_access_name = "INVALID_STAGE_ACCESS";
216 if (usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size())) {
217 stage_access_name = syncStageAccessInfoByStageAccessIndex[usage_index].name;
218 }
219 return std::string(stage_access_name);
220}
221
John Zulauf397e68b2022-04-19 11:44:07 -0600222struct SyncNodeFormatter {
223 const debug_report_data *report_data;
224 const BASE_NODE *node;
225 const char *label;
226
227 SyncNodeFormatter(const SyncValidator &sync_state, const CMD_BUFFER_STATE *cb_state)
228 : report_data(sync_state.report_data), node(cb_state), label("command_buffer") {}
229 SyncNodeFormatter(const SyncValidator &sync_state, const QUEUE_STATE *q_state)
230 : report_data(sync_state.report_data), node(q_state), label("queue") {}
231};
232
233std::ostream &operator<<(std::ostream &out, const SyncNodeFormatter &formater) {
234 if (formater.node) {
John Zulauf3298da92022-09-01 13:58:39 -0600235 out << formater.label << ": " << formater.report_data->FormatHandle(formater.node->Handle()).c_str();
John Zulauf397e68b2022-04-19 11:44:07 -0600236 if (formater.node->Destroyed()) {
237 out << " (destroyed)";
238 }
239 } else {
John Zulauf3298da92022-09-01 13:58:39 -0600240 out << formater.label << ": null handle";
John Zulauf397e68b2022-04-19 11:44:07 -0600241 }
242 return out;
243}
244
245std::ostream &operator<<(std::ostream &out, const HazardResult &hazard) {
246 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
247 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
248 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
249 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
250 out << "(";
251 if (!hazard.recorded_access.get()) {
252 // if we have a recorded usage the usage is reported from the recorded contexts point of view
253 out << "usage: " << usage_info.name << ", ";
254 }
255 out << "prior_usage: " << stage_access_name;
256 if (IsHazardVsRead(hazard.hazard)) {
257 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
258 out << ", read_barriers: " << string_VkPipelineStageFlags2KHR(barriers);
259 } else {
260 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
261 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
262 }
263 return out;
264}
265
John Zulauf4fa68462021-04-26 21:04:22 -0600266struct NoopBarrierAction {
267 explicit NoopBarrierAction() {}
268 void operator()(ResourceAccessState *access) const {}
John Zulauf5c628d02021-05-04 15:46:36 -0600269 const bool layout_transition = false;
John Zulauf4fa68462021-04-26 21:04:22 -0600270};
271
John Zulaufdab327f2022-07-08 12:02:05 -0600272static void InitSubpassContexts(VkQueueFlags queue_flags, const RENDER_PASS_STATE &rp_state, const AccessContext *external_context,
273 std::vector<AccessContext> &subpass_contexts) {
274 const auto &create_info = rp_state.createInfo;
275 // Add this for all subpasses here so that they exsist during next subpass validation
276 subpass_contexts.clear();
277 subpass_contexts.reserve(create_info.subpassCount);
278 for (uint32_t pass = 0; pass < create_info.subpassCount; pass++) {
279 subpass_contexts.emplace_back(pass, queue_flags, rp_state.subpass_dependencies, subpass_contexts, external_context);
280 }
281}
282
John Zulauf4fa68462021-04-26 21:04:22 -0600283// NOTE: Make sure the proxy doesn't outlive from, as the proxy is pointing directly to access contexts owned by from.
284CommandBufferAccessContext::CommandBufferAccessContext(const CommandBufferAccessContext &from, AsProxyContext dummy)
285 : CommandBufferAccessContext(from.sync_state_) {
286 // Copy only the needed fields out of from for a temporary, proxy command buffer context
287 cb_state_ = from.cb_state_;
288 queue_flags_ = from.queue_flags_;
289 destroyed_ = from.destroyed_;
John Zulauf8a7b03d2022-09-20 11:41:19 -0600290 access_log_ = std::make_shared<AccessLog>(*from.access_log_); // potentially large, but no choice given tagging lookup.
John Zulauf4fa68462021-04-26 21:04:22 -0600291 command_number_ = from.command_number_;
292 subcommand_number_ = from.subcommand_number_;
293 reset_count_ = from.reset_count_;
294
295 const auto *from_context = from.GetCurrentAccessContext();
296 assert(from_context);
297
298 // Construct a fully resolved single access context out of from
299 const NoopBarrierAction noop_barrier;
300 for (AccessAddressType address_type : kAddressTypes) {
301 from_context->ResolveAccessRange(address_type, kFullRange, noop_barrier,
302 &cb_access_context_.GetAccessStateMap(address_type), nullptr);
303 }
304 // The proxy has flatten the current render pass context (if any), but the async contexts are needed for hazard detection
305 cb_access_context_.ImportAsyncContexts(*from_context);
306
307 events_context_ = from.events_context_;
308
309 // We don't want to copy the full render_pass_context_ history just for the proxy.
310}
311
312std::string CommandBufferAccessContext::FormatUsage(const ResourceUsageTag tag) const {
John Zulauf8a7b03d2022-09-20 11:41:19 -0600313 if (tag >= access_log_->size()) return std::string();
John Zulauf397e68b2022-04-19 11:44:07 -0600314
John Zulauf4fa68462021-04-26 21:04:22 -0600315 std::stringstream out;
John Zulauf8a7b03d2022-09-20 11:41:19 -0600316 assert(tag < access_log_->size());
317 const auto &record = (*access_log_)[tag];
John Zulauf397e68b2022-04-19 11:44:07 -0600318 out << record;
319 if (cb_state_.get() != record.cb_state) {
John Zulauf3298da92022-09-01 13:58:39 -0600320 out << ", " << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf4fa68462021-04-26 21:04:22 -0600321 }
John Zulaufd142c9a2022-04-12 14:22:44 -0600322 out << ", reset_no: " << std::to_string(record.reset_count);
John Zulauf4fa68462021-04-26 21:04:22 -0600323 return out.str();
324}
John Zulauf397e68b2022-04-19 11:44:07 -0600325
John Zulauf4fa68462021-04-26 21:04:22 -0600326std::string CommandBufferAccessContext::FormatUsage(const ResourceFirstAccess &access) const {
327 std::stringstream out;
328 out << "(recorded_usage: " << string_UsageIndex(access.usage_index);
329 out << ", " << FormatUsage(access.tag) << ")";
330 return out.str();
331}
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700332
John Zulauf397e68b2022-04-19 11:44:07 -0600333std::string CommandExecutionContext::FormatHazard(const HazardResult &hazard) const {
John Zulauf1dae9192020-06-16 15:46:44 -0600334 std::stringstream out;
John Zulauf397e68b2022-04-19 11:44:07 -0600335 out << hazard;
336 out << ", " << FormatUsage(hazard.tag) << ")";
John Zulauf1dae9192020-06-16 15:46:44 -0600337 return out.str();
338}
339
John Zulaufdab327f2022-07-08 12:02:05 -0600340
John Zulauf0223f142022-07-06 09:05:39 -0600341bool CommandExecutionContext::ValidForSyncOps() const {
342 bool valid = GetCurrentEventsContext() && GetCurrentAccessContext();
343 assert(valid);
344 return valid;
345}
346
John Zulaufd14743a2020-07-03 09:42:39 -0600347// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
348// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
349// also reflects this special case for read hazard detection (using access instead of exec scope)
Jeremy Gebben40a22942020-12-22 14:22:06 -0700350static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700351static const SyncStageAccessFlags kColorAttachmentAccessScope =
352 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
353 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
354 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
355 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebben40a22942020-12-22 14:22:06 -0700356static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
357 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700358static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
359 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
360 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
361 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -0700362static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700363static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600364
John Zulauf8e3c3e92021-01-06 11:19:36 -0700365ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700366 {{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
John Zulauf8e3c3e92021-01-06 11:19:36 -0700367 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
368 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
369 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
370
John Zulaufee984022022-04-13 16:39:50 -0600371// Sometimes we have an internal access conflict, and we using the kInvalidTag to set and detect in temporary/proxy contexts
372static const ResourceUsageTag kInvalidTag(ResourceUsageRecord::kMaxIndex);
John Zulaufb027cdb2020-05-21 14:25:22 -0600373
Jeremy Gebben62c3bf42021-07-21 15:38:24 -0600374static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600375
John Zulaufcb7e1672022-05-04 13:46:08 -0600376VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
locke-lunarg3c038002020-04-30 23:08:08 -0600377 if (size == VK_WHOLE_SIZE) {
378 return (whole_size - offset);
379 }
380 return size;
381}
382
John Zulauf3e86bf02020-09-12 10:47:57 -0600383static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
384 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
385}
386
John Zulauf16adfc92020-04-08 10:28:33 -0600387template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600388static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600389 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
390}
391
John Zulauf355e49b2020-04-24 15:11:15 -0600392static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600393
John Zulauf3e86bf02020-09-12 10:47:57 -0600394static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
395 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
396}
397
398static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
399 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
400}
401
John Zulauf4a6105a2020-11-17 15:11:05 -0700402// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
403//
John Zulauf10f1f522020-12-18 12:00:35 -0700404// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
405//
John Zulauf4a6105a2020-11-17 15:11:05 -0700406// Usage:
407// Constructor() -- initializes the generator to point to the begin of the space declared.
408// * -- the current range of the generator empty signfies end
409// ++ -- advance to the next non-empty range (or end)
410
411// A wrapper for a single range with the same semantics as the actual generators below
412template <typename KeyType>
413class SingleRangeGenerator {
414 public:
415 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700416 const KeyType &operator*() const { return current_; }
417 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700418 SingleRangeGenerator &operator++() {
419 current_ = KeyType(); // just one real range
420 return *this;
421 }
422
423 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
424
425 private:
426 SingleRangeGenerator() = default;
427 const KeyType range_;
428 KeyType current_;
429};
430
John Zulaufae842002021-04-15 18:20:55 -0600431// Generate the ranges that are the intersection of range and the entries in the RangeMap
432template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
433class MapRangesRangeGenerator {
John Zulauf4a6105a2020-11-17 15:11:05 -0700434 public:
John Zulaufd5115702021-01-18 12:34:33 -0700435 // Default constructed is safe to dereference for "empty" test, but for no other operation.
John Zulaufae842002021-04-15 18:20:55 -0600436 MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
John Zulaufd5115702021-01-18 12:34:33 -0700437 // Default construction for KeyType *must* be empty range
438 assert(current_.empty());
439 }
John Zulaufae842002021-04-15 18:20:55 -0600440 MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700441 SeekBegin();
442 }
John Zulaufae842002021-04-15 18:20:55 -0600443 MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
John Zulaufd5115702021-01-18 12:34:33 -0700444
John Zulauf4a6105a2020-11-17 15:11:05 -0700445 const KeyType &operator*() const { return current_; }
446 const KeyType *operator->() const { return &current_; }
John Zulaufae842002021-04-15 18:20:55 -0600447 MapRangesRangeGenerator &operator++() {
448 ++map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700449 UpdateCurrent();
450 return *this;
451 }
452
John Zulaufae842002021-04-15 18:20:55 -0600453 bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700454
John Zulaufae842002021-04-15 18:20:55 -0600455 protected:
John Zulauf4a6105a2020-11-17 15:11:05 -0700456 void UpdateCurrent() {
John Zulaufae842002021-04-15 18:20:55 -0600457 if (map_pos_ != map_->cend()) {
458 current_ = range_ & map_pos_->first;
John Zulauf4a6105a2020-11-17 15:11:05 -0700459 } else {
460 current_ = KeyType();
461 }
462 }
463 void SeekBegin() {
John Zulaufae842002021-04-15 18:20:55 -0600464 map_pos_ = map_->lower_bound(range_);
John Zulauf4a6105a2020-11-17 15:11:05 -0700465 UpdateCurrent();
466 }
John Zulaufae842002021-04-15 18:20:55 -0600467
468 // Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
469 // Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
470 template <typename Pred>
471 MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
472 do {
473 ++map_pos_;
474 } while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
475 UpdateCurrent();
476 return *this;
477 }
478
John Zulauf4a6105a2020-11-17 15:11:05 -0700479 const KeyType range_;
John Zulaufae842002021-04-15 18:20:55 -0600480 const RangeMap *map_;
481 typename RangeMap::const_iterator map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700482 KeyType current_;
483};
John Zulaufd5115702021-01-18 12:34:33 -0700484using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulaufae842002021-04-15 18:20:55 -0600485using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700486
John Zulaufae842002021-04-15 18:20:55 -0600487// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
488template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
489class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
490 public:
491 using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
492 // Default constructed is safe to dereference for "empty" test, but for no other operation.
493 PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
494 PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
495 : Base(filter, range), pred_(pred) {}
496 PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
497
498 PredicatedMapRangesRangeGenerator &operator++() {
499 Base::PredicatedIncrement(pred_);
500 return *this;
501 }
502
503 protected:
504 Predicate pred_;
505};
John Zulauf4a6105a2020-11-17 15:11:05 -0700506
507// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulaufae842002021-04-15 18:20:55 -0600508// Templated to allow for different Range generators or map sources...
509template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::key_type>
John Zulauf4a6105a2020-11-17 15:11:05 -0700510class FilteredGeneratorGenerator {
511 public:
John Zulaufd5115702021-01-18 12:34:33 -0700512 // Default constructed is safe to dereference for "empty" test, but for no other operation.
513 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
514 // Default construction for KeyType *must* be empty range
515 assert(current_.empty());
516 }
John Zulaufae842002021-04-15 18:20:55 -0600517 FilteredGeneratorGenerator(const RangeMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700518 SeekBegin();
519 }
John Zulaufd5115702021-01-18 12:34:33 -0700520 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700521 const KeyType &operator*() const { return current_; }
522 const KeyType *operator->() const { return &current_; }
523 FilteredGeneratorGenerator &operator++() {
524 KeyType gen_range = GenRange();
525 KeyType filter_range = FilterRange();
526 current_ = KeyType();
527 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
528 if (gen_range.end > filter_range.end) {
529 // if the generated range is beyond the filter_range, advance the filter range
530 filter_range = AdvanceFilter();
531 } else {
532 gen_range = AdvanceGen();
533 }
534 current_ = gen_range & filter_range;
535 }
536 return *this;
537 }
538
539 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
540
541 private:
542 KeyType AdvanceFilter() {
543 ++filter_pos_;
544 auto filter_range = FilterRange();
545 if (filter_range.valid()) {
546 FastForwardGen(filter_range);
547 }
548 return filter_range;
549 }
550 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700551 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700552 auto gen_range = GenRange();
553 if (gen_range.valid()) {
554 FastForwardFilter(gen_range);
555 }
556 return gen_range;
557 }
558
559 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700560 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700561
562 KeyType FastForwardFilter(const KeyType &range) {
563 auto filter_range = FilterRange();
564 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700565 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700566 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
567 if (retry_count < kRetryLimit) {
568 ++filter_pos_;
569 filter_range = FilterRange();
570 retry_count++;
571 } else {
572 // Okay we've tried walking, do a seek.
573 filter_pos_ = filter_->lower_bound(range);
574 break;
575 }
576 }
577 return FilterRange();
578 }
579
580 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
581 // faster.
582 KeyType FastForwardGen(const KeyType &range) {
583 auto gen_range = GenRange();
584 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700585 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700586 gen_range = GenRange();
587 }
588 return gen_range;
589 }
590
591 void SeekBegin() {
592 auto gen_range = GenRange();
593 if (gen_range.empty()) {
594 current_ = KeyType();
595 filter_pos_ = filter_->cend();
596 } else {
597 filter_pos_ = filter_->lower_bound(gen_range);
598 current_ = gen_range & FilterRange();
599 }
600 }
601
John Zulaufae842002021-04-15 18:20:55 -0600602 const RangeMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700603 RangeGen gen_;
John Zulaufae842002021-04-15 18:20:55 -0600604 typename RangeMap::const_iterator filter_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700605 KeyType current_;
606};
607
608using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
609
John Zulauf5c5e88d2019-12-26 11:22:02 -0700610
John Zulauf3e86bf02020-09-12 10:47:57 -0600611ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
612 VkDeviceSize stride) {
613 VkDeviceSize range_start = offset + first_index * stride;
614 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600615 if (count == UINT32_MAX) {
616 range_size = buf_whole_size - range_start;
617 } else {
618 range_size = count * stride;
619 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600620 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600621}
622
locke-lunarg654e3692020-06-04 17:19:15 -0600623SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
624 VkShaderStageFlagBits stage_flag) {
625 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
626 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
627 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
628 }
629 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
630 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
631 assert(0);
632 }
633 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
634 return stage_access->second.uniform_read;
635 }
636
637 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
638 // Because if write hazard happens, read hazard might or might not happen.
639 // But if write hazard doesn't happen, read hazard is impossible to happen.
640 if (descriptor_data.is_writable) {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700641 return stage_access->second.storage_write;
locke-lunarg654e3692020-06-04 17:19:15 -0600642 }
Jeremy Gebben40a22942020-12-22 14:22:06 -0700643 // TODO: sampled_read
644 return stage_access->second.storage_read;
locke-lunarg654e3692020-06-04 17:19:15 -0600645}
646
locke-lunarg37047832020-06-12 13:44:45 -0600647bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
648 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
649 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
650 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
651 ? true
652 : false;
653}
654
655bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
656 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
657 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
658 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
659 ? true
660 : false;
661}
662
John Zulauf355e49b2020-04-24 15:11:15 -0600663// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600664template <typename Action>
665static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
666 Action &action) {
667 // At this point the "apply over range" logic only supports a single memory binding
668 if (!SimpleBinding(image_state)) return;
669 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600670 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700671 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
Aitor Camachoe67f2c72022-06-08 14:41:58 +0200672 image_state.createInfo.extent, base_address, false);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600673 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700674 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600675 }
676}
677
John Zulauf7635de32020-05-29 17:14:15 -0600678// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
679// Used by both validation and record operations
680//
681// The signature for Action() reflect the needs of both uses.
682template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -0700683void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
684 uint32_t subpass) {
John Zulauf7635de32020-05-29 17:14:15 -0600685 const auto &rp_ci = rp_state.createInfo;
686 const auto *attachment_ci = rp_ci.pAttachments;
687 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
688
689 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
690 const auto *color_attachments = subpass_ci.pColorAttachments;
691 const auto *color_resolve = subpass_ci.pResolveAttachments;
692 if (color_resolve && color_attachments) {
693 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
694 const auto &color_attach = color_attachments[i].attachment;
695 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
696 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
697 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700698 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
699 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600700 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700701 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
702 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600703 }
704 }
705 }
706
707 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700708 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600709 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
710 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
711 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
712 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
713 const auto src_ci = attachment_ci[src_at];
714 // The formats are required to match so we can pick either
715 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
716 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
717 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
John Zulauf7635de32020-05-29 17:14:15 -0600718
719 // Figure out which aspects are actually touched during resolve operations
720 const char *aspect_string = nullptr;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700721 AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600722 if (resolve_depth && resolve_stencil) {
John Zulauf7635de32020-05-29 17:14:15 -0600723 aspect_string = "depth/stencil";
724 } else if (resolve_depth) {
725 // Validate depth only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700726 gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600727 aspect_string = "depth";
728 } else if (resolve_stencil) {
729 // Validate all stencil only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700730 gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600731 aspect_string = "stencil";
732 }
733
John Zulaufd0ec59f2021-03-13 14:25:08 -0700734 if (aspect_string) {
735 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
736 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
737 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
738 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulauf7635de32020-05-29 17:14:15 -0600739 }
740 }
741}
742
743// Action for validating resolve operations
744class ValidateResolveAction {
745 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700746 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
sjfricke0bea06e2022-06-05 09:22:26 +0900747 const CommandExecutionContext &exec_context, CMD_TYPE cmd_type)
John Zulauf7635de32020-05-29 17:14:15 -0600748 : render_pass_(render_pass),
749 subpass_(subpass),
750 context_(context),
John Zulaufbb890452021-12-14 11:30:18 -0700751 exec_context_(exec_context),
sjfricke0bea06e2022-06-05 09:22:26 +0900752 cmd_type_(cmd_type),
John Zulauf7635de32020-05-29 17:14:15 -0600753 skip_(false) {}
754 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
John Zulaufd0ec59f2021-03-13 14:25:08 -0700755 const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage,
756 SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600757 HazardResult hazard;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700758 hazard = context_.DetectHazard(view_gen, gen_type, current_usage, ordering_rule);
John Zulauf7635de32020-05-29 17:14:15 -0600759 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +0900760 skip_ |= exec_context_.GetSyncState().LogError(
761 render_pass_, string_SyncHazardVUID(hazard.hazard),
762 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32 " to resolve attachment %" PRIu32
763 ". Access info %s.",
764 CommandTypeString(cmd_type_), string_SyncHazard(hazard.hazard), subpass_, aspect_name, attachment_name, src_at,
765 dst_at, exec_context_.FormatHazard(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600766 }
767 }
768 // Providing a mechanism for the constructing caller to get the result of the validation
769 bool GetSkip() const { return skip_; }
770
771 private:
772 VkRenderPass render_pass_;
773 const uint32_t subpass_;
774 const AccessContext &context_;
John Zulaufbb890452021-12-14 11:30:18 -0700775 const CommandExecutionContext &exec_context_;
sjfricke0bea06e2022-06-05 09:22:26 +0900776 CMD_TYPE cmd_type_;
John Zulauf7635de32020-05-29 17:14:15 -0600777 bool skip_;
778};
779
780// Update action for resolve operations
781class UpdateStateResolveAction {
782 public:
John Zulauf14940722021-04-12 15:19:02 -0600783 UpdateStateResolveAction(AccessContext &context, ResourceUsageTag tag) : context_(context), tag_(tag) {}
John Zulaufd0ec59f2021-03-13 14:25:08 -0700784 void operator()(const char *, const char *, uint32_t, uint32_t, const AttachmentViewGen &view_gen,
785 AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600786 // Ignores validation only arguments...
John Zulaufd0ec59f2021-03-13 14:25:08 -0700787 context_.UpdateAccessState(view_gen, gen_type, current_usage, ordering_rule, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600788 }
789
790 private:
791 AccessContext &context_;
John Zulauf14940722021-04-12 15:19:02 -0600792 const ResourceUsageTag tag_;
John Zulauf7635de32020-05-29 17:14:15 -0600793};
794
John Zulauf59e25072020-07-17 10:55:21 -0600795void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
John Zulauf14940722021-04-12 15:19:02 -0600796 const SyncStageAccessFlags &prior_, const ResourceUsageTag tag_) {
John Zulauf4fa68462021-04-26 21:04:22 -0600797 access_state = layer_data::make_unique<const ResourceAccessState>(*access_state_);
John Zulauf59e25072020-07-17 10:55:21 -0600798 usage_index = usage_index_;
799 hazard = hazard_;
800 prior_access = prior_;
801 tag = tag_;
802}
803
John Zulauf4fa68462021-04-26 21:04:22 -0600804void HazardResult::AddRecordedAccess(const ResourceFirstAccess &first_access) {
805 recorded_access = layer_data::make_unique<const ResourceFirstAccess>(first_access);
806}
807
John Zulauf1d5f9c12022-05-13 14:51:08 -0600808void AccessContext::DeleteAccess(const AddressRange &address) { GetAccessStateMap(address.type).erase_range(address.range); }
809
John Zulauf540266b2020-04-06 18:54:53 -0600810AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
811 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600812 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600813 Reset();
814 const auto &subpass_dep = dependencies[subpass];
John Zulauf22aefed2021-03-11 18:14:35 -0700815 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
816 prev_.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
John Zulauf355e49b2020-04-24 15:11:15 -0600817 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600818 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600819 const auto prev_pass = prev_dep.first->pass;
820 const auto &prev_barriers = prev_dep.second;
821 assert(prev_dep.second.size());
822 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
823 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700824 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600825
826 async_.reserve(subpass_dep.async.size());
827 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700828 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600829 }
John Zulauf22aefed2021-03-11 18:14:35 -0700830 if (has_barrier_from_external) {
831 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
832 prev_.emplace_back(external_context, queue_flags, subpass_dep.barrier_from_external);
833 src_external_ = &prev_.back();
John Zulaufe5da6e52020-03-18 15:32:18 -0600834 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600835 if (subpass_dep.barrier_to_external.size()) {
836 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600837 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700838}
839
John Zulauf8a7b03d2022-09-20 11:41:19 -0600840void AccessContext::Trim() {
841 auto normalize = [](AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) { access.second.Normalize(); };
842 ForAll(normalize);
843
844 // TODO consolidate map after normalization
845#if 0
846 for (auto& map : access_state_maps_) {
847 map.consolidate();
848 }
849#endif
850}
851
852void AccessContext::AddReferencedTags(ResourceUsageTagSet &used) const {
853 auto gather = [&used](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
854 access.second.GatherReferencedTags(used);
855 };
856 ConstForAll(gather);
857}
858
John Zulauf5f13a792020-03-10 07:31:21 -0600859template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600860HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600861 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600862 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600863 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600864
865 HazardResult hazard;
866 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
867 hazard = detector.Detect(prev);
868 }
869 return hazard;
870}
871
John Zulauf4a6105a2020-11-17 15:11:05 -0700872template <typename Action>
873void AccessContext::ForAll(Action &&action) {
874 for (const auto address_type : kAddressTypes) {
875 auto &accesses = GetAccessStateMap(address_type);
John Zulauf1d5f9c12022-05-13 14:51:08 -0600876 for (auto &access : accesses) {
John Zulauf4a6105a2020-11-17 15:11:05 -0700877 action(address_type, access);
878 }
879 }
880}
881
John Zulauff26fca92022-08-15 11:53:34 -0600882template <typename Action>
883void AccessContext::ConstForAll(Action &&action) const {
884 for (const auto address_type : kAddressTypes) {
885 auto &accesses = GetAccessStateMap(address_type);
886 for (auto &access : accesses) {
887 action(address_type, access);
888 }
889 }
890}
891
John Zulauf3da08bb2022-08-01 17:56:56 -0600892template <typename Predicate>
893void AccessContext::EraseIf(Predicate &&pred) {
894 for (const auto address_type : kAddressTypes) {
895 auto &accesses = GetAccessStateMap(address_type);
896 // Note: Don't forward, we don't want r-values moved, since we're going to make multiple calls.
897 layer_data::EraseIf(accesses, pred);
898 }
899}
900
John Zulauf3d84f1b2020-03-09 13:33:25 -0600901// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
902// the DAG of the contexts (for example subpasses)
903template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600904HazardResult AccessContext::DetectHazard(AccessAddressType type, Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600905 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600906 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600907
John Zulauf1a224292020-06-30 14:52:13 -0600908 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600909 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
910 // so we'll check these first
911 for (const auto &async_context : async_) {
912 hazard = async_context->DetectAsyncHazard(type, detector, range);
913 if (hazard.hazard) return hazard;
914 }
John Zulauf5f13a792020-03-10 07:31:21 -0600915 }
916
John Zulauf1a224292020-06-30 14:52:13 -0600917 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600918
John Zulauf69133422020-05-20 14:55:53 -0600919 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600920 const auto the_end = accesses.cend(); // End is not invalidated
921 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600922 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600923
John Zulauf3cafbf72021-03-26 16:55:19 -0600924 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600925 // Cover any leading gap, or gap between entries
926 if (detect_prev) {
927 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
928 // Cover any leading gap, or gap between entries
929 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600930 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600931 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600932 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600933 if (hazard.hazard) return hazard;
934 }
John Zulauf69133422020-05-20 14:55:53 -0600935 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
936 gap.begin = pos->first.end;
937 }
938
939 hazard = detector.Detect(pos);
940 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600941 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600942 }
943
944 if (detect_prev) {
945 // Detect in the trailing empty as needed
946 gap.end = range.end;
947 if (gap.non_empty()) {
948 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600949 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600950 }
951
952 return hazard;
953}
954
955// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
956template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700957HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
958 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600959 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600960 auto pos = accesses.lower_bound(range);
961 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600962
John Zulauf3d84f1b2020-03-09 13:33:25 -0600963 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600964 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700965 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600966 if (hazard.hazard) break;
967 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600968 }
John Zulauf16adfc92020-04-08 10:28:33 -0600969
John Zulauf3d84f1b2020-03-09 13:33:25 -0600970 return hazard;
971}
972
John Zulaufb02c1eb2020-10-06 16:33:36 -0600973struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700974 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600975 void operator()(ResourceAccessState *access) const {
976 assert(access);
977 access->ApplyBarriers(barriers, true);
978 }
979 const std::vector<SyncBarrier> &barriers;
980};
981
John Zulaufe0757ba2022-06-10 16:51:45 -0600982struct QueueTagOffsetBarrierAction {
983 QueueTagOffsetBarrierAction(QueueId qid, ResourceUsageTag offset) : queue_id(qid), tag_offset(offset) {}
984 void operator()(ResourceAccessState *access) const {
985 access->OffsetTag(tag_offset);
986 access->SetQueueId(queue_id);
987 };
988 QueueId queue_id;
989 ResourceUsageTag tag_offset;
990};
991
John Zulauf22aefed2021-03-11 18:14:35 -0700992struct ApplyTrackbackStackAction {
993 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
994 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
995 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600996 void operator()(ResourceAccessState *access) const {
997 assert(access);
998 assert(!access->HasPendingState());
999 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -06001000 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
1001 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -07001002 if (previous_barrier) {
1003 assert(bool(*previous_barrier));
1004 (*previous_barrier)(access);
1005 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001006 }
1007 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -07001008 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001009};
1010
1011// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
1012// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
1013// *different* map from dest.
1014// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
1015// range [first, last)
1016template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -06001017static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
1018 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -06001019 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -06001020 auto at = entry;
1021 for (auto pos = first; pos != last; ++pos) {
1022 // Every member of the input iterator range must fit within the remaining portion of entry
1023 assert(at->first.includes(pos->first));
1024 assert(at != dest->end());
1025 // Trim up at to the same size as the entry to resolve
1026 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001027 auto access = pos->second; // intentional copy
1028 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -06001029 at->second.Resolve(access);
1030 ++at; // Go to the remaining unused section of entry
1031 }
1032}
1033
John Zulaufa0a98292020-09-18 09:30:10 -06001034static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
1035 SyncBarrier merged = {};
1036 for (const auto &barrier : barriers) {
1037 merged.Merge(barrier);
1038 }
1039 return merged;
1040}
John Zulaufb02c1eb2020-10-06 16:33:36 -06001041template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -07001042void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -06001043 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
1044 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001045 if (!range.non_empty()) return;
1046
John Zulauf355e49b2020-04-24 15:11:15 -06001047 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
1048 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001049 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -06001050 if (current->pos_B->valid) {
1051 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001052 auto access = src_pos->second; // intentional copy
1053 barrier_action(&access);
John Zulauf16adfc92020-04-08 10:28:33 -06001054 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001055 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
1056 trimmed->second.Resolve(access);
1057 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -06001058 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001059 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -06001060 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -06001061 }
John Zulauf16adfc92020-04-08 10:28:33 -06001062 } else {
1063 // we have to descend to fill this gap
1064 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001065 ResourceAccessRange recurrence_range = current_range;
1066 // The current context is empty for the current range, so recur to fill the gap.
1067 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1068 // is not valid, to minimize that recurrence
1069 if (current->pos_B.at_end()) {
1070 // Do the remainder here....
1071 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001072 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001073 // Recur only over the range until B becomes valid (within the limits of range).
1074 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001075 }
John Zulauf22aefed2021-03-11 18:14:35 -07001076 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1077
John Zulauf355e49b2020-04-24 15:11:15 -06001078 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1079 // iterator of the outer while.
1080
1081 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1082 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1083 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001084 const auto seek_to = recurrence_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
locke-lunarg88dbb542020-06-23 22:05:42 -06001085 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001086 current.seek(seek_to);
1087 } else if (!current->pos_A->valid && infill_state) {
1088 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1089 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1090 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001091 }
John Zulauf5f13a792020-03-10 07:31:21 -06001092 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001093 if (current->range.non_empty()) {
1094 ++current;
1095 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001096 }
John Zulauf1a224292020-06-30 14:52:13 -06001097
1098 // Infill if range goes passed both the current and resolve map prior contents
1099 if (recur_to_infill && (current->range.end < range.end)) {
1100 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001101 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001102 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001103}
1104
John Zulauf22aefed2021-03-11 18:14:35 -07001105template <typename BarrierAction>
1106void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1107 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1108 const BarrierAction &previous_barrier) const {
1109 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1110 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1111}
1112
John Zulauf43cc7462020-12-03 12:33:12 -07001113void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001114 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1115 const ResourceAccessStateFunction *previous_barrier) const {
1116 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001117 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001118 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1119 ResourceAccessState state_copy;
1120 if (previous_barrier) {
1121 assert(bool(*previous_barrier));
1122 state_copy = *infill_state;
1123 (*previous_barrier)(&state_copy);
1124 infill_state = &state_copy;
1125 }
1126 sparse_container::update_range_value(*descent_map, range, *infill_state,
1127 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001128 }
1129 } else {
1130 // Look for something to fill the gap further along.
1131 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001132 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001133 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001134 }
John Zulauf5f13a792020-03-10 07:31:21 -06001135 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001136}
1137
John Zulauf4a6105a2020-11-17 15:11:05 -07001138// Non-lazy import of all accesses, WaitEvents needs this.
1139void AccessContext::ResolvePreviousAccesses() {
1140 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001141 if (!prev_.size()) return; // If no previous contexts, nothing to do
1142
John Zulauf4a6105a2020-11-17 15:11:05 -07001143 for (const auto address_type : kAddressTypes) {
1144 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1145 }
1146}
1147
John Zulauf43cc7462020-12-03 12:33:12 -07001148AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1149 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001150}
1151
John Zulauf1507ee42020-05-18 11:33:09 -06001152static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001153 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1154 ? SYNC_ACCESS_INDEX_NONE
1155 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1156 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001157 return stage_access;
1158}
1159static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001160 const auto stage_access =
1161 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1162 ? SYNC_ACCESS_INDEX_NONE
1163 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1164 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001165 return stage_access;
1166}
1167
John Zulauf7635de32020-05-29 17:14:15 -06001168// Caller must manage returned pointer
1169static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001170 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001171 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001172 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1173 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001174 return proxy;
1175}
1176
John Zulaufb02c1eb2020-10-06 16:33:36 -06001177template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001178void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1179 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1180 const ResourceAccessState *infill_state) const {
1181 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1182 if (!attachment_gen) return;
1183
1184 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1185 const AccessAddressType address_type = view_gen.GetAddressType();
1186 for (; range_gen->non_empty(); ++range_gen) {
1187 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001188 }
John Zulauf62f10592020-04-03 12:20:02 -06001189}
1190
John Zulauf1d5f9c12022-05-13 14:51:08 -06001191template <typename ResolveOp>
1192void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1193 const ResourceAccessState *infill_state, bool recur_to_infill) {
1194 for (auto address_type : kAddressTypes) {
1195 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1196 recur_to_infill);
1197 }
1198}
1199
John Zulauf7635de32020-05-29 17:14:15 -06001200// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001201bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001202 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001203 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001204 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001205 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1206 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1207 // those affects have not been recorded yet.
1208 //
1209 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1210 // to apply and only copy then, if this proves a hot spot.
1211 std::unique_ptr<AccessContext> proxy_for_prev;
1212 TrackBack proxy_track_back;
1213
John Zulauf355e49b2020-04-24 15:11:15 -06001214 const auto &transitions = rp_state.subpass_transitions[subpass];
1215 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001216 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1217
1218 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001219 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001220 if (prev_needs_proxy) {
1221 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001222 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001223 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001224 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001225 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001226 }
1227 track_back = &proxy_track_back;
1228 }
1229 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001230 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001231 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001232 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001233 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001234 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1235 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1236 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1237 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1238 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1239 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001240 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001241 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1242 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1243 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1244 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1245 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001246 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001247 }
John Zulauf355e49b2020-04-24 15:11:15 -06001248 }
1249 }
1250 return skip;
1251}
1252
John Zulaufbb890452021-12-14 11:30:18 -07001253bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001254 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001255 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001256 bool skip = false;
1257 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001258
John Zulauf1507ee42020-05-18 11:33:09 -06001259 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1260 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001261 const auto &view_gen = attachment_views[i];
1262 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001263 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001264
1265 // Need check in the following way
1266 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1267 // vs. transition
1268 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1269 // for each aspect loaded.
1270
1271 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001272 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001273 const bool is_color = !(has_depth || has_stencil);
1274
1275 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001276 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001277
John Zulaufaff20662020-06-01 14:07:58 -06001278 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001279 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001280
John Zulaufb02c1eb2020-10-06 16:33:36 -06001281 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001282 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001283 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001284 aspect = "color";
1285 } else {
John Zulauf57261402021-08-13 11:32:06 -06001286 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001287 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1288 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001289 aspect = "depth";
1290 }
John Zulauf57261402021-08-13 11:32:06 -06001291 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001292 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1293 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001294 aspect = "stencil";
1295 checked_stencil = true;
1296 }
1297 }
1298
1299 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001300 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001301 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001302 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001303 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001304 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001305 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001306 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1307 " aspect %s during load with loadOp %s.",
1308 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1309 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001310 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001311 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001312 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001313 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001314 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001315 }
1316 }
1317 }
1318 }
1319 return skip;
1320}
1321
John Zulaufaff20662020-06-01 14:07:58 -06001322// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1323// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1324// store is part of the same Next/End operation.
1325// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001326bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001327 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001328 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001329 bool skip = false;
1330 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001331
1332 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1333 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001334 const AttachmentViewGen &view_gen = attachment_views[i];
1335 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001336 const auto &ci = attachment_ci[i];
1337
1338 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1339 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1340 // sake, we treat DONT_CARE as writing.
1341 const bool has_depth = FormatHasDepth(ci.format);
1342 const bool has_stencil = FormatHasStencil(ci.format);
1343 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001344 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001345 if (!has_stencil && !store_op_stores) continue;
1346
1347 HazardResult hazard;
1348 const char *aspect = nullptr;
1349 bool checked_stencil = false;
1350 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001351 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1352 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001353 aspect = "color";
1354 } else {
John Zulauf57261402021-08-13 11:32:06 -06001355 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001356 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001357 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1358 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001359 aspect = "depth";
1360 }
1361 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001362 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1363 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001364 aspect = "stencil";
1365 checked_stencil = true;
1366 }
1367 }
1368
1369 if (hazard.hazard) {
1370 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1371 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001372 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1373 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1374 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001375 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1376 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001377 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001378 }
1379 }
1380 }
1381 return skip;
1382}
1383
John Zulaufbb890452021-12-14 11:30:18 -07001384bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001385 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001386 CMD_TYPE cmd_type, uint32_t subpass) const {
1387 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001388 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001389 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001390}
1391
John Zulauf06f6f1e2022-04-19 15:28:11 -06001392void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1393
John Zulauf3d84f1b2020-03-09 13:33:25 -06001394class HazardDetector {
1395 SyncStageAccessIndex usage_index_;
1396
1397 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001398 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001399 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001400 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001401 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001402 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001403};
1404
John Zulauf69133422020-05-20 14:55:53 -06001405class HazardDetectorWithOrdering {
1406 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001407 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001408
1409 public:
1410 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001411 return pos->second.DetectHazard(usage_index_, ordering_rule_, QueueSyncState::kQueueIdInvalid);
John Zulauf69133422020-05-20 14:55:53 -06001412 }
John Zulauf14940722021-04-12 15:19:02 -06001413 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001414 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001415 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001416 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001417};
1418
John Zulauf16adfc92020-04-08 10:28:33 -06001419HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001420 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001421 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001422 const auto base_address = ResourceBaseAddress(buffer);
1423 HazardDetector detector(usage_index);
1424 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001425}
1426
John Zulauf69133422020-05-20 14:55:53 -06001427template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001428HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1429 DetectOptions options) const {
1430 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1431 if (!attachment_gen) return HazardResult();
1432
1433 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1434 const auto address_type = view_gen.GetAddressType();
1435 for (; range_gen->non_empty(); ++range_gen) {
1436 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1437 if (hazard.hazard) return hazard;
1438 }
1439
1440 return HazardResult();
1441}
1442
1443template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001444HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1445 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001446 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001447 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001448 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001449 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001450 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001451 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001452 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001453 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001454 if (hazard.hazard) return hazard;
1455 }
1456 return HazardResult();
1457}
John Zulauf110413c2021-03-20 05:38:38 -06001458template <typename Detector>
1459HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001460 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1461 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001462 if (!SimpleBinding(image)) return HazardResult();
1463 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001464 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1465 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001466 const auto address_type = ImageAddressType(image);
1467 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001468 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1469 if (hazard.hazard) return hazard;
1470 }
1471 return HazardResult();
1472}
John Zulauf69133422020-05-20 14:55:53 -06001473
John Zulauf540266b2020-04-06 18:54:53 -06001474HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1475 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001476 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001477 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1478 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001479 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001480 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001481}
1482
1483HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001484 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001485 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001486 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001487}
1488
John Zulaufd0ec59f2021-03-13 14:25:08 -07001489HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1490 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1491 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1492 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1493}
1494
John Zulauf69133422020-05-20 14:55:53 -06001495HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001496 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001497 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001498 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001499 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001500}
1501
John Zulauf3d84f1b2020-03-09 13:33:25 -06001502class BarrierHazardDetector {
1503 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001504 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001505 SyncStageAccessFlags src_access_scope)
1506 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1507
John Zulauf5f13a792020-03-10 07:31:21 -06001508 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001509 return pos->second.DetectBarrierHazard(usage_index_, QueueSyncState::kQueueIdInvalid, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001510 }
John Zulauf14940722021-04-12 15:19:02 -06001511 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001512 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001513 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001514 }
1515
1516 private:
1517 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001518 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001519 SyncStageAccessFlags src_access_scope_;
1520};
1521
John Zulauf4a6105a2020-11-17 15:11:05 -07001522class EventBarrierHazardDetector {
1523 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001524 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001525 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope, QueueId queue_id,
John Zulauf14940722021-04-12 15:19:02 -06001526 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001527 : usage_index_(usage_index),
1528 src_exec_scope_(src_exec_scope),
1529 src_access_scope_(src_access_scope),
1530 event_scope_(event_scope),
John Zulaufe0757ba2022-06-10 16:51:45 -06001531 scope_queue_id_(queue_id),
1532 scope_tag_(scope_tag),
John Zulauf4a6105a2020-11-17 15:11:05 -07001533 scope_pos_(event_scope.cbegin()),
John Zulaufe0757ba2022-06-10 16:51:45 -06001534 scope_end_(event_scope.cend()) {}
John Zulauf4a6105a2020-11-17 15:11:05 -07001535
John Zulaufe0757ba2022-06-10 16:51:45 -06001536 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) {
1537 // Need to piece together coverage of pos->first range:
1538 // Copy the range as we'll be chopping it up as needed
1539 ResourceAccessRange range = pos->first;
1540 const ResourceAccessState &access = pos->second;
1541 HazardResult hazard;
1542
1543 bool in_scope = AdvanceScope(range);
1544 bool unscoped_tested = false;
1545 while (in_scope && !hazard.IsHazard()) {
1546 if (range.begin < ScopeBegin()) {
1547 if (!unscoped_tested) {
1548 unscoped_tested = true;
1549 hazard = access.DetectHazard(usage_index_);
1550 }
1551 // Note: don't need to check for in_scope as AdvanceScope true means range and ScopeRange intersect.
1552 // Thus a [ ScopeBegin, range.end ) will be non-empty.
1553 range.begin = ScopeBegin();
1554 } else { // in_scope implied that ScopeRange and range intersect
1555 hazard = access.DetectBarrierHazard(usage_index_, ScopeState(), src_exec_scope_, src_access_scope_, scope_queue_id_,
1556 scope_tag_);
1557 if (!hazard.IsHazard()) {
1558 range.begin = ScopeEnd();
1559 in_scope = AdvanceScope(range); // contains a non_empty check
1560 }
1561 }
John Zulauf4a6105a2020-11-17 15:11:05 -07001562 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001563 if (range.non_empty() && !hazard.IsHazard() && !unscoped_tested) {
1564 hazard = access.DetectHazard(usage_index_);
1565 }
1566 return hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07001567 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001568
John Zulauf14940722021-04-12 15:19:02 -06001569 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001570 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1571 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1572 }
1573
1574 private:
John Zulaufe0757ba2022-06-10 16:51:45 -06001575 bool ScopeInvalid() const { return scope_pos_ == scope_end_; }
1576 bool ScopeValid() const { return !ScopeInvalid(); }
1577 void ScopeSeek(const ResourceAccessRange &range) { scope_pos_ = event_scope_.lower_bound(range); }
1578
1579 // Hiding away the std::pair grunge...
1580 ResourceAddress ScopeBegin() const { return scope_pos_->first.begin; }
1581 ResourceAddress ScopeEnd() const { return scope_pos_->first.end; }
1582 const ResourceAccessRange &ScopeRange() const { return scope_pos_->first; }
1583 const ResourceAccessState &ScopeState() const { return scope_pos_->second; }
1584
1585 bool AdvanceScope(const ResourceAccessRange &range) {
1586 // Note: non_empty is (valid && !empty), so don't change !non_empty to empty...
1587 if (!range.non_empty()) return false;
1588 if (ScopeInvalid()) return false;
1589
1590 if (ScopeRange().strictly_less(range)) {
1591 ScopeSeek(range);
1592 }
1593
1594 return ScopeValid() && ScopeRange().intersects(range);
1595 }
1596
John Zulauf4a6105a2020-11-17 15:11:05 -07001597 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001598 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001599 SyncStageAccessFlags src_access_scope_;
1600 const SyncEventState::ScopeMap &event_scope_;
John Zulaufe0757ba2022-06-10 16:51:45 -06001601 QueueId scope_queue_id_;
1602 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001603 SyncEventState::ScopeMap::const_iterator scope_pos_;
1604 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001605};
1606
John Zulaufe0757ba2022-06-10 16:51:45 -06001607HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1608 VkPipelineStageFlags2KHR src_exec_scope,
1609 const SyncStageAccessFlags &src_access_scope, QueueId queue_id,
1610 const SyncEventState &sync_event, AccessContext::DetectOptions options) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001611 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1612 // first access scope map to use, and there's no easy way to plumb it in below.
1613 const auto address_type = ImageAddressType(image);
1614 const auto &event_scope = sync_event.FirstScope(address_type);
1615
1616 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001617 event_scope, queue_id, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001618 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001619}
1620
John Zulaufd0ec59f2021-03-13 14:25:08 -07001621HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1622 DetectOptions options) const {
1623 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1624 barrier.src_access_scope);
1625 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1626}
1627
Jeremy Gebben40a22942020-12-22 14:22:06 -07001628HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001629 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001630 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001631 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001632 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001633 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001634}
1635
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001636HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001637 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001638 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001639}
John Zulauf355e49b2020-04-24 15:11:15 -06001640
John Zulauf9cb530d2019-09-30 14:14:10 -06001641template <typename Flags, typename Map>
1642SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1643 SyncStageAccessFlags scope = 0;
1644 for (const auto &bit_scope : map) {
1645 if (flag_mask < bit_scope.first) break;
1646
1647 if (flag_mask & bit_scope.first) {
1648 scope |= bit_scope.second;
1649 }
1650 }
1651 return scope;
1652}
1653
Jeremy Gebben40a22942020-12-22 14:22:06 -07001654SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001655 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1656}
1657
Jeremy Gebben40a22942020-12-22 14:22:06 -07001658SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1659 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001660}
1661
Jeremy Gebben40a22942020-12-22 14:22:06 -07001662// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1663SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001664 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1665 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1666 // of the union of all stage/access types for all the stages and the same unions for the access mask...
John Zulauf9cb530d2019-09-30 14:14:10 -06001667 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1668}
1669
1670template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001671void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001672 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1673 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001674 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001675 auto pos = accesses->lower_bound(range);
1676 if (pos == accesses->end() || !pos->first.intersects(range)) {
1677 // The range is empty, fill it with a default value.
1678 pos = action.Infill(accesses, pos, range);
1679 } else if (range.begin < pos->first.begin) {
1680 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001681 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001682 } else if (pos->first.begin < range.begin) {
1683 // Trim the beginning if needed
1684 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1685 ++pos;
1686 }
1687
1688 const auto the_end = accesses->end();
1689 while ((pos != the_end) && pos->first.intersects(range)) {
1690 if (pos->first.end > range.end) {
1691 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1692 }
1693
1694 pos = action(accesses, pos);
1695 if (pos == the_end) break;
1696
1697 auto next = pos;
1698 ++next;
1699 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1700 // Need to infill if next is disjoint
1701 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001702 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001703 next = action.Infill(accesses, next, new_range);
1704 }
1705 pos = next;
1706 }
1707}
John Zulaufd5115702021-01-18 12:34:33 -07001708
1709// Give a comparable interface for range generators and ranges
1710template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001711void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001712 assert(range);
1713 UpdateMemoryAccessState(accesses, *range, action);
1714}
1715
John Zulauf4a6105a2020-11-17 15:11:05 -07001716template <typename Action, typename RangeGen>
1717void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1718 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001719 RangeGen &range_gen = *range_gen_arg; // Non-const references must be * by style requirement but deref-ing * iterator is a pain
John Zulauf4a6105a2020-11-17 15:11:05 -07001720 for (; range_gen->non_empty(); ++range_gen) {
1721 UpdateMemoryAccessState(accesses, *range_gen, action);
1722 }
1723}
John Zulauf9cb530d2019-09-30 14:14:10 -06001724
John Zulaufd0ec59f2021-03-13 14:25:08 -07001725template <typename Action, typename RangeGen>
1726void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1727 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1728 for (; range_gen->non_empty(); ++range_gen) {
1729 UpdateMemoryAccessState(accesses, *range_gen, action);
1730 }
1731}
John Zulauf9cb530d2019-09-30 14:14:10 -06001732struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001733 using Iterator = ResourceAccessRangeMap::iterator;
1734 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001735 // this is only called on gaps, and never returns a gap.
1736 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001737 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001738 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001739 }
John Zulauf5f13a792020-03-10 07:31:21 -06001740
John Zulauf5c5e88d2019-12-26 11:22:02 -07001741 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001742 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001743 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001744 return pos;
1745 }
1746
John Zulauf43cc7462020-12-03 12:33:12 -07001747 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001748 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001749 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001750 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001751 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001752 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001753 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001754 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001755};
1756
John Zulauf4a6105a2020-11-17 15:11:05 -07001757// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001758struct PipelineBarrierOp {
1759 SyncBarrier barrier;
1760 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001761 ResourceAccessState::QueueScopeOps scope;
1762 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
John Zulauff26fca92022-08-15 11:53:34 -06001763 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {
1764 if (queue_id != QueueSyncState::kQueueIdInvalid) {
1765 // This is a submit time application... supress layout transitions to not taint the QueueBatchContext write state
1766 layout_transition = false;
1767 }
1768 }
John Zulaufd5115702021-01-18 12:34:33 -07001769 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001770 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001771};
John Zulauf00119522022-05-23 19:07:42 -06001772
John Zulaufecf4ac52022-06-06 10:08:42 -06001773// Batch barrier ops don't modify in place, and thus don't need to hold pending state, and also are *never* layout transitions.
1774struct BatchBarrierOp : public PipelineBarrierOp {
1775 void operator()(ResourceAccessState *access_state) const {
1776 access_state->ApplyBarrier(scope, barrier, layout_transition);
1777 access_state->ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
1778 }
1779 BatchBarrierOp(QueueId queue_id, const SyncBarrier &barrier_) : PipelineBarrierOp(queue_id, barrier_, false) {}
1780};
1781
John Zulauf4a6105a2020-11-17 15:11:05 -07001782// The barrier operation for wait events
1783struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001784 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001785 SyncBarrier barrier;
1786 bool layout_transition;
John Zulaufe0757ba2022-06-10 16:51:45 -06001787
1788 WaitEventBarrierOp(const QueueId scope_queue_, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
John Zulauf00119522022-05-23 19:07:42 -06001789 bool layout_transition_)
John Zulauff26fca92022-08-15 11:53:34 -06001790 : scope_ops(scope_queue_, scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {
1791 if (scope_queue_ != QueueSyncState::kQueueIdInvalid) {
1792 // This is a submit time application... supress layout transitions to not taint the QueueBatchContext write state
1793 layout_transition = false;
1794 }
1795 }
John Zulaufb7578302022-05-19 13:50:18 -06001796 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001797};
John Zulauf1e331ec2020-12-04 18:29:38 -07001798
John Zulauf4a6105a2020-11-17 15:11:05 -07001799// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1800// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1801// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001802template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001803class ApplyBarrierOpsFunctor {
1804 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001805 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001806 // Only called with a gap, and pos at the lower_bound(range)
1807 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1808 if (!infill_default_) {
1809 return pos;
1810 }
1811 ResourceAccessState default_state;
1812 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1813 return inserted;
1814 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001815
John Zulauf5c628d02021-05-04 15:46:36 -06001816 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001817 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001818 for (const auto &op : barrier_ops_) {
1819 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001820 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001821
John Zulauf89311b42020-09-29 16:28:47 -06001822 if (resolve_) {
1823 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1824 // another walk
1825 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001826 }
1827 return pos;
1828 }
1829
John Zulauf89311b42020-09-29 16:28:47 -06001830 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001831 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1832 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001833 barrier_ops_.reserve(size_hint);
1834 }
John Zulauf5c628d02021-05-04 15:46:36 -06001835 void EmplaceBack(const BarrierOp &op) {
1836 barrier_ops_.emplace_back(op);
1837 infill_default_ |= op.layout_transition;
1838 }
John Zulauf89311b42020-09-29 16:28:47 -06001839
1840 private:
1841 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001842 bool infill_default_;
1843 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001844 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001845};
1846
John Zulauf4a6105a2020-11-17 15:11:05 -07001847// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1848// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1849template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001850class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1851 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1852
John Zulauf4a6105a2020-11-17 15:11:05 -07001853 public:
John Zulaufee984022022-04-13 16:39:50 -06001854 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001855};
1856
John Zulauf1e331ec2020-12-04 18:29:38 -07001857// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001858class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1859 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1860
John Zulauf1e331ec2020-12-04 18:29:38 -07001861 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001862 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001863};
1864
John Zulauf8e3c3e92021-01-06 11:19:36 -07001865void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001866 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001867 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001868 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001869}
1870
John Zulauf8e3c3e92021-01-06 11:19:36 -07001871void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001872 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001873 if (!SimpleBinding(buffer)) return;
1874 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001875 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001876}
John Zulauf355e49b2020-04-24 15:11:15 -06001877
John Zulauf8e3c3e92021-01-06 11:19:36 -07001878void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001879 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1880 if (!SimpleBinding(image)) return;
1881 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001882 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001883 const auto address_type = ImageAddressType(image);
1884 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1885 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1886}
1887void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001888 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001889 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001890 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001891 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001892 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001893 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001894 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001895 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001896 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001897}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001898
1899void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001900 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001901 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1902 if (!gen) return;
1903 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1904 const auto address_type = view_gen.GetAddressType();
1905 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1906 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001907}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001908
John Zulauf8e3c3e92021-01-06 11:19:36 -07001909void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001910 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001911 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001912 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1913 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001914 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001915}
1916
John Zulaufd0ec59f2021-03-13 14:25:08 -07001917template <typename Action, typename RangeGen>
1918void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1919 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1920 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001921}
1922
1923template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001924void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1925 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1926 if (!gen) return;
1927 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001928}
1929
John Zulaufd0ec59f2021-03-13 14:25:08 -07001930void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1931 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001932 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001933 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001934 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001935}
1936
John Zulaufd0ec59f2021-03-13 14:25:08 -07001937void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001938 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001939 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001940
1941 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1942 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001943 const auto &view_gen = attachment_views[i];
1944 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001945
1946 const auto &ci = attachment_ci[i];
1947 const bool has_depth = FormatHasDepth(ci.format);
1948 const bool has_stencil = FormatHasStencil(ci.format);
1949 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001950 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001951
1952 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001953 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1954 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001955 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001956 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001957 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1958 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001959 }
John Zulauf57261402021-08-13 11:32:06 -06001960 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001961 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001962 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1963 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001964 }
1965 }
1966 }
1967 }
1968}
1969
John Zulauf540266b2020-04-06 18:54:53 -06001970template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001971void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001972 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001973 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001974 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001975 }
1976}
1977
1978void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001979 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1980 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001981 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001982 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001983 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001984 }
1985 }
1986}
1987
John Zulauf4fa68462021-04-26 21:04:22 -06001988// Caller must ensure that lifespan of this is less than from
1989void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1990
John Zulauf355e49b2020-04-24 15:11:15 -06001991// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001992HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1993 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001994
John Zulauf355e49b2020-04-24 15:11:15 -06001995 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001996 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001997
1998 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001999 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
2000 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07002001 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002002 if (!hazard.hazard) {
2003 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07002004 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06002005 }
John Zulaufa0a98292020-09-18 09:30:10 -06002006
John Zulauf355e49b2020-04-24 15:11:15 -06002007 return hazard;
2008}
2009
John Zulaufb02c1eb2020-10-06 16:33:36 -06002010void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06002011 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002012 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06002013 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002014 for (const auto &transition : transitions) {
2015 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002016 const auto &view_gen = attachment_views[transition.attachment];
2017 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002018
2019 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
2020 assert(trackback);
2021
2022 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07002023 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002024 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002025 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06002026 auto &target_map = GetAccessStateMap(address_type);
2027 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002028 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
2029 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002030 }
2031
John Zulauf86356ca2020-10-19 11:46:41 -06002032 // If there were no transitions skip this global map walk
2033 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07002034 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07002035 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06002036 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002037}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002038
sjfricke0bea06e2022-06-05 09:22:26 +09002039bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002040 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002041 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002042 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002043 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002044 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002045 return skip;
2046 }
sjfricke0bea06e2022-06-05 09:22:26 +09002047 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002048
2049 using DescriptorClass = cvdescriptorset::DescriptorClass;
2050 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2051 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002052 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2053
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002054 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002055 const auto raster_state = pipe->RasterizationState();
2056 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002057 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002058 }
locke-lunarg61870c22020-06-09 14:51:50 -06002059 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002060 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002061 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2062 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002063 SyncStageAccessIndex sync_index =
2064 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2065
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002066 for (uint32_t index = 0; index < binding->count; index++) {
2067 const auto *descriptor = binding->GetDescriptor(index);
locke-lunarg61870c22020-06-09 14:51:50 -06002068 switch (descriptor->GetClass()) {
2069 case DescriptorClass::ImageSampler:
2070 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002071 if (descriptor->Invalid()) {
2072 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002073 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002074
2075 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2076 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2077 const auto *img_view_state = image_descriptor->GetImageViewState();
2078 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2079
John Zulauf361fb532020-07-22 10:45:39 -06002080 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002081 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2082 // Descriptors, so we do not have to worry about depth slicing here.
2083 // See: VUID 00343
2084 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002085 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002086 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002087
2088 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2089 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2090 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002091 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002092 hazard =
2093 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2094 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002095 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002096 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2097 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002098 }
John Zulauf110413c2021-03-20 05:38:38 -06002099
John Zulauf33fc1d52020-07-17 11:01:10 -06002100 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002101 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002102 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002103 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2104 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002105 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002106 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2107 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2108 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002109 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2110 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002111 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002112 }
2113 break;
2114 }
2115 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002116 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2117 if (texel_descriptor->Invalid()) {
2118 continue;
2119 }
2120 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2121 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002122 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002123 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002124 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002125 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002126 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002127 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002128 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002129 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2130 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2131 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002132 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002133 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002134 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002135 }
2136 break;
2137 }
2138 case DescriptorClass::GeneralBuffer: {
2139 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002140 if (buffer_descriptor->Invalid()) {
2141 continue;
2142 }
2143 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002144 const ResourceAccessRange range =
2145 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002146 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002147 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002148 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002149 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002150 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002151 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002152 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2153 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2154 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002155 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002156 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002157 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002158 }
2159 break;
2160 }
2161 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2162 default:
2163 break;
2164 }
2165 }
2166 }
2167 }
2168 return skip;
2169}
2170
2171void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002172 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002173 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002174 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002175 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002176 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002177 return;
2178 }
2179
2180 using DescriptorClass = cvdescriptorset::DescriptorClass;
2181 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2182 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002183 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2184
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002185 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002186 const auto raster_state = pipe->RasterizationState();
2187 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002188 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002189 }
locke-lunarg61870c22020-06-09 14:51:50 -06002190 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002191 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002192 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2193 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002194 SyncStageAccessIndex sync_index =
2195 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2196
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002197 for (uint32_t i = 0; i < binding->count; i++) {
2198 const auto *descriptor = binding->GetDescriptor(i);
locke-lunarg61870c22020-06-09 14:51:50 -06002199 switch (descriptor->GetClass()) {
2200 case DescriptorClass::ImageSampler:
2201 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002202 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2203 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2204 if (image_descriptor->Invalid()) {
2205 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002206 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002207 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002208 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2209 // Descriptors, so we do not have to worry about depth slicing here.
2210 // See: VUID 00343
2211 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002212 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002213 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002214 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2215 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2216 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2217 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002218 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002219 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2220 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002221 }
locke-lunarg61870c22020-06-09 14:51:50 -06002222 break;
2223 }
2224 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002225 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2226 if (texel_descriptor->Invalid()) {
2227 continue;
2228 }
2229 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2230 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002231 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002232 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002233 break;
2234 }
2235 case DescriptorClass::GeneralBuffer: {
2236 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002237 if (buffer_descriptor->Invalid()) {
2238 continue;
2239 }
2240 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002241 const ResourceAccessRange range =
2242 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002243 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002244 break;
2245 }
2246 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2247 default:
2248 break;
2249 }
2250 }
2251 }
2252 }
2253}
2254
sjfricke0bea06e2022-06-05 09:22:26 +09002255bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002256 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002257 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002258 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002259 return skip;
2260 }
2261
2262 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2263 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002264 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002265
2266 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002267 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002268 if (binding_description.binding < binding_buffers_size) {
2269 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002270 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002271
locke-lunarg1ae57d62020-11-18 10:49:19 -07002272 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002273 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2274 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002275 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002276 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002277 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002278 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002279 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002280 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2281 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002282 }
2283 }
2284 }
2285 return skip;
2286}
2287
John Zulauf14940722021-04-12 15:19:02 -06002288void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002289 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002290 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002291 return;
2292 }
2293 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2294 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002295 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002296
2297 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002298 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002299 if (binding_description.binding < binding_buffers_size) {
2300 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002301 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002302
locke-lunarg1ae57d62020-11-18 10:49:19 -07002303 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002304 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2305 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002306 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2307 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002308 }
2309 }
2310}
2311
sjfricke0bea06e2022-06-05 09:22:26 +09002312bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002313 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002314 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002315 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002316 }
locke-lunarg61870c22020-06-09 14:51:50 -06002317
locke-lunarg1ae57d62020-11-18 10:49:19 -07002318 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002319 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002320 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2321 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002322 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002323 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002324 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002325 index_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002326 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2327 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002328 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002329 }
2330
2331 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2332 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002333 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002334 return skip;
2335}
2336
John Zulauf14940722021-04-12 15:19:02 -06002337void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002338 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) return;
locke-lunarg61870c22020-06-09 14:51:50 -06002339
locke-lunarg1ae57d62020-11-18 10:49:19 -07002340 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002341 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002342 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2343 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002344 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002345
2346 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2347 // We will detect more accurate range in the future.
2348 RecordDrawVertex(UINT32_MAX, 0, tag);
2349}
2350
sjfricke0bea06e2022-06-05 09:22:26 +09002351bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002352 bool skip = false;
2353 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002354 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002355 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002356}
2357
John Zulauf14940722021-04-12 15:19:02 -06002358void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002359 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002360 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002361 }
locke-lunarg61870c22020-06-09 14:51:50 -06002362}
2363
John Zulauf00119522022-05-23 19:07:42 -06002364QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2365
sjfricke0bea06e2022-06-05 09:22:26 +09002366ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002367 const VkRect2D &render_area,
2368 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002369 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002370 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2371 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulaufab84f242022-08-04 18:38:40 -06002372 render_pass_contexts_.emplace_back(layer_data::make_unique<RenderPassAccessContext>(rp_state, render_area, GetQueueFlags(),
2373 attachment_views, &cb_access_context_));
2374 current_renderpass_context_ = render_pass_contexts_.back().get();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002375 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002376 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002377 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002378}
2379
sjfricke0bea06e2022-06-05 09:22:26 +09002380ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002381 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002382 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002383
sjfricke0bea06e2022-06-05 09:22:26 +09002384 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2385 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2386 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002387
2388 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002389 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002390 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002391}
2392
sjfricke0bea06e2022-06-05 09:22:26 +09002393ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002394 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002395 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002396
sjfricke0bea06e2022-06-05 09:22:26 +09002397 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2398 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002399
2400 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002401 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002402 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002403 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002404}
2405
John Zulauf4a6105a2020-11-17 15:11:05 -07002406void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2407 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002408 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002409 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002410 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002411 }
2412}
2413
John Zulaufae842002021-04-15 18:20:55 -06002414// The is the recorded cb context
John Zulauf0223f142022-07-06 09:05:39 -06002415bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext &exec_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002416 uint32_t index) const {
John Zulauf0223f142022-07-06 09:05:39 -06002417 if (!exec_context.ValidForSyncOps()) return false;
2418
2419 const QueueId queue_id = exec_context.GetQueueId();
2420 const ResourceUsageTag base_tag = exec_context.GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002421 bool skip = false;
2422 ResourceUsageRange tag_range = {0, 0};
2423 const AccessContext *recorded_context = GetCurrentAccessContext();
2424 assert(recorded_context);
2425 HazardResult hazard;
John Zulaufdab327f2022-07-08 12:02:05 -06002426 ReplayGuard replay_guard(exec_context, *this);
2427
John Zulaufbb890452021-12-14 11:30:18 -07002428 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002429 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002430 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002431 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002432 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002433 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002434 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2435 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002436 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002437 };
2438 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002439 // we update the range to any include layout transition first use writes,
2440 // as they are stored along with the source scope (as effective barrier) when recorded
2441 tag_range.end = sync_op.tag + 1;
John Zulauf0223f142022-07-06 09:05:39 -06002442 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, exec_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002443
John Zulauf0223f142022-07-06 09:05:39 -06002444 // We're allowing for the ReplayRecord to modify the exec_context (e.g. for Renderpass operations), so
2445 // we need to fetch the current access context each time
John Zulaufdab327f2022-07-08 12:02:05 -06002446 hazard = exec_context.DetectFirstUseHazard(tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002447 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002448 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002449 }
2450 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002451 // Record the barrier into the proxy context.
John Zulauf0223f142022-07-06 09:05:39 -06002452 sync_op.sync_op->ReplayRecord(exec_context, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002453 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002454 }
2455
2456 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002457 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulauf0223f142022-07-06 09:05:39 -06002458 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *exec_context.GetCurrentAccessContext());
John Zulaufae842002021-04-15 18:20:55 -06002459 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002460 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002461 }
2462
2463 return skip;
2464}
2465
sjfricke0bea06e2022-06-05 09:22:26 +09002466void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002467 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2468 assert(recorded_context);
2469
2470 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2471 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002472 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002473 // we update the range to any include layout transition first use writes,
2474 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf0223f142022-07-06 09:05:39 -06002475 sync_op.sync_op->ReplayRecord(*this, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002476 }
2477
2478 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2479 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002480 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002481}
2482
John Zulauf1d5f9c12022-05-13 14:51:08 -06002483void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002484 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002485 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002486}
2487
John Zulaufdab327f2022-07-08 12:02:05 -06002488HazardResult CommandBufferAccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
2489 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, *GetCurrentAccessContext());
2490}
2491
John Zulauf3c788ef2022-02-22 12:12:30 -07002492ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002493 // The execution references ensure lifespan for the referenced child CB's...
2494 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002495 InsertRecordedAccessLogEntries(recorded_context);
2496 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002497 return tag_range;
2498}
2499
John Zulauf3c788ef2022-02-22 12:12:30 -07002500void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
John Zulauf8a7b03d2022-09-20 11:41:19 -06002501 cbs_referenced_->emplace(recorded_context.GetCBStateShared());
2502 access_log_->insert(access_log_->end(), recorded_context.access_log_->cbegin(), recorded_context.access_log_->cend());
John Zulauf3c788ef2022-02-22 12:12:30 -07002503}
2504
John Zulauf41a9c7c2021-12-07 15:59:53 -07002505ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
John Zulauf8a7b03d2022-09-20 11:41:19 -06002506 ResourceUsageTag next = access_log_->size();
2507 access_log_->emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002508 return next;
2509}
2510
2511ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2512 command_number_++;
2513 subcommand_number_ = 0;
John Zulauf8a7b03d2022-09-20 11:41:19 -06002514 ResourceUsageTag next = access_log_->size();
2515 access_log_->emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002516 return next;
2517}
2518
2519ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2520 if (index == 0) {
2521 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2522 }
2523 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2524}
2525
John Zulaufbb890452021-12-14 11:30:18 -07002526void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2527 auto tag = sync_op->Record(this);
2528 // As renderpass operations can have side effects on the command buffer access context,
2529 // update the sync operation to record these if any.
John Zulaufbb890452021-12-14 11:30:18 -07002530 sync_ops_.emplace_back(tag, std::move(sync_op));
2531}
2532
John Zulaufae842002021-04-15 18:20:55 -06002533class HazardDetectFirstUse {
2534 public:
John Zulauf0223f142022-07-06 09:05:39 -06002535 HazardDetectFirstUse(const ResourceAccessState &recorded_use, QueueId queue_id, const ResourceUsageRange &tag_range)
2536 : recorded_use_(recorded_use), queue_id_(queue_id), tag_range_(tag_range) {}
John Zulaufae842002021-04-15 18:20:55 -06002537 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06002538 return pos->second.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufae842002021-04-15 18:20:55 -06002539 }
2540 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2541 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2542 }
2543
2544 private:
2545 const ResourceAccessState &recorded_use_;
John Zulaufec943ec2022-06-29 07:52:56 -06002546 const QueueId queue_id_;
John Zulaufae842002021-04-15 18:20:55 -06002547 const ResourceUsageRange &tag_range_;
2548};
2549
2550// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2551// hazards will be detected
John Zulaufec943ec2022-06-29 07:52:56 -06002552HazardResult AccessContext::DetectFirstUseHazard(QueueId queue_id, const ResourceUsageRange &tag_range,
John Zulauf0223f142022-07-06 09:05:39 -06002553 const AccessContext &access_context) const {
John Zulaufae842002021-04-15 18:20:55 -06002554 HazardResult hazard;
2555 for (const auto address_type : kAddressTypes) {
2556 const auto &recorded_access_map = GetAccessStateMap(address_type);
2557 for (const auto &recorded_access : recorded_access_map) {
2558 // Cull any entries not in the current tag range
2559 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulauf0223f142022-07-06 09:05:39 -06002560 HazardDetectFirstUse detector(recorded_access.second, queue_id, tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002561 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2562 if (hazard.hazard) break;
2563 }
2564 }
2565
2566 return hazard;
2567}
2568
John Zulaufbb890452021-12-14 11:30:18 -07002569bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002570 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002571 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002572 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002573 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002574 if (!pipe) {
2575 return skip;
2576 }
2577
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002578 const auto raster_state = pipe->RasterizationState();
2579 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002580 return skip;
2581 }
sjfricke0bea06e2022-06-05 09:22:26 +09002582 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002583 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002584 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002585
John Zulauf1a224292020-06-30 14:52:13 -06002586 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002587 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002588 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2589 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002590 if (location >= subpass.colorAttachmentCount ||
2591 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002592 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002593 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002594 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2595 if (!view_gen.IsValid()) continue;
2596 HazardResult hazard =
2597 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2598 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002599 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002600 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002601 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002602 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002603 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002604 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002605 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2606 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002607 }
2608 }
2609 }
locke-lunarg37047832020-06-12 13:44:45 -06002610
2611 // PHASE1 TODO: Add layout based read/vs. write selection.
2612 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002613 const auto ds_state = pipe->DepthStencilState();
2614 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002615
2616 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2617 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2618 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002619 bool depth_write = false, stencil_write = false;
2620
2621 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002622 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002623 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2624 depth_write = true;
2625 }
2626 // PHASE1 TODO: It needs to check if stencil is writable.
2627 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2628 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2629 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002630 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002631 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2632 stencil_write = true;
2633 }
2634
2635 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2636 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002637 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2638 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2639 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002640 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002641 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002642 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002643 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002644 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002645 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002646 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002647 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002648 }
2649 }
2650 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002651 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2652 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2653 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002654 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002655 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002656 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002657 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002658 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002659 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002660 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002661 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002662 }
locke-lunarg61870c22020-06-09 14:51:50 -06002663 }
2664 }
2665 return skip;
2666}
2667
sjfricke0bea06e2022-06-05 09:22:26 +09002668void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2669 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002670 if (!pipe) {
2671 return;
2672 }
2673
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002674 const auto *raster_state = pipe->RasterizationState();
2675 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002676 return;
2677 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002678 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002679 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002680
John Zulauf1a224292020-06-30 14:52:13 -06002681 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002682 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002683 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2684 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002685 if (location >= subpass.colorAttachmentCount ||
2686 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002687 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002688 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002689 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2690 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2691 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2692 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002693 }
2694 }
locke-lunarg37047832020-06-12 13:44:45 -06002695
2696 // PHASE1 TODO: Add layout based read/vs. write selection.
2697 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002698 const auto *ds_state = pipe->DepthStencilState();
2699 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002700 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2701 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2702 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002703 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002704 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2705 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002706
2707 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002708 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2709 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002710 depth_write = true;
2711 }
2712 // PHASE1 TODO: It needs to check if stencil is writable.
2713 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2714 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2715 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002716 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002717 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2718 stencil_write = true;
2719 }
2720
John Zulaufd0ec59f2021-03-13 14:25:08 -07002721 if (depth_write || stencil_write) {
2722 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2723 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2724 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2725 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002726 }
locke-lunarg61870c22020-06-09 14:51:50 -06002727 }
2728}
2729
sjfricke0bea06e2022-06-05 09:22:26 +09002730bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002731 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002732 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002733 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002734 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002735 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002736 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002737
John Zulauf355e49b2020-04-24 15:11:15 -06002738 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002739 if (next_subpass >= subpass_contexts_.size()) {
2740 return skip;
2741 }
John Zulauf1507ee42020-05-18 11:33:09 -06002742 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002743 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002744 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002745 if (!skip) {
2746 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2747 // on a copy of the (empty) next context.
2748 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2749 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002750 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002751 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002752 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002753 }
John Zulauf7635de32020-05-29 17:14:15 -06002754 return skip;
2755}
sjfricke0bea06e2022-06-05 09:22:26 +09002756bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002757 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002758 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002759 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002760 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002761 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2762 cmd_type);
2763 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002764 return skip;
2765}
2766
John Zulauf64ffe552021-02-06 10:25:07 -07002767AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002768 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002769}
2770
John Zulaufbb890452021-12-14 11:30:18 -07002771bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002772 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002773 bool skip = false;
2774
John Zulauf7635de32020-05-29 17:14:15 -06002775 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2776 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2777 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2778 // to apply and only copy then, if this proves a hot spot.
2779 std::unique_ptr<AccessContext> proxy_for_current;
2780
John Zulauf355e49b2020-04-24 15:11:15 -06002781 // Validate the "finalLayout" transitions to external
2782 // Get them from where there we're hidding in the extra entry.
2783 const auto &final_transitions = rp_state_->subpass_transitions.back();
2784 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002785 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002786 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002787 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2788 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002789
2790 if (transition.prev_pass == current_subpass_) {
2791 if (!proxy_for_current) {
2792 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
John Zulauf64ffe552021-02-06 10:25:07 -07002793 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002794 }
2795 context = proxy_for_current.get();
2796 }
2797
John Zulaufa0a98292020-09-18 09:30:10 -06002798 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2799 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002800 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002801 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002802 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002803 if (hazard.tag == kInvalidTag) {
2804 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002805 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002806 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2807 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2808 " final image layout transition (old_layout: %s, new_layout: %s).",
2809 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2810 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2811 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002812 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002813 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2814 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2815 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2816 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2817 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002818 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002819 }
John Zulauf355e49b2020-04-24 15:11:15 -06002820 }
2821 }
2822 return skip;
2823}
2824
John Zulauf14940722021-04-12 15:19:02 -06002825void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002826 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002827 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002828}
2829
John Zulauf14940722021-04-12 15:19:02 -06002830void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002831 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2832 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002833
2834 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2835 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002836 const AttachmentViewGen &view_gen = attachment_views_[i];
2837 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002838
2839 const auto &ci = attachment_ci[i];
2840 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002841 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002842 const bool is_color = !(has_depth || has_stencil);
2843
2844 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002845 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2846 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2847 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2848 SyncOrdering::kColorAttachment, tag);
2849 }
John Zulauf1507ee42020-05-18 11:33:09 -06002850 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002851 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002852 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2853 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2854 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2855 SyncOrdering::kDepthStencilAttachment, tag);
2856 }
John Zulauf1507ee42020-05-18 11:33:09 -06002857 }
2858 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002859 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2860 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2861 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2862 SyncOrdering::kDepthStencilAttachment, tag);
2863 }
John Zulauf1507ee42020-05-18 11:33:09 -06002864 }
2865 }
2866 }
2867 }
2868}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002869AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2870 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2871 AttachmentViewGenVector view_gens;
2872 VkExtent3D extent = CastTo3D(render_area.extent);
2873 VkOffset3D offset = CastTo3D(render_area.offset);
2874 view_gens.reserve(attachment_views.size());
2875 for (const auto *view : attachment_views) {
2876 view_gens.emplace_back(view, offset, extent);
2877 }
2878 return view_gens;
2879}
John Zulauf64ffe552021-02-06 10:25:07 -07002880RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2881 VkQueueFlags queue_flags,
2882 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2883 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002884 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulaufdab327f2022-07-08 12:02:05 -06002885 // Add this for all subpasses here so that they exist during next subpass validation
2886 InitSubpassContexts(queue_flags, rp_state, external_context, subpass_contexts_);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002887 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002888}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002889void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002890 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002891 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2892 RecordLayoutTransitions(barrier_tag);
2893 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002894}
John Zulauf1507ee42020-05-18 11:33:09 -06002895
John Zulauf41a9c7c2021-12-07 15:59:53 -07002896void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2897 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002898 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002899 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2900 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002901
ziga-lunarg31a3e772022-03-22 11:48:46 +01002902 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2903 return;
2904 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002905 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2906 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002907 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002908 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2909 RecordLayoutTransitions(barrier_tag);
2910 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002911}
2912
John Zulauf41a9c7c2021-12-07 15:59:53 -07002913void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2914 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002915 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002916 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2917 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002918
John Zulauf355e49b2020-04-24 15:11:15 -06002919 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002920 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002921
2922 // Add the "finalLayout" transitions to external
2923 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002924 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2925 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2926 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002927 const auto &final_transitions = rp_state_->subpass_transitions.back();
2928 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002929 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002930 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002931 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002932 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002933 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002934 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002935 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002936 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002937 }
2938}
2939
John Zulauf06f6f1e2022-04-19 15:28:11 -06002940SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2941 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002942 SyncExecScope result;
2943 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002944 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002945 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002946 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002947 return result;
2948}
2949
Jeremy Gebben40a22942020-12-22 14:22:06 -07002950SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002951 SyncExecScope result;
2952 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002953 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2954 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002955 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002956 return result;
2957}
2958
John Zulaufecf4ac52022-06-06 10:08:42 -06002959SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2960 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2961
2962SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2963 : src_exec_scope(src), src_access_scope(src.valid_accesses), dst_exec_scope(dst), dst_access_scope(src.valid_accesses) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002964
2965template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002966SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2967 : src_exec_scope(src),
2968 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2969 dst_exec_scope(dst),
2970 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002971
2972SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002973 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2974 if (barrier) {
2975 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002976 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002977 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002978
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002979 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002980 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002981 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2982
2983 } else {
2984 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002985 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002986 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2987
2988 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002989 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002990 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2991 }
2992}
2993
2994template <typename Barrier>
2995SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2996 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2997 src_exec_scope = src.exec_scope;
2998 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2999
3000 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07003001 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07003002 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003003}
3004
John Zulaufb02c1eb2020-10-06 16:33:36 -06003005// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
3006void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06003007 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003008 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06003009 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06003010 }
3011}
3012
John Zulauf89311b42020-09-29 16:28:47 -06003013// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
3014// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
3015// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07003016void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003017 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003018 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06003019 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06003020 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003021 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06003022 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06003023 }
John Zulaufbb890452021-12-14 11:30:18 -07003024 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06003025}
John Zulauf9cb530d2019-09-30 14:14:10 -06003026HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
3027 HazardResult hazard;
3028 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003029 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06003030 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003031 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06003032 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003033 }
3034 } else {
John Zulauf361fb532020-07-22 10:45:39 -06003035 // Write operation:
3036 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
3037 // If reads exists -- test only against them because either:
3038 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
3039 // * the read weren't hazards, and thus if the write is safe w.r.t. the reads, no hazard vs. last_write is possible if
3040 // the current write happens after the reads, so just test the write against the reades
3041 // Otherwise test against last_write
3042 //
3043 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07003044 if (last_reads.size()) {
3045 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06003046 if (IsReadHazard(usage_stage, read_access)) {
3047 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3048 break;
3049 }
3050 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003051 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06003052 // Write-After-Write check -- if we have a previous write to test against
3053 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003054 }
3055 }
3056 return hazard;
3057}
3058
John Zulaufec943ec2022-06-29 07:52:56 -06003059HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule,
3060 QueueId queue_id) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003061 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulaufec943ec2022-06-29 07:52:56 -06003062 return DetectHazard(usage_index, ordering, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003063}
3064
John Zulaufec943ec2022-06-29 07:52:56 -06003065HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering,
3066 QueueId queue_id) const {
John Zulauf69133422020-05-20 14:55:53 -06003067 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3068 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003069 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003070 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003071 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulaufec943ec2022-06-29 07:52:56 -06003072 const bool last_write_is_ordered = (last_write & ordering.access_scope).any() && (write_queue == queue_id);
John Zulauf4285ee92020-09-23 10:20:52 -06003073 if (IsRead(usage_bit)) {
3074 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3075 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3076 if (is_raw_hazard) {
3077 // NOTE: we know last_write is non-zero
3078 // See if the ordering rules save us from the simple RAW check above
3079 // First check to see if the current usage is covered by the ordering rules
3080 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3081 const bool usage_is_ordered =
3082 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3083 if (usage_is_ordered) {
3084 // Now see of the most recent write (or a subsequent read) are ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003085 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(queue_id, ordering));
John Zulauf4285ee92020-09-23 10:20:52 -06003086 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003087 }
3088 }
John Zulauf4285ee92020-09-23 10:20:52 -06003089 if (is_raw_hazard) {
3090 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3091 }
John Zulauf5c628d02021-05-04 15:46:36 -06003092 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3093 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
John Zulaufec943ec2022-06-29 07:52:56 -06003094 return DetectBarrierHazard(usage_index, queue_id, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003095 } else {
3096 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003097 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003098 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003099 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003100 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003101 if (usage_write_is_ordered) {
3102 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
John Zulaufec943ec2022-06-29 07:52:56 -06003103 ordered_stages = GetOrderedStages(queue_id, ordering);
John Zulauf4285ee92020-09-23 10:20:52 -06003104 }
3105 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3106 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003107 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003108 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3109 if (IsReadHazard(usage_stage, read_access)) {
3110 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3111 break;
3112 }
John Zulaufd14743a2020-07-03 09:42:39 -06003113 }
3114 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003115 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3116 bool ilt_ilt_hazard = false;
3117 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3118 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3119 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3120 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3121 }
3122 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003123 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003124 }
John Zulauf69133422020-05-20 14:55:53 -06003125 }
3126 }
3127 return hazard;
3128}
3129
John Zulaufec943ec2022-06-29 07:52:56 -06003130HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, QueueId queue_id,
3131 const ResourceUsageRange &tag_range) const {
John Zulaufae842002021-04-15 18:20:55 -06003132 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003133 using Size = FirstAccesses::size_type;
3134 const auto &recorded_accesses = recorded_use.first_accesses_;
3135 Size count = recorded_accesses.size();
3136 if (count) {
3137 const auto &last_access = recorded_accesses.back();
3138 bool do_write_last = IsWrite(last_access.usage_index);
3139 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003140
John Zulauf4fa68462021-04-26 21:04:22 -06003141 for (Size i = 0; i < count; ++count) {
3142 const auto &first = recorded_accesses[i];
3143 // Skip and quit logic
3144 if (first.tag < tag_range.begin) continue;
3145 if (first.tag >= tag_range.end) {
3146 do_write_last = false; // ignore last since we know it can't be in tag_range
3147 break;
3148 }
3149
John Zulaufec943ec2022-06-29 07:52:56 -06003150 hazard = DetectHazard(first.usage_index, first.ordering_rule, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003151 if (hazard.hazard) {
3152 hazard.AddRecordedAccess(first);
3153 break;
3154 }
3155 }
3156
3157 if (do_write_last && tag_range.includes(last_access.tag)) {
3158 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3159 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3160 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3161 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3162 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3163 // the barrier that applies them
3164 barrier |= recorded_use.first_write_layout_ordering_;
3165 }
3166 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3167 // the active context
3168 if (recorded_use.first_read_stages_) {
3169 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3170 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3171 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3172 // active context.
3173 barrier.exec_scope |= recorded_use.first_read_stages_;
3174 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3175 barrier.access_scope |= FlagBit(last_access.usage_index);
3176 }
John Zulaufec943ec2022-06-29 07:52:56 -06003177 hazard = DetectHazard(last_access.usage_index, barrier, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003178 if (hazard.hazard) {
3179 hazard.AddRecordedAccess(last_access);
3180 }
3181 }
John Zulaufae842002021-04-15 18:20:55 -06003182 }
3183 return hazard;
3184}
3185
John Zulauf2f952d22020-02-10 11:34:51 -07003186// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003187HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003188 HazardResult hazard;
3189 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003190 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3191 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3192 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003193 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003194 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003195 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003196 }
3197 } else {
John Zulauf14940722021-04-12 15:19:02 -06003198 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003199 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003200 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003201 // Any reads during the other subpass will conflict with this write, so we need to check them all.
John Zulaufab7756b2020-12-29 16:10:16 -07003202 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003203 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003204 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003205 break;
3206 }
3207 }
John Zulauf2f952d22020-02-10 11:34:51 -07003208 }
3209 }
3210 return hazard;
3211}
3212
John Zulaufae842002021-04-15 18:20:55 -06003213HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3214 ResourceUsageTag start_tag) const {
3215 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003216 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003217 // Skip and quit logic
3218 if (first.tag < tag_range.begin) continue;
3219 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003220
3221 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003222 if (hazard.hazard) {
3223 hazard.AddRecordedAccess(first);
3224 break;
3225 }
John Zulaufae842002021-04-15 18:20:55 -06003226 }
3227 return hazard;
3228}
3229
John Zulaufec943ec2022-06-29 07:52:56 -06003230HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, QueueId queue_id,
3231 VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003232 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003233 // Only supporting image layout transitions for now
3234 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3235 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003236 // only test for WAW if there no intervening read operations.
3237 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003238 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003239 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003240 for (const auto &read_access : last_reads) {
John Zulaufec943ec2022-06-29 07:52:56 -06003241 if (read_access.IsReadBarrierHazard(queue_id, src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003242 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003243 break;
3244 }
3245 }
John Zulaufec943ec2022-06-29 07:52:56 -06003246 } else if (last_write.any() && IsWriteBarrierHazard(queue_id, src_exec_scope, src_access_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003247 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3248 }
3249
3250 return hazard;
3251}
3252
John Zulaufe0757ba2022-06-10 16:51:45 -06003253HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3254 VkPipelineStageFlags2KHR src_exec_scope,
3255 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3256 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003257 // Only supporting image layout transitions for now
3258 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3259 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003260
John Zulaufe0757ba2022-06-10 16:51:45 -06003261 if ((write_tag >= event_tag) && last_write.any()) {
3262 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3263 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3264 } else {
3265 // only test for WAW if there no intervening read operations.
3266 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3267 if (last_reads.size()) {
3268 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3269 // first scope, or they are a hazard.
3270 const ReadStates &scope_reads = scope_state.last_reads;
3271 const ReadStates::size_type scope_read_count = scope_reads.size();
3272 // Since the hasn't been a write:
3273 // * The current read state is a superset of the scoped one
3274 // * The stage order is the same.
3275 assert(last_reads.size() >= scope_read_count);
3276 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3277 const ReadState &scope_read = scope_reads[read_idx];
3278 const ReadState &current_read = last_reads[read_idx];
3279 assert(scope_read.stage == current_read.stage);
3280 if (current_read.tag > event_tag) {
3281 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3282 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3283 } else {
3284 // The read is in the events first synchronization scope, so we use a barrier hazard check
3285 // If the read stage is not in the src sync scope
3286 // *AND* not execution chained with an existing sync barrier (that's the or)
3287 // then the barrier access is unsafe (R/W after R)
3288 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3289 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3290 break;
3291 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003292 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003293 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003294 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3295 const ReadState &current_read = last_reads[scope_read_count];
3296 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3297 }
3298 } else if (last_write.any()) {
3299 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
John Zulauf4a6105a2020-11-17 15:11:05 -07003300 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3301 // So do a normal barrier hazard check
John Zulauf7ad6a1d2022-09-02 11:46:33 -06003302 if (scope_state.IsWriteBarrierHazard(event_queue, src_exec_scope, src_access_scope)) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003303 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003304 }
John Zulauf361fb532020-07-22 10:45:39 -06003305 }
John Zulaufd14743a2020-07-03 09:42:39 -06003306 }
John Zulauf361fb532020-07-22 10:45:39 -06003307
John Zulauf0cb5be22020-01-23 12:18:22 -07003308 return hazard;
3309}
3310
John Zulauf5f13a792020-03-10 07:31:21 -06003311// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3312// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3313// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3314void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003315 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003316 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3317 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003318 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003319 } else if (other.write_tag == write_tag) {
3320 // In the *equals* case for write operations, we merged the write barriers and the read state (but without the
John Zulauf5f13a792020-03-10 07:31:21 -06003321 // dependency chaining logic or any stage expansion)
3322 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003323 pending_write_barriers |= other.pending_write_barriers;
3324 pending_layout_transition |= other.pending_layout_transition;
3325 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003326 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003327
John Zulaufd14743a2020-07-03 09:42:39 -06003328 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003329 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003330 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003331 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003332 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003333 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003334 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003335 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3336 // but we should wait on profiling data for that.
3337 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003338 auto &my_read = last_reads[my_read_index];
3339 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003340 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003341 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003342 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003343 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003344 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003345 my_read.pending_dep_chain = other_read.pending_dep_chain;
3346 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3347 // May require tracking more than one access per stage.
3348 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003349 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003350 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003351 // Since I'm overwriting the fragement stage read, also update the input attachment info
3352 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003353 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003354 }
John Zulauf14940722021-04-12 15:19:02 -06003355 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003356 // The read tags match so merge the barriers
3357 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003358 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003359 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003360 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003361
John Zulauf5f13a792020-03-10 07:31:21 -06003362 break;
3363 }
3364 }
3365 } else {
3366 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003367 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003368 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003369 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003370 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003371 }
John Zulauf5f13a792020-03-10 07:31:21 -06003372 }
3373 }
John Zulauf361fb532020-07-22 10:45:39 -06003374 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003375 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3376 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003377
3378 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3379 // of the copy and other into this using the update first logic.
3380 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3381 // of the other first_accesses... )
3382 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3383 FirstAccesses firsts(std::move(first_accesses_));
3384 first_accesses_.clear();
3385 first_read_stages_ = 0U;
3386 auto a = firsts.begin();
3387 auto a_end = firsts.end();
3388 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003389 // TODO: Determine whether some tag offset will be needed for PHASE II
3390 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003391 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3392 ++a;
3393 }
3394 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3395 }
3396 for (; a != a_end; ++a) {
3397 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3398 }
3399 }
John Zulauf5f13a792020-03-10 07:31:21 -06003400}
3401
John Zulauf14940722021-04-12 15:19:02 -06003402void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003403 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3404 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003405 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003406 // Mulitple outstanding reads may be of interest and do dependency chains independently
3407 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3408 const auto usage_stage = PipelineStageBit(usage_index);
3409 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003410 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003411 for (auto &read_access : last_reads) {
3412 if (read_access.stage == usage_stage) {
3413 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003414 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003415 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003416 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003417 } else {
3418 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3419 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3420 // that sync_stages is a subset of barriers may not apply.
3421 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003422 }
3423 }
3424 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003425 for (auto &read_access : last_reads) {
3426 if (read_access.barriers & usage_stage) {
3427 read_access.sync_stages |= usage_stage;
3428 }
3429 }
John Zulaufab7756b2020-12-29 16:10:16 -07003430 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003431 last_read_stages |= usage_stage;
3432 }
John Zulauf4285ee92020-09-23 10:20:52 -06003433
3434 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
Jeremy Gebben40a22942020-12-22 14:22:06 -07003435 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003436 // TODO Revisit re: multiple reads for a given stage
3437 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003438 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003439 } else {
3440 // Assume write
3441 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003442 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003443 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003444 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003445}
John Zulauf5f13a792020-03-10 07:31:21 -06003446
John Zulauf89311b42020-09-29 16:28:47 -06003447// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3448// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3449// We can overwrite them as *this* write is now after them.
3450//
3451// Note: intentionally ignore pending barriers and chains (i.e. don't apply or clear them), let ApplyPendingBarriers handle them.
John Zulauf14940722021-04-12 15:19:02 -06003452void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003453 ClearRead();
3454 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003455 write_tag = tag;
3456 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003457}
3458
John Zulauf1d5f9c12022-05-13 14:51:08 -06003459void ResourceAccessState::ClearWrite() {
3460 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3461 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3462 write_barriers.reset();
3463 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3464 last_write.reset();
3465
3466 write_tag = 0;
3467 write_queue = QueueSyncState::kQueueIdInvalid;
3468}
3469
3470void ResourceAccessState::ClearRead() {
3471 last_reads.clear();
3472 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3473}
3474
John Zulauf8a7b03d2022-09-20 11:41:19 -06003475void ResourceAccessState::ClearPending() {
3476 pending_write_dep_chain = VK_PIPELINE_STAGE_2_NONE;
3477 pending_layout_transition = false;
3478 pending_write_barriers.reset();
3479 pending_layout_ordering_ = OrderingBarrier();
3480}
3481
3482void ResourceAccessState::ClearFirstUse() {
3483 first_accesses_.clear();
3484 first_read_stages_ = VK_PIPELINE_STAGE_2_NONE;
3485 first_write_layout_ordering_ = OrderingBarrier();
3486}
3487
John Zulauf89311b42020-09-29 16:28:47 -06003488// Apply the memory barrier without updating the existing barriers. The execution barrier
3489// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3490// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3491// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003492template <typename ScopeOps>
3493void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003494 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3495 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003496 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
John Zulaufb7578302022-05-19 13:50:18 -06003497 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003498 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3499 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003500 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003501 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003502 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003503 if (layout_transition) {
3504 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3505 }
John Zulaufa0a98292020-09-18 09:30:10 -06003506 }
John Zulauf89311b42020-09-29 16:28:47 -06003507 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3508 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003509
John Zulauf89311b42020-09-29 16:28:47 -06003510 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003511 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3512 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003513 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3514
John Zulaufab7756b2020-12-29 16:10:16 -07003515 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003516 // The | implements the "dependency chain" logic for this access, as the barriers field stores the second sync scope
John Zulaufb7578302022-05-19 13:50:18 -06003517 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003518 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3519 stages_in_scope |= read_access.stage;
3520 }
3521 }
3522
3523 for (auto &read_access : last_reads) {
3524 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3525 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3526 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3527 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003528 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003529 }
3530 }
John Zulaufa0a98292020-09-18 09:30:10 -06003531 }
John Zulaufa0a98292020-09-18 09:30:10 -06003532}
3533
John Zulauf14940722021-04-12 15:19:02 -06003534void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003535 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003536 // SetWrite clobbers the last_reads array, and thus we don't have to clear the read_state out.
John Zulauf89311b42020-09-29 16:28:47 -06003537 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003538 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003539 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3540 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003541 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003542 }
John Zulauf89311b42020-09-29 16:28:47 -06003543
3544 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003545 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003546 for (auto &read_access : last_reads) {
3547 read_access.barriers |= read_access.pending_dep_chain;
3548 read_execution_barriers |= read_access.barriers;
3549 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003550 }
3551
3552 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3553 write_dependency_chain |= pending_write_dep_chain;
3554 write_barriers |= pending_write_barriers;
3555 pending_write_dep_chain = 0;
3556 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003557}
3558
John Zulaufecf4ac52022-06-06 10:08:42 -06003559// Assumes signal queue != wait queue
3560void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3561 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3562 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3563 assert(signal.queue != wait.queue);
3564 for (auto &read_access : last_reads) {
3565 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3566 // Deflects WAR on wait queue
3567 read_access.barriers = wait.exec_scope;
3568 } else {
3569 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3570 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3571 }
3572 }
3573 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3574 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3575 read_execution_barriers = wait.exec_scope;
3576 write_barriers = wait.valid_accesses;
3577 } else {
3578 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3579 write_barriers.reset();
3580 }
3581 write_dependency_chain = read_execution_barriers;
3582}
3583
John Zulauf3da08bb2022-08-01 17:56:56 -06003584bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) const {
3585 return (usage_queue == queue) && (usage_tag <= tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003586}
3587
John Zulauf3da08bb2022-08-01 17:56:56 -06003588bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) const { return queue == usage_queue; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003589
John Zulauf3da08bb2022-08-01 17:56:56 -06003590bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) const { return tag <= usage_tag; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003591
3592// Return if the resulting state is "empty"
3593template <typename Pred>
3594bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3595 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3596
3597 // Use the predicate to build a mask of the read stages we are synchronizing
3598 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003599 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003600 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003601 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3602 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003603 }
3604 }
3605
John Zulauf434c4e62022-05-19 16:03:56 -06003606 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3607 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3608 uint32_t unsync_count = 0;
3609 for (auto &read_access : last_reads) {
3610 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3611 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3612 sync_reads |= read_access.stage;
3613 } else {
3614 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003615 }
3616 }
3617
3618 if (unsync_count) {
3619 if (sync_reads) {
3620 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3621 ReadStates unsync_reads;
3622 unsync_reads.reserve(unsync_count);
3623 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3624 for (auto &read_access : last_reads) {
3625 if (0 == (read_access.stage & sync_reads)) {
3626 unsync_reads.emplace_back(read_access);
3627 unsync_read_stages |= read_access.stage;
3628 }
3629 }
3630 last_read_stages = unsync_read_stages;
3631 last_reads = std::move(unsync_reads);
3632 }
3633 } else {
3634 // Nothing remains (or it was empty to begin with)
3635 ClearRead();
3636 }
3637
3638 bool all_clear = last_reads.size() == 0;
3639 if (last_write.any()) {
3640 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3641 // Clear any predicated write, or any the write from any any access with synchronized reads.
3642 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3643 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3644 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3645 ClearWrite();
3646 } else {
3647 all_clear = false;
3648 }
3649 }
3650 return all_clear;
3651}
3652
John Zulaufae842002021-04-15 18:20:55 -06003653bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3654 if (!first_accesses_.size()) return false;
3655 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3656 return tag_range.intersects(first_access_range);
3657}
3658
John Zulauf1d5f9c12022-05-13 14:51:08 -06003659void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3660 if (last_write.any()) write_tag += offset;
3661 for (auto &read_access : last_reads) {
3662 read_access.tag += offset;
3663 }
3664 for (auto &first : first_accesses_) {
3665 first.tag += offset;
3666 }
3667}
3668
3669ResourceAccessState::ResourceAccessState()
3670 : write_barriers(~SyncStageAccessFlags(0)),
3671 write_dependency_chain(0),
3672 write_tag(),
3673 write_queue(QueueSyncState::kQueueIdInvalid),
3674 last_write(0),
3675 input_attachment_read(false),
3676 last_read_stages(0),
3677 read_execution_barriers(0),
3678 pending_write_dep_chain(0),
3679 pending_layout_transition(false),
3680 pending_write_barriers(0),
3681 pending_layout_ordering_(),
3682 first_accesses_(),
3683 first_read_stages_(0U),
3684 first_write_layout_ordering_() {}
3685
John Zulauf59e25072020-07-17 10:55:21 -06003686// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003687VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3688 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003689
John Zulaufab7756b2020-12-29 16:10:16 -07003690 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003691 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003692 barriers = read_access.barriers;
3693 break;
John Zulauf59e25072020-07-17 10:55:21 -06003694 }
3695 }
John Zulauf4285ee92020-09-23 10:20:52 -06003696
John Zulauf59e25072020-07-17 10:55:21 -06003697 return barriers;
3698}
3699
John Zulauf1d5f9c12022-05-13 14:51:08 -06003700void ResourceAccessState::SetQueueId(QueueId id) {
3701 for (auto &read_access : last_reads) {
3702 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3703 read_access.queue = id;
3704 }
3705 }
3706 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3707 write_queue = id;
3708 }
3709}
3710
John Zulauf00119522022-05-23 19:07:42 -06003711bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3712 return 0 != (write_dependency_chain & src_exec_scope);
3713}
3714
3715bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3716 return (src_access_scope & last_write).any();
3717}
3718
John Zulaufec943ec2022-06-29 07:52:56 -06003719bool ResourceAccessState::WriteBarrierInScope(const SyncStageAccessFlags &src_access_scope) const {
3720 return (write_barriers & src_access_scope).any();
3721}
3722
John Zulaufb7578302022-05-19 13:50:18 -06003723bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3724 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003725 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3726}
3727
3728bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3729 SyncStageAccessFlags src_access_scope) const {
3730 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003731}
3732
John Zulaufe0757ba2022-06-10 16:51:45 -06003733bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3734 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003735 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3736 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3737 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003738 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003739}
3740
John Zulaufec943ec2022-06-29 07:52:56 -06003741bool ResourceAccessState::WriteInChainedScope(VkPipelineStageFlags2KHR src_exec_scope,
3742 const SyncStageAccessFlags &src_access_scope) const {
3743 return WriteInChain(src_exec_scope) && WriteBarrierInScope(src_access_scope);
3744}
3745
John Zulauf8a7b03d2022-09-20 11:41:19 -06003746// As ReadStates must be unique by stage, this is as good a sort as needed
3747bool operator<(const ResourceAccessState::ReadState &lhs, const ResourceAccessState::ReadState &rhs) {
3748 return lhs.stage < rhs.stage;
3749}
3750
3751void ResourceAccessState::Normalize() {
3752 if (!last_write.any()) {
3753 ClearWrite();
3754 }
3755 if (!last_reads.size()) {
3756 ClearRead();
3757 } else {
3758 // Sort the reads in stage order for consistent comparisons
3759 std::sort(last_reads.begin(), last_reads.end());
3760 for (auto &read_access : last_reads) {
3761 read_access.Normalize();
3762 }
3763 }
3764
3765 ClearPending();
3766 ClearFirstUse();
3767}
3768
3769void ResourceAccessState::GatherReferencedTags(ResourceUsageTagSet &used) const {
3770 if (last_write.any()) {
3771 used.insert(write_tag);
3772 }
3773
3774 for (const auto &read_access : last_reads) {
3775 used.insert(read_access.tag);
3776 }
3777}
3778
John Zulaufcb7e1672022-05-04 13:46:08 -06003779bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003780 assert(IsRead(usage));
3781 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3782 // * the previous reads are not hazards, and thus last_write must be visible and available to
3783 // any reads that happen after.
3784 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3785 // the current read will be also not be a hazard, thus reporting a hazard here adds no needed information.
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003786 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003787}
3788
John Zulaufec943ec2022-06-29 07:52:56 -06003789VkPipelineStageFlags2 ResourceAccessState::GetOrderedStages(QueueId queue_id, const OrderingBarrier &ordering) const {
3790 // At apply queue submission order limits on the effect of ordering
3791 VkPipelineStageFlags2 non_qso_stages = VK_PIPELINE_STAGE_2_NONE;
3792 if (queue_id != QueueSyncState::kQueueIdInvalid) {
3793 for (const auto &read_access : last_reads) {
3794 if (read_access.queue != queue_id) {
3795 non_qso_stages |= read_access.stage;
3796 }
3797 }
3798 }
John Zulauf4285ee92020-09-23 10:20:52 -06003799 // Whether the stage are in the ordering scope only matters if the current write is ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003800 const VkPipelineStageFlags2 read_stages_in_qso = last_read_stages & ~non_qso_stages;
3801 VkPipelineStageFlags2 ordered_stages = read_stages_in_qso & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003802 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003803 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003804 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003805 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
Jeremy Gebben40a22942020-12-22 14:22:06 -07003806 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003807 }
3808
3809 return ordered_stages;
3810}
3811
John Zulauf14940722021-04-12 15:19:02 -06003812void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003813 // Only record until we record a write.
3814 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003815 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003816 if (0 == (usage_stage & first_read_stages_)) {
3817 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003818 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003819 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003820 if (0 == (read_execution_barriers & usage_stage)) {
3821 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3822 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3823 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003824 }
3825 }
3826}
3827
John Zulauf4fa68462021-04-26 21:04:22 -06003828void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3829 // Only call this after recording an image layout transition
3830 assert(first_accesses_.size());
3831 if (first_accesses_.back().tag == tag) {
3832 // If this layout transition is the the first write, add the additional ordering rules that guard the ILT
Samuel Iglesias Gonsálvez9b4660b2021-10-21 08:50:39 +02003833 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003834 first_write_layout_ordering_ = layout_ordering;
3835 }
3836}
3837
John Zulauf1d5f9c12022-05-13 14:51:08 -06003838ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3839 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3840 : stage(stage_),
3841 access(access_),
3842 barriers(barriers_),
3843 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3844 tag(tag_),
3845 queue(QueueSyncState::kQueueIdInvalid),
3846 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3847
John Zulaufee984022022-04-13 16:39:50 -06003848void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3849 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3850 stage = stage_;
3851 access = access_;
3852 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003853 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003854 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003855 pending_dep_chain = VK_PIPELINE_STAGE_2_NONE; // If this is a new read, we aren't applying a barrier set.
John Zulaufee984022022-04-13 16:39:50 -06003856}
3857
John Zulauf00119522022-05-23 19:07:42 -06003858// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3859// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3860// that have bee applied (via semaphore) to those accesses can be chained off of.
3861bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3862 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3863 return (exec_scope & effective_stages) != 0;
3864}
3865
John Zulauf697c0e12022-04-19 16:31:12 -06003866ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3867 ResourceUsageRange reserve;
3868 reserve.begin = tag_limit_.fetch_add(tag_count);
3869 reserve.end = reserve.begin + tag_count;
3870 return reserve;
3871}
3872
John Zulauf3da08bb2022-08-01 17:56:56 -06003873void SyncValidator::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
3874 // We need to go through every queue batch context and clear all accesses this wait synchronizes
3875 // As usual -- two groups, the "last batch" and the signaled semaphores
3876 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
3877 // QueueBatchContext, track which we've done to avoid duplicate traversals
3878 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
3879 for (auto &batch : queue_batch_contexts) {
3880 batch->ApplyTaggedWait(queue_id, tag);
3881 }
3882}
3883
3884void SyncValidator::UpdateFenceWaitInfo(VkFence fence, QueueId queue_id, ResourceUsageTag tag) {
3885 if (fence != VK_NULL_HANDLE) {
3886 // Overwrite the current fence wait information
3887 // NOTE: Not doing fence usage validation here, leaving that in CoreChecks intentionally
3888 auto fence_state = Get<FENCE_STATE>(fence);
3889 waitable_fences_[fence] = {fence_state, tag, queue_id};
3890 }
3891}
3892
3893void SyncValidator::WaitForFence(VkFence fence) {
3894 auto fence_it = waitable_fences_.find(fence);
3895 if (fence_it != waitable_fences_.end()) {
3896 // The fence may no longer be waitable for several valid reasons.
3897 FenceSyncState &wait_for = fence_it->second;
3898 ApplyTaggedWait(wait_for.queue_id, wait_for.tag);
3899 waitable_fences_.erase(fence_it);
3900 }
3901}
3902
John Zulaufbbda4572022-04-19 16:20:45 -06003903const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3904 return GetMappedPlainFromShared(queue_sync_states_, queue);
3905}
3906
3907QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3908
3909std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3910 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3911}
3912
3913std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3914 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3915}
3916
John Zulaufe0757ba2022-06-10 16:51:45 -06003917template <typename T>
3918struct GetBatchTraits {};
3919template <>
3920struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3921 using Batch = std::shared_ptr<QueueBatchContext>;
3922 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3923};
3924
3925template <>
3926struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3927 using Batch = std::shared_ptr<QueueBatchContext>;
3928 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3929};
3930
3931template <typename BatchSet, typename Map, typename Predicate>
3932static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003933 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003934 for (auto &entry : map) {
3935 // Intentional copy
3936 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003937 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003938 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003939 return snapshot;
3940}
3941
3942template <typename Predicate>
3943QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003944 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003945}
3946
3947template <typename Predicate>
3948QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003949 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3950}
3951
3952QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3953 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3954 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3955 if (batch && !layer_data::Contains(snapshot, batch)) {
3956 snapshot.emplace(batch);
3957 }
3958 return false;
3959 };
3960 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3961 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003962}
3963
John Zulaufa8700a52022-08-18 16:22:08 -06003964struct QueueSubmitCmdState {
3965 std::shared_ptr<const QueueSyncState> queue;
3966 std::shared_ptr<QueueBatchContext> last_batch;
3967 std::string submit_func_name;
John Zulaufa8700a52022-08-18 16:22:08 -06003968 SignaledSemaphores signaled;
John Zulauf8a7b03d2022-09-20 11:41:19 -06003969 QueueSubmitCmdState(const char *func_name, const SignaledSemaphores &parent_semaphores)
3970 : submit_func_name(func_name), signaled(parent_semaphores) {}
John Zulaufa8700a52022-08-18 16:22:08 -06003971};
3972
3973bool QueueBatchContext::DoQueueSubmitValidate(const SyncValidator &sync_state, QueueSubmitCmdState &cmd_state,
3974 const VkSubmitInfo2 &batch_info) {
3975 bool skip = false;
3976
3977 // For each submit in the batch...
3978 for (const auto &cb : command_buffers_) {
John Zulauf8a7b03d2022-09-20 11:41:19 -06003979 if (cb.cb->GetTagLimit() == 0) {
3980 batch_.cb_index++;
3981 continue; // Skip empty CB's but also skip the unused index for correct reporting
3982 }
John Zulaufa8700a52022-08-18 16:22:08 -06003983 skip |= cb.cb->ValidateFirstUse(*this, cmd_state.submit_func_name.c_str(), cb.index);
3984
3985 // The barriers have already been applied in ValidatFirstUse
3986 ResourceUsageRange tag_range = ImportRecordedAccessLog(*cb.cb);
3987 ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
3988 }
3989 return skip;
3990}
3991
John Zulaufcb7e1672022-05-04 13:46:08 -06003992bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3993 const std::shared_ptr<QueueBatchContext> &batch,
3994 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003995 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003996 const SyncExecScope exec_scope =
3997 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3998 const VkSemaphore sem = sem_state->semaphore();
3999 auto signal_it = signaled_.find(sem);
4000 std::shared_ptr<Signal> insert_signal;
4001 if (signal_it == signaled_.end()) {
4002 if (prev_) {
4003 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
4004 if (prev_sig) {
4005 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
4006 insert_signal = std::make_shared<Signal>(*prev_sig);
4007 }
4008 }
4009 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
4010 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06004011 }
John Zulaufcb7e1672022-05-04 13:46:08 -06004012
4013 bool success = false;
4014 if (!signal_it->second) {
4015 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
4016 success = true;
4017 }
4018
4019 return success;
4020}
4021
John Zulaufecf4ac52022-06-06 10:08:42 -06004022std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
4023 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06004024 const auto found_it = signaled_.find(sem);
4025 if (found_it != signaled_.end()) {
4026 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
4027 // a bit.
4028 unsignaled = std::move(found_it->second);
4029 if (!prev_) {
4030 // No parent, not need to keep the entry
4031 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
4032 signaled_.erase(found_it);
4033 }
4034 } else if (prev_) {
4035 // We can't unsignal prev_ because it's const * by design.
4036 // We put in an empty placeholder
4037 signaled_.emplace(sem, std::shared_ptr<Signal>());
4038 unsignaled = GetPrev(sem);
4039 }
4040 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
4041 // but CoreChecks should have reported it
4042
4043 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06004044 return unsignaled;
4045}
4046
John Zulaufcb7e1672022-05-04 13:46:08 -06004047void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
4048 // Overwrite the s tate with the last state from this
4049 if (from) {
4050 assert(sem == from->sem_state->semaphore());
4051 signaled_[sem] = std::move(from);
4052 } else {
4053 signaled_.erase(sem);
4054 }
4055}
4056
4057void SignaledSemaphores::Reset() {
4058 signaled_.clear();
4059 prev_ = nullptr;
4060}
4061
John Zulaufea943c52022-02-22 11:05:17 -07004062std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
4063 // If we don't have one, make it.
4064 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
4065 assert(cb_state.get());
4066 auto queue_flags = cb_state->GetQueueFlags();
4067 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
4068}
4069
John Zulaufcb7e1672022-05-04 13:46:08 -06004070std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07004071 return GetMappedInsert(cb_access_state, command_buffer,
4072 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
4073}
4074
4075std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
4076 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
4077}
4078
4079const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
4080 return GetMappedPlainFromShared(cb_access_state, command_buffer);
4081}
4082
4083CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
4084 return GetAccessContextShared(command_buffer).get();
4085}
4086
4087CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
4088 return GetMappedPlainFromShared(cb_access_state, command_buffer);
4089}
4090
John Zulaufd1f85d42020-04-15 12:23:15 -06004091void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004092 auto *access_context = GetAccessContextNoInsert(command_buffer);
4093 if (access_context) {
4094 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06004095 }
4096}
4097
John Zulaufd1f85d42020-04-15 12:23:15 -06004098void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
4099 auto access_found = cb_access_state.find(command_buffer);
4100 if (access_found != cb_access_state.end()) {
4101 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06004102 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06004103 cb_access_state.erase(access_found);
4104 }
4105}
4106
John Zulauf9cb530d2019-09-30 14:14:10 -06004107bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4108 uint32_t regionCount, const VkBufferCopy *pRegions) const {
4109 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004110 const auto *cb_context = GetAccessContext(commandBuffer);
4111 assert(cb_context);
4112 if (!cb_context) return skip;
4113 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06004114
John Zulauf3d84f1b2020-03-09 13:33:25 -06004115 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004116 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4117 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004118
4119 for (uint32_t region = 0; region < regionCount; region++) {
4120 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004121 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004122 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004123 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004124 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004125 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004126 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004127 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004128 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06004129 }
John Zulauf9cb530d2019-09-30 14:14:10 -06004130 }
John Zulauf16adfc92020-04-08 10:28:33 -06004131 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004132 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004133 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004134 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004135 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004136 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004137 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004138 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06004139 }
4140 }
4141 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06004142 }
4143 return skip;
4144}
4145
4146void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4147 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004148 auto *cb_context = GetAccessContext(commandBuffer);
4149 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004150 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004151 auto *context = cb_context->GetCurrentAccessContext();
4152
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004153 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4154 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06004155
4156 for (uint32_t region = 0; region < regionCount; region++) {
4157 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004158 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004159 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004160 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004161 }
John Zulauf16adfc92020-04-08 10:28:33 -06004162 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004163 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004164 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004165 }
4166 }
4167}
4168
John Zulauf4a6105a2020-11-17 15:11:05 -07004169void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4170 // Clear out events from the command buffer contexts
4171 for (auto &cb_context : cb_access_state) {
4172 cb_context.second->RecordDestroyEvent(event);
4173 }
4174}
4175
Tony-LunarGef035472021-11-02 10:23:33 -06004176bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4177 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004178 bool skip = false;
4179 const auto *cb_context = GetAccessContext(commandBuffer);
4180 assert(cb_context);
4181 if (!cb_context) return skip;
4182 const auto *context = cb_context->GetCurrentAccessContext();
4183
4184 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004185 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4186 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004187
4188 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4189 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4190 if (src_buffer) {
4191 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004192 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004193 if (hazard.hazard) {
4194 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004195 skip |=
4196 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4197 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4198 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4199 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004200 }
4201 }
4202 if (dst_buffer && !skip) {
4203 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004204 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004205 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004206 skip |=
4207 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4208 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4209 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4210 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004211 }
4212 }
4213 if (skip) break;
4214 }
4215 return skip;
4216}
4217
Tony-LunarGef035472021-11-02 10:23:33 -06004218bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4219 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4220 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4221}
4222
4223bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4224 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4225}
4226
4227void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004228 auto *cb_context = GetAccessContext(commandBuffer);
4229 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004230 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004231 auto *context = cb_context->GetCurrentAccessContext();
4232
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004233 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4234 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004235
4236 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4237 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4238 if (src_buffer) {
4239 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004240 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004241 }
4242 if (dst_buffer) {
4243 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004244 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004245 }
4246 }
4247}
4248
Tony-LunarGef035472021-11-02 10:23:33 -06004249void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4250 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4251}
4252
4253void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4254 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4255}
4256
John Zulauf5c5e88d2019-12-26 11:22:02 -07004257bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4258 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4259 const VkImageCopy *pRegions) const {
4260 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004261 const auto *cb_access_context = GetAccessContext(commandBuffer);
4262 assert(cb_access_context);
4263 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004264
John Zulauf3d84f1b2020-03-09 13:33:25 -06004265 const auto *context = cb_access_context->GetCurrentAccessContext();
4266 assert(context);
4267 if (!context) return skip;
4268
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004269 auto src_image = Get<IMAGE_STATE>(srcImage);
4270 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004271 for (uint32_t region = 0; region < regionCount; region++) {
4272 const auto &copy_region = pRegions[region];
4273 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004274 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004275 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004276 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004277 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004278 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004279 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004280 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004281 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004282 }
4283
4284 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004285 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004286 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004287 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004288 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004289 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004290 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004291 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004292 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004293 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004294 }
4295 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004296
John Zulauf5c5e88d2019-12-26 11:22:02 -07004297 return skip;
4298}
4299
4300void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4301 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4302 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004303 auto *cb_access_context = GetAccessContext(commandBuffer);
4304 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004305 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004306 auto *context = cb_access_context->GetCurrentAccessContext();
4307 assert(context);
4308
Jeremy Gebben9f537102021-10-05 16:37:12 -06004309 auto src_image = Get<IMAGE_STATE>(srcImage);
4310 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004311
4312 for (uint32_t region = 0; region < regionCount; region++) {
4313 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004314 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004315 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004316 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004317 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004318 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004319 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004320 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004321 }
4322 }
4323}
4324
Tony-LunarGb61514a2021-11-02 12:36:51 -06004325bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4326 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004327 bool skip = false;
4328 const auto *cb_access_context = GetAccessContext(commandBuffer);
4329 assert(cb_access_context);
4330 if (!cb_access_context) return skip;
4331
4332 const auto *context = cb_access_context->GetCurrentAccessContext();
4333 assert(context);
4334 if (!context) return skip;
4335
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004336 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4337 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004338
Jeff Leger178b1e52020-10-05 12:22:23 -04004339 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4340 const auto &copy_region = pCopyImageInfo->pRegions[region];
4341 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004342 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004343 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004344 if (hazard.hazard) {
4345 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004346 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004347 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004348 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004349 }
4350 }
4351
4352 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004353 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004354 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004355 if (hazard.hazard) {
4356 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004357 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004358 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004359 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004360 }
4361 if (skip) break;
4362 }
4363 }
4364
4365 return skip;
4366}
4367
Tony-LunarGb61514a2021-11-02 12:36:51 -06004368bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4369 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4370 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4371}
4372
4373bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4374 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4375}
4376
4377void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004378 auto *cb_access_context = GetAccessContext(commandBuffer);
4379 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004380 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004381 auto *context = cb_access_context->GetCurrentAccessContext();
4382 assert(context);
4383
Jeremy Gebben9f537102021-10-05 16:37:12 -06004384 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4385 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004386
4387 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4388 const auto &copy_region = pCopyImageInfo->pRegions[region];
4389 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004390 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004391 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004392 }
4393 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004394 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004395 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004396 }
4397 }
4398}
4399
Tony-LunarGb61514a2021-11-02 12:36:51 -06004400void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4401 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4402}
4403
4404void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4405 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4406}
4407
John Zulauf9cb530d2019-09-30 14:14:10 -06004408bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4409 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4410 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4411 uint32_t bufferMemoryBarrierCount,
4412 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4413 uint32_t imageMemoryBarrierCount,
4414 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4415 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004416 const auto *cb_access_context = GetAccessContext(commandBuffer);
4417 assert(cb_access_context);
4418 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004419
John Zulauf36ef9282021-02-02 11:47:24 -07004420 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4421 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4422 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4423 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004424 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004425 return skip;
4426}
4427
4428void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4429 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4430 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4431 uint32_t bufferMemoryBarrierCount,
4432 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4433 uint32_t imageMemoryBarrierCount,
4434 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004435 auto *cb_access_context = GetAccessContext(commandBuffer);
4436 assert(cb_access_context);
4437 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004438
John Zulauf1bf30522021-09-03 15:39:06 -06004439 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4440 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4441 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4442 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004443}
4444
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004445bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4446 const VkDependencyInfoKHR *pDependencyInfo) const {
4447 bool skip = false;
4448 const auto *cb_access_context = GetAccessContext(commandBuffer);
4449 assert(cb_access_context);
4450 if (!cb_access_context) return skip;
4451
4452 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4453 skip = pipeline_barrier.Validate(*cb_access_context);
4454 return skip;
4455}
4456
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004457bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4458 const VkDependencyInfo *pDependencyInfo) const {
4459 bool skip = false;
4460 const auto *cb_access_context = GetAccessContext(commandBuffer);
4461 assert(cb_access_context);
4462 if (!cb_access_context) return skip;
4463
4464 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4465 skip = pipeline_barrier.Validate(*cb_access_context);
4466 return skip;
4467}
4468
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004469void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4470 auto *cb_access_context = GetAccessContext(commandBuffer);
4471 assert(cb_access_context);
4472 if (!cb_access_context) return;
4473
John Zulauf1bf30522021-09-03 15:39:06 -06004474 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4475 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004476}
4477
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004478void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4479 auto *cb_access_context = GetAccessContext(commandBuffer);
4480 assert(cb_access_context);
4481 if (!cb_access_context) return;
4482
4483 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4484 *pDependencyInfo);
4485}
4486
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004487void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004488 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004489 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004490
John Zulauf5f13a792020-03-10 07:31:21 -06004491 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4492 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004493 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004494 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4495 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004496
John Zulauf1d5f9c12022-05-13 14:51:08 -06004497 QueueId queue_id = QueueSyncState::kQueueIdBase;
4498 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004499 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004500 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004501 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4502 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004503}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004504
John Zulauf355e49b2020-04-24 15:11:15 -06004505bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004506 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004507 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004508 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004509 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004510 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004511 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004512 }
John Zulauf355e49b2020-04-24 15:11:15 -06004513 return skip;
4514}
4515
4516bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4517 VkSubpassContents contents) const {
4518 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004519 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004520 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004521 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004522 return skip;
4523}
4524
4525bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004526 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004527 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004528 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004529 return skip;
4530}
4531
4532bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4533 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004534 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004535 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004536 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004537 return skip;
4538}
4539
John Zulauf3d84f1b2020-03-09 13:33:25 -06004540void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4541 VkResult result) {
4542 // The state tracker sets up the command buffer state
4543 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4544
4545 // Create/initialize the structure that trackers accesses at the command buffer scope.
4546 auto cb_access_context = GetAccessContext(commandBuffer);
4547 assert(cb_access_context);
4548 cb_access_context->Reset();
4549}
4550
4551void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004552 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004553 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004554 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004555 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004556 }
4557}
4558
4559void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4560 VkSubpassContents contents) {
4561 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004562 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004563 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004564 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004565}
4566
4567void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4568 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4569 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004570 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004571}
4572
4573void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4574 const VkRenderPassBeginInfo *pRenderPassBegin,
4575 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4576 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004577 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004578}
4579
Mike Schuchardt2df08912020-12-15 16:28:09 -08004580bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004581 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004582 bool skip = false;
4583
4584 auto cb_context = GetAccessContext(commandBuffer);
4585 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004586 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004587 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004588 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004589}
4590
4591bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4592 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004593 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004594 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004595 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004596 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4597 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004598 return skip;
4599}
4600
Mike Schuchardt2df08912020-12-15 16:28:09 -08004601bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4602 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004603 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004604 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004605 return skip;
4606}
4607
4608bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4609 const VkSubpassEndInfo *pSubpassEndInfo) const {
4610 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004611 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004612 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004613}
4614
4615void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004616 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004617 auto cb_context = GetAccessContext(commandBuffer);
4618 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004619 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004620
sjfricke0bea06e2022-06-05 09:22:26 +09004621 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004622}
4623
4624void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4625 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004626 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004627 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004628 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004629}
4630
4631void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4632 const VkSubpassEndInfo *pSubpassEndInfo) {
4633 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004634 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004635}
4636
4637void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4638 const VkSubpassEndInfo *pSubpassEndInfo) {
4639 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004640 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004641}
4642
sfricke-samsung85584a72021-09-30 21:43:38 -07004643bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004644 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004645 bool skip = false;
4646
4647 auto cb_context = GetAccessContext(commandBuffer);
4648 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004649 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004650
sjfricke0bea06e2022-06-05 09:22:26 +09004651 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004652 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004653 return skip;
4654}
4655
4656bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4657 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004658 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004659 return skip;
4660}
4661
Mike Schuchardt2df08912020-12-15 16:28:09 -08004662bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004663 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004664 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004665 return skip;
4666}
4667
4668bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004669 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004670 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004671 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004672 return skip;
4673}
4674
sjfricke0bea06e2022-06-05 09:22:26 +09004675void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4676 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004677 // Resolve the all subpass contexts to the command buffer contexts
4678 auto cb_context = GetAccessContext(commandBuffer);
4679 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004680 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004681
sjfricke0bea06e2022-06-05 09:22:26 +09004682 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004683}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004684
John Zulauf33fc1d52020-07-17 11:01:10 -06004685// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4686// updates to a resource which do not conflict at the byte level.
4687// TODO: Revisit this rule to see if it needs to be tighter or looser
4688// TODO: Add programatic control over suppression heuristics
4689bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4690 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4691}
4692
John Zulauf3d84f1b2020-03-09 13:33:25 -06004693void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004694 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004695 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004696}
4697
4698void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004699 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004700 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004701}
4702
4703void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004704 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004705 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004706}
locke-lunarga19c71d2020-03-02 18:17:04 -07004707
sfricke-samsung71f04e32022-03-16 01:21:21 -05004708template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004709bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004710 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4711 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004712 bool skip = false;
4713 const auto *cb_access_context = GetAccessContext(commandBuffer);
4714 assert(cb_access_context);
4715 if (!cb_access_context) return skip;
4716
4717 const auto *context = cb_access_context->GetCurrentAccessContext();
4718 assert(context);
4719 if (!context) return skip;
4720
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004721 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4722 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004723
4724 for (uint32_t region = 0; region < regionCount; region++) {
4725 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004726 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004727 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004728 if (src_buffer) {
4729 ResourceAccessRange src_range =
4730 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004731 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004732 if (hazard.hazard) {
4733 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004734 skip |=
4735 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4736 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4737 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4738 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004739 }
4740 }
4741
Jeremy Gebben40a22942020-12-22 14:22:06 -07004742 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004743 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004744 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004745 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004746 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004747 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004748 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004749 }
4750 if (skip) break;
4751 }
4752 if (skip) break;
4753 }
4754 return skip;
4755}
4756
Jeff Leger178b1e52020-10-05 12:22:23 -04004757bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4758 VkImageLayout dstImageLayout, uint32_t regionCount,
4759 const VkBufferImageCopy *pRegions) const {
4760 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004761 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004762}
4763
4764bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4765 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4766 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4767 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004768 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4769}
4770
4771bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4772 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4773 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4774 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4775 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004776}
4777
sfricke-samsung71f04e32022-03-16 01:21:21 -05004778template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004779void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004780 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4781 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004782 auto *cb_access_context = GetAccessContext(commandBuffer);
4783 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004784
Jeff Leger178b1e52020-10-05 12:22:23 -04004785 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004786 auto *context = cb_access_context->GetCurrentAccessContext();
4787 assert(context);
4788
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004789 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4790 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004791
4792 for (uint32_t region = 0; region < regionCount; region++) {
4793 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004794 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004795 if (src_buffer) {
4796 ResourceAccessRange src_range =
4797 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004798 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004799 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004800 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004801 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004802 }
4803 }
4804}
4805
Jeff Leger178b1e52020-10-05 12:22:23 -04004806void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4807 VkImageLayout dstImageLayout, uint32_t regionCount,
4808 const VkBufferImageCopy *pRegions) {
4809 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004810 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004811}
4812
4813void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4814 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4815 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4816 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4817 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004818 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4819}
4820
4821void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4822 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4823 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4824 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4825 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4826 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004827}
4828
sfricke-samsung71f04e32022-03-16 01:21:21 -05004829template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004830bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004831 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4832 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004833 bool skip = false;
4834 const auto *cb_access_context = GetAccessContext(commandBuffer);
4835 assert(cb_access_context);
4836 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004837
locke-lunarga19c71d2020-03-02 18:17:04 -07004838 const auto *context = cb_access_context->GetCurrentAccessContext();
4839 assert(context);
4840 if (!context) return skip;
4841
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004842 auto src_image = Get<IMAGE_STATE>(srcImage);
4843 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004844 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004845 for (uint32_t region = 0; region < regionCount; region++) {
4846 const auto &copy_region = pRegions[region];
4847 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004848 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004849 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004850 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004851 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004852 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004853 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004854 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004855 }
John Zulauf477700e2021-01-06 11:41:49 -07004856 if (dst_mem) {
4857 ResourceAccessRange dst_range =
4858 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004859 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004860 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004861 skip |=
4862 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4863 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4864 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4865 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004866 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004867 }
4868 }
4869 if (skip) break;
4870 }
4871 return skip;
4872}
4873
Jeff Leger178b1e52020-10-05 12:22:23 -04004874bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4875 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4876 const VkBufferImageCopy *pRegions) const {
4877 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004878 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004879}
4880
4881bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4882 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4883 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4884 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004885 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4886}
4887
4888bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4889 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4890 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4891 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4892 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004893}
4894
sfricke-samsung71f04e32022-03-16 01:21:21 -05004895template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004896void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004897 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004898 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004899 auto *cb_access_context = GetAccessContext(commandBuffer);
4900 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004901
Jeff Leger178b1e52020-10-05 12:22:23 -04004902 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004903 auto *context = cb_access_context->GetCurrentAccessContext();
4904 assert(context);
4905
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004906 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004907 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004908 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004909 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004910
4911 for (uint32_t region = 0; region < regionCount; region++) {
4912 const auto &copy_region = pRegions[region];
4913 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004914 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004915 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004916 if (dst_buffer) {
4917 ResourceAccessRange dst_range =
4918 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004919 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004920 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004921 }
4922 }
4923}
4924
Jeff Leger178b1e52020-10-05 12:22:23 -04004925void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4926 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4927 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004928 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004929}
4930
4931void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4932 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4933 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4934 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4935 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004936 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4937}
4938
4939void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4940 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4941 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4942 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4943 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4944 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004945}
4946
4947template <typename RegionType>
4948bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4949 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004950 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004951 bool skip = false;
4952 const auto *cb_access_context = GetAccessContext(commandBuffer);
4953 assert(cb_access_context);
4954 if (!cb_access_context) return skip;
4955
4956 const auto *context = cb_access_context->GetCurrentAccessContext();
4957 assert(context);
4958 if (!context) return skip;
4959
sjfricke0bea06e2022-06-05 09:22:26 +09004960 const char *caller_name = CommandTypeString(cmd_type);
4961
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004962 auto src_image = Get<IMAGE_STATE>(srcImage);
4963 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004964
4965 for (uint32_t region = 0; region < regionCount; region++) {
4966 const auto &blit_region = pRegions[region];
4967 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004968 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4969 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4970 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4971 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4972 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4973 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004974 auto hazard =
4975 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004976 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004977 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004978 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004979 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004980 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004981 }
4982 }
4983
4984 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004985 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4986 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4987 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4988 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4989 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4990 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004991 auto hazard =
4992 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004993 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004994 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004995 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004996 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004997 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004998 }
4999 if (skip) break;
5000 }
5001 }
5002
5003 return skip;
5004}
5005
Jeff Leger178b1e52020-10-05 12:22:23 -04005006bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5007 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5008 const VkImageBlit *pRegions, VkFilter filter) const {
5009 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09005010 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04005011}
5012
5013bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
5014 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
5015 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
5016 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09005017 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04005018}
5019
Tony-LunarG542ae912021-11-04 16:06:44 -06005020bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
5021 const VkBlitImageInfo2 *pBlitImageInfo) const {
5022 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09005023 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
5024 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06005025}
5026
Jeff Leger178b1e52020-10-05 12:22:23 -04005027template <typename RegionType>
5028void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5029 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5030 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07005031 auto *cb_access_context = GetAccessContext(commandBuffer);
5032 assert(cb_access_context);
5033 auto *context = cb_access_context->GetCurrentAccessContext();
5034 assert(context);
5035
Jeremy Gebben9f537102021-10-05 16:37:12 -06005036 auto src_image = Get<IMAGE_STATE>(srcImage);
5037 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07005038
5039 for (uint32_t region = 0; region < regionCount; region++) {
5040 const auto &blit_region = pRegions[region];
5041 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06005042 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
5043 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
5044 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
5045 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
5046 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
5047 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07005048 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005049 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07005050 }
5051 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06005052 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
5053 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
5054 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
5055 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
5056 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
5057 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07005058 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005059 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07005060 }
5061 }
5062}
locke-lunarg36ba2592020-04-03 09:42:04 -06005063
Jeff Leger178b1e52020-10-05 12:22:23 -04005064void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5065 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5066 const VkImageBlit *pRegions, VkFilter filter) {
5067 auto *cb_access_context = GetAccessContext(commandBuffer);
5068 assert(cb_access_context);
5069 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
5070 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5071 pRegions, filter);
5072 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
5073}
5074
5075void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
5076 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
5077 auto *cb_access_context = GetAccessContext(commandBuffer);
5078 assert(cb_access_context);
5079 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
5080 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
5081 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
5082 pBlitImageInfo->filter, tag);
5083}
5084
Tony-LunarG542ae912021-11-04 16:06:44 -06005085void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
5086 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
5087 auto *cb_access_context = GetAccessContext(commandBuffer);
5088 assert(cb_access_context);
5089 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
5090 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
5091 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
5092 pBlitImageInfo->filter, tag);
5093}
5094
John Zulauffaea0ee2021-01-14 14:01:32 -07005095bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5096 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
5097 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005098 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005099 bool skip = false;
5100 if (drawCount == 0) return skip;
5101
sjfricke0bea06e2022-06-05 09:22:26 +09005102 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005103 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06005104 VkDeviceSize size = struct_size;
5105 if (drawCount == 1 || stride == size) {
5106 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06005107 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06005108 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5109 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005110 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005111 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06005112 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005113 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005114 }
5115 } else {
5116 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005117 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06005118 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5119 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005120 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005121 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
5122 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5123 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005124 break;
5125 }
5126 }
5127 }
5128 return skip;
5129}
5130
John Zulauf14940722021-04-12 15:19:02 -06005131void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06005132 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
5133 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005134 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06005135 VkDeviceSize size = struct_size;
5136 if (drawCount == 1 || stride == size) {
5137 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06005138 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005139 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005140 } else {
5141 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005142 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005143 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
5144 tag);
locke-lunargff255f92020-05-13 18:53:52 -06005145 }
5146 }
5147}
5148
John Zulauffaea0ee2021-01-14 14:01:32 -07005149bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5150 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005151 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005152 bool skip = false;
5153
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005154 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005155 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005156 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5157 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005158 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005159 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
5160 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5161 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005162 }
5163 return skip;
5164}
5165
John Zulauf14940722021-04-12 15:19:02 -06005166void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005167 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005168 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005169 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005170}
5171
locke-lunarg36ba2592020-04-03 09:42:04 -06005172bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005173 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005174 const auto *cb_access_context = GetAccessContext(commandBuffer);
5175 assert(cb_access_context);
5176 if (!cb_access_context) return skip;
5177
sjfricke0bea06e2022-06-05 09:22:26 +09005178 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005179 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005180}
5181
5182void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005183 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005184 auto *cb_access_context = GetAccessContext(commandBuffer);
5185 assert(cb_access_context);
5186 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005187
locke-lunarg61870c22020-06-09 14:51:50 -06005188 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005189}
locke-lunarge1a67022020-04-29 00:15:36 -06005190
5191bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005192 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005193 const auto *cb_access_context = GetAccessContext(commandBuffer);
5194 assert(cb_access_context);
5195 if (!cb_access_context) return skip;
5196
5197 const auto *context = cb_access_context->GetCurrentAccessContext();
5198 assert(context);
5199 if (!context) return skip;
5200
sjfricke0bea06e2022-06-05 09:22:26 +09005201 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005202 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005203 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005204 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005205}
5206
5207void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005208 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005209 auto *cb_access_context = GetAccessContext(commandBuffer);
5210 assert(cb_access_context);
5211 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5212 auto *context = cb_access_context->GetCurrentAccessContext();
5213 assert(context);
5214
locke-lunarg61870c22020-06-09 14:51:50 -06005215 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5216 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005217}
5218
5219bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5220 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005221 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005222 const auto *cb_access_context = GetAccessContext(commandBuffer);
5223 assert(cb_access_context);
5224 if (!cb_access_context) return skip;
5225
sjfricke0bea06e2022-06-05 09:22:26 +09005226 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5227 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5228 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005229 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005230}
5231
5232void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5233 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005234 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005235 auto *cb_access_context = GetAccessContext(commandBuffer);
5236 assert(cb_access_context);
5237 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005238
locke-lunarg61870c22020-06-09 14:51:50 -06005239 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5240 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5241 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005242}
5243
5244bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5245 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005246 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005247 const auto *cb_access_context = GetAccessContext(commandBuffer);
5248 assert(cb_access_context);
5249 if (!cb_access_context) return skip;
5250
sjfricke0bea06e2022-06-05 09:22:26 +09005251 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5252 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5253 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005254 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005255}
5256
5257void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5258 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005259 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005260 auto *cb_access_context = GetAccessContext(commandBuffer);
5261 assert(cb_access_context);
5262 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005263
locke-lunarg61870c22020-06-09 14:51:50 -06005264 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5265 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5266 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005267}
5268
5269bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5270 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005271 bool skip = false;
5272 if (drawCount == 0) return skip;
5273
locke-lunargff255f92020-05-13 18:53:52 -06005274 const auto *cb_access_context = GetAccessContext(commandBuffer);
5275 assert(cb_access_context);
5276 if (!cb_access_context) return skip;
5277
5278 const auto *context = cb_access_context->GetCurrentAccessContext();
5279 assert(context);
5280 if (!context) return skip;
5281
sjfricke0bea06e2022-06-05 09:22:26 +09005282 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5283 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005284 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005285 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005286
5287 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5288 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5289 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005290 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005291 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005292}
5293
5294void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5295 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005296 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005297 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005298 auto *cb_access_context = GetAccessContext(commandBuffer);
5299 assert(cb_access_context);
5300 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5301 auto *context = cb_access_context->GetCurrentAccessContext();
5302 assert(context);
5303
locke-lunarg61870c22020-06-09 14:51:50 -06005304 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5305 cb_access_context->RecordDrawSubpassAttachment(tag);
5306 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005307
5308 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5309 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5310 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005311 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005312}
5313
5314bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5315 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005316 bool skip = false;
5317 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005318 const auto *cb_access_context = GetAccessContext(commandBuffer);
5319 assert(cb_access_context);
5320 if (!cb_access_context) return skip;
5321
5322 const auto *context = cb_access_context->GetCurrentAccessContext();
5323 assert(context);
5324 if (!context) return skip;
5325
sjfricke0bea06e2022-06-05 09:22:26 +09005326 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5327 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005328 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005329 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005330
5331 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5332 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5333 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005334 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005335 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005336}
5337
5338void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5339 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005340 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005341 auto *cb_access_context = GetAccessContext(commandBuffer);
5342 assert(cb_access_context);
5343 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5344 auto *context = cb_access_context->GetCurrentAccessContext();
5345 assert(context);
5346
locke-lunarg61870c22020-06-09 14:51:50 -06005347 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5348 cb_access_context->RecordDrawSubpassAttachment(tag);
5349 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005350
5351 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5352 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5353 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005354 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005355}
5356
5357bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5358 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005359 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005360 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005361 const auto *cb_access_context = GetAccessContext(commandBuffer);
5362 assert(cb_access_context);
5363 if (!cb_access_context) return skip;
5364
5365 const auto *context = cb_access_context->GetCurrentAccessContext();
5366 assert(context);
5367 if (!context) return skip;
5368
sjfricke0bea06e2022-06-05 09:22:26 +09005369 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5370 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005371 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005372 maxDrawCount, stride, cmd_type);
5373 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005374
5375 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5376 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5377 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005378 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005379 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005380}
5381
5382bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5383 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5384 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005385 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005386 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005387}
5388
sfricke-samsung85584a72021-09-30 21:43:38 -07005389void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5390 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5391 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005392 auto *cb_access_context = GetAccessContext(commandBuffer);
5393 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005394 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005395 auto *context = cb_access_context->GetCurrentAccessContext();
5396 assert(context);
5397
locke-lunarg61870c22020-06-09 14:51:50 -06005398 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5399 cb_access_context->RecordDrawSubpassAttachment(tag);
5400 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5401 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005402
5403 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5404 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5405 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005406 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005407}
5408
sfricke-samsung85584a72021-09-30 21:43:38 -07005409void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5410 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5411 uint32_t stride) {
5412 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5413 stride);
5414 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5415 CMD_DRAWINDIRECTCOUNT);
5416}
locke-lunarge1a67022020-04-29 00:15:36 -06005417bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5418 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5419 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005420 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005421 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005422}
5423
5424void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5425 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5426 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005427 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5428 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005429 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5430 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005431}
5432
5433bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5434 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5435 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005436 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005437 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005438}
5439
5440void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5441 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5442 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005443 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5444 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005445 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5446 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005447}
5448
5449bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5450 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005451 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005452 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005453 const auto *cb_access_context = GetAccessContext(commandBuffer);
5454 assert(cb_access_context);
5455 if (!cb_access_context) return skip;
5456
5457 const auto *context = cb_access_context->GetCurrentAccessContext();
5458 assert(context);
5459 if (!context) return skip;
5460
sjfricke0bea06e2022-06-05 09:22:26 +09005461 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5462 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005463 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005464 offset, maxDrawCount, stride, cmd_type);
5465 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005466
5467 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5468 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5469 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005470 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005471 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005472}
5473
5474bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5475 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5476 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005477 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005478 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005479}
5480
sfricke-samsung85584a72021-09-30 21:43:38 -07005481void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5482 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5483 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005484 auto *cb_access_context = GetAccessContext(commandBuffer);
5485 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005486 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005487 auto *context = cb_access_context->GetCurrentAccessContext();
5488 assert(context);
5489
locke-lunarg61870c22020-06-09 14:51:50 -06005490 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5491 cb_access_context->RecordDrawSubpassAttachment(tag);
5492 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5493 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005494
5495 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5496 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005497 // We will update the index and vertex buffer in SubmitQueue in the future.
5498 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005499}
5500
sfricke-samsung85584a72021-09-30 21:43:38 -07005501void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5502 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5503 uint32_t maxDrawCount, uint32_t stride) {
5504 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5505 maxDrawCount, stride);
5506 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5507 CMD_DRAWINDEXEDINDIRECTCOUNT);
5508}
5509
locke-lunarge1a67022020-04-29 00:15:36 -06005510bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5511 VkDeviceSize offset, VkBuffer countBuffer,
5512 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5513 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005514 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005515 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005516}
5517
5518void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5519 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5520 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005521 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5522 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005523 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5524 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005525}
5526
5527bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5528 VkDeviceSize offset, VkBuffer countBuffer,
5529 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5530 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005531 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005532 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005533}
5534
5535void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5536 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5537 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005538 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5539 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005540 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5541 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005542}
5543
5544bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5545 const VkClearColorValue *pColor, uint32_t rangeCount,
5546 const VkImageSubresourceRange *pRanges) const {
5547 bool skip = false;
5548 const auto *cb_access_context = GetAccessContext(commandBuffer);
5549 assert(cb_access_context);
5550 if (!cb_access_context) return skip;
5551
5552 const auto *context = cb_access_context->GetCurrentAccessContext();
5553 assert(context);
5554 if (!context) return skip;
5555
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005556 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005557
5558 for (uint32_t index = 0; index < rangeCount; index++) {
5559 const auto &range = pRanges[index];
5560 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005561 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005562 if (hazard.hazard) {
5563 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005564 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005565 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005566 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005567 }
5568 }
5569 }
5570 return skip;
5571}
5572
5573void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5574 const VkClearColorValue *pColor, uint32_t rangeCount,
5575 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005576 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005577 auto *cb_access_context = GetAccessContext(commandBuffer);
5578 assert(cb_access_context);
5579 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5580 auto *context = cb_access_context->GetCurrentAccessContext();
5581 assert(context);
5582
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005583 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005584
5585 for (uint32_t index = 0; index < rangeCount; index++) {
5586 const auto &range = pRanges[index];
5587 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005588 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005589 }
5590 }
5591}
5592
5593bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5594 VkImageLayout imageLayout,
5595 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5596 const VkImageSubresourceRange *pRanges) const {
5597 bool skip = false;
5598 const auto *cb_access_context = GetAccessContext(commandBuffer);
5599 assert(cb_access_context);
5600 if (!cb_access_context) return skip;
5601
5602 const auto *context = cb_access_context->GetCurrentAccessContext();
5603 assert(context);
5604 if (!context) return skip;
5605
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005606 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005607
5608 for (uint32_t index = 0; index < rangeCount; index++) {
5609 const auto &range = pRanges[index];
5610 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005611 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005612 if (hazard.hazard) {
5613 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005614 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005615 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005616 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005617 }
5618 }
5619 }
5620 return skip;
5621}
5622
5623void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5624 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5625 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005626 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005627 auto *cb_access_context = GetAccessContext(commandBuffer);
5628 assert(cb_access_context);
5629 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5630 auto *context = cb_access_context->GetCurrentAccessContext();
5631 assert(context);
5632
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005633 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005634
5635 for (uint32_t index = 0; index < rangeCount; index++) {
5636 const auto &range = pRanges[index];
5637 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005638 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005639 }
5640 }
5641}
5642
5643bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5644 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5645 VkDeviceSize dstOffset, VkDeviceSize stride,
5646 VkQueryResultFlags flags) const {
5647 bool skip = false;
5648 const auto *cb_access_context = GetAccessContext(commandBuffer);
5649 assert(cb_access_context);
5650 if (!cb_access_context) return skip;
5651
5652 const auto *context = cb_access_context->GetCurrentAccessContext();
5653 assert(context);
5654 if (!context) return skip;
5655
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005656 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005657
5658 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005659 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005660 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005661 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005662 skip |=
5663 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5664 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005665 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005666 }
5667 }
locke-lunargff255f92020-05-13 18:53:52 -06005668
5669 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005670 return skip;
5671}
5672
5673void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5674 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5675 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005676 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5677 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005678 auto *cb_access_context = GetAccessContext(commandBuffer);
5679 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005680 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005681 auto *context = cb_access_context->GetCurrentAccessContext();
5682 assert(context);
5683
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005684 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005685
5686 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005687 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005688 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005689 }
locke-lunargff255f92020-05-13 18:53:52 -06005690
5691 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005692}
5693
5694bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5695 VkDeviceSize size, uint32_t data) const {
5696 bool skip = false;
5697 const auto *cb_access_context = GetAccessContext(commandBuffer);
5698 assert(cb_access_context);
5699 if (!cb_access_context) return skip;
5700
5701 const auto *context = cb_access_context->GetCurrentAccessContext();
5702 assert(context);
5703 if (!context) return skip;
5704
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005705 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005706
5707 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005708 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005709 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005710 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005711 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005712 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005713 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005714 }
5715 }
5716 return skip;
5717}
5718
5719void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5720 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005721 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005722 auto *cb_access_context = GetAccessContext(commandBuffer);
5723 assert(cb_access_context);
5724 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5725 auto *context = cb_access_context->GetCurrentAccessContext();
5726 assert(context);
5727
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005728 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005729
5730 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005731 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005732 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005733 }
5734}
5735
5736bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5737 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5738 const VkImageResolve *pRegions) const {
5739 bool skip = false;
5740 const auto *cb_access_context = GetAccessContext(commandBuffer);
5741 assert(cb_access_context);
5742 if (!cb_access_context) return skip;
5743
5744 const auto *context = cb_access_context->GetCurrentAccessContext();
5745 assert(context);
5746 if (!context) return skip;
5747
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005748 auto src_image = Get<IMAGE_STATE>(srcImage);
5749 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005750
5751 for (uint32_t region = 0; region < regionCount; region++) {
5752 const auto &resolve_region = pRegions[region];
5753 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005754 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005755 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005756 if (hazard.hazard) {
5757 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005758 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005759 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005760 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005761 }
5762 }
5763
5764 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005765 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005766 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005767 if (hazard.hazard) {
5768 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005769 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005770 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005771 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005772 }
5773 if (skip) break;
5774 }
5775 }
5776
5777 return skip;
5778}
5779
5780void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5781 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5782 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005783 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5784 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005785 auto *cb_access_context = GetAccessContext(commandBuffer);
5786 assert(cb_access_context);
5787 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5788 auto *context = cb_access_context->GetCurrentAccessContext();
5789 assert(context);
5790
Jeremy Gebben9f537102021-10-05 16:37:12 -06005791 auto src_image = Get<IMAGE_STATE>(srcImage);
5792 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005793
5794 for (uint32_t region = 0; region < regionCount; region++) {
5795 const auto &resolve_region = pRegions[region];
5796 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005797 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005798 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005799 }
5800 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005801 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005802 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005803 }
5804 }
5805}
5806
Tony-LunarG562fc102021-11-12 13:58:35 -07005807bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5808 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005809 bool skip = false;
5810 const auto *cb_access_context = GetAccessContext(commandBuffer);
5811 assert(cb_access_context);
5812 if (!cb_access_context) return skip;
5813
5814 const auto *context = cb_access_context->GetCurrentAccessContext();
5815 assert(context);
5816 if (!context) return skip;
5817
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005818 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5819 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005820
5821 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5822 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5823 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005824 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005825 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005826 if (hazard.hazard) {
5827 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005828 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005829 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005830 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005831 }
5832 }
5833
5834 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005835 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005836 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005837 if (hazard.hazard) {
5838 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005839 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005840 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005841 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005842 }
5843 if (skip) break;
5844 }
5845 }
5846
5847 return skip;
5848}
5849
Tony-LunarG562fc102021-11-12 13:58:35 -07005850bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5851 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5852 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5853}
5854
5855bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5856 const VkResolveImageInfo2 *pResolveImageInfo) const {
5857 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5858}
5859
5860void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5861 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005862 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5863 auto *cb_access_context = GetAccessContext(commandBuffer);
5864 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005865 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005866 auto *context = cb_access_context->GetCurrentAccessContext();
5867 assert(context);
5868
Jeremy Gebben9f537102021-10-05 16:37:12 -06005869 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5870 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005871
5872 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5873 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5874 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005875 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005876 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005877 }
5878 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005879 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005880 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005881 }
5882 }
5883}
5884
Tony-LunarG562fc102021-11-12 13:58:35 -07005885void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5886 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5887 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5888}
5889
5890void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5891 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5892}
5893
locke-lunarge1a67022020-04-29 00:15:36 -06005894bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5895 VkDeviceSize dataSize, const void *pData) const {
5896 bool skip = false;
5897 const auto *cb_access_context = GetAccessContext(commandBuffer);
5898 assert(cb_access_context);
5899 if (!cb_access_context) return skip;
5900
5901 const auto *context = cb_access_context->GetCurrentAccessContext();
5902 assert(context);
5903 if (!context) return skip;
5904
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005905 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005906
5907 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005908 // VK_WHOLE_SIZE not allowed
5909 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005910 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005911 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005912 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005913 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005914 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005915 }
5916 }
5917 return skip;
5918}
5919
5920void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5921 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005922 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005923 auto *cb_access_context = GetAccessContext(commandBuffer);
5924 assert(cb_access_context);
5925 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5926 auto *context = cb_access_context->GetCurrentAccessContext();
5927 assert(context);
5928
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005929 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005930
5931 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005932 // VK_WHOLE_SIZE not allowed
5933 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005934 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005935 }
5936}
locke-lunargff255f92020-05-13 18:53:52 -06005937
5938bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5939 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5940 bool skip = false;
5941 const auto *cb_access_context = GetAccessContext(commandBuffer);
5942 assert(cb_access_context);
5943 if (!cb_access_context) return skip;
5944
5945 const auto *context = cb_access_context->GetCurrentAccessContext();
5946 assert(context);
5947 if (!context) return skip;
5948
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005949 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005950
5951 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005952 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005953 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005954 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005955 skip |=
5956 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5957 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005958 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005959 }
5960 }
5961 return skip;
5962}
5963
5964void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5965 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005966 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005967 auto *cb_access_context = GetAccessContext(commandBuffer);
5968 assert(cb_access_context);
5969 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5970 auto *context = cb_access_context->GetCurrentAccessContext();
5971 assert(context);
5972
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005973 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005974
5975 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005976 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005977 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005978 }
5979}
John Zulauf49beb112020-11-04 16:06:31 -07005980
5981bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5982 bool skip = false;
5983 const auto *cb_context = GetAccessContext(commandBuffer);
5984 assert(cb_context);
5985 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005986 const auto *access_context = cb_context->GetCurrentAccessContext();
5987 assert(access_context);
5988 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005989
John Zulaufe0757ba2022-06-10 16:51:45 -06005990 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005991 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005992}
5993
5994void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5995 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5996 auto *cb_context = GetAccessContext(commandBuffer);
5997 assert(cb_context);
5998 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005999
6000 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
6001 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07006002}
6003
John Zulauf4edde622021-02-15 08:54:50 -07006004bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
6005 const VkDependencyInfoKHR *pDependencyInfo) const {
6006 bool skip = false;
6007 const auto *cb_context = GetAccessContext(commandBuffer);
6008 assert(cb_context);
6009 if (!cb_context || !pDependencyInfo) return skip;
6010
John Zulaufe0757ba2022-06-10 16:51:45 -06006011 const auto *access_context = cb_context->GetCurrentAccessContext();
6012 assert(access_context);
6013 if (!access_context) return skip;
6014
6015 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07006016 return set_event_op.Validate(*cb_context);
6017}
6018
Tony-LunarGc43525f2021-11-15 16:12:38 -07006019bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
6020 const VkDependencyInfo *pDependencyInfo) const {
6021 bool skip = false;
6022 const auto *cb_context = GetAccessContext(commandBuffer);
6023 assert(cb_context);
6024 if (!cb_context || !pDependencyInfo) return skip;
6025
John Zulaufe0757ba2022-06-10 16:51:45 -06006026 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07006027 return set_event_op.Validate(*cb_context);
6028}
6029
John Zulauf4edde622021-02-15 08:54:50 -07006030void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
6031 const VkDependencyInfoKHR *pDependencyInfo) {
6032 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
6033 auto *cb_context = GetAccessContext(commandBuffer);
6034 assert(cb_context);
6035 if (!cb_context || !pDependencyInfo) return;
6036
John Zulaufe0757ba2022-06-10 16:51:45 -06006037 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
6038 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07006039}
6040
Tony-LunarGc43525f2021-11-15 16:12:38 -07006041void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
6042 const VkDependencyInfo *pDependencyInfo) {
6043 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
6044 auto *cb_context = GetAccessContext(commandBuffer);
6045 assert(cb_context);
6046 if (!cb_context || !pDependencyInfo) return;
6047
John Zulaufe0757ba2022-06-10 16:51:45 -06006048 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
6049 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07006050}
6051
John Zulauf49beb112020-11-04 16:06:31 -07006052bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
6053 VkPipelineStageFlags stageMask) const {
6054 bool skip = false;
6055 const auto *cb_context = GetAccessContext(commandBuffer);
6056 assert(cb_context);
6057 if (!cb_context) return skip;
6058
John Zulauf36ef9282021-02-02 11:47:24 -07006059 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07006060 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07006061}
6062
6063void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
6064 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
6065 auto *cb_context = GetAccessContext(commandBuffer);
6066 assert(cb_context);
6067 if (!cb_context) return;
6068
John Zulauf1bf30522021-09-03 15:39:06 -06006069 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07006070}
6071
John Zulauf4edde622021-02-15 08:54:50 -07006072bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
6073 VkPipelineStageFlags2KHR stageMask) const {
6074 bool skip = false;
6075 const auto *cb_context = GetAccessContext(commandBuffer);
6076 assert(cb_context);
6077 if (!cb_context) return skip;
6078
6079 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
6080 return reset_event_op.Validate(*cb_context);
6081}
6082
Tony-LunarGa2662db2021-11-16 07:26:24 -07006083bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
6084 VkPipelineStageFlags2 stageMask) const {
6085 bool skip = false;
6086 const auto *cb_context = GetAccessContext(commandBuffer);
6087 assert(cb_context);
6088 if (!cb_context) return skip;
6089
6090 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
6091 return reset_event_op.Validate(*cb_context);
6092}
6093
John Zulauf4edde622021-02-15 08:54:50 -07006094void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
6095 VkPipelineStageFlags2KHR stageMask) {
6096 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
6097 auto *cb_context = GetAccessContext(commandBuffer);
6098 assert(cb_context);
6099 if (!cb_context) return;
6100
John Zulauf1bf30522021-09-03 15:39:06 -06006101 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07006102}
6103
Tony-LunarGa2662db2021-11-16 07:26:24 -07006104void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
6105 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
6106 auto *cb_context = GetAccessContext(commandBuffer);
6107 assert(cb_context);
6108 if (!cb_context) return;
6109
6110 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
6111}
6112
John Zulauf49beb112020-11-04 16:06:31 -07006113bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6114 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6115 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6116 uint32_t bufferMemoryBarrierCount,
6117 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6118 uint32_t imageMemoryBarrierCount,
6119 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
6120 bool skip = false;
6121 const auto *cb_context = GetAccessContext(commandBuffer);
6122 assert(cb_context);
6123 if (!cb_context) return skip;
6124
John Zulauf36ef9282021-02-02 11:47:24 -07006125 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
6126 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
6127 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07006128 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07006129}
6130
6131void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6132 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6133 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6134 uint32_t bufferMemoryBarrierCount,
6135 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6136 uint32_t imageMemoryBarrierCount,
6137 const VkImageMemoryBarrier *pImageMemoryBarriers) {
6138 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
6139 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
6140 imageMemoryBarrierCount, pImageMemoryBarriers);
6141
6142 auto *cb_context = GetAccessContext(commandBuffer);
6143 assert(cb_context);
6144 if (!cb_context) return;
6145
John Zulauf1bf30522021-09-03 15:39:06 -06006146 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06006147 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06006148 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07006149}
6150
John Zulauf4edde622021-02-15 08:54:50 -07006151bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6152 const VkDependencyInfoKHR *pDependencyInfos) const {
6153 bool skip = false;
6154 const auto *cb_context = GetAccessContext(commandBuffer);
6155 assert(cb_context);
6156 if (!cb_context) return skip;
6157
6158 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6159 skip |= wait_events_op.Validate(*cb_context);
6160 return skip;
6161}
6162
6163void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6164 const VkDependencyInfoKHR *pDependencyInfos) {
6165 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6166
6167 auto *cb_context = GetAccessContext(commandBuffer);
6168 assert(cb_context);
6169 if (!cb_context) return;
6170
John Zulauf1bf30522021-09-03 15:39:06 -06006171 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6172 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006173}
6174
Tony-LunarG1364cf52021-11-17 16:10:11 -07006175bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6176 const VkDependencyInfo *pDependencyInfos) const {
6177 bool skip = false;
6178 const auto *cb_context = GetAccessContext(commandBuffer);
6179 assert(cb_context);
6180 if (!cb_context) return skip;
6181
6182 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6183 skip |= wait_events_op.Validate(*cb_context);
6184 return skip;
6185}
6186
6187void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6188 const VkDependencyInfo *pDependencyInfos) {
6189 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6190
6191 auto *cb_context = GetAccessContext(commandBuffer);
6192 assert(cb_context);
6193 if (!cb_context) return;
6194
6195 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6196 pDependencyInfos);
6197}
6198
John Zulauf4a6105a2020-11-17 15:11:05 -07006199void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006200 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006201 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006202 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006203}
6204
6205// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006206SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006207 IgnoreReason reason = NotIgnored;
6208
sjfricke0bea06e2022-06-05 09:22:26 +09006209 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006210 reason = SetVsWait2;
6211 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6212 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006213 } else if (unsynchronized_set) {
6214 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006215 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006216 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006217 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006218 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006219 } else {
6220 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006221 }
6222
6223 return reason;
6224}
6225
Jeremy Gebben40a22942020-12-22 14:22:06 -07006226bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006227 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6228 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6229 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006230}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006231
John Zulauf8a7b03d2022-09-20 11:41:19 -06006232void SyncEventState::AddReferencedTags(ResourceUsageTagSet &referenced) const {
6233 if (first_scope) {
6234 first_scope->AddReferencedTags(referenced);
6235 }
6236}
6237
sjfricke0bea06e2022-06-05 09:22:26 +09006238SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006239 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6240 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006241 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6242 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6243 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006244 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006245 auto &barrier_set = barriers_[0];
6246 barrier_set.dependency_flags = dependencyFlags;
6247 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6248 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006249 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006250 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6251 pMemoryBarriers);
6252 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6253 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6254 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6255 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006256}
6257
sjfricke0bea06e2022-06-05 09:22:26 +09006258SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006259 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006260 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006261 for (uint32_t i = 0; i < event_count; i++) {
6262 const auto &dep_info = dep_infos[i];
6263 auto &barrier_set = barriers_[i];
6264 barrier_set.dependency_flags = dep_info.dependencyFlags;
6265 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6266 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6267 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6268 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6269 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6270 dep_info.pMemoryBarriers);
6271 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6272 dep_info.pBufferMemoryBarriers);
6273 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6274 dep_info.pImageMemoryBarriers);
6275 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006276}
6277
sjfricke0bea06e2022-06-05 09:22:26 +09006278SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006279 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6280 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6281 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6282 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6283 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006284 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6285 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6286 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006287
sjfricke0bea06e2022-06-05 09:22:26 +09006288SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006289 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006290 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006291
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006292bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6293 bool skip = false;
6294 const auto *context = cb_context.GetCurrentAccessContext();
6295 assert(context);
6296 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006297 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6298
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006299 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006300 const auto &barrier_set = barriers_[0];
6301 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6302 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6303 const auto *image_state = image_barrier.image.get();
6304 if (!image_state) continue;
6305 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6306 if (hazard.hazard) {
6307 // PHASE1 TODO -- add tag information to log msg when useful.
6308 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006309 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006310 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6311 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6312 string_SyncHazard(hazard.hazard), image_barrier.index,
6313 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006314 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006315 }
6316 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006317 return skip;
6318}
6319
John Zulaufd5115702021-01-18 12:34:33 -07006320struct SyncOpPipelineBarrierFunctorFactory {
6321 using BarrierOpFunctor = PipelineBarrierOp;
6322 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6323 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6324 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6325 using BufferRange = ResourceAccessRange;
6326 using ImageRange = subresource_adapter::ImageRangeGenerator;
6327 using GlobalRange = ResourceAccessRange;
6328
John Zulauf00119522022-05-23 19:07:42 -06006329 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6330 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006331 }
John Zulauf14940722021-04-12 15:19:02 -06006332 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006333 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6334 }
John Zulauf00119522022-05-23 19:07:42 -06006335 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6336 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006337 }
6338
6339 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6340 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6341 const auto base_address = ResourceBaseAddress(buffer);
6342 return (range + base_address);
6343 }
John Zulauf110413c2021-03-20 05:38:38 -06006344 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006345 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006346
6347 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006348 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006349 return range_gen;
6350 }
6351 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6352};
6353
6354template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006355void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6356 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006357 for (const auto &barrier : barriers) {
6358 const auto *state = barrier.GetState();
6359 if (state) {
6360 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006361 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006362 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6363 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6364 }
6365 }
6366}
6367
6368template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006369void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6370 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006371 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6372 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006373 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006374 }
6375 for (const auto address_type : kAddressTypes) {
6376 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6377 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6378 }
6379}
6380
John Zulaufdab327f2022-07-08 12:02:05 -06006381ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006382 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006383 ReplayRecord(*cb_context, tag);
John Zulauf4fa68462021-04-26 21:04:22 -06006384 return tag;
6385}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006386
John Zulauf0223f142022-07-06 09:05:39 -06006387void SyncOpPipelineBarrier::ReplayRecord(CommandExecutionContext &exec_context, const ResourceUsageTag tag) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006388 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006389 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6390 assert(barriers_.size() == 1);
6391 const auto &barrier_set = barriers_[0];
John Zulauf0223f142022-07-06 09:05:39 -06006392 if (!exec_context.ValidForSyncOps()) return;
6393
6394 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6395 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6396 const auto queue_id = exec_context.GetQueueId();
John Zulauf00119522022-05-23 19:07:42 -06006397 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6398 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6399 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006400 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006401 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006402 } else {
6403 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006404 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006405 }
6406 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006407}
6408
John Zulauf8eda1562021-04-13 17:06:41 -06006409bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006410 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006411 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6412 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006413 return false;
6414}
6415
John Zulauf4edde622021-02-15 08:54:50 -07006416void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6417 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6418 const VkMemoryBarrier *barriers) {
6419 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006420 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006421 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006422 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006423 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006424 }
6425 if (0 == memory_barrier_count) {
6426 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006427 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006428 }
John Zulauf4edde622021-02-15 08:54:50 -07006429 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006430}
6431
John Zulauf4edde622021-02-15 08:54:50 -07006432void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6433 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6434 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6435 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006436 for (uint32_t index = 0; index < barrier_count; index++) {
6437 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006438 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006439 if (buffer) {
6440 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6441 const auto range = MakeRange(barrier.offset, barrier_size);
6442 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006443 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006444 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006445 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006446 }
6447 }
6448}
6449
John Zulauf4edde622021-02-15 08:54:50 -07006450void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006451 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006452 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006453 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006454 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006455 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6456 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6457 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006458 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006459 }
John Zulauf4edde622021-02-15 08:54:50 -07006460 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006461}
6462
John Zulauf4edde622021-02-15 08:54:50 -07006463void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6464 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006465 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006466 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006467 for (uint32_t index = 0; index < barrier_count; index++) {
6468 const auto &barrier = barriers[index];
6469 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6470 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006471 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006472 if (buffer) {
6473 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6474 const auto range = MakeRange(barrier.offset, barrier_size);
6475 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006476 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006477 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006478 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006479 }
6480 }
6481}
6482
John Zulauf4edde622021-02-15 08:54:50 -07006483void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6484 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6485 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6486 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006487 for (uint32_t index = 0; index < barrier_count; index++) {
6488 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006489 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006490 if (image) {
6491 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6492 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006493 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006494 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006495 image_memory_barriers.emplace_back();
6496 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006497 }
6498 }
6499}
John Zulaufd5115702021-01-18 12:34:33 -07006500
John Zulauf4edde622021-02-15 08:54:50 -07006501void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6502 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006503 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006504 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006505 for (uint32_t index = 0; index < barrier_count; index++) {
6506 const auto &barrier = barriers[index];
6507 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6508 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006509 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006510 if (image) {
6511 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6512 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006513 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006514 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006515 image_memory_barriers.emplace_back();
6516 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006517 }
6518 }
6519}
6520
sjfricke0bea06e2022-06-05 09:22:26 +09006521SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6522 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6523 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6524 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6525 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6526 const VkImageMemoryBarrier *pImageMemoryBarriers)
6527 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006528 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6529 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006530 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006531}
6532
sjfricke0bea06e2022-06-05 09:22:26 +09006533SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6534 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6535 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006536 MakeEventsList(sync_state, eventCount, pEvents);
6537 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6538}
6539
John Zulauf610e28c2021-08-03 17:46:23 -06006540const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6541
John Zulaufd5115702021-01-18 12:34:33 -07006542bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006543 bool skip = false;
6544 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006545 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006546
John Zulauf610e28c2021-08-03 17:46:23 -06006547 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006548 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6549 const auto &barrier_set = barriers_[barrier_set_index];
6550 if (barrier_set.single_exec_scope) {
6551 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6552 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6553 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6554 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6555 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6556 } else {
6557 const auto &barriers = barrier_set.memory_barriers;
6558 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6559 const auto &barrier = barriers[barrier_index];
6560 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6561 const std::string vuid =
6562 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6563 skip =
6564 sync_state.LogInfo(command_buffer_handle, vuid,
6565 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6566 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6567 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6568 }
6569 }
6570 }
6571 }
John Zulaufd5115702021-01-18 12:34:33 -07006572 }
6573
John Zulauf610e28c2021-08-03 17:46:23 -06006574 // The rest is common to record time and replay time.
6575 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6576 return skip;
6577}
6578
John Zulaufbb890452021-12-14 11:30:18 -07006579bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006580 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006581 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006582 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006583
Jeremy Gebben40a22942020-12-22 14:22:06 -07006584 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006585 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006586 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006587 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006588 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006589 size_t barrier_set_index = 0;
6590 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006591 for (const auto &event : events_) {
6592 const auto *sync_event = events_context->Get(event.get());
6593 const auto &barrier_set = barriers_[barrier_set_index];
6594 if (!sync_event) {
6595 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6596 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6597 // new validation error... wait without previously submitted set event...
6598 events_not_found = true; // Demote "extra_stage_bits" error to warning, to avoid false positives at *record time*
John Zulauf4edde622021-02-15 08:54:50 -07006599 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006600 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006601 }
John Zulauf610e28c2021-08-03 17:46:23 -06006602
6603 // For replay calls, don't revalidate "same command buffer" events
6604 if (sync_event->last_command_tag > base_tag) continue;
6605
John Zulauf78394fc2021-07-12 15:41:40 -06006606 const auto event_handle = sync_event->event->event();
6607 // TODO add "destroyed" checks
6608
John Zulaufe0757ba2022-06-10 16:51:45 -06006609 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006610 // Only accumulate barrier and event stages if there is a pending set in the current context
6611 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6612 event_stage_masks |= sync_event->scope.mask_param;
6613 }
6614
John Zulauf78394fc2021-07-12 15:41:40 -06006615 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006616
sjfricke0bea06e2022-06-05 09:22:26 +09006617 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006618 if (ignore_reason) {
6619 switch (ignore_reason) {
6620 case SyncEventState::ResetWaitRace:
6621 case SyncEventState::Reset2WaitRace: {
6622 // Four permuations of Reset and Wait calls...
6623 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006624 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006625 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006626 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6627 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006628 }
6629 const char *const message =
6630 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6631 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6632 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006633 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006634 break;
6635 }
6636 case SyncEventState::SetRace: {
6637 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6638 // this event
6639 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6640 const char *const message =
6641 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6642 const char *const reason = "First synchronization scope is undefined.";
6643 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6644 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006645 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006646 break;
6647 }
6648 case SyncEventState::MissingStageBits: {
6649 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6650 // Issue error message that event waited for is not in wait events scope
6651 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6652 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6653 ". Bits missing from srcStageMask %s. %s";
6654 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6655 sync_state.report_data->FormatHandle(event_handle).c_str(),
6656 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006657 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006658 break;
6659 }
6660 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006661 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006662 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6663 sync_state.report_data->FormatHandle(event_handle).c_str(),
6664 CommandTypeString(sync_event->last_command));
6665 break;
6666 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006667 case SyncEventState::MissingSetEvent: {
6668 // TODO: There are conditions at queue submit time where we can definitively say that
6669 // a missing set event is an error. Add those if not captured in CoreChecks
6670 break;
6671 }
John Zulauf78394fc2021-07-12 15:41:40 -06006672 default:
6673 assert(ignore_reason == SyncEventState::NotIgnored);
6674 }
6675 } else if (barrier_set.image_memory_barriers.size()) {
6676 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006677 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006678 assert(context);
6679 for (const auto &image_memory_barrier : image_memory_barriers) {
6680 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6681 const auto *image_state = image_memory_barrier.image.get();
6682 if (!image_state) continue;
6683 const auto &subresource_range = image_memory_barrier.range;
6684 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006685 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6686 src_access_scope, queue_id, *sync_event,
6687 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006688 if (hazard.hazard) {
6689 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6690 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6691 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6692 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006693 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006694 break;
6695 }
6696 }
6697 }
6698 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6699 // 03839
6700 barrier_set_index += barrier_set_incr;
6701 }
John Zulaufd5115702021-01-18 12:34:33 -07006702
6703 // Note that we can't check for HOST in pEvents as we don't track that set event type
John Zulauf4edde622021-02-15 08:54:50 -07006704 const auto extra_stage_bits = (barrier_mask_params & ~VK_PIPELINE_STAGE_2_HOST_BIT_KHR) & ~event_stage_masks;
John Zulaufd5115702021-01-18 12:34:33 -07006705 if (extra_stage_bits) {
6706 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006707 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6708 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006709 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006710 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006711 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006712 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006713 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006714 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006715 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006716 " vkCmdSetEvent may be in previously submitted command buffer.");
6717 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006718 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006719 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006720 }
6721 }
6722 return skip;
6723}
6724
6725struct SyncOpWaitEventsFunctorFactory {
6726 using BarrierOpFunctor = WaitEventBarrierOp;
6727 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6728 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6729 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6730 using BufferRange = EventSimpleRangeGenerator;
6731 using ImageRange = EventImageRangeGenerator;
6732 using GlobalRange = EventSimpleRangeGenerator;
6733
6734 // Need to restrict to only valid exec and access scope for this event
6735 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6736 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006737 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006738 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6739 return barrier;
6740 }
John Zulauf00119522022-05-23 19:07:42 -06006741 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006742 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006743 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006744 }
John Zulauf14940722021-04-12 15:19:02 -06006745 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006746 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6747 }
John Zulauf00119522022-05-23 19:07:42 -06006748 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006749 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006750 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006751 }
6752
6753 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6754 const AccessAddressType address_type = GetAccessAddressType(buffer);
6755 const auto base_address = ResourceBaseAddress(buffer);
6756 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6757 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6758 return filtered_range_gen;
6759 }
John Zulauf110413c2021-03-20 05:38:38 -06006760 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006761 if (!SimpleBinding(image)) return ImageRange();
6762 const auto address_type = GetAccessAddressType(image);
6763 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006764 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6765 false);
John Zulaufd5115702021-01-18 12:34:33 -07006766 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6767
6768 return filtered_range_gen;
6769 }
6770 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6771 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6772 }
6773 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6774 SyncEventState *sync_event;
6775};
6776
John Zulaufdab327f2022-07-08 12:02:05 -06006777ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006778 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006779
John Zulauf0223f142022-07-06 09:05:39 -06006780 ReplayRecord(*cb_context, tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006781 return tag;
6782}
6783
John Zulauf0223f142022-07-06 09:05:39 -06006784void SyncOpWaitEvents::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006785 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6786 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6787 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
John Zulauf0223f142022-07-06 09:05:39 -06006788 if (!exec_context.ValidForSyncOps()) return;
6789 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6790 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6791 const QueueId queue_id = exec_context.GetQueueId();
6792
John Zulaufd5115702021-01-18 12:34:33 -07006793 access_context->ResolvePreviousAccesses();
6794
John Zulauf4edde622021-02-15 08:54:50 -07006795 size_t barrier_set_index = 0;
6796 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6797 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006798 for (auto &event_shared : events_) {
6799 if (!event_shared.get()) continue;
6800 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006801
sjfricke0bea06e2022-06-05 09:22:26 +09006802 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006803 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006804
John Zulauf4edde622021-02-15 08:54:50 -07006805 const auto &barrier_set = barriers_[barrier_set_index];
6806 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006807 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006808 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6809 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6810 // of the barriers is maintained.
6811 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006812 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6813 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6814 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006815
6816 // Apply the global barrier to the event itself (for race condition tracking)
6817 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6818 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6819 sync_event->barriers |= dst.exec_scope;
6820 } else {
6821 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6822 sync_event->barriers = 0U;
6823 }
John Zulauf4edde622021-02-15 08:54:50 -07006824 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006825 }
6826
6827 // Apply the pending barriers
6828 ResolvePendingBarrierFunctor apply_pending_action(tag);
6829 access_context->ApplyToContext(apply_pending_action);
6830}
6831
John Zulauf8eda1562021-04-13 17:06:41 -06006832bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006833 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6834 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006835}
6836
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006837bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6838 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6839 bool skip = false;
6840 const auto *cb_access_context = GetAccessContext(commandBuffer);
6841 assert(cb_access_context);
6842 if (!cb_access_context) return skip;
6843
6844 const auto *context = cb_access_context->GetCurrentAccessContext();
6845 assert(context);
6846 if (!context) return skip;
6847
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006848 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006849
6850 if (dst_buffer) {
6851 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6852 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6853 if (hazard.hazard) {
6854 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6855 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6856 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006857 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006858 }
6859 }
6860 return skip;
6861}
6862
John Zulauf669dfd52021-01-27 17:15:28 -07006863void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006864 events_.reserve(event_count);
6865 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006866 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006867 }
6868}
John Zulauf6ce24372021-01-30 05:56:25 -07006869
sjfricke0bea06e2022-06-05 09:22:26 +09006870SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006871 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006872 : SyncOpBase(cmd_type),
6873 event_(sync_state.Get<EVENT_STATE>(event)),
6874 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006875
John Zulauf1bf30522021-09-03 15:39:06 -06006876bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6877 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6878}
6879
John Zulaufbb890452021-12-14 11:30:18 -07006880bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6881 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006882 assert(events_context);
6883 bool skip = false;
6884 if (!events_context) return skip;
6885
John Zulaufbb890452021-12-14 11:30:18 -07006886 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006887 const auto *sync_event = events_context->Get(event_);
6888 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6889
John Zulauf1bf30522021-09-03 15:39:06 -06006890 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6891
John Zulauf6ce24372021-01-30 05:56:25 -07006892 const char *const set_wait =
6893 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6894 "hazards.";
6895 const char *message = set_wait; // Only one message this call.
6896 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6897 const char *vuid = nullptr;
6898 switch (sync_event->last_command) {
6899 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006900 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006901 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006902 // Needs a barrier between set and reset
6903 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6904 break;
John Zulauf4edde622021-02-15 08:54:50 -07006905 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006906 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006907 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006908 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6909 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6910 break;
6911 }
6912 default:
6913 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006914 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6915 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006916 break;
6917 }
6918 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006919 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6920 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006921 CommandTypeString(sync_event->last_command));
6922 }
6923 }
6924 return skip;
6925}
6926
John Zulaufdab327f2022-07-08 12:02:05 -06006927ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006928 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006929 ReplayRecord(*cb_context, tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006930 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006931}
6932
John Zulauf8eda1562021-04-13 17:06:41 -06006933bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006934 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6935 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006936}
6937
John Zulauf0223f142022-07-06 09:05:39 -06006938void SyncOpResetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
6939 if (!exec_context.ValidForSyncOps()) return;
6940 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6941
John Zulaufe0757ba2022-06-10 16:51:45 -06006942 auto *sync_event = events_context->GetFromShared(event_);
6943 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6944
6945 // Update the event state
6946 sync_event->last_command = cmd_type_;
6947 sync_event->last_command_tag = tag;
6948 sync_event->unsynchronized_set = CMD_NONE;
6949 sync_event->ResetFirstScope();
6950 sync_event->barriers = 0U;
6951}
John Zulauf8eda1562021-04-13 17:06:41 -06006952
sjfricke0bea06e2022-06-05 09:22:26 +09006953SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006954 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006955 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006956 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006957 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006958 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006959 dep_info_() {
6960 // Snapshot the current access_context for later inspection at wait time.
6961 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6962 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6963 // or Submit time reference.
6964 if (access_context) {
6965 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6966 }
6967}
John Zulauf4edde622021-02-15 08:54:50 -07006968
sjfricke0bea06e2022-06-05 09:22:26 +09006969SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006970 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006971 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006972 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006973 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006974 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006975 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6976 if (access_context) {
6977 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6978 }
6979}
John Zulauf6ce24372021-01-30 05:56:25 -07006980
6981bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006982 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6983}
6984bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006985 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6986 return DoValidate(exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006987}
6988
John Zulaufbb890452021-12-14 11:30:18 -07006989bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006990 bool skip = false;
6991
John Zulaufbb890452021-12-14 11:30:18 -07006992 const auto &sync_state = exec_context.GetSyncState();
6993 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006994 assert(events_context);
6995 if (!events_context) return skip;
6996
6997 const auto *sync_event = events_context->Get(event_);
6998 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6999
John Zulauf610e28c2021-08-03 17:46:23 -06007000 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
7001
John Zulauf6ce24372021-01-30 05:56:25 -07007002 const char *const reset_set =
7003 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
7004 "hazards.";
7005 const char *const wait =
7006 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
7007
7008 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07007009 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07007010 const char *message = nullptr;
7011 switch (sync_event->last_command) {
7012 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07007013 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07007014 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07007015 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07007016 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07007017 message = reset_set;
7018 break;
7019 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07007020 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07007021 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07007022 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07007023 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07007024 message = reset_set;
7025 break;
7026 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07007027 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07007028 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07007029 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07007030 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07007031 message = wait;
7032 break;
7033 default:
7034 // The only other valid last command that wasn't one.
7035 assert(sync_event->last_command == CMD_NONE);
7036 break;
7037 }
John Zulauf4edde622021-02-15 08:54:50 -07007038 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07007039 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07007040 std::string vuid("SYNC-");
7041 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06007042 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
7043 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07007044 CommandTypeString(sync_event->last_command));
7045 }
7046 }
7047
7048 return skip;
7049}
7050
John Zulaufdab327f2022-07-08 12:02:05 -06007051ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007052 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07007053 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06007054 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06007055 assert(recorded_context_);
7056 if (recorded_context_ && events_context) {
7057 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06007058 }
7059 return tag;
7060}
John Zulauf6ce24372021-01-30 05:56:25 -07007061
John Zulauf0223f142022-07-06 09:05:39 -06007062void SyncOpSetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06007063 // Create a copy of the current context, and merge in the state snapshot at record set event time
7064 // Note: we mustn't change the recorded context copy, as a given CB could be submitted more than once (in generaL)
John Zulauf0223f142022-07-06 09:05:39 -06007065 if (!exec_context.ValidForSyncOps()) return;
7066 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
7067 AccessContext *access_context = exec_context.GetCurrentAccessContext();
7068 const QueueId queue_id = exec_context.GetQueueId();
7069
John Zulauf8a7b03d2022-09-20 11:41:19 -06007070 // Note: merged_context is a copy of the access_context, combined with the recorded context
John Zulaufe0757ba2022-06-10 16:51:45 -06007071 auto merged_context = std::make_shared<AccessContext>(*access_context);
7072 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
John Zulauf8a7b03d2022-09-20 11:41:19 -06007073 merged_context->Trim(); // Ensure the copy is minimal and normalized
John Zulaufe0757ba2022-06-10 16:51:45 -06007074 DoRecord(queue_id, tag, merged_context, events_context);
7075}
7076
7077void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
7078 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07007079 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06007080 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07007081
7082 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
7083 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
7084 // any issues caused by naive scope setting here.
7085
7086 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
7087 // Given:
7088 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
7089 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
7090
7091 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
7092 sync_event->unsynchronized_set = sync_event->last_command;
7093 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06007094 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07007095 // We only set the scope if there isn't one
7096 sync_event->scope = src_exec_scope_;
7097
John Zulaufe0757ba2022-06-10 16:51:45 -06007098 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
7099 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07007100 sync_event->unsynchronized_set = CMD_NONE;
7101 sync_event->first_scope_tag = tag;
7102 }
John Zulauf4edde622021-02-15 08:54:50 -07007103 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09007104 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06007105 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07007106 sync_event->barriers = 0U;
7107}
John Zulauf64ffe552021-02-06 10:25:07 -07007108
sjfricke0bea06e2022-06-05 09:22:26 +09007109SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07007110 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07007111 const VkSubpassBeginInfo *pSubpassBeginInfo)
John Zulaufdab327f2022-07-08 12:02:05 -06007112 : SyncOpBase(cmd_type), rp_context_(nullptr) {
John Zulauf64ffe552021-02-06 10:25:07 -07007113 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06007114 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07007115 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007116 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07007117 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06007118 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07007119 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
7120 // Note that this a safe to presist as long as shared_attachments is not cleared
7121 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08007122 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07007123 attachments_.emplace_back(attachment.get());
7124 }
7125 }
7126 if (pSubpassBeginInfo) {
7127 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
7128 }
7129 }
7130}
7131
7132bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7133 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
7134 bool skip = false;
7135
7136 assert(rp_state_.get());
7137 if (nullptr == rp_state_.get()) return skip;
7138 auto &rp_state = *rp_state_.get();
7139
7140 const uint32_t subpass = 0;
7141
7142 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
7143 // hasn't happened yet)
7144 const std::vector<AccessContext> empty_context_vector;
7145 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
7146 cb_context.GetCurrentAccessContext());
7147
7148 // Validate attachment operations
7149 if (attachments_.size() == 0) return skip;
7150 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07007151
7152 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
7153 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
7154 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
7155 // operations (though it's currently a messy approach)
7156 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09007157 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007158
7159 // Validate load operations if there were no layout transition hazards
7160 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06007161 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09007162 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007163 }
7164
7165 return skip;
7166}
7167
John Zulaufdab327f2022-07-08 12:02:05 -06007168ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) {
John Zulauf64ffe552021-02-06 10:25:07 -07007169 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09007170 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
John Zulaufdab327f2022-07-08 12:02:05 -06007171 const ResourceUsageTag begin_tag =
7172 cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
7173
7174 // Note: this state update must be after RecordBeginRenderPass as there is no current render pass until that function runs
7175 rp_context_ = cb_context->GetCurrentRenderPassContext();
7176
7177 return begin_tag;
John Zulauf64ffe552021-02-06 10:25:07 -07007178}
7179
John Zulauf8eda1562021-04-13 17:06:41 -06007180bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007181 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007182 return false;
7183}
7184
John Zulaufdab327f2022-07-08 12:02:05 -06007185void SyncOpBeginRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7186 // Need to update the exec_contexts state (which for RenderPass operations *must* be a QueueBatchContext, as
7187 // render pass operations are not allowed in secondary command buffers.
7188 const QueueId queue_id = exec_context.GetQueueId();
7189 assert(queue_id != QueueSyncState::kQueueIdInvalid); // Renderpass replay only valid at submit (not exec) time
7190 if (queue_id == QueueSyncState::kQueueIdInvalid) return;
7191
7192 exec_context.BeginRenderPassReplay(*this, tag);
7193}
John Zulauf8eda1562021-04-13 17:06:41 -06007194
sjfricke0bea06e2022-06-05 09:22:26 +09007195SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7196 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7197 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007198 if (pSubpassBeginInfo) {
7199 subpass_begin_info_.initialize(pSubpassBeginInfo);
7200 }
7201 if (pSubpassEndInfo) {
7202 subpass_end_info_.initialize(pSubpassEndInfo);
7203 }
7204}
7205
7206bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7207 bool skip = false;
7208 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7209 if (!renderpass_context) return skip;
7210
sjfricke0bea06e2022-06-05 09:22:26 +09007211 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007212 return skip;
7213}
7214
John Zulaufdab327f2022-07-08 12:02:05 -06007215ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007216 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007217}
7218
7219bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007220 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007221 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07007222}
7223
sjfricke0bea06e2022-06-05 09:22:26 +09007224SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7225 const VkSubpassEndInfo *pSubpassEndInfo)
7226 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007227 if (pSubpassEndInfo) {
7228 subpass_end_info_.initialize(pSubpassEndInfo);
7229 }
7230}
7231
John Zulaufdab327f2022-07-08 12:02:05 -06007232void SyncOpNextSubpass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7233 exec_context.NextSubpassReplay();
7234}
John Zulauf8eda1562021-04-13 17:06:41 -06007235
John Zulauf64ffe552021-02-06 10:25:07 -07007236bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7237 bool skip = false;
7238 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7239
7240 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007241 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007242 return skip;
7243}
7244
John Zulaufdab327f2022-07-08 12:02:05 -06007245ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007246 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007247}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007248
John Zulauf8eda1562021-04-13 17:06:41 -06007249bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007250 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007251 return false;
7252}
7253
John Zulaufdab327f2022-07-08 12:02:05 -06007254void SyncOpEndRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7255 exec_context.EndRenderPassReplay();
7256}
John Zulauf8eda1562021-04-13 17:06:41 -06007257
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007258void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7259 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7260 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7261 auto *cb_access_context = GetAccessContext(commandBuffer);
7262 assert(cb_access_context);
7263 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7264 auto *context = cb_access_context->GetCurrentAccessContext();
7265 assert(context);
7266
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007267 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007268
7269 if (dst_buffer) {
7270 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7271 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7272 }
7273}
John Zulaufd05c5842021-03-26 11:32:16 -06007274
John Zulaufae842002021-04-15 18:20:55 -06007275bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7276 const VkCommandBuffer *pCommandBuffers) const {
7277 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007278 const auto *cb_context = GetAccessContext(commandBuffer);
7279 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007280
7281 // Heavyweight, but we need a proxy copy of the active command buffer access context
7282 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007283
7284 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007285 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007286 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7287
John Zulaufae842002021-04-15 18:20:55 -06007288 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7289 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007290
7291 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7292 assert(recorded_context);
John Zulauf0223f142022-07-06 09:05:39 -06007293 skip |= recorded_cb_context->ValidateFirstUse(proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007294
7295 // The barriers have already been applied in ValidatFirstUse
7296 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007297 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007298 }
7299
John Zulaufae842002021-04-15 18:20:55 -06007300 return skip;
7301}
7302
7303void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7304 const VkCommandBuffer *pCommandBuffers) {
7305 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007306 auto *cb_context = GetAccessContext(commandBuffer);
7307 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007308 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007309 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007310 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7311 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007312 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007313 }
John Zulaufae842002021-04-15 18:20:55 -06007314}
7315
John Zulauf1d5f9c12022-05-13 14:51:08 -06007316void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7317 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7318 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7319
7320 const auto queue_state = GetQueueSyncStateShared(queue);
7321 if (!queue_state) return; // Invalid queue
7322 QueueId waited_queue = queue_state->GetQueueId();
John Zulauf3da08bb2022-08-01 17:56:56 -06007323 ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007324
John Zulauf3da08bb2022-08-01 17:56:56 -06007325 // Eliminate waitable fences from the current queue.
7326 layer_data::EraseIf(waitable_fences_, [waited_queue](const SignaledFence &sf) { return sf.second.queue_id == waited_queue; });
John Zulauf1d5f9c12022-05-13 14:51:08 -06007327}
7328
7329void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7330 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007331
7332 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7333 for (auto &batch : queue_batch_contexts) {
7334 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007335 }
7336
John Zulauf3da08bb2022-08-01 17:56:56 -06007337 // As we we've waited for everything on device, any waits are mooted.
7338 waitable_fences_.clear();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007339}
7340
John Zulauf697c0e12022-04-19 16:31:12 -06007341template <>
7342thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7343
John Zulaufbbda4572022-04-19 16:20:45 -06007344bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7345 VkFence fence) const {
John Zulaufa8700a52022-08-18 16:22:08 -06007346 SubmitInfoConverter submit_info(submitCount, pSubmits);
John Zulauf3298da92022-09-01 13:58:39 -06007347 return ValidateQueueSubmit(queue, submitCount, submit_info.info2s.data(), fence, "vkQueueSubmit");
John Zulaufa8700a52022-08-18 16:22:08 -06007348}
7349
7350bool SyncValidator::ValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2 *pSubmits, VkFence fence,
7351 const char *func_name) const {
John Zulaufbbda4572022-04-19 16:20:45 -06007352 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007353
7354 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007355 if (!enabled[sync_validation_queue_submit]) return skip;
7356
John Zulauf8a7b03d2022-09-20 11:41:19 -06007357 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, func_name, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007358 cmd_state->queue = GetQueueSyncStateShared(queue);
7359 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007360
John Zulauf697c0e12022-04-19 16:31:12 -06007361 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7362 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7363
7364 // verify each submit batch
7365 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7366 // most recently created batch
7367 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7368 std::shared_ptr<QueueBatchContext> batch;
7369 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
John Zulaufa8700a52022-08-18 16:22:08 -06007370 const VkSubmitInfo2 &submit = pSubmits[batch_idx];
John Zulauf8a7b03d2022-09-20 11:41:19 -06007371 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue, submit_id, batch_idx);
John Zulaufa8700a52022-08-18 16:22:08 -06007372 batch->SetupCommandBufferInfo(submit);
7373 batch->SetupAccessContext(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007374
John Zulaufe0757ba2022-06-10 16:51:45 -06007375 // Skip import and validation of empty batches
7376 if (batch->GetTagRange().size()) {
John Zulauf8a7b03d2022-09-20 11:41:19 -06007377 batch->SetupBatchTags();
John Zulaufa8700a52022-08-18 16:22:08 -06007378 skip |= batch->DoQueueSubmitValidate(*this, *cmd_state, submit);
John Zulauf697c0e12022-04-19 16:31:12 -06007379 }
7380
John Zulaufe0757ba2022-06-10 16:51:45 -06007381 // Empty batches could have semaphores, though.
John Zulaufa8700a52022-08-18 16:22:08 -06007382 for (uint32_t sem_idx = 0; sem_idx < submit.signalSemaphoreInfoCount; ++sem_idx) {
7383 const VkSemaphoreSubmitInfo &semaphore_info = submit.pSignalSemaphoreInfos[sem_idx];
John Zulauf697c0e12022-04-19 16:31:12 -06007384 // Make a copy of the state, signal the copy and pend it...
John Zulaufa8700a52022-08-18 16:22:08 -06007385 auto sem_state = Get<SEMAPHORE_STATE>(semaphore_info.semaphore);
John Zulauf697c0e12022-04-19 16:31:12 -06007386 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007387 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007388 }
7389 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7390 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7391 last_batch = batch;
7392 }
7393 // The most recently created batch will become the queue's "last batch" in the record phase
7394 if (batch) {
7395 cmd_state->last_batch = std::move(batch);
7396 }
7397
7398 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007399 return skip;
7400}
7401
7402void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7403 VkResult result) {
7404 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007405
John Zulaufa8700a52022-08-18 16:22:08 -06007406 RecordQueueSubmit(queue, fence, result);
7407}
7408
7409void SyncValidator::RecordQueueSubmit(VkQueue queue, VkFence fence, VkResult result) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007410 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007411 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7412
John Zulaufcb7e1672022-05-04 13:46:08 -06007413 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7414 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007415 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007416
7417 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007418 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7419
John Zulauf697c0e12022-04-19 16:31:12 -06007420 // Don't need to look up the queue state again, but we need a non-const version
7421 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007422
John Zulaufcb7e1672022-05-04 13:46:08 -06007423 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7424 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7425 // QBC's are those referenced by unwaited signals and the last batch.
7426 for (auto &sig_sem : cmd_state->signaled) {
7427 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007428 auto &sig_batch = sig_sem.second->batch;
John Zulaufe0757ba2022-06-10 16:51:45 -06007429 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7430 if (sig_batch != cmd_state->last_batch) {
7431 sig_batch->ResetEventsContext();
John Zulauf8a7b03d2022-09-20 11:41:19 -06007432 // Make sure that retained batches are minimal, and trim after the events contexts has been cleared.
7433 sig_batch->Trim();
John Zulaufe0757ba2022-06-10 16:51:45 -06007434 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007435 }
7436 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007437 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007438 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007439
John Zulaufcb7e1672022-05-04 13:46:08 -06007440 // Update the queue to point to the last batch from the submit
7441 if (cmd_state->last_batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007442 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7443 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7444 auto last_batch = queue_state->LastBatch();
7445 if (last_batch) {
7446 last_batch->ResetEventsContext();
7447 }
John Zulauf8a7b03d2022-09-20 11:41:19 -06007448 cmd_state->last_batch->Trim();
John Zulaufcb7e1672022-05-04 13:46:08 -06007449 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007450 }
7451
John Zulauf3da08bb2022-08-01 17:56:56 -06007452 ResourceUsageRange fence_tag_range = ReserveGlobalTagRange(1U);
7453 UpdateFenceWaitInfo(fence, queue_state->GetQueueId(), fence_tag_range.begin);
John Zulaufbbda4572022-04-19 16:20:45 -06007454}
7455
7456bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7457 VkFence fence) const {
John Zulauf3298da92022-09-01 13:58:39 -06007458 return ValidateQueueSubmit(queue, submitCount, pSubmits, fence, "vkQueueSubmit2KHR");
John Zulaufa8700a52022-08-18 16:22:08 -06007459}
7460bool SyncValidator::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7461 VkFence fence) const {
John Zulauf3298da92022-09-01 13:58:39 -06007462 return ValidateQueueSubmit(queue, submitCount, pSubmits, fence, "vkQueueSubmit2");
John Zulaufbbda4572022-04-19 16:20:45 -06007463}
7464
7465void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7466 VkFence fence, VkResult result) {
7467 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulaufa8700a52022-08-18 16:22:08 -06007468 RecordQueueSubmit(queue, fence, result);
7469}
7470void SyncValidator::PostCallRecordQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits, VkFence fence,
7471 VkResult result) {
7472 StateTracker::PostCallRecordQueueSubmit2(queue, submitCount, pSubmits, fence, result);
7473 RecordQueueSubmit(queue, fence, result);
John Zulaufbbda4572022-04-19 16:20:45 -06007474}
7475
John Zulauf3da08bb2022-08-01 17:56:56 -06007476void SyncValidator::PostCallRecordGetFenceStatus(VkDevice device, VkFence fence, VkResult result) {
7477 StateTracker::PostCallRecordGetFenceStatus(device, fence, result);
7478 if (!enabled[sync_validation_queue_submit]) return;
7479 if (result == VK_SUCCESS) {
7480 // fence is signalled, mark it as waited for
7481 WaitForFence(fence);
7482 }
7483}
7484
7485void SyncValidator::PostCallRecordWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll,
7486 uint64_t timeout, VkResult result) {
7487 StateTracker::PostCallRecordWaitForFences(device, fenceCount, pFences, waitAll, timeout, result);
7488 if (!enabled[sync_validation_queue_submit]) return;
7489 if ((result == VK_SUCCESS) && ((VK_TRUE == waitAll) || (1 == fenceCount))) {
7490 // We can only know the pFences have signal if we waited for all of them, or there was only one of them
7491 for (uint32_t i = 0; i < fenceCount; i++) {
7492 WaitForFence(pFences[i]);
7493 }
7494 }
7495}
7496
John Zulaufd0ec59f2021-03-13 14:25:08 -07007497AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7498 : view_(view), view_mask_(), gen_store_() {
7499 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7500 const IMAGE_STATE &image_state = *view_->image_state.get();
7501 const auto base_address = ResourceBaseAddress(image_state);
7502 const auto *encoder = image_state.fragment_encoder.get();
7503 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007504 // Get offset and extent for the view, accounting for possible depth slicing
7505 const VkOffset3D zero_offset = view->GetOffset();
7506 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007507 // Intentional copy
7508 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7509 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007510 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7511 view->IsDepthSliced());
7512 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007513
7514 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7515 if (depth && (depth != view_mask_)) {
7516 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007517 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007518 }
7519 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7520 if (stencil && (stencil != view_mask_)) {
7521 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007522 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7523 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007524 }
7525}
7526
7527const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7528 const ImageRangeGen *got = nullptr;
7529 switch (gen_type) {
7530 case kViewSubresource:
7531 got = &gen_store_[kViewSubresource];
7532 break;
7533 case kRenderArea:
7534 got = &gen_store_[kRenderArea];
7535 break;
7536 case kDepthOnlyRenderArea:
7537 got =
7538 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7539 break;
7540 case kStencilOnlyRenderArea:
7541 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7542 : &gen_store_[Gen::kStencilOnlyRenderArea];
7543 break;
7544 default:
7545 assert(got);
7546 }
7547 return got;
7548}
7549
7550AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7551 assert(IsValid());
7552 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7553 if (depth_op) {
7554 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7555 if (stencil_op) {
7556 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7557 return kRenderArea;
7558 }
7559 return kDepthOnlyRenderArea;
7560 }
7561 if (stencil_op) {
7562 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7563 return kStencilOnlyRenderArea;
7564 }
7565
7566 assert(depth_op || stencil_op);
7567 return kRenderArea;
7568}
7569
7570AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007571
John Zulaufe0757ba2022-06-10 16:51:45 -06007572void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007573 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7574 for (auto &event_pair : map_) {
7575 assert(event_pair.second); // Shouldn't be storing empty
7576 auto &sync_event = *event_pair.second;
7577 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
John Zulaufe0757ba2022-06-10 16:51:45 -06007578 // But only if occuring before the tag
7579 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007580 sync_event.barriers |= dst.exec_scope;
7581 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7582 }
7583 }
7584}
John Zulaufbb890452021-12-14 11:30:18 -07007585
John Zulaufe0757ba2022-06-10 16:51:45 -06007586void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7587 const SyncExecScope src_scope =
7588 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7589 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7590 ApplyBarrier(src_scope, dst_scope, tag);
7591}
7592
7593SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7594 // We need a deep copy of the const context to update during validation phase
7595 for (const auto &event : from.map_) {
7596 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7597 }
7598 return *this;
7599}
7600
John Zulauf8a7b03d2022-09-20 11:41:19 -06007601void SyncEventsContext::AddReferencedTags(ResourceUsageTagSet &referenced) const {
7602 for (const auto &event : map_) {
7603 const std::shared_ptr<const SyncEventState> &event_state = event.second;
7604 if (event_state) {
7605 event_state->AddReferencedTags(referenced);
7606 }
7607 }
7608}
7609
7610QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state, uint64_t submit_index,
7611 uint32_t batch_index)
John Zulaufdab327f2022-07-08 12:02:05 -06007612 : CommandExecutionContext(&sync_state),
7613 queue_state_(&queue_state),
7614 tag_range_(0, 0),
7615 current_access_context_(&access_context_),
John Zulauf8a7b03d2022-09-20 11:41:19 -06007616 batch_log_(),
7617 batch_(queue_state, submit_index, batch_index) {}
7618
7619void QueueBatchContext::Trim() {
7620 // Clean up unneeded access context contents and log information
7621 access_context_.Trim();
7622
7623 ResourceUsageTagSet used_tags;
7624 access_context_.AddReferencedTags(used_tags);
7625
7626 // Note: AccessContexts in the SyncEventsState are trimmed when created.
7627 events_context_.AddReferencedTags(used_tags);
7628
7629 // Only conserve AccessLog references that are referenced by used_tags
7630 batch_log_.Trim(used_tags);
7631}
John Zulaufcb7e1672022-05-04 13:46:08 -06007632
John Zulauf1d5f9c12022-05-13 14:51:08 -06007633void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007634 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007635}
John Zulauf697c0e12022-04-19 16:31:12 -06007636
7637VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7638
John Zulauf1d5f9c12022-05-13 14:51:08 -06007639void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
John Zulauf3da08bb2022-08-01 17:56:56 -06007640 ResourceAccessState::QueueTagPredicate predicate{queue_id, tag};
7641 access_context_.EraseIf([&predicate](ResourceAccessRangeMap::value_type &access) {
7642 // Apply..Wait returns true if the waited access is empty...
7643 return access.second.ApplyQueueTagWait(predicate);
7644 });
John Zulaufe0757ba2022-06-10 16:51:45 -06007645
7646 if (queue_id == GetQueueId()) {
7647 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7648 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007649}
7650
7651// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007652void QueueBatchContext::ApplyDeviceWait() {
7653 access_context_.Reset();
7654 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7655}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007656
John Zulaufdab327f2022-07-08 12:02:05 -06007657HazardResult QueueBatchContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
7658 // Queue batch handling requires dealing with renderpass state and picking the correct access context
7659 if (rp_replay_) {
7660 return rp_replay_.replay_context->DetectFirstUseHazard(GetQueueId(), tag_range, *current_access_context_);
7661 }
7662 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, access_context_);
7663}
7664
7665void QueueBatchContext::BeginRenderPassReplay(const SyncOpBeginRenderPass &begin_op, const ResourceUsageTag tag) {
7666 current_access_context_ = rp_replay_.Begin(GetQueueFlags(), begin_op, access_context_);
7667 current_access_context_->ResolvePreviousAccesses();
7668}
7669
7670void QueueBatchContext::NextSubpassReplay() {
7671 current_access_context_ = rp_replay_.Next();
7672 current_access_context_->ResolvePreviousAccesses();
7673}
7674
7675void QueueBatchContext::EndRenderPassReplay() {
7676 rp_replay_.End(access_context_);
7677 current_access_context_ = &access_context_;
7678}
7679
7680AccessContext *QueueBatchContext::RenderPassReplayState::Begin(VkQueueFlags queue_flags, const SyncOpBeginRenderPass &begin_op_,
7681 const AccessContext &external_context) {
7682 Reset();
7683
7684 begin_op = &begin_op_;
7685 subpass = 0;
7686
7687 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7688 assert(rp_context);
7689 replay_context = &rp_context->GetContexts()[0];
7690
7691 InitSubpassContexts(queue_flags, *rp_context->GetRenderPassState(), &external_context, subpass_contexts);
7692 return &subpass_contexts[0];
7693}
7694
7695AccessContext *QueueBatchContext::RenderPassReplayState::Next() {
7696 subpass++;
7697
7698 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7699
7700 replay_context = &rp_context->GetContexts()[subpass];
7701 return &subpass_contexts[subpass];
7702}
7703
7704void QueueBatchContext::RenderPassReplayState::End(AccessContext &external_context) {
7705 external_context.ResolveChildContexts(subpass_contexts);
7706 Reset();
7707}
7708
John Zulaufecf4ac52022-06-06 10:08:42 -06007709class ApplySemaphoreBarrierAction {
7710 public:
7711 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7712 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7713
7714 private:
7715 const SemaphoreScope &signal_;
7716 const SemaphoreScope wait_;
7717};
7718
7719std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7720 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007721 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007722 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007723
John Zulaufcb7e1672022-05-04 13:46:08 -06007724 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7725 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007726 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007727
John Zulaufecf4ac52022-06-06 10:08:42 -06007728 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007729
John Zulaufecf4ac52022-06-06 10:08:42 -06007730 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007731 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007732 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7733 if (signal_scope.queue == wait_scope.queue) {
7734 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7735 // valid accesses for the sync scope.
7736 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7737 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7738 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007739 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007740 } else {
7741 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7742 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007743 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007744 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7745 // enforce deep constness.
7746 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007747}
7748
John Zulaufa8700a52022-08-18 16:22:08 -06007749void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const VkSubmitInfo2 &submit_info,
John Zulaufcb7e1672022-05-04 13:46:08 -06007750 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007751 // Copy in the event state from the previous batch (on this queue)
7752 if (prev) {
7753 events_context_.DeepCopy(prev->events_context_);
7754 }
7755
John Zulaufecf4ac52022-06-06 10:08:42 -06007756 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7757 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
John Zulaufa8700a52022-08-18 16:22:08 -06007758 const uint32_t wait_count = submit_info.waitSemaphoreInfoCount;
7759 const VkSemaphoreSubmitInfo *wait_infos = submit_info.pWaitSemaphoreInfos;
7760 for (const auto &wait_info : layer_data::make_span(wait_infos, wait_count)) {
7761 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(wait_info.semaphore, wait_info.stageMask, signaled);
John Zulaufecf4ac52022-06-06 10:08:42 -06007762 if (resolved) {
7763 batches_resolved.emplace(std::move(resolved));
7764 }
John Zulaufa8700a52022-08-18 16:22:08 -06007765 }
John Zulauf697c0e12022-04-19 16:31:12 -06007766
John Zulaufecf4ac52022-06-06 10:08:42 -06007767 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7768 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7769 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf8a7b03d2022-09-20 11:41:19 -06007770 batches_resolved.emplace(prev);
7771 }
7772
7773 // Get all the log information for the resolved contexts
7774 for (const auto &batch : batches_resolved) {
7775 batch_log_.Import(batch->batch_log_);
John Zulauf78cb2082022-04-20 16:37:48 -06007776 }
7777
John Zulauf697c0e12022-04-19 16:31:12 -06007778 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007779 async_batches_ =
John Zulauf8a7b03d2022-09-20 11:41:19 -06007780 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved](const std::shared_ptr<const QueueBatchContext> &batch) {
7781 return !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007782 });
7783 for (const auto &async_batch : async_batches_) {
7784 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
John Zulauf8a7b03d2022-09-20 11:41:19 -06007785 // We need to snapshot the async log information for async hazard reporting
7786 batch_log_.Import(async_batch->batch_log_);
John Zulauf697c0e12022-04-19 16:31:12 -06007787 }
7788}
7789
John Zulaufa8700a52022-08-18 16:22:08 -06007790void QueueBatchContext::SetupCommandBufferInfo(const VkSubmitInfo2 &submit_info) {
John Zulauf697c0e12022-04-19 16:31:12 -06007791 // Create the list of command buffers to submit
John Zulaufa8700a52022-08-18 16:22:08 -06007792 const uint32_t cb_count = submit_info.commandBufferInfoCount;
7793 const VkCommandBufferSubmitInfo *const cb_infos = submit_info.pCommandBufferInfos;
John Zulauf697c0e12022-04-19 16:31:12 -06007794 command_buffers_.reserve(cb_count);
John Zulaufa8700a52022-08-18 16:22:08 -06007795
7796 for (const auto &cb_info : layer_data::make_span(cb_infos, cb_count)) {
7797 auto cb_context = sync_state_->GetAccessContextShared(cb_info.commandBuffer);
John Zulauf697c0e12022-04-19 16:31:12 -06007798 if (cb_context) {
7799 tag_range_.end += cb_context->GetTagLimit();
John Zulaufa8700a52022-08-18 16:22:08 -06007800 command_buffers_.emplace_back(static_cast<uint32_t>(&cb_info - cb_infos), std::move(cb_context));
John Zulauf697c0e12022-04-19 16:31:12 -06007801 }
7802 }
7803}
7804
7805// Look up the usage informaiton from the local or global logger
7806std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
John Zulauf697c0e12022-04-19 16:31:12 -06007807 std::stringstream out;
John Zulauf8a7b03d2022-09-20 11:41:19 -06007808 BatchAccessLog::AccessRecord access = batch_log_[tag];
John Zulauf697c0e12022-04-19 16:31:12 -06007809 if (access.IsValid()) {
John Zulauf8a7b03d2022-09-20 11:41:19 -06007810 const BatchAccessLog::BatchRecord &batch = *access.batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007811 const ResourceUsageRecord &record = *access.record;
7812 // Queue and Batch information
7813 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7814 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7815
7816 // Commandbuffer Usages Information
John Zulauf3298da92022-09-01 13:58:39 -06007817 out << ", " << record;
7818 out << ", " << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf697c0e12022-04-19 16:31:12 -06007819 out << ", reset_no: " << std::to_string(record.reset_count);
7820 }
7821 return out.str();
7822}
7823
7824VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7825
John Zulauf00119522022-05-23 19:07:42 -06007826QueueId QueueBatchContext::GetQueueId() const {
7827 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7828 return id;
7829}
7830
John Zulauf8a7b03d2022-09-20 11:41:19 -06007831void QueueBatchContext::SetupBatchTags() {
John Zulauf697c0e12022-04-19 16:31:12 -06007832 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7833 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7834 SetTagBias(global_tags.begin);
John Zulauf697c0e12022-04-19 16:31:12 -06007835}
7836
7837void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
John Zulauf8a7b03d2022-09-20 11:41:19 -06007838 const ResourceUsageTag end_tag = batch_log_.Import(batch_, submitted_cb);
7839 batch_.bias = end_tag;
7840 batch_.cb_index++;
John Zulauf697c0e12022-04-19 16:31:12 -06007841}
7842
7843void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7844 const auto size = tag_range_.size();
7845 tag_range_.begin = bias;
7846 tag_range_.end = bias + size;
7847 access_context_.SetStartTag(bias);
John Zulauf8a7b03d2022-09-20 11:41:19 -06007848 batch_.bias = bias;
John Zulauf697c0e12022-04-19 16:31:12 -06007849}
7850
7851// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7852// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7853// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7854// the contexts Resolve all history from previous all contexts when created
7855void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7856 last_batch_ = std::move(last);
John Zulauf697c0e12022-04-19 16:31:12 -06007857}
7858
7859// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7860// scope state.
7861// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7862// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7863uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7864
John Zulaufecf4ac52022-06-06 10:08:42 -06007865// This is a const method, force the returned value to be const
7866std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007867 std::shared_ptr<Signal> prev_state;
7868 if (prev_) {
7869 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7870 }
7871 return prev_state;
7872}
John Zulaufecf4ac52022-06-06 10:08:42 -06007873
7874SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7875 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7876 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7877 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7878 assert(batch);
7879 assert(sem_state);
7880}
John Zulauf3da08bb2022-08-01 17:56:56 -06007881
7882FenceSyncState::FenceSyncState() : fence(), tag(kInvalidTag), queue_id(QueueSyncState::kQueueIdInvalid) {}
John Zulaufa8700a52022-08-18 16:22:08 -06007883
7884VkSemaphoreSubmitInfo SubmitInfoConverter::BatchStore::WaitSemaphore(const VkSubmitInfo &info, uint32_t index) {
7885 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7886 semaphore_info.semaphore = info.pWaitSemaphores[index];
7887 semaphore_info.stageMask = info.pWaitDstStageMask[index];
7888 return semaphore_info;
7889}
7890VkCommandBufferSubmitInfo SubmitInfoConverter::BatchStore::CommandBuffer(const VkSubmitInfo &info, uint32_t index) {
7891 auto cb_info = lvl_init_struct<VkCommandBufferSubmitInfo>();
7892 cb_info.commandBuffer = info.pCommandBuffers[index];
7893 return cb_info;
7894}
7895
7896VkSemaphoreSubmitInfo SubmitInfoConverter::BatchStore::SignalSemaphore(const VkSubmitInfo &info, uint32_t index) {
7897 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7898 semaphore_info.semaphore = info.pSignalSemaphores[index];
7899 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7900 return semaphore_info;
7901}
7902
7903SubmitInfoConverter::BatchStore::BatchStore(const VkSubmitInfo &info) {
7904 info2 = lvl_init_struct<VkSubmitInfo2>();
7905
7906 info2.waitSemaphoreInfoCount = info.waitSemaphoreCount;
7907 waits.reserve(info2.waitSemaphoreInfoCount);
7908 for (uint32_t i = 0; i < info2.waitSemaphoreInfoCount; ++i) {
7909 waits.emplace_back(WaitSemaphore(info, i));
7910 }
7911 info2.pWaitSemaphoreInfos = waits.data();
7912
7913 info2.commandBufferInfoCount = info.commandBufferCount;
7914 cbs.reserve(info2.commandBufferInfoCount);
7915 for (uint32_t i = 0; i < info2.commandBufferInfoCount; ++i) {
7916 cbs.emplace_back(CommandBuffer(info, i));
7917 }
7918 info2.pCommandBufferInfos = cbs.data();
7919
7920 info2.signalSemaphoreInfoCount = info.signalSemaphoreCount;
7921 signals.reserve(info2.signalSemaphoreInfoCount);
7922 for (uint32_t i = 0; i < info2.signalSemaphoreInfoCount; ++i) {
7923 signals.emplace_back(SignalSemaphore(info, i));
7924 }
7925 info2.pSignalSemaphoreInfos = signals.data();
7926}
7927
7928SubmitInfoConverter::SubmitInfoConverter(uint32_t count, const VkSubmitInfo *infos) {
7929 info_store.reserve(count);
7930 info2s.reserve(count);
7931 for (uint32_t batch = 0; batch < count; ++batch) {
7932 info_store.emplace_back(infos[batch]);
7933 info2s.emplace_back(info_store.back().info2);
7934 }
7935}
John Zulauf8a7b03d2022-09-20 11:41:19 -06007936
7937ResourceUsageTag BatchAccessLog::Import(const BatchRecord &batch, const CommandBufferAccessContext &cb_access) {
7938 ResourceUsageTag bias = batch.bias;
7939 ResourceUsageTag tag_limit = bias + cb_access.GetTagLimit();
7940 ResourceUsageRange import_range = {bias, tag_limit};
7941 log_map_.insert(std::make_pair(import_range, CBSubmitLog(batch, cb_access)));
7942 return tag_limit;
7943}
7944
7945void BatchAccessLog::Import(const BatchAccessLog &other) {
7946 for (const auto &entry : other.log_map_) {
7947 log_map_.insert(entry);
7948 }
7949}
7950
7951// Trim: Remove any unreferenced AccessLog ranges from a BatchAccessLog
7952//
7953// In order to contain memory growth in the AccessLog information regarding prior submitted command buffers,
7954// the Trim call removes any AccessLog references that do not correspond to any tags in use. The set of referenced tag, used_tags,
7955// is generated by scanning the AccessContext and EventContext of the containing QueueBatchContext.
7956//
7957// Upon return the BatchAccessLog should only contain references to the AccessLog information needed by the
7958// containing parent QueueBatchContext.
7959//
7960// The algorithm used is another example of the "parallel iteration" pattern common within SyncVal. In this case we are
7961// traversing the ordered range_map containing the AccessLog references and the ordered set of tags in use.
7962//
7963// To efficiently perform the parallel iteration, optimizations within this function include:
7964// * when ranges are detected that have no tags referenced, all ranges between the last tag and the current tag are erased
7965// * when used tags prior to the current range are found, all tags up to the current range are skipped
7966// * when a tag is found within the current range, that range is skipped (and thus kept in the map), and further used tags
7967// within the range are skipped.
7968//
7969// Note that for each subcase, any "next steps" logic is designed to be handled within the subsequent iteration -- meaning that
7970// each subcase simply handles the specifics of the current update/skip/erase action needed, and leaves the iterators in a sensible
7971// state for the top of loop... intentionally eliding special case handling.
7972void BatchAccessLog::Trim(const ResourceUsageTagSet &used_tags) {
7973 auto current_tag = used_tags.cbegin();
7974 const auto end_tag = used_tags.cend();
7975 auto current_map_range = log_map_.begin();
7976 const auto end_map = log_map_.end();
7977
7978 while (current_map_range != end_map) {
7979 if (current_tag == end_tag) {
7980 // We're out of tags, the rest of the map isn't referenced, so erase it
7981 current_map_range = log_map_.erase(current_map_range, end_map);
7982 } else {
7983 auto &range = current_map_range->first;
7984 const ResourceUsageTag tag = *current_tag;
7985 if (tag < range.begin) {
7986 // Skip to the next tag potentially in range
7987 // if this is end_tag, we'll handle that next iteration
7988 current_tag = used_tags.lower_bound(range.begin);
7989 } else if (tag >= range.end) {
7990 // This tag is beyond the current range, delete all ranges between current_map_range,
7991 // and the next that includes the tag. Next is not erased.
7992 auto next_used = log_map_.lower_bound(ResourceUsageRange(tag, tag + 1));
7993 current_map_range = log_map_.erase(current_map_range, next_used);
7994 } else {
7995 // Skip the rest of the tags in this range
7996 // If this is end, the next iteration will handle
7997 current_tag = used_tags.lower_bound(range.end);
7998
7999 // This is a range we will keep, advance to the next. Next iteration handles end condition
8000 ++current_map_range;
8001 }
8002 }
8003 }
8004}
8005
8006BatchAccessLog::AccessRecord BatchAccessLog::operator[](ResourceUsageTag tag) const {
8007 auto found_log = log_map_.find(tag);
8008 if (found_log != log_map_.cend()) {
8009 return found_log->second[tag];
8010 }
8011 assert("tag not found" == nullptr);
8012 return AccessRecord();
8013}
8014
8015BatchAccessLog::AccessRecord BatchAccessLog::CBSubmitLog::operator[](ResourceUsageTag tag) const {
8016 assert(tag >= batch_.bias);
8017 const size_t index = tag - batch_.bias;
8018 assert(log_);
8019 assert(index < log_->size());
8020 return AccessRecord{&batch_, &(*log_)[index]};
8021}