blob: 1b3c8c6e234fe8a4f726b06f1c87baec2ff0088a [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:
91 return "SYNC-HAZARD-READ_AFTER_WRITE";
92 break;
93 case SyncHazard::WRITE_AFTER_READ:
94 return "SYNC-HAZARD-WRITE_AFTER_READ";
95 break;
96 case SyncHazard::WRITE_AFTER_WRITE:
97 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
98 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) {
235 out << ", " << formater.label << ": " << formater.report_data->FormatHandle(formater.node->Handle()).c_str();
236 if (formater.node->Destroyed()) {
237 out << " (destroyed)";
238 }
239 } else {
240 out << ", " << formater.label << ": null handle";
241 }
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
272// NOTE: Make sure the proxy doesn't outlive from, as the proxy is pointing directly to access contexts owned by from.
273CommandBufferAccessContext::CommandBufferAccessContext(const CommandBufferAccessContext &from, AsProxyContext dummy)
274 : CommandBufferAccessContext(from.sync_state_) {
275 // Copy only the needed fields out of from for a temporary, proxy command buffer context
276 cb_state_ = from.cb_state_;
277 queue_flags_ = from.queue_flags_;
278 destroyed_ = from.destroyed_;
279 access_log_ = from.access_log_; // potentially large, but no choice given tagging lookup.
280 command_number_ = from.command_number_;
281 subcommand_number_ = from.subcommand_number_;
282 reset_count_ = from.reset_count_;
283
284 const auto *from_context = from.GetCurrentAccessContext();
285 assert(from_context);
286
287 // Construct a fully resolved single access context out of from
288 const NoopBarrierAction noop_barrier;
289 for (AccessAddressType address_type : kAddressTypes) {
290 from_context->ResolveAccessRange(address_type, kFullRange, noop_barrier,
291 &cb_access_context_.GetAccessStateMap(address_type), nullptr);
292 }
293 // The proxy has flatten the current render pass context (if any), but the async contexts are needed for hazard detection
294 cb_access_context_.ImportAsyncContexts(*from_context);
295
296 events_context_ = from.events_context_;
297
298 // We don't want to copy the full render_pass_context_ history just for the proxy.
299}
300
301std::string CommandBufferAccessContext::FormatUsage(const ResourceUsageTag tag) const {
John Zulauf397e68b2022-04-19 11:44:07 -0600302 if (tag >= access_log_.size()) return std::string();
303
John Zulauf4fa68462021-04-26 21:04:22 -0600304 std::stringstream out;
305 assert(tag < access_log_.size());
306 const auto &record = access_log_[tag];
John Zulauf397e68b2022-04-19 11:44:07 -0600307 out << record;
308 if (cb_state_.get() != record.cb_state) {
309 out << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf4fa68462021-04-26 21:04:22 -0600310 }
John Zulaufd142c9a2022-04-12 14:22:44 -0600311 out << ", reset_no: " << std::to_string(record.reset_count);
John Zulauf4fa68462021-04-26 21:04:22 -0600312 return out.str();
313}
John Zulauf397e68b2022-04-19 11:44:07 -0600314
John Zulauf4fa68462021-04-26 21:04:22 -0600315std::string CommandBufferAccessContext::FormatUsage(const ResourceFirstAccess &access) const {
316 std::stringstream out;
317 out << "(recorded_usage: " << string_UsageIndex(access.usage_index);
318 out << ", " << FormatUsage(access.tag) << ")";
319 return out.str();
320}
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700321
John Zulauf397e68b2022-04-19 11:44:07 -0600322std::string CommandExecutionContext::FormatHazard(const HazardResult &hazard) const {
John Zulauf1dae9192020-06-16 15:46:44 -0600323 std::stringstream out;
John Zulauf397e68b2022-04-19 11:44:07 -0600324 out << hazard;
325 out << ", " << FormatUsage(hazard.tag) << ")";
John Zulauf1dae9192020-06-16 15:46:44 -0600326 return out.str();
327}
328
John Zulaufd14743a2020-07-03 09:42:39 -0600329// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
330// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
331// also reflects this special case for read hazard detection (using access instead of exec scope)
Jeremy Gebben40a22942020-12-22 14:22:06 -0700332static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700333static const SyncStageAccessFlags kColorAttachmentAccessScope =
334 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
335 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
336 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
337 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebben40a22942020-12-22 14:22:06 -0700338static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
339 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 -0700340static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
341 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
342 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
343 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -0700344static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700345static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600346
John Zulauf8e3c3e92021-01-06 11:19:36 -0700347ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700348 {{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
John Zulauf8e3c3e92021-01-06 11:19:36 -0700349 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
350 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
351 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
352
John Zulaufee984022022-04-13 16:39:50 -0600353// Sometimes we have an internal access conflict, and we using the kInvalidTag to set and detect in temporary/proxy contexts
354static const ResourceUsageTag kInvalidTag(ResourceUsageRecord::kMaxIndex);
John Zulaufb027cdb2020-05-21 14:25:22 -0600355
Jeremy Gebben62c3bf42021-07-21 15:38:24 -0600356static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600357
John Zulaufcb7e1672022-05-04 13:46:08 -0600358VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
locke-lunarg3c038002020-04-30 23:08:08 -0600359 if (size == VK_WHOLE_SIZE) {
360 return (whole_size - offset);
361 }
362 return size;
363}
364
John Zulauf3e86bf02020-09-12 10:47:57 -0600365static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
366 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
367}
368
John Zulauf16adfc92020-04-08 10:28:33 -0600369template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600370static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600371 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
372}
373
John Zulauf355e49b2020-04-24 15:11:15 -0600374static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600375
John Zulauf3e86bf02020-09-12 10:47:57 -0600376static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
377 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
378}
379
380static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
381 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
382}
383
John Zulauf4a6105a2020-11-17 15:11:05 -0700384// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
385//
John Zulauf10f1f522020-12-18 12:00:35 -0700386// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
387//
John Zulauf4a6105a2020-11-17 15:11:05 -0700388// Usage:
389// Constructor() -- initializes the generator to point to the begin of the space declared.
390// * -- the current range of the generator empty signfies end
391// ++ -- advance to the next non-empty range (or end)
392
393// A wrapper for a single range with the same semantics as the actual generators below
394template <typename KeyType>
395class SingleRangeGenerator {
396 public:
397 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700398 const KeyType &operator*() const { return current_; }
399 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700400 SingleRangeGenerator &operator++() {
401 current_ = KeyType(); // just one real range
402 return *this;
403 }
404
405 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
406
407 private:
408 SingleRangeGenerator() = default;
409 const KeyType range_;
410 KeyType current_;
411};
412
John Zulaufae842002021-04-15 18:20:55 -0600413// Generate the ranges that are the intersection of range and the entries in the RangeMap
414template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
415class MapRangesRangeGenerator {
John Zulauf4a6105a2020-11-17 15:11:05 -0700416 public:
John Zulaufd5115702021-01-18 12:34:33 -0700417 // Default constructed is safe to dereference for "empty" test, but for no other operation.
John Zulaufae842002021-04-15 18:20:55 -0600418 MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
John Zulaufd5115702021-01-18 12:34:33 -0700419 // Default construction for KeyType *must* be empty range
420 assert(current_.empty());
421 }
John Zulaufae842002021-04-15 18:20:55 -0600422 MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700423 SeekBegin();
424 }
John Zulaufae842002021-04-15 18:20:55 -0600425 MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
John Zulaufd5115702021-01-18 12:34:33 -0700426
John Zulauf4a6105a2020-11-17 15:11:05 -0700427 const KeyType &operator*() const { return current_; }
428 const KeyType *operator->() const { return &current_; }
John Zulaufae842002021-04-15 18:20:55 -0600429 MapRangesRangeGenerator &operator++() {
430 ++map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700431 UpdateCurrent();
432 return *this;
433 }
434
John Zulaufae842002021-04-15 18:20:55 -0600435 bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700436
John Zulaufae842002021-04-15 18:20:55 -0600437 protected:
John Zulauf4a6105a2020-11-17 15:11:05 -0700438 void UpdateCurrent() {
John Zulaufae842002021-04-15 18:20:55 -0600439 if (map_pos_ != map_->cend()) {
440 current_ = range_ & map_pos_->first;
John Zulauf4a6105a2020-11-17 15:11:05 -0700441 } else {
442 current_ = KeyType();
443 }
444 }
445 void SeekBegin() {
John Zulaufae842002021-04-15 18:20:55 -0600446 map_pos_ = map_->lower_bound(range_);
John Zulauf4a6105a2020-11-17 15:11:05 -0700447 UpdateCurrent();
448 }
John Zulaufae842002021-04-15 18:20:55 -0600449
450 // Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
451 // Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
452 template <typename Pred>
453 MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
454 do {
455 ++map_pos_;
456 } while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
457 UpdateCurrent();
458 return *this;
459 }
460
John Zulauf4a6105a2020-11-17 15:11:05 -0700461 const KeyType range_;
John Zulaufae842002021-04-15 18:20:55 -0600462 const RangeMap *map_;
463 typename RangeMap::const_iterator map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700464 KeyType current_;
465};
John Zulaufd5115702021-01-18 12:34:33 -0700466using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulaufae842002021-04-15 18:20:55 -0600467using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700468
John Zulaufae842002021-04-15 18:20:55 -0600469// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
470template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
471class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
472 public:
473 using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
474 // Default constructed is safe to dereference for "empty" test, but for no other operation.
475 PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
476 PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
477 : Base(filter, range), pred_(pred) {}
478 PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
479
480 PredicatedMapRangesRangeGenerator &operator++() {
481 Base::PredicatedIncrement(pred_);
482 return *this;
483 }
484
485 protected:
486 Predicate pred_;
487};
John Zulauf4a6105a2020-11-17 15:11:05 -0700488
489// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulaufae842002021-04-15 18:20:55 -0600490// Templated to allow for different Range generators or map sources...
491template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::key_type>
John Zulauf4a6105a2020-11-17 15:11:05 -0700492class FilteredGeneratorGenerator {
493 public:
John Zulaufd5115702021-01-18 12:34:33 -0700494 // Default constructed is safe to dereference for "empty" test, but for no other operation.
495 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
496 // Default construction for KeyType *must* be empty range
497 assert(current_.empty());
498 }
John Zulaufae842002021-04-15 18:20:55 -0600499 FilteredGeneratorGenerator(const RangeMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700500 SeekBegin();
501 }
John Zulaufd5115702021-01-18 12:34:33 -0700502 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700503 const KeyType &operator*() const { return current_; }
504 const KeyType *operator->() const { return &current_; }
505 FilteredGeneratorGenerator &operator++() {
506 KeyType gen_range = GenRange();
507 KeyType filter_range = FilterRange();
508 current_ = KeyType();
509 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
510 if (gen_range.end > filter_range.end) {
511 // if the generated range is beyond the filter_range, advance the filter range
512 filter_range = AdvanceFilter();
513 } else {
514 gen_range = AdvanceGen();
515 }
516 current_ = gen_range & filter_range;
517 }
518 return *this;
519 }
520
521 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
522
523 private:
524 KeyType AdvanceFilter() {
525 ++filter_pos_;
526 auto filter_range = FilterRange();
527 if (filter_range.valid()) {
528 FastForwardGen(filter_range);
529 }
530 return filter_range;
531 }
532 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700533 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700534 auto gen_range = GenRange();
535 if (gen_range.valid()) {
536 FastForwardFilter(gen_range);
537 }
538 return gen_range;
539 }
540
541 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700542 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700543
544 KeyType FastForwardFilter(const KeyType &range) {
545 auto filter_range = FilterRange();
546 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700547 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700548 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
549 if (retry_count < kRetryLimit) {
550 ++filter_pos_;
551 filter_range = FilterRange();
552 retry_count++;
553 } else {
554 // Okay we've tried walking, do a seek.
555 filter_pos_ = filter_->lower_bound(range);
556 break;
557 }
558 }
559 return FilterRange();
560 }
561
562 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
563 // faster.
564 KeyType FastForwardGen(const KeyType &range) {
565 auto gen_range = GenRange();
566 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700567 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700568 gen_range = GenRange();
569 }
570 return gen_range;
571 }
572
573 void SeekBegin() {
574 auto gen_range = GenRange();
575 if (gen_range.empty()) {
576 current_ = KeyType();
577 filter_pos_ = filter_->cend();
578 } else {
579 filter_pos_ = filter_->lower_bound(gen_range);
580 current_ = gen_range & FilterRange();
581 }
582 }
583
John Zulaufae842002021-04-15 18:20:55 -0600584 const RangeMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700585 RangeGen gen_;
John Zulaufae842002021-04-15 18:20:55 -0600586 typename RangeMap::const_iterator filter_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700587 KeyType current_;
588};
589
590using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
591
John Zulauf5c5e88d2019-12-26 11:22:02 -0700592
John Zulauf3e86bf02020-09-12 10:47:57 -0600593ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
594 VkDeviceSize stride) {
595 VkDeviceSize range_start = offset + first_index * stride;
596 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600597 if (count == UINT32_MAX) {
598 range_size = buf_whole_size - range_start;
599 } else {
600 range_size = count * stride;
601 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600602 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600603}
604
locke-lunarg654e3692020-06-04 17:19:15 -0600605SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
606 VkShaderStageFlagBits stage_flag) {
607 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
608 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
609 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
610 }
611 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
612 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
613 assert(0);
614 }
615 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
616 return stage_access->second.uniform_read;
617 }
618
619 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
620 // Because if write hazard happens, read hazard might or might not happen.
621 // But if write hazard doesn't happen, read hazard is impossible to happen.
622 if (descriptor_data.is_writable) {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700623 return stage_access->second.storage_write;
locke-lunarg654e3692020-06-04 17:19:15 -0600624 }
Jeremy Gebben40a22942020-12-22 14:22:06 -0700625 // TODO: sampled_read
626 return stage_access->second.storage_read;
locke-lunarg654e3692020-06-04 17:19:15 -0600627}
628
locke-lunarg37047832020-06-12 13:44:45 -0600629bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
630 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
631 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
632 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
633 ? true
634 : false;
635}
636
637bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
638 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
639 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
640 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
641 ? true
642 : false;
643}
644
John Zulauf355e49b2020-04-24 15:11:15 -0600645// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600646template <typename Action>
647static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
648 Action &action) {
649 // At this point the "apply over range" logic only supports a single memory binding
650 if (!SimpleBinding(image_state)) return;
651 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600652 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700653 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
Aitor Camachoe67f2c72022-06-08 14:41:58 +0200654 image_state.createInfo.extent, base_address, false);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600655 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700656 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600657 }
658}
659
John Zulauf7635de32020-05-29 17:14:15 -0600660// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
661// Used by both validation and record operations
662//
663// The signature for Action() reflect the needs of both uses.
664template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -0700665void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
666 uint32_t subpass) {
John Zulauf7635de32020-05-29 17:14:15 -0600667 const auto &rp_ci = rp_state.createInfo;
668 const auto *attachment_ci = rp_ci.pAttachments;
669 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
670
671 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
672 const auto *color_attachments = subpass_ci.pColorAttachments;
673 const auto *color_resolve = subpass_ci.pResolveAttachments;
674 if (color_resolve && color_attachments) {
675 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
676 const auto &color_attach = color_attachments[i].attachment;
677 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
678 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
679 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700680 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
681 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600682 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700683 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
684 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600685 }
686 }
687 }
688
689 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700690 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600691 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
692 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
693 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
694 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
695 const auto src_ci = attachment_ci[src_at];
696 // The formats are required to match so we can pick either
697 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
698 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
699 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
John Zulauf7635de32020-05-29 17:14:15 -0600700
701 // Figure out which aspects are actually touched during resolve operations
702 const char *aspect_string = nullptr;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700703 AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600704 if (resolve_depth && resolve_stencil) {
John Zulauf7635de32020-05-29 17:14:15 -0600705 aspect_string = "depth/stencil";
706 } else if (resolve_depth) {
707 // Validate depth only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700708 gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600709 aspect_string = "depth";
710 } else if (resolve_stencil) {
711 // Validate all stencil only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700712 gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600713 aspect_string = "stencil";
714 }
715
John Zulaufd0ec59f2021-03-13 14:25:08 -0700716 if (aspect_string) {
717 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
718 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
719 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
720 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulauf7635de32020-05-29 17:14:15 -0600721 }
722 }
723}
724
725// Action for validating resolve operations
726class ValidateResolveAction {
727 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700728 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
sjfricke0bea06e2022-06-05 09:22:26 +0900729 const CommandExecutionContext &exec_context, CMD_TYPE cmd_type)
John Zulauf7635de32020-05-29 17:14:15 -0600730 : render_pass_(render_pass),
731 subpass_(subpass),
732 context_(context),
John Zulaufbb890452021-12-14 11:30:18 -0700733 exec_context_(exec_context),
sjfricke0bea06e2022-06-05 09:22:26 +0900734 cmd_type_(cmd_type),
John Zulauf7635de32020-05-29 17:14:15 -0600735 skip_(false) {}
736 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 -0700737 const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage,
738 SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600739 HazardResult hazard;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700740 hazard = context_.DetectHazard(view_gen, gen_type, current_usage, ordering_rule);
John Zulauf7635de32020-05-29 17:14:15 -0600741 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +0900742 skip_ |= exec_context_.GetSyncState().LogError(
743 render_pass_, string_SyncHazardVUID(hazard.hazard),
744 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32 " to resolve attachment %" PRIu32
745 ". Access info %s.",
746 CommandTypeString(cmd_type_), string_SyncHazard(hazard.hazard), subpass_, aspect_name, attachment_name, src_at,
747 dst_at, exec_context_.FormatHazard(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600748 }
749 }
750 // Providing a mechanism for the constructing caller to get the result of the validation
751 bool GetSkip() const { return skip_; }
752
753 private:
754 VkRenderPass render_pass_;
755 const uint32_t subpass_;
756 const AccessContext &context_;
John Zulaufbb890452021-12-14 11:30:18 -0700757 const CommandExecutionContext &exec_context_;
sjfricke0bea06e2022-06-05 09:22:26 +0900758 CMD_TYPE cmd_type_;
John Zulauf7635de32020-05-29 17:14:15 -0600759 bool skip_;
760};
761
762// Update action for resolve operations
763class UpdateStateResolveAction {
764 public:
John Zulauf14940722021-04-12 15:19:02 -0600765 UpdateStateResolveAction(AccessContext &context, ResourceUsageTag tag) : context_(context), tag_(tag) {}
John Zulaufd0ec59f2021-03-13 14:25:08 -0700766 void operator()(const char *, const char *, uint32_t, uint32_t, const AttachmentViewGen &view_gen,
767 AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600768 // Ignores validation only arguments...
John Zulaufd0ec59f2021-03-13 14:25:08 -0700769 context_.UpdateAccessState(view_gen, gen_type, current_usage, ordering_rule, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600770 }
771
772 private:
773 AccessContext &context_;
John Zulauf14940722021-04-12 15:19:02 -0600774 const ResourceUsageTag tag_;
John Zulauf7635de32020-05-29 17:14:15 -0600775};
776
John Zulauf59e25072020-07-17 10:55:21 -0600777void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
John Zulauf14940722021-04-12 15:19:02 -0600778 const SyncStageAccessFlags &prior_, const ResourceUsageTag tag_) {
John Zulauf4fa68462021-04-26 21:04:22 -0600779 access_state = layer_data::make_unique<const ResourceAccessState>(*access_state_);
John Zulauf59e25072020-07-17 10:55:21 -0600780 usage_index = usage_index_;
781 hazard = hazard_;
782 prior_access = prior_;
783 tag = tag_;
784}
785
John Zulauf4fa68462021-04-26 21:04:22 -0600786void HazardResult::AddRecordedAccess(const ResourceFirstAccess &first_access) {
787 recorded_access = layer_data::make_unique<const ResourceFirstAccess>(first_access);
788}
789
John Zulauf1d5f9c12022-05-13 14:51:08 -0600790void AccessContext::DeleteAccess(const AddressRange &address) { GetAccessStateMap(address.type).erase_range(address.range); }
791
John Zulauf540266b2020-04-06 18:54:53 -0600792AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
793 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600794 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600795 Reset();
796 const auto &subpass_dep = dependencies[subpass];
John Zulauf22aefed2021-03-11 18:14:35 -0700797 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
798 prev_.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
John Zulauf355e49b2020-04-24 15:11:15 -0600799 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600800 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600801 const auto prev_pass = prev_dep.first->pass;
802 const auto &prev_barriers = prev_dep.second;
803 assert(prev_dep.second.size());
804 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
805 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700806 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600807
808 async_.reserve(subpass_dep.async.size());
809 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700810 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600811 }
John Zulauf22aefed2021-03-11 18:14:35 -0700812 if (has_barrier_from_external) {
813 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
814 prev_.emplace_back(external_context, queue_flags, subpass_dep.barrier_from_external);
815 src_external_ = &prev_.back();
John Zulaufe5da6e52020-03-18 15:32:18 -0600816 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600817 if (subpass_dep.barrier_to_external.size()) {
818 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600819 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700820}
821
John Zulauf5f13a792020-03-10 07:31:21 -0600822template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600823HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600824 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600825 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600826 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600827
828 HazardResult hazard;
829 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
830 hazard = detector.Detect(prev);
831 }
832 return hazard;
833}
834
John Zulauf4a6105a2020-11-17 15:11:05 -0700835template <typename Action>
836void AccessContext::ForAll(Action &&action) {
837 for (const auto address_type : kAddressTypes) {
838 auto &accesses = GetAccessStateMap(address_type);
John Zulauf1d5f9c12022-05-13 14:51:08 -0600839 for (auto &access : accesses) {
John Zulauf4a6105a2020-11-17 15:11:05 -0700840 action(address_type, access);
841 }
842 }
843}
844
John Zulauf3d84f1b2020-03-09 13:33:25 -0600845// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
846// the DAG of the contexts (for example subpasses)
847template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600848HazardResult AccessContext::DetectHazard(AccessAddressType type, Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600849 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600850 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600851
John Zulauf1a224292020-06-30 14:52:13 -0600852 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600853 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
854 // so we'll check these first
855 for (const auto &async_context : async_) {
856 hazard = async_context->DetectAsyncHazard(type, detector, range);
857 if (hazard.hazard) return hazard;
858 }
John Zulauf5f13a792020-03-10 07:31:21 -0600859 }
860
John Zulauf1a224292020-06-30 14:52:13 -0600861 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600862
John Zulauf69133422020-05-20 14:55:53 -0600863 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600864 const auto the_end = accesses.cend(); // End is not invalidated
865 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600866 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600867
John Zulauf3cafbf72021-03-26 16:55:19 -0600868 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600869 // Cover any leading gap, or gap between entries
870 if (detect_prev) {
871 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
872 // Cover any leading gap, or gap between entries
873 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600874 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600875 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600876 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600877 if (hazard.hazard) return hazard;
878 }
John Zulauf69133422020-05-20 14:55:53 -0600879 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
880 gap.begin = pos->first.end;
881 }
882
883 hazard = detector.Detect(pos);
884 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600885 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600886 }
887
888 if (detect_prev) {
889 // Detect in the trailing empty as needed
890 gap.end = range.end;
891 if (gap.non_empty()) {
892 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600893 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600894 }
895
896 return hazard;
897}
898
899// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
900template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700901HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
902 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600903 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600904 auto pos = accesses.lower_bound(range);
905 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600906
John Zulauf3d84f1b2020-03-09 13:33:25 -0600907 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600908 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700909 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600910 if (hazard.hazard) break;
911 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600912 }
John Zulauf16adfc92020-04-08 10:28:33 -0600913
John Zulauf3d84f1b2020-03-09 13:33:25 -0600914 return hazard;
915}
916
John Zulaufb02c1eb2020-10-06 16:33:36 -0600917struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700918 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600919 void operator()(ResourceAccessState *access) const {
920 assert(access);
921 access->ApplyBarriers(barriers, true);
922 }
923 const std::vector<SyncBarrier> &barriers;
924};
925
John Zulaufe0757ba2022-06-10 16:51:45 -0600926struct QueueTagOffsetBarrierAction {
927 QueueTagOffsetBarrierAction(QueueId qid, ResourceUsageTag offset) : queue_id(qid), tag_offset(offset) {}
928 void operator()(ResourceAccessState *access) const {
929 access->OffsetTag(tag_offset);
930 access->SetQueueId(queue_id);
931 };
932 QueueId queue_id;
933 ResourceUsageTag tag_offset;
934};
935
John Zulauf22aefed2021-03-11 18:14:35 -0700936struct ApplyTrackbackStackAction {
937 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
938 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
939 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600940 void operator()(ResourceAccessState *access) const {
941 assert(access);
942 assert(!access->HasPendingState());
943 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600944 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
945 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700946 if (previous_barrier) {
947 assert(bool(*previous_barrier));
948 (*previous_barrier)(access);
949 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600950 }
951 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700952 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600953};
954
955// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
956// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
957// *different* map from dest.
958// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
959// range [first, last)
960template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600961static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
962 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600963 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600964 auto at = entry;
965 for (auto pos = first; pos != last; ++pos) {
966 // Every member of the input iterator range must fit within the remaining portion of entry
967 assert(at->first.includes(pos->first));
968 assert(at != dest->end());
969 // Trim up at to the same size as the entry to resolve
970 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600971 auto access = pos->second; // intentional copy
972 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600973 at->second.Resolve(access);
974 ++at; // Go to the remaining unused section of entry
975 }
976}
977
John Zulaufa0a98292020-09-18 09:30:10 -0600978static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
979 SyncBarrier merged = {};
980 for (const auto &barrier : barriers) {
981 merged.Merge(barrier);
982 }
983 return merged;
984}
985
John Zulaufb02c1eb2020-10-06 16:33:36 -0600986template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700987void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600988 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
989 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600990 if (!range.non_empty()) return;
991
John Zulauf355e49b2020-04-24 15:11:15 -0600992 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
993 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600994 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -0600995 if (current->pos_B->valid) {
996 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600997 auto access = src_pos->second; // intentional copy
998 barrier_action(&access);
999
John Zulauf16adfc92020-04-08 10:28:33 -06001000 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001001 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
1002 trimmed->second.Resolve(access);
1003 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -06001004 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001005 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -06001006 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -06001007 }
John Zulauf16adfc92020-04-08 10:28:33 -06001008 } else {
1009 // we have to descend to fill this gap
1010 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001011 ResourceAccessRange recurrence_range = current_range;
1012 // The current context is empty for the current range, so recur to fill the gap.
1013 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1014 // is not valid, to minimize that recurrence
1015 if (current->pos_B.at_end()) {
1016 // Do the remainder here....
1017 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001018 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001019 // Recur only over the range until B becomes valid (within the limits of range).
1020 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001021 }
John Zulauf22aefed2021-03-11 18:14:35 -07001022 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1023
John Zulauf355e49b2020-04-24 15:11:15 -06001024 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1025 // iterator of the outer while.
1026
1027 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1028 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1029 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001030 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 -06001031 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001032 current.seek(seek_to);
1033 } else if (!current->pos_A->valid && infill_state) {
1034 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1035 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1036 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001037 }
John Zulauf5f13a792020-03-10 07:31:21 -06001038 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001039 if (current->range.non_empty()) {
1040 ++current;
1041 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001042 }
John Zulauf1a224292020-06-30 14:52:13 -06001043
1044 // Infill if range goes passed both the current and resolve map prior contents
1045 if (recur_to_infill && (current->range.end < range.end)) {
1046 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001047 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001048 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001049}
1050
John Zulauf22aefed2021-03-11 18:14:35 -07001051template <typename BarrierAction>
1052void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1053 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1054 const BarrierAction &previous_barrier) const {
1055 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1056 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1057}
1058
John Zulauf43cc7462020-12-03 12:33:12 -07001059void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001060 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1061 const ResourceAccessStateFunction *previous_barrier) const {
1062 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001063 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001064 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1065 ResourceAccessState state_copy;
1066 if (previous_barrier) {
1067 assert(bool(*previous_barrier));
1068 state_copy = *infill_state;
1069 (*previous_barrier)(&state_copy);
1070 infill_state = &state_copy;
1071 }
1072 sparse_container::update_range_value(*descent_map, range, *infill_state,
1073 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001074 }
1075 } else {
1076 // Look for something to fill the gap further along.
1077 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001078 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001079 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001080 }
John Zulauf5f13a792020-03-10 07:31:21 -06001081 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001082}
1083
John Zulauf4a6105a2020-11-17 15:11:05 -07001084// Non-lazy import of all accesses, WaitEvents needs this.
1085void AccessContext::ResolvePreviousAccesses() {
1086 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001087 if (!prev_.size()) return; // If no previous contexts, nothing to do
1088
John Zulauf4a6105a2020-11-17 15:11:05 -07001089 for (const auto address_type : kAddressTypes) {
1090 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1091 }
1092}
1093
John Zulauf43cc7462020-12-03 12:33:12 -07001094AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1095 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001096}
1097
John Zulauf1507ee42020-05-18 11:33:09 -06001098static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001099 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1100 ? SYNC_ACCESS_INDEX_NONE
1101 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1102 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001103 return stage_access;
1104}
1105static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001106 const auto stage_access =
1107 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1108 ? SYNC_ACCESS_INDEX_NONE
1109 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1110 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001111 return stage_access;
1112}
1113
John Zulauf7635de32020-05-29 17:14:15 -06001114// Caller must manage returned pointer
1115static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001116 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001117 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001118 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1119 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001120 return proxy;
1121}
1122
John Zulaufb02c1eb2020-10-06 16:33:36 -06001123template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001124void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1125 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1126 const ResourceAccessState *infill_state) const {
1127 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1128 if (!attachment_gen) return;
1129
1130 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1131 const AccessAddressType address_type = view_gen.GetAddressType();
1132 for (; range_gen->non_empty(); ++range_gen) {
1133 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001134 }
John Zulauf62f10592020-04-03 12:20:02 -06001135}
1136
John Zulauf1d5f9c12022-05-13 14:51:08 -06001137template <typename ResolveOp>
1138void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1139 const ResourceAccessState *infill_state, bool recur_to_infill) {
1140 for (auto address_type : kAddressTypes) {
1141 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1142 recur_to_infill);
1143 }
1144}
1145
John Zulauf7635de32020-05-29 17:14:15 -06001146// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001147bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001148 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001149 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001150 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001151 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1152 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1153 // those affects have not been recorded yet.
1154 //
1155 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1156 // to apply and only copy then, if this proves a hot spot.
1157 std::unique_ptr<AccessContext> proxy_for_prev;
1158 TrackBack proxy_track_back;
1159
John Zulauf355e49b2020-04-24 15:11:15 -06001160 const auto &transitions = rp_state.subpass_transitions[subpass];
1161 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001162 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1163
1164 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001165 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001166 if (prev_needs_proxy) {
1167 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001168 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001169 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001170 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001171 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001172 }
1173 track_back = &proxy_track_back;
1174 }
1175 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001176 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001177 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001178 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001179 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001180 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1181 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1182 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1183 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1184 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1185 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001186 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001187 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1188 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1189 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1190 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1191 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001192 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001193 }
John Zulauf355e49b2020-04-24 15:11:15 -06001194 }
1195 }
1196 return skip;
1197}
1198
John Zulaufbb890452021-12-14 11:30:18 -07001199bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001200 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001201 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001202 bool skip = false;
1203 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001204
John Zulauf1507ee42020-05-18 11:33:09 -06001205 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1206 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001207 const auto &view_gen = attachment_views[i];
1208 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001209 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001210
1211 // Need check in the following way
1212 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1213 // vs. transition
1214 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1215 // for each aspect loaded.
1216
1217 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001218 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001219 const bool is_color = !(has_depth || has_stencil);
1220
1221 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001222 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001223
John Zulaufaff20662020-06-01 14:07:58 -06001224 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001225 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001226
John Zulaufb02c1eb2020-10-06 16:33:36 -06001227 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001228 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001229 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001230 aspect = "color";
1231 } else {
John Zulauf57261402021-08-13 11:32:06 -06001232 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001233 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1234 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001235 aspect = "depth";
1236 }
John Zulauf57261402021-08-13 11:32:06 -06001237 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001238 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1239 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001240 aspect = "stencil";
1241 checked_stencil = true;
1242 }
1243 }
1244
1245 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001246 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001247 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001248 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001249 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001250 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001251 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001252 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1253 " aspect %s during load with loadOp %s.",
1254 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1255 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001256 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001257 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001258 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001259 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001260 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001261 }
1262 }
1263 }
1264 }
1265 return skip;
1266}
1267
John Zulaufaff20662020-06-01 14:07:58 -06001268// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1269// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1270// store is part of the same Next/End operation.
1271// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001272bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001273 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001274 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001275 bool skip = false;
1276 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001277
1278 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1279 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001280 const AttachmentViewGen &view_gen = attachment_views[i];
1281 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001282 const auto &ci = attachment_ci[i];
1283
1284 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1285 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1286 // sake, we treat DONT_CARE as writing.
1287 const bool has_depth = FormatHasDepth(ci.format);
1288 const bool has_stencil = FormatHasStencil(ci.format);
1289 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001290 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001291 if (!has_stencil && !store_op_stores) continue;
1292
1293 HazardResult hazard;
1294 const char *aspect = nullptr;
1295 bool checked_stencil = false;
1296 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001297 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1298 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001299 aspect = "color";
1300 } else {
John Zulauf57261402021-08-13 11:32:06 -06001301 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001302 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001303 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1304 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001305 aspect = "depth";
1306 }
1307 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001308 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1309 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001310 aspect = "stencil";
1311 checked_stencil = true;
1312 }
1313 }
1314
1315 if (hazard.hazard) {
1316 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1317 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001318 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1319 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1320 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001321 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1322 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001323 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001324 }
1325 }
1326 }
1327 return skip;
1328}
1329
John Zulaufbb890452021-12-14 11:30:18 -07001330bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001331 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001332 CMD_TYPE cmd_type, uint32_t subpass) const {
1333 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001334 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001335 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001336}
1337
John Zulauf06f6f1e2022-04-19 15:28:11 -06001338void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1339
John Zulauf3d84f1b2020-03-09 13:33:25 -06001340class HazardDetector {
1341 SyncStageAccessIndex usage_index_;
1342
1343 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001344 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001345 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001346 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001347 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001348 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001349};
1350
John Zulauf69133422020-05-20 14:55:53 -06001351class HazardDetectorWithOrdering {
1352 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001353 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001354
1355 public:
1356 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001357 return pos->second.DetectHazard(usage_index_, ordering_rule_, QueueSyncState::kQueueIdInvalid);
John Zulauf69133422020-05-20 14:55:53 -06001358 }
John Zulauf14940722021-04-12 15:19:02 -06001359 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001360 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001361 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001362 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001363};
1364
John Zulauf16adfc92020-04-08 10:28:33 -06001365HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001366 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001367 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001368 const auto base_address = ResourceBaseAddress(buffer);
1369 HazardDetector detector(usage_index);
1370 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001371}
1372
John Zulauf69133422020-05-20 14:55:53 -06001373template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001374HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1375 DetectOptions options) const {
1376 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1377 if (!attachment_gen) return HazardResult();
1378
1379 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1380 const auto address_type = view_gen.GetAddressType();
1381 for (; range_gen->non_empty(); ++range_gen) {
1382 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1383 if (hazard.hazard) return hazard;
1384 }
1385
1386 return HazardResult();
1387}
1388
1389template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001390HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1391 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001392 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001393 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001394 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001395 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001396 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001397 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001398 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001399 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001400 if (hazard.hazard) return hazard;
1401 }
1402 return HazardResult();
1403}
John Zulauf110413c2021-03-20 05:38:38 -06001404template <typename Detector>
1405HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001406 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1407 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001408 if (!SimpleBinding(image)) return HazardResult();
1409 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001410 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1411 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001412 const auto address_type = ImageAddressType(image);
1413 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001414 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1415 if (hazard.hazard) return hazard;
1416 }
1417 return HazardResult();
1418}
John Zulauf69133422020-05-20 14:55:53 -06001419
John Zulauf540266b2020-04-06 18:54:53 -06001420HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1421 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001422 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001423 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1424 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001425 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001426 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001427}
1428
1429HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001430 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001431 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001432 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001433}
1434
John Zulaufd0ec59f2021-03-13 14:25:08 -07001435HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1436 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1437 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1438 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1439}
1440
John Zulauf69133422020-05-20 14:55:53 -06001441HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001442 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001443 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001444 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001445 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001446}
1447
John Zulauf3d84f1b2020-03-09 13:33:25 -06001448class BarrierHazardDetector {
1449 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001450 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001451 SyncStageAccessFlags src_access_scope)
1452 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1453
John Zulauf5f13a792020-03-10 07:31:21 -06001454 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001455 return pos->second.DetectBarrierHazard(usage_index_, QueueSyncState::kQueueIdInvalid, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001456 }
John Zulauf14940722021-04-12 15:19:02 -06001457 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001458 // 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 -07001459 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001460 }
1461
1462 private:
1463 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001464 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001465 SyncStageAccessFlags src_access_scope_;
1466};
1467
John Zulauf4a6105a2020-11-17 15:11:05 -07001468class EventBarrierHazardDetector {
1469 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001470 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001471 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope, QueueId queue_id,
John Zulauf14940722021-04-12 15:19:02 -06001472 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001473 : usage_index_(usage_index),
1474 src_exec_scope_(src_exec_scope),
1475 src_access_scope_(src_access_scope),
1476 event_scope_(event_scope),
John Zulaufe0757ba2022-06-10 16:51:45 -06001477 scope_queue_id_(queue_id),
1478 scope_tag_(scope_tag),
John Zulauf4a6105a2020-11-17 15:11:05 -07001479 scope_pos_(event_scope.cbegin()),
John Zulaufe0757ba2022-06-10 16:51:45 -06001480 scope_end_(event_scope.cend()) {}
John Zulauf4a6105a2020-11-17 15:11:05 -07001481
John Zulaufe0757ba2022-06-10 16:51:45 -06001482 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) {
1483 // Need to piece together coverage of pos->first range:
1484 // Copy the range as we'll be chopping it up as needed
1485 ResourceAccessRange range = pos->first;
1486 const ResourceAccessState &access = pos->second;
1487 HazardResult hazard;
1488
1489 bool in_scope = AdvanceScope(range);
1490 bool unscoped_tested = false;
1491 while (in_scope && !hazard.IsHazard()) {
1492 if (range.begin < ScopeBegin()) {
1493 if (!unscoped_tested) {
1494 unscoped_tested = true;
1495 hazard = access.DetectHazard(usage_index_);
1496 }
1497 // Note: don't need to check for in_scope as AdvanceScope true means range and ScopeRange intersect.
1498 // Thus a [ ScopeBegin, range.end ) will be non-empty.
1499 range.begin = ScopeBegin();
1500 } else { // in_scope implied that ScopeRange and range intersect
1501 hazard = access.DetectBarrierHazard(usage_index_, ScopeState(), src_exec_scope_, src_access_scope_, scope_queue_id_,
1502 scope_tag_);
1503 if (!hazard.IsHazard()) {
1504 range.begin = ScopeEnd();
1505 in_scope = AdvanceScope(range); // contains a non_empty check
1506 }
1507 }
John Zulauf4a6105a2020-11-17 15:11:05 -07001508 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001509 if (range.non_empty() && !hazard.IsHazard() && !unscoped_tested) {
1510 hazard = access.DetectHazard(usage_index_);
1511 }
1512 return hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07001513 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001514
John Zulauf14940722021-04-12 15:19:02 -06001515 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001516 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1517 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1518 }
1519
1520 private:
John Zulaufe0757ba2022-06-10 16:51:45 -06001521 bool ScopeInvalid() const { return scope_pos_ == scope_end_; }
1522 bool ScopeValid() const { return !ScopeInvalid(); }
1523 void ScopeSeek(const ResourceAccessRange &range) { scope_pos_ = event_scope_.lower_bound(range); }
1524
1525 // Hiding away the std::pair grunge...
1526 ResourceAddress ScopeBegin() const { return scope_pos_->first.begin; }
1527 ResourceAddress ScopeEnd() const { return scope_pos_->first.end; }
1528 const ResourceAccessRange &ScopeRange() const { return scope_pos_->first; }
1529 const ResourceAccessState &ScopeState() const { return scope_pos_->second; }
1530
1531 bool AdvanceScope(const ResourceAccessRange &range) {
1532 // Note: non_empty is (valid && !empty), so don't change !non_empty to empty...
1533 if (!range.non_empty()) return false;
1534 if (ScopeInvalid()) return false;
1535
1536 if (ScopeRange().strictly_less(range)) {
1537 ScopeSeek(range);
1538 }
1539
1540 return ScopeValid() && ScopeRange().intersects(range);
1541 }
1542
John Zulauf4a6105a2020-11-17 15:11:05 -07001543 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001544 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001545 SyncStageAccessFlags src_access_scope_;
1546 const SyncEventState::ScopeMap &event_scope_;
John Zulaufe0757ba2022-06-10 16:51:45 -06001547 QueueId scope_queue_id_;
1548 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001549 SyncEventState::ScopeMap::const_iterator scope_pos_;
1550 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001551};
1552
John Zulaufe0757ba2022-06-10 16:51:45 -06001553HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1554 VkPipelineStageFlags2KHR src_exec_scope,
1555 const SyncStageAccessFlags &src_access_scope, QueueId queue_id,
1556 const SyncEventState &sync_event, AccessContext::DetectOptions options) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001557 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1558 // first access scope map to use, and there's no easy way to plumb it in below.
1559 const auto address_type = ImageAddressType(image);
1560 const auto &event_scope = sync_event.FirstScope(address_type);
1561
1562 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001563 event_scope, queue_id, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001564 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001565}
1566
John Zulaufd0ec59f2021-03-13 14:25:08 -07001567HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1568 DetectOptions options) const {
1569 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1570 barrier.src_access_scope);
1571 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1572}
1573
Jeremy Gebben40a22942020-12-22 14:22:06 -07001574HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001575 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001576 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001577 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001578 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001579 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001580}
1581
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001582HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001583 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001584 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001585}
John Zulauf355e49b2020-04-24 15:11:15 -06001586
John Zulauf9cb530d2019-09-30 14:14:10 -06001587template <typename Flags, typename Map>
1588SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1589 SyncStageAccessFlags scope = 0;
1590 for (const auto &bit_scope : map) {
1591 if (flag_mask < bit_scope.first) break;
1592
1593 if (flag_mask & bit_scope.first) {
1594 scope |= bit_scope.second;
1595 }
1596 }
1597 return scope;
1598}
1599
Jeremy Gebben40a22942020-12-22 14:22:06 -07001600SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001601 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1602}
1603
Jeremy Gebben40a22942020-12-22 14:22:06 -07001604SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1605 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001606}
1607
Jeremy Gebben40a22942020-12-22 14:22:06 -07001608// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1609SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001610 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1611 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1612 // 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 -06001613 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1614}
1615
1616template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001617void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001618 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1619 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001620 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001621 auto pos = accesses->lower_bound(range);
1622 if (pos == accesses->end() || !pos->first.intersects(range)) {
1623 // The range is empty, fill it with a default value.
1624 pos = action.Infill(accesses, pos, range);
1625 } else if (range.begin < pos->first.begin) {
1626 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001627 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001628 } else if (pos->first.begin < range.begin) {
1629 // Trim the beginning if needed
1630 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1631 ++pos;
1632 }
1633
1634 const auto the_end = accesses->end();
1635 while ((pos != the_end) && pos->first.intersects(range)) {
1636 if (pos->first.end > range.end) {
1637 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1638 }
1639
1640 pos = action(accesses, pos);
1641 if (pos == the_end) break;
1642
1643 auto next = pos;
1644 ++next;
1645 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1646 // Need to infill if next is disjoint
1647 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001648 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001649 next = action.Infill(accesses, next, new_range);
1650 }
1651 pos = next;
1652 }
1653}
John Zulaufd5115702021-01-18 12:34:33 -07001654
1655// Give a comparable interface for range generators and ranges
1656template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001657void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001658 assert(range);
1659 UpdateMemoryAccessState(accesses, *range, action);
1660}
1661
John Zulauf4a6105a2020-11-17 15:11:05 -07001662template <typename Action, typename RangeGen>
1663void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1664 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001665 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 -07001666 for (; range_gen->non_empty(); ++range_gen) {
1667 UpdateMemoryAccessState(accesses, *range_gen, action);
1668 }
1669}
John Zulauf9cb530d2019-09-30 14:14:10 -06001670
John Zulaufd0ec59f2021-03-13 14:25:08 -07001671template <typename Action, typename RangeGen>
1672void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1673 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1674 for (; range_gen->non_empty(); ++range_gen) {
1675 UpdateMemoryAccessState(accesses, *range_gen, action);
1676 }
1677}
John Zulauf9cb530d2019-09-30 14:14:10 -06001678struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001679 using Iterator = ResourceAccessRangeMap::iterator;
1680 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001681 // this is only called on gaps, and never returns a gap.
1682 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001683 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001684 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001685 }
John Zulauf5f13a792020-03-10 07:31:21 -06001686
John Zulauf5c5e88d2019-12-26 11:22:02 -07001687 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001688 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001689 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001690 return pos;
1691 }
1692
John Zulauf43cc7462020-12-03 12:33:12 -07001693 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001694 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001695 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001696 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001697 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001698 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001699 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001700 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001701};
1702
John Zulauf4a6105a2020-11-17 15:11:05 -07001703// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001704struct PipelineBarrierOp {
1705 SyncBarrier barrier;
1706 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001707 ResourceAccessState::QueueScopeOps scope;
1708 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
1709 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {}
John Zulaufd5115702021-01-18 12:34:33 -07001710 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001711 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001712};
John Zulauf00119522022-05-23 19:07:42 -06001713
John Zulaufecf4ac52022-06-06 10:08:42 -06001714// Batch barrier ops don't modify in place, and thus don't need to hold pending state, and also are *never* layout transitions.
1715struct BatchBarrierOp : public PipelineBarrierOp {
1716 void operator()(ResourceAccessState *access_state) const {
1717 access_state->ApplyBarrier(scope, barrier, layout_transition);
1718 access_state->ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
1719 }
1720 BatchBarrierOp(QueueId queue_id, const SyncBarrier &barrier_) : PipelineBarrierOp(queue_id, barrier_, false) {}
1721};
1722
John Zulauf4a6105a2020-11-17 15:11:05 -07001723// The barrier operation for wait events
1724struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001725 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001726 SyncBarrier barrier;
1727 bool layout_transition;
John Zulaufe0757ba2022-06-10 16:51:45 -06001728
1729 WaitEventBarrierOp(const QueueId scope_queue_, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
John Zulauf00119522022-05-23 19:07:42 -06001730 bool layout_transition_)
John Zulaufe0757ba2022-06-10 16:51:45 -06001731 : scope_ops(scope_queue_, scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
John Zulaufb7578302022-05-19 13:50:18 -06001732 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001733};
John Zulauf1e331ec2020-12-04 18:29:38 -07001734
John Zulauf4a6105a2020-11-17 15:11:05 -07001735// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1736// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1737// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001738template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001739class ApplyBarrierOpsFunctor {
1740 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001741 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001742 // Only called with a gap, and pos at the lower_bound(range)
1743 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1744 if (!infill_default_) {
1745 return pos;
1746 }
1747 ResourceAccessState default_state;
1748 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1749 return inserted;
1750 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001751
John Zulauf5c628d02021-05-04 15:46:36 -06001752 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001753 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001754 for (const auto &op : barrier_ops_) {
1755 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001756 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001757
John Zulauf89311b42020-09-29 16:28:47 -06001758 if (resolve_) {
1759 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1760 // another walk
1761 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001762 }
1763 return pos;
1764 }
1765
John Zulauf89311b42020-09-29 16:28:47 -06001766 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001767 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1768 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001769 barrier_ops_.reserve(size_hint);
1770 }
John Zulauf5c628d02021-05-04 15:46:36 -06001771 void EmplaceBack(const BarrierOp &op) {
1772 barrier_ops_.emplace_back(op);
1773 infill_default_ |= op.layout_transition;
1774 }
John Zulauf89311b42020-09-29 16:28:47 -06001775
1776 private:
1777 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001778 bool infill_default_;
1779 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001780 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001781};
1782
John Zulauf4a6105a2020-11-17 15:11:05 -07001783// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1784// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1785template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001786class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1787 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1788
John Zulauf4a6105a2020-11-17 15:11:05 -07001789 public:
John Zulaufee984022022-04-13 16:39:50 -06001790 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001791};
1792
John Zulauf1e331ec2020-12-04 18:29:38 -07001793// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001794class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1795 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1796
John Zulauf1e331ec2020-12-04 18:29:38 -07001797 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001798 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001799};
1800
John Zulauf8e3c3e92021-01-06 11:19:36 -07001801void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001802 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001803 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001804 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001805}
1806
John Zulauf8e3c3e92021-01-06 11:19:36 -07001807void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001808 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001809 if (!SimpleBinding(buffer)) return;
1810 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001811 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001812}
John Zulauf355e49b2020-04-24 15:11:15 -06001813
John Zulauf8e3c3e92021-01-06 11:19:36 -07001814void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001815 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1816 if (!SimpleBinding(image)) return;
1817 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001818 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001819 const auto address_type = ImageAddressType(image);
1820 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1821 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1822}
1823void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001824 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001825 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001826 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001827 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001828 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001829 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001830 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001831 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001832 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001833}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001834
1835void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001836 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001837 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1838 if (!gen) return;
1839 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1840 const auto address_type = view_gen.GetAddressType();
1841 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1842 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001843}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001844
John Zulauf8e3c3e92021-01-06 11:19:36 -07001845void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001846 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001847 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001848 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1849 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001850 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001851}
1852
John Zulaufd0ec59f2021-03-13 14:25:08 -07001853template <typename Action, typename RangeGen>
1854void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1855 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1856 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001857}
1858
1859template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001860void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1861 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1862 if (!gen) return;
1863 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001864}
1865
John Zulaufd0ec59f2021-03-13 14:25:08 -07001866void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1867 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001868 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001869 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001870 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001871}
1872
John Zulaufd0ec59f2021-03-13 14:25:08 -07001873void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001874 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001875 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001876
1877 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1878 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001879 const auto &view_gen = attachment_views[i];
1880 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001881
1882 const auto &ci = attachment_ci[i];
1883 const bool has_depth = FormatHasDepth(ci.format);
1884 const bool has_stencil = FormatHasStencil(ci.format);
1885 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001886 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001887
1888 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001889 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1890 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001891 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001892 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001893 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1894 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001895 }
John Zulauf57261402021-08-13 11:32:06 -06001896 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001897 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001898 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1899 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001900 }
1901 }
1902 }
1903 }
1904}
1905
John Zulauf540266b2020-04-06 18:54:53 -06001906template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001907void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001908 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001909 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001910 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001911 }
1912}
1913
1914void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001915 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1916 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001917 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001918 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001919 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001920 }
1921 }
1922}
1923
John Zulauf4fa68462021-04-26 21:04:22 -06001924// Caller must ensure that lifespan of this is less than from
1925void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1926
John Zulauf355e49b2020-04-24 15:11:15 -06001927// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001928HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1929 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001930
John Zulauf355e49b2020-04-24 15:11:15 -06001931 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001932 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001933
1934 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001935 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1936 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001937 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001938 if (!hazard.hazard) {
1939 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001940 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001941 }
John Zulaufa0a98292020-09-18 09:30:10 -06001942
John Zulauf355e49b2020-04-24 15:11:15 -06001943 return hazard;
1944}
1945
John Zulaufb02c1eb2020-10-06 16:33:36 -06001946void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001947 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001948 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001949 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001950 for (const auto &transition : transitions) {
1951 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001952 const auto &view_gen = attachment_views[transition.attachment];
1953 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001954
1955 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1956 assert(trackback);
1957
1958 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001959 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001960 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001961 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001962 auto &target_map = GetAccessStateMap(address_type);
1963 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001964 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1965 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001966 }
1967
John Zulauf86356ca2020-10-19 11:46:41 -06001968 // If there were no transitions skip this global map walk
1969 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001970 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001971 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001972 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001973}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001974
sjfricke0bea06e2022-06-05 09:22:26 +09001975bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06001976 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001977 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001978 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001979 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001980 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001981 return skip;
1982 }
sjfricke0bea06e2022-06-05 09:22:26 +09001983 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06001984
1985 using DescriptorClass = cvdescriptorset::DescriptorClass;
1986 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1987 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06001988 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1989
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001990 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001991 const auto raster_state = pipe->RasterizationState();
1992 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001993 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001994 }
locke-lunarg61870c22020-06-09 14:51:50 -06001995 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001996 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06001997 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
1998 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06001999 SyncStageAccessIndex sync_index =
2000 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2001
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002002 for (uint32_t index = 0; index < binding->count; index++) {
2003 const auto *descriptor = binding->GetDescriptor(index);
locke-lunarg61870c22020-06-09 14:51:50 -06002004 switch (descriptor->GetClass()) {
2005 case DescriptorClass::ImageSampler:
2006 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002007 if (descriptor->Invalid()) {
2008 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002009 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002010
2011 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2012 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2013 const auto *img_view_state = image_descriptor->GetImageViewState();
2014 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2015
John Zulauf361fb532020-07-22 10:45:39 -06002016 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002017 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2018 // Descriptors, so we do not have to worry about depth slicing here.
2019 // See: VUID 00343
2020 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002021 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002022 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002023
2024 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2025 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2026 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002027 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002028 hazard =
2029 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2030 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002031 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002032 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2033 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002034 }
John Zulauf110413c2021-03-20 05:38:38 -06002035
John Zulauf33fc1d52020-07-17 11:01:10 -06002036 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002037 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002038 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002039 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2040 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002041 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002042 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2043 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2044 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002045 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2046 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002047 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002048 }
2049 break;
2050 }
2051 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002052 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2053 if (texel_descriptor->Invalid()) {
2054 continue;
2055 }
2056 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2057 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002058 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002059 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002060 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002061 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002062 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002063 "%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 +09002064 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002065 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2066 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2067 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002068 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002069 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002070 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002071 }
2072 break;
2073 }
2074 case DescriptorClass::GeneralBuffer: {
2075 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002076 if (buffer_descriptor->Invalid()) {
2077 continue;
2078 }
2079 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002080 const ResourceAccessRange range =
2081 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002082 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002083 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002084 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002085 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002086 "%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 +09002087 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002088 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2089 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2090 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002091 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002092 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002093 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002094 }
2095 break;
2096 }
2097 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2098 default:
2099 break;
2100 }
2101 }
2102 }
2103 }
2104 return skip;
2105}
2106
2107void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002108 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002109 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002110 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002111 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002112 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002113 return;
2114 }
2115
2116 using DescriptorClass = cvdescriptorset::DescriptorClass;
2117 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2118 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002119 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2120
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002121 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002122 const auto raster_state = pipe->RasterizationState();
2123 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002124 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002125 }
locke-lunarg61870c22020-06-09 14:51:50 -06002126 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002127 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002128 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2129 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002130 SyncStageAccessIndex sync_index =
2131 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2132
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002133 for (uint32_t i = 0; i < binding->count; i++) {
2134 const auto *descriptor = binding->GetDescriptor(i);
locke-lunarg61870c22020-06-09 14:51:50 -06002135 switch (descriptor->GetClass()) {
2136 case DescriptorClass::ImageSampler:
2137 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002138 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2139 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2140 if (image_descriptor->Invalid()) {
2141 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002142 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002143 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002144 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2145 // Descriptors, so we do not have to worry about depth slicing here.
2146 // See: VUID 00343
2147 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002148 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002149 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002150 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2151 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2152 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2153 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002154 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002155 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2156 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002157 }
locke-lunarg61870c22020-06-09 14:51:50 -06002158 break;
2159 }
2160 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002161 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2162 if (texel_descriptor->Invalid()) {
2163 continue;
2164 }
2165 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2166 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002167 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002168 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002169 break;
2170 }
2171 case DescriptorClass::GeneralBuffer: {
2172 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002173 if (buffer_descriptor->Invalid()) {
2174 continue;
2175 }
2176 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002177 const ResourceAccessRange range =
2178 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002179 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002180 break;
2181 }
2182 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2183 default:
2184 break;
2185 }
2186 }
2187 }
2188 }
2189}
2190
sjfricke0bea06e2022-06-05 09:22:26 +09002191bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002192 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002193 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002194 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002195 return skip;
2196 }
2197
2198 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2199 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002200 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002201
2202 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002203 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002204 if (binding_description.binding < binding_buffers_size) {
2205 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002206 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002207
locke-lunarg1ae57d62020-11-18 10:49:19 -07002208 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002209 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2210 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002211 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002212 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002213 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002214 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002215 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002216 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2217 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002218 }
2219 }
2220 }
2221 return skip;
2222}
2223
John Zulauf14940722021-04-12 15:19:02 -06002224void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002225 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002226 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002227 return;
2228 }
2229 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2230 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002231 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002232
2233 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002234 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002235 if (binding_description.binding < binding_buffers_size) {
2236 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002237 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002238
locke-lunarg1ae57d62020-11-18 10:49:19 -07002239 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002240 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2241 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002242 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2243 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002244 }
2245 }
2246}
2247
sjfricke0bea06e2022-06-05 09:22:26 +09002248bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002249 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002250 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002251 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002252 }
locke-lunarg61870c22020-06-09 14:51:50 -06002253
locke-lunarg1ae57d62020-11-18 10:49:19 -07002254 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002255 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002256 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2257 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002258 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002259 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002260 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002261 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 +09002262 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2263 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002264 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002265 }
2266
2267 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2268 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002269 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002270 return skip;
2271}
2272
John Zulauf14940722021-04-12 15:19:02 -06002273void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002274 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 -06002275
locke-lunarg1ae57d62020-11-18 10:49:19 -07002276 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002277 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002278 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2279 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002280 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002281
2282 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2283 // We will detect more accurate range in the future.
2284 RecordDrawVertex(UINT32_MAX, 0, tag);
2285}
2286
sjfricke0bea06e2022-06-05 09:22:26 +09002287bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002288 bool skip = false;
2289 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002290 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002291 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002292}
2293
John Zulauf14940722021-04-12 15:19:02 -06002294void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002295 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002296 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002297 }
locke-lunarg61870c22020-06-09 14:51:50 -06002298}
2299
John Zulauf00119522022-05-23 19:07:42 -06002300QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2301
sjfricke0bea06e2022-06-05 09:22:26 +09002302ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002303 const VkRect2D &render_area,
2304 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002305 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002306 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2307 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002308 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002309 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002310 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002311 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002312 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002313}
2314
sjfricke0bea06e2022-06-05 09:22:26 +09002315ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002316 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002317 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002318
sjfricke0bea06e2022-06-05 09:22:26 +09002319 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2320 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2321 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002322
2323 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002324 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002325 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002326}
2327
sjfricke0bea06e2022-06-05 09:22:26 +09002328ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002329 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002330 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002331
sjfricke0bea06e2022-06-05 09:22:26 +09002332 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2333 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002334
2335 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002336 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002337 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002338 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002339}
2340
John Zulauf4a6105a2020-11-17 15:11:05 -07002341void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2342 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002343 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002344 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002345 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002346 }
2347}
2348
John Zulaufae842002021-04-15 18:20:55 -06002349// The is the recorded cb context
John Zulaufbb890452021-12-14 11:30:18 -07002350bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext *proxy_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002351 uint32_t index) const {
2352 assert(proxy_context);
John Zulauf00119522022-05-23 19:07:42 -06002353 SyncEventsContext *const events_context = proxy_context->GetCurrentEventsContext();
2354 AccessContext *const access_context = proxy_context->GetCurrentAccessContext();
2355 const QueueId queue_id = proxy_context->GetQueueId();
John Zulauf4fa68462021-04-26 21:04:22 -06002356 const ResourceUsageTag base_tag = proxy_context->GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002357 bool skip = false;
2358 ResourceUsageRange tag_range = {0, 0};
2359 const AccessContext *recorded_context = GetCurrentAccessContext();
2360 assert(recorded_context);
2361 HazardResult hazard;
John Zulaufbb890452021-12-14 11:30:18 -07002362 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002363 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002364 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002365 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002366 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002367 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002368 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2369 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002370 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002371 };
John Zulaufbb890452021-12-14 11:30:18 -07002372 const ReplayTrackbackBarriersAction *replay_context = nullptr;
John Zulaufae842002021-04-15 18:20:55 -06002373 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002374 // we update the range to any include layout transition first use writes,
2375 // as they are stored along with the source scope (as effective barrier) when recorded
2376 tag_range.end = sync_op.tag + 1;
John Zulauf610e28c2021-08-03 17:46:23 -06002377 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, proxy_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002378
John Zulaufec943ec2022-06-29 07:52:56 -06002379 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002380 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002381 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002382 }
2383 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002384 // Record the barrier into the proxy context.
John Zulauf00119522022-05-23 19:07:42 -06002385 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulaufbb890452021-12-14 11:30:18 -07002386 replay_context = sync_op.sync_op->GetReplayTrackback();
John Zulauf4fa68462021-04-26 21:04:22 -06002387 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002388 }
2389
John Zulaufbb890452021-12-14 11:30:18 -07002390 // Renderpasses may not cross command buffer boundaries
2391 assert(replay_context == nullptr);
2392
John Zulaufae842002021-04-15 18:20:55 -06002393 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002394 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulaufec943ec2022-06-29 07:52:56 -06002395 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002396 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002397 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002398 }
2399
2400 return skip;
2401}
2402
sjfricke0bea06e2022-06-05 09:22:26 +09002403void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf00119522022-05-23 19:07:42 -06002404 SyncEventsContext *const events_context = GetCurrentEventsContext();
2405 AccessContext *const access_context = GetCurrentAccessContext();
2406 const QueueId queue_id = GetQueueId();
2407
John Zulauf4fa68462021-04-26 21:04:22 -06002408 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2409 assert(recorded_context);
2410
2411 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2412 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002413 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002414 // we update the range to any include layout transition first use writes,
2415 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf00119522022-05-23 19:07:42 -06002416 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002417 }
2418
2419 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2420 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002421 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002422}
2423
John Zulauf1d5f9c12022-05-13 14:51:08 -06002424void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002425 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002426 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002427}
2428
John Zulauf3c788ef2022-02-22 12:12:30 -07002429ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002430 // The execution references ensure lifespan for the referenced child CB's...
2431 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002432 InsertRecordedAccessLogEntries(recorded_context);
2433 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002434 return tag_range;
2435}
2436
John Zulauf3c788ef2022-02-22 12:12:30 -07002437void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2438 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2439 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2440}
2441
John Zulauf41a9c7c2021-12-07 15:59:53 -07002442ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2443 ResourceUsageTag next = access_log_.size();
2444 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2445 return next;
2446}
2447
2448ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2449 command_number_++;
2450 subcommand_number_ = 0;
2451 ResourceUsageTag next = access_log_.size();
2452 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2453 return next;
2454}
2455
2456ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2457 if (index == 0) {
2458 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2459 }
2460 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2461}
2462
John Zulaufbb890452021-12-14 11:30:18 -07002463void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2464 auto tag = sync_op->Record(this);
2465 // As renderpass operations can have side effects on the command buffer access context,
2466 // update the sync operation to record these if any.
2467 if (current_renderpass_context_) {
2468 const auto &rpc = *current_renderpass_context_;
2469 sync_op->SetReplayContext(rpc.GetCurrentSubpass(), rpc.GetReplayContext());
2470 }
2471 sync_ops_.emplace_back(tag, std::move(sync_op));
2472}
2473
John Zulaufae842002021-04-15 18:20:55 -06002474class HazardDetectFirstUse {
2475 public:
John Zulaufec943ec2022-06-29 07:52:56 -06002476 HazardDetectFirstUse(const ResourceAccessState &recorded_use, QueueId queue_id, const ResourceUsageRange &tag_range,
John Zulaufbb890452021-12-14 11:30:18 -07002477 const ReplayTrackbackBarriersAction *replay_barrier)
John Zulaufec943ec2022-06-29 07:52:56 -06002478 : recorded_use_(recorded_use), queue_id_(queue_id), tag_range_(tag_range), replay_barrier_(replay_barrier) {}
John Zulaufae842002021-04-15 18:20:55 -06002479 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufbb890452021-12-14 11:30:18 -07002480 if (replay_barrier_) {
2481 // Intentional copy to apply the replay barrier
2482 auto access = pos->second;
2483 (*replay_barrier_)(&access);
John Zulaufec943ec2022-06-29 07:52:56 -06002484 return access.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufbb890452021-12-14 11:30:18 -07002485 }
John Zulaufec943ec2022-06-29 07:52:56 -06002486 return pos->second.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufae842002021-04-15 18:20:55 -06002487 }
2488 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2489 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2490 }
2491
2492 private:
2493 const ResourceAccessState &recorded_use_;
John Zulaufec943ec2022-06-29 07:52:56 -06002494 const QueueId queue_id_;
John Zulaufae842002021-04-15 18:20:55 -06002495 const ResourceUsageRange &tag_range_;
John Zulaufbb890452021-12-14 11:30:18 -07002496 const ReplayTrackbackBarriersAction *replay_barrier_;
John Zulaufae842002021-04-15 18:20:55 -06002497};
2498
2499// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2500// hazards will be detected
John Zulaufec943ec2022-06-29 07:52:56 -06002501HazardResult AccessContext::DetectFirstUseHazard(QueueId queue_id, const ResourceUsageRange &tag_range,
2502 const AccessContext &access_context,
John Zulaufbb890452021-12-14 11:30:18 -07002503 const ReplayTrackbackBarriersAction *replay_barrier) const {
John Zulaufae842002021-04-15 18:20:55 -06002504 HazardResult hazard;
2505 for (const auto address_type : kAddressTypes) {
2506 const auto &recorded_access_map = GetAccessStateMap(address_type);
2507 for (const auto &recorded_access : recorded_access_map) {
2508 // Cull any entries not in the current tag range
2509 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulaufec943ec2022-06-29 07:52:56 -06002510 HazardDetectFirstUse detector(recorded_access.second, queue_id, tag_range, replay_barrier);
John Zulaufae842002021-04-15 18:20:55 -06002511 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2512 if (hazard.hazard) break;
2513 }
2514 }
2515
2516 return hazard;
2517}
2518
John Zulaufbb890452021-12-14 11:30:18 -07002519bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002520 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002521 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002522 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002523 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002524 if (!pipe) {
2525 return skip;
2526 }
2527
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002528 const auto raster_state = pipe->RasterizationState();
2529 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002530 return skip;
2531 }
sjfricke0bea06e2022-06-05 09:22:26 +09002532 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002533 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002534 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002535
John Zulauf1a224292020-06-30 14:52:13 -06002536 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002537 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002538 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2539 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002540 if (location >= subpass.colorAttachmentCount ||
2541 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002542 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002543 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002544 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2545 if (!view_gen.IsValid()) continue;
2546 HazardResult hazard =
2547 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2548 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002549 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002550 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002551 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002552 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002553 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002554 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002555 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2556 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002557 }
2558 }
2559 }
locke-lunarg37047832020-06-12 13:44:45 -06002560
2561 // PHASE1 TODO: Add layout based read/vs. write selection.
2562 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002563 const auto ds_state = pipe->DepthStencilState();
2564 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002565
2566 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2567 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2568 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002569 bool depth_write = false, stencil_write = false;
2570
2571 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002572 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002573 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2574 depth_write = true;
2575 }
2576 // PHASE1 TODO: It needs to check if stencil is writable.
2577 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2578 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2579 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002580 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002581 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2582 stencil_write = true;
2583 }
2584
2585 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2586 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002587 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2588 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2589 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002590 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002591 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002592 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002593 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002594 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002595 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002596 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002597 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002598 }
2599 }
2600 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002601 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2602 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2603 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002604 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002605 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002606 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002607 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002608 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002609 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002610 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002611 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002612 }
locke-lunarg61870c22020-06-09 14:51:50 -06002613 }
2614 }
2615 return skip;
2616}
2617
sjfricke0bea06e2022-06-05 09:22:26 +09002618void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2619 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002620 if (!pipe) {
2621 return;
2622 }
2623
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002624 const auto *raster_state = pipe->RasterizationState();
2625 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002626 return;
2627 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002628 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002629 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002630
John Zulauf1a224292020-06-30 14:52:13 -06002631 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002632 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002633 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2634 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002635 if (location >= subpass.colorAttachmentCount ||
2636 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002637 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002638 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002639 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2640 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2641 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2642 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002643 }
2644 }
locke-lunarg37047832020-06-12 13:44:45 -06002645
2646 // PHASE1 TODO: Add layout based read/vs. write selection.
2647 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002648 const auto *ds_state = pipe->DepthStencilState();
2649 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002650 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2651 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2652 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002653 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002654 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2655 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002656
2657 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002658 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2659 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002660 depth_write = true;
2661 }
2662 // PHASE1 TODO: It needs to check if stencil is writable.
2663 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2664 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2665 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002666 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002667 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2668 stencil_write = true;
2669 }
2670
John Zulaufd0ec59f2021-03-13 14:25:08 -07002671 if (depth_write || stencil_write) {
2672 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2673 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2674 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2675 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002676 }
locke-lunarg61870c22020-06-09 14:51:50 -06002677 }
2678}
2679
sjfricke0bea06e2022-06-05 09:22:26 +09002680bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002681 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002682 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002683 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002684 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002685 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002686 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002687
John Zulauf355e49b2020-04-24 15:11:15 -06002688 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002689 if (next_subpass >= subpass_contexts_.size()) {
2690 return skip;
2691 }
John Zulauf1507ee42020-05-18 11:33:09 -06002692 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002693 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002694 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002695 if (!skip) {
2696 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2697 // on a copy of the (empty) next context.
2698 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2699 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002700 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002701 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002702 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002703 }
John Zulauf7635de32020-05-29 17:14:15 -06002704 return skip;
2705}
sjfricke0bea06e2022-06-05 09:22:26 +09002706bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002707 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002708 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002709 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002710 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002711 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2712 cmd_type);
2713 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002714 return skip;
2715}
2716
John Zulauf64ffe552021-02-06 10:25:07 -07002717AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002718 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002719}
2720
John Zulaufbb890452021-12-14 11:30:18 -07002721bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002722 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002723 bool skip = false;
2724
John Zulauf7635de32020-05-29 17:14:15 -06002725 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2726 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2727 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2728 // to apply and only copy then, if this proves a hot spot.
2729 std::unique_ptr<AccessContext> proxy_for_current;
2730
John Zulauf355e49b2020-04-24 15:11:15 -06002731 // Validate the "finalLayout" transitions to external
2732 // Get them from where there we're hidding in the extra entry.
2733 const auto &final_transitions = rp_state_->subpass_transitions.back();
2734 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002735 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002736 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002737 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2738 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002739
2740 if (transition.prev_pass == current_subpass_) {
2741 if (!proxy_for_current) {
2742 // 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 -07002743 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002744 }
2745 context = proxy_for_current.get();
2746 }
2747
John Zulaufa0a98292020-09-18 09:30:10 -06002748 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2749 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002750 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002751 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002752 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002753 if (hazard.tag == kInvalidTag) {
2754 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002755 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002756 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2757 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2758 " final image layout transition (old_layout: %s, new_layout: %s).",
2759 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2760 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2761 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002762 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002763 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2764 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2765 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2766 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2767 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002768 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002769 }
John Zulauf355e49b2020-04-24 15:11:15 -06002770 }
2771 }
2772 return skip;
2773}
2774
John Zulauf14940722021-04-12 15:19:02 -06002775void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002776 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002777 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002778}
2779
John Zulauf14940722021-04-12 15:19:02 -06002780void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002781 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2782 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002783
2784 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2785 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002786 const AttachmentViewGen &view_gen = attachment_views_[i];
2787 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002788
2789 const auto &ci = attachment_ci[i];
2790 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002791 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002792 const bool is_color = !(has_depth || has_stencil);
2793
2794 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002795 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2796 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2797 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2798 SyncOrdering::kColorAttachment, tag);
2799 }
John Zulauf1507ee42020-05-18 11:33:09 -06002800 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002801 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002802 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2803 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2804 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2805 SyncOrdering::kDepthStencilAttachment, tag);
2806 }
John Zulauf1507ee42020-05-18 11:33:09 -06002807 }
2808 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002809 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2810 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2811 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2812 SyncOrdering::kDepthStencilAttachment, tag);
2813 }
John Zulauf1507ee42020-05-18 11:33:09 -06002814 }
2815 }
2816 }
2817 }
2818}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002819AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2820 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2821 AttachmentViewGenVector view_gens;
2822 VkExtent3D extent = CastTo3D(render_area.extent);
2823 VkOffset3D offset = CastTo3D(render_area.offset);
2824 view_gens.reserve(attachment_views.size());
2825 for (const auto *view : attachment_views) {
2826 view_gens.emplace_back(view, offset, extent);
2827 }
2828 return view_gens;
2829}
John Zulauf64ffe552021-02-06 10:25:07 -07002830RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2831 VkQueueFlags queue_flags,
2832 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2833 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002834 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulauf355e49b2020-04-24 15:11:15 -06002835 // Add this for all subpasses here so that they exsist during next subpass validation
John Zulauf64ffe552021-02-06 10:25:07 -07002836 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
John Zulaufbb890452021-12-14 11:30:18 -07002837 replay_context_ = std::make_shared<ReplayRenderpassContext>();
2838 auto &replay_subpass_contexts = replay_context_->subpass_contexts;
2839 replay_subpass_contexts.reserve(rp_state_->createInfo.subpassCount);
John Zulauf355e49b2020-04-24 15:11:15 -06002840 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002841 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulaufbb890452021-12-14 11:30:18 -07002842 replay_subpass_contexts.emplace_back(queue_flags, rp_state_->subpass_dependencies[pass], replay_subpass_contexts);
John Zulauf355e49b2020-04-24 15:11:15 -06002843 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002844 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002845}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002846void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002847 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002848 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2849 RecordLayoutTransitions(barrier_tag);
2850 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002851}
John Zulauf1507ee42020-05-18 11:33:09 -06002852
John Zulauf41a9c7c2021-12-07 15:59:53 -07002853void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2854 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002855 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002856 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2857 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002858
ziga-lunarg31a3e772022-03-22 11:48:46 +01002859 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2860 return;
2861 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002862 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2863 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002864 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002865 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2866 RecordLayoutTransitions(barrier_tag);
2867 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002868}
2869
John Zulauf41a9c7c2021-12-07 15:59:53 -07002870void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2871 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002872 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002873 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2874 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002875
John Zulauf355e49b2020-04-24 15:11:15 -06002876 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002877 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002878
2879 // Add the "finalLayout" transitions to external
2880 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002881 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2882 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2883 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002884 const auto &final_transitions = rp_state_->subpass_transitions.back();
2885 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002886 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002887 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002888 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002889 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002890 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002891 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002892 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002893 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002894 }
2895}
2896
John Zulauf06f6f1e2022-04-19 15:28:11 -06002897SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2898 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002899 SyncExecScope result;
2900 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002901 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002902 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002903 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002904 return result;
2905}
2906
Jeremy Gebben40a22942020-12-22 14:22:06 -07002907SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002908 SyncExecScope result;
2909 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002910 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2911 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002912 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002913 return result;
2914}
2915
John Zulaufecf4ac52022-06-06 10:08:42 -06002916SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2917 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2918
2919SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2920 : 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 -07002921
2922template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002923SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2924 : src_exec_scope(src),
2925 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2926 dst_exec_scope(dst),
2927 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002928
2929SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002930 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2931 if (barrier) {
2932 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002933 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002934 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002935
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002936 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002937 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002938 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2939
2940 } else {
2941 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002942 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002943 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2944
2945 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002946 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002947 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2948 }
2949}
2950
2951template <typename Barrier>
2952SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2953 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2954 src_exec_scope = src.exec_scope;
2955 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2956
2957 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002958 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002959 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002960}
2961
John Zulaufb02c1eb2020-10-06 16:33:36 -06002962// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2963void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002964 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002965 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002966 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002967 }
2968}
2969
John Zulauf89311b42020-09-29 16:28:47 -06002970// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2971// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2972// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002973void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002974 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002975 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002976 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002977 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002978 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002979 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002980 }
John Zulaufbb890452021-12-14 11:30:18 -07002981 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002982}
John Zulauf9cb530d2019-09-30 14:14:10 -06002983HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2984 HazardResult hazard;
2985 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002986 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002987 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002988 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002989 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002990 }
2991 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002992 // Write operation:
2993 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2994 // If reads exists -- test only against them because either:
2995 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2996 // * 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
2997 // the current write happens after the reads, so just test the write against the reades
2998 // Otherwise test against last_write
2999 //
3000 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07003001 if (last_reads.size()) {
3002 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06003003 if (IsReadHazard(usage_stage, read_access)) {
3004 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3005 break;
3006 }
3007 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003008 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06003009 // Write-After-Write check -- if we have a previous write to test against
3010 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003011 }
3012 }
3013 return hazard;
3014}
3015
John Zulaufec943ec2022-06-29 07:52:56 -06003016HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule,
3017 QueueId queue_id) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003018 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulaufec943ec2022-06-29 07:52:56 -06003019 return DetectHazard(usage_index, ordering, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003020}
3021
John Zulaufec943ec2022-06-29 07:52:56 -06003022HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering,
3023 QueueId queue_id) const {
John Zulauf69133422020-05-20 14:55:53 -06003024 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3025 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003026 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003027 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003028 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulaufec943ec2022-06-29 07:52:56 -06003029 const bool last_write_is_ordered = (last_write & ordering.access_scope).any() && (write_queue == queue_id);
John Zulauf4285ee92020-09-23 10:20:52 -06003030 if (IsRead(usage_bit)) {
3031 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3032 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3033 if (is_raw_hazard) {
3034 // NOTE: we know last_write is non-zero
3035 // See if the ordering rules save us from the simple RAW check above
3036 // First check to see if the current usage is covered by the ordering rules
3037 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3038 const bool usage_is_ordered =
3039 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3040 if (usage_is_ordered) {
3041 // Now see of the most recent write (or a subsequent read) are ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003042 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(queue_id, ordering));
John Zulauf4285ee92020-09-23 10:20:52 -06003043 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003044 }
3045 }
John Zulauf4285ee92020-09-23 10:20:52 -06003046 if (is_raw_hazard) {
3047 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3048 }
John Zulauf5c628d02021-05-04 15:46:36 -06003049 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3050 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
John Zulaufec943ec2022-06-29 07:52:56 -06003051 return DetectBarrierHazard(usage_index, queue_id, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003052 } else {
3053 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003054 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003055 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003056 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003057 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003058 if (usage_write_is_ordered) {
3059 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
John Zulaufec943ec2022-06-29 07:52:56 -06003060 ordered_stages = GetOrderedStages(queue_id, ordering);
John Zulauf4285ee92020-09-23 10:20:52 -06003061 }
3062 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3063 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003064 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003065 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3066 if (IsReadHazard(usage_stage, read_access)) {
3067 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3068 break;
3069 }
John Zulaufd14743a2020-07-03 09:42:39 -06003070 }
3071 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003072 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3073 bool ilt_ilt_hazard = false;
3074 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3075 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3076 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3077 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3078 }
3079 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003080 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003081 }
John Zulauf69133422020-05-20 14:55:53 -06003082 }
3083 }
3084 return hazard;
3085}
3086
John Zulaufec943ec2022-06-29 07:52:56 -06003087HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, QueueId queue_id,
3088 const ResourceUsageRange &tag_range) const {
John Zulaufae842002021-04-15 18:20:55 -06003089 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003090 using Size = FirstAccesses::size_type;
3091 const auto &recorded_accesses = recorded_use.first_accesses_;
3092 Size count = recorded_accesses.size();
3093 if (count) {
3094 const auto &last_access = recorded_accesses.back();
3095 bool do_write_last = IsWrite(last_access.usage_index);
3096 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003097
John Zulauf4fa68462021-04-26 21:04:22 -06003098 for (Size i = 0; i < count; ++count) {
3099 const auto &first = recorded_accesses[i];
3100 // Skip and quit logic
3101 if (first.tag < tag_range.begin) continue;
3102 if (first.tag >= tag_range.end) {
3103 do_write_last = false; // ignore last since we know it can't be in tag_range
3104 break;
3105 }
3106
John Zulaufec943ec2022-06-29 07:52:56 -06003107 hazard = DetectHazard(first.usage_index, first.ordering_rule, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003108 if (hazard.hazard) {
3109 hazard.AddRecordedAccess(first);
3110 break;
3111 }
3112 }
3113
3114 if (do_write_last && tag_range.includes(last_access.tag)) {
3115 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3116 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3117 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3118 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3119 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3120 // the barrier that applies them
3121 barrier |= recorded_use.first_write_layout_ordering_;
3122 }
3123 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3124 // the active context
3125 if (recorded_use.first_read_stages_) {
3126 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3127 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3128 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3129 // active context.
3130 barrier.exec_scope |= recorded_use.first_read_stages_;
3131 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3132 barrier.access_scope |= FlagBit(last_access.usage_index);
3133 }
John Zulaufec943ec2022-06-29 07:52:56 -06003134 hazard = DetectHazard(last_access.usage_index, barrier, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003135 if (hazard.hazard) {
3136 hazard.AddRecordedAccess(last_access);
3137 }
3138 }
John Zulaufae842002021-04-15 18:20:55 -06003139 }
3140 return hazard;
3141}
3142
John Zulauf2f952d22020-02-10 11:34:51 -07003143// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003144HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003145 HazardResult hazard;
3146 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003147 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3148 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3149 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003150 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003151 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003152 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003153 }
3154 } else {
John Zulauf14940722021-04-12 15:19:02 -06003155 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003156 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003157 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003158 // 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 -07003159 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003160 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003161 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003162 break;
3163 }
3164 }
John Zulauf2f952d22020-02-10 11:34:51 -07003165 }
3166 }
3167 return hazard;
3168}
3169
John Zulaufae842002021-04-15 18:20:55 -06003170HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3171 ResourceUsageTag start_tag) const {
3172 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003173 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003174 // Skip and quit logic
3175 if (first.tag < tag_range.begin) continue;
3176 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003177
3178 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003179 if (hazard.hazard) {
3180 hazard.AddRecordedAccess(first);
3181 break;
3182 }
John Zulaufae842002021-04-15 18:20:55 -06003183 }
3184 return hazard;
3185}
3186
John Zulaufec943ec2022-06-29 07:52:56 -06003187HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, QueueId queue_id,
3188 VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003189 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003190 // Only supporting image layout transitions for now
3191 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3192 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003193 // only test for WAW if there no intervening read operations.
3194 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003195 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003196 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003197 for (const auto &read_access : last_reads) {
John Zulaufec943ec2022-06-29 07:52:56 -06003198 if (read_access.IsReadBarrierHazard(queue_id, src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003199 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003200 break;
3201 }
3202 }
John Zulaufec943ec2022-06-29 07:52:56 -06003203 } else if (last_write.any() && IsWriteBarrierHazard(queue_id, src_exec_scope, src_access_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003204 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3205 }
3206
3207 return hazard;
3208}
3209
John Zulaufe0757ba2022-06-10 16:51:45 -06003210HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3211 VkPipelineStageFlags2KHR src_exec_scope,
3212 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3213 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003214 // Only supporting image layout transitions for now
3215 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3216 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003217
John Zulaufe0757ba2022-06-10 16:51:45 -06003218 if ((write_tag >= event_tag) && last_write.any()) {
3219 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3220 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3221 } else {
3222 // only test for WAW if there no intervening read operations.
3223 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3224 if (last_reads.size()) {
3225 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3226 // first scope, or they are a hazard.
3227 const ReadStates &scope_reads = scope_state.last_reads;
3228 const ReadStates::size_type scope_read_count = scope_reads.size();
3229 // Since the hasn't been a write:
3230 // * The current read state is a superset of the scoped one
3231 // * The stage order is the same.
3232 assert(last_reads.size() >= scope_read_count);
3233 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3234 const ReadState &scope_read = scope_reads[read_idx];
3235 const ReadState &current_read = last_reads[read_idx];
3236 assert(scope_read.stage == current_read.stage);
3237 if (current_read.tag > event_tag) {
3238 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3239 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3240 } else {
3241 // The read is in the events first synchronization scope, so we use a barrier hazard check
3242 // If the read stage is not in the src sync scope
3243 // *AND* not execution chained with an existing sync barrier (that's the or)
3244 // then the barrier access is unsafe (R/W after R)
3245 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3246 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3247 break;
3248 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003249 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003250 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003251 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3252 const ReadState &current_read = last_reads[scope_read_count];
3253 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3254 }
3255 } else if (last_write.any()) {
3256 // 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 -07003257 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3258 // So do a normal barrier hazard check
John Zulaufe0757ba2022-06-10 16:51:45 -06003259 if (scope_state.IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3260 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003261 }
John Zulauf361fb532020-07-22 10:45:39 -06003262 }
John Zulaufd14743a2020-07-03 09:42:39 -06003263 }
John Zulauf361fb532020-07-22 10:45:39 -06003264
John Zulauf0cb5be22020-01-23 12:18:22 -07003265 return hazard;
3266}
3267
John Zulauf5f13a792020-03-10 07:31:21 -06003268// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3269// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3270// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3271void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003272 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003273 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3274 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003275 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003276 } else if (other.write_tag == write_tag) {
3277 // 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 -06003278 // dependency chaining logic or any stage expansion)
3279 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003280 pending_write_barriers |= other.pending_write_barriers;
3281 pending_layout_transition |= other.pending_layout_transition;
3282 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003283 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003284
John Zulaufd14743a2020-07-03 09:42:39 -06003285 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003286 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003287 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003288 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003289 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003290 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003291 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003292 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3293 // but we should wait on profiling data for that.
3294 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003295 auto &my_read = last_reads[my_read_index];
3296 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003297 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003298 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003299 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003300 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003301 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003302 my_read.pending_dep_chain = other_read.pending_dep_chain;
3303 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3304 // May require tracking more than one access per stage.
3305 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003306 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003307 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003308 // Since I'm overwriting the fragement stage read, also update the input attachment info
3309 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003310 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003311 }
John Zulauf14940722021-04-12 15:19:02 -06003312 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003313 // The read tags match so merge the barriers
3314 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003315 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003316 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003317 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003318
John Zulauf5f13a792020-03-10 07:31:21 -06003319 break;
3320 }
3321 }
3322 } else {
3323 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003324 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003325 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003326 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003327 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003328 }
John Zulauf5f13a792020-03-10 07:31:21 -06003329 }
3330 }
John Zulauf361fb532020-07-22 10:45:39 -06003331 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003332 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3333 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003334
3335 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3336 // of the copy and other into this using the update first logic.
3337 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3338 // of the other first_accesses... )
3339 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3340 FirstAccesses firsts(std::move(first_accesses_));
3341 first_accesses_.clear();
3342 first_read_stages_ = 0U;
3343 auto a = firsts.begin();
3344 auto a_end = firsts.end();
3345 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003346 // TODO: Determine whether some tag offset will be needed for PHASE II
3347 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003348 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3349 ++a;
3350 }
3351 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3352 }
3353 for (; a != a_end; ++a) {
3354 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3355 }
3356 }
John Zulauf5f13a792020-03-10 07:31:21 -06003357}
3358
John Zulauf14940722021-04-12 15:19:02 -06003359void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003360 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3361 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003362 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003363 // Mulitple outstanding reads may be of interest and do dependency chains independently
3364 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3365 const auto usage_stage = PipelineStageBit(usage_index);
3366 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003367 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003368 for (auto &read_access : last_reads) {
3369 if (read_access.stage == usage_stage) {
3370 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003371 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003372 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003373 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003374 } else {
3375 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3376 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3377 // that sync_stages is a subset of barriers may not apply.
3378 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003379 }
3380 }
3381 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003382 for (auto &read_access : last_reads) {
3383 if (read_access.barriers & usage_stage) {
3384 read_access.sync_stages |= usage_stage;
3385 }
3386 }
John Zulaufab7756b2020-12-29 16:10:16 -07003387 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003388 last_read_stages |= usage_stage;
3389 }
John Zulauf4285ee92020-09-23 10:20:52 -06003390
3391 // 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 -07003392 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003393 // TODO Revisit re: multiple reads for a given stage
3394 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003395 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003396 } else {
3397 // Assume write
3398 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003399 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003400 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003401 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003402}
John Zulauf5f13a792020-03-10 07:31:21 -06003403
John Zulauf89311b42020-09-29 16:28:47 -06003404// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3405// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3406// We can overwrite them as *this* write is now after them.
3407//
3408// 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 -06003409void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003410 ClearRead();
3411 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003412 write_tag = tag;
3413 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003414}
3415
John Zulauf1d5f9c12022-05-13 14:51:08 -06003416void ResourceAccessState::ClearWrite() {
3417 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3418 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3419 write_barriers.reset();
3420 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3421 last_write.reset();
3422
3423 write_tag = 0;
3424 write_queue = QueueSyncState::kQueueIdInvalid;
3425}
3426
3427void ResourceAccessState::ClearRead() {
3428 last_reads.clear();
3429 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3430}
3431
John Zulauf89311b42020-09-29 16:28:47 -06003432// Apply the memory barrier without updating the existing barriers. The execution barrier
3433// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3434// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3435// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003436template <typename ScopeOps>
3437void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003438 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3439 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003440 // 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 -06003441 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003442 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3443 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003444 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003445 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003446 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003447 if (layout_transition) {
3448 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3449 }
John Zulaufa0a98292020-09-18 09:30:10 -06003450 }
John Zulauf89311b42020-09-29 16:28:47 -06003451 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3452 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003453
John Zulauf89311b42020-09-29 16:28:47 -06003454 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003455 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3456 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003457 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3458
John Zulaufab7756b2020-12-29 16:10:16 -07003459 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003460 // 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 -06003461 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003462 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3463 stages_in_scope |= read_access.stage;
3464 }
3465 }
3466
3467 for (auto &read_access : last_reads) {
3468 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3469 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3470 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3471 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003472 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003473 }
3474 }
John Zulaufa0a98292020-09-18 09:30:10 -06003475 }
John Zulaufa0a98292020-09-18 09:30:10 -06003476}
3477
John Zulauf14940722021-04-12 15:19:02 -06003478void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003479 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003480 // 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 -06003481 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003482 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003483 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3484 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003485 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003486 }
John Zulauf89311b42020-09-29 16:28:47 -06003487
3488 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003489 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003490 for (auto &read_access : last_reads) {
3491 read_access.barriers |= read_access.pending_dep_chain;
3492 read_execution_barriers |= read_access.barriers;
3493 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003494 }
3495
3496 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3497 write_dependency_chain |= pending_write_dep_chain;
3498 write_barriers |= pending_write_barriers;
3499 pending_write_dep_chain = 0;
3500 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003501}
3502
John Zulaufecf4ac52022-06-06 10:08:42 -06003503// Assumes signal queue != wait queue
3504void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3505 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3506 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3507 assert(signal.queue != wait.queue);
3508 for (auto &read_access : last_reads) {
3509 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3510 // Deflects WAR on wait queue
3511 read_access.barriers = wait.exec_scope;
3512 } else {
3513 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3514 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3515 }
3516 }
3517 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3518 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3519 read_execution_barriers = wait.exec_scope;
3520 write_barriers = wait.valid_accesses;
3521 } else {
3522 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3523 write_barriers.reset();
3524 }
3525 write_dependency_chain = read_execution_barriers;
3526}
3527
John Zulauf1d5f9c12022-05-13 14:51:08 -06003528bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) {
3529 return (queue == usage_queue) && (tag <= usage_tag);
3530}
3531
3532bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) { return queue == usage_queue; }
3533
3534bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) { return tag <= usage_tag; }
3535
3536// Return if the resulting state is "empty"
3537template <typename Pred>
3538bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3539 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3540
3541 // Use the predicate to build a mask of the read stages we are synchronizing
3542 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003543 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003544 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003545 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3546 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003547 }
3548 }
3549
John Zulauf434c4e62022-05-19 16:03:56 -06003550 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3551 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3552 uint32_t unsync_count = 0;
3553 for (auto &read_access : last_reads) {
3554 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3555 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3556 sync_reads |= read_access.stage;
3557 } else {
3558 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003559 }
3560 }
3561
3562 if (unsync_count) {
3563 if (sync_reads) {
3564 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3565 ReadStates unsync_reads;
3566 unsync_reads.reserve(unsync_count);
3567 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3568 for (auto &read_access : last_reads) {
3569 if (0 == (read_access.stage & sync_reads)) {
3570 unsync_reads.emplace_back(read_access);
3571 unsync_read_stages |= read_access.stage;
3572 }
3573 }
3574 last_read_stages = unsync_read_stages;
3575 last_reads = std::move(unsync_reads);
3576 }
3577 } else {
3578 // Nothing remains (or it was empty to begin with)
3579 ClearRead();
3580 }
3581
3582 bool all_clear = last_reads.size() == 0;
3583 if (last_write.any()) {
3584 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3585 // Clear any predicated write, or any the write from any any access with synchronized reads.
3586 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3587 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3588 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3589 ClearWrite();
3590 } else {
3591 all_clear = false;
3592 }
3593 }
3594 return all_clear;
3595}
3596
John Zulaufae842002021-04-15 18:20:55 -06003597bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3598 if (!first_accesses_.size()) return false;
3599 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3600 return tag_range.intersects(first_access_range);
3601}
3602
John Zulauf1d5f9c12022-05-13 14:51:08 -06003603void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3604 if (last_write.any()) write_tag += offset;
3605 for (auto &read_access : last_reads) {
3606 read_access.tag += offset;
3607 }
3608 for (auto &first : first_accesses_) {
3609 first.tag += offset;
3610 }
3611}
3612
3613ResourceAccessState::ResourceAccessState()
3614 : write_barriers(~SyncStageAccessFlags(0)),
3615 write_dependency_chain(0),
3616 write_tag(),
3617 write_queue(QueueSyncState::kQueueIdInvalid),
3618 last_write(0),
3619 input_attachment_read(false),
3620 last_read_stages(0),
3621 read_execution_barriers(0),
3622 pending_write_dep_chain(0),
3623 pending_layout_transition(false),
3624 pending_write_barriers(0),
3625 pending_layout_ordering_(),
3626 first_accesses_(),
3627 first_read_stages_(0U),
3628 first_write_layout_ordering_() {}
3629
John Zulauf59e25072020-07-17 10:55:21 -06003630// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003631VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3632 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003633
John Zulaufab7756b2020-12-29 16:10:16 -07003634 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003635 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003636 barriers = read_access.barriers;
3637 break;
John Zulauf59e25072020-07-17 10:55:21 -06003638 }
3639 }
John Zulauf4285ee92020-09-23 10:20:52 -06003640
John Zulauf59e25072020-07-17 10:55:21 -06003641 return barriers;
3642}
3643
John Zulauf1d5f9c12022-05-13 14:51:08 -06003644void ResourceAccessState::SetQueueId(QueueId id) {
3645 for (auto &read_access : last_reads) {
3646 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3647 read_access.queue = id;
3648 }
3649 }
3650 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3651 write_queue = id;
3652 }
3653}
3654
John Zulauf00119522022-05-23 19:07:42 -06003655bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3656 return 0 != (write_dependency_chain & src_exec_scope);
3657}
3658
3659bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3660 return (src_access_scope & last_write).any();
3661}
3662
John Zulaufec943ec2022-06-29 07:52:56 -06003663bool ResourceAccessState::WriteBarrierInScope(const SyncStageAccessFlags &src_access_scope) const {
3664 return (write_barriers & src_access_scope).any();
3665}
3666
John Zulaufb7578302022-05-19 13:50:18 -06003667bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3668 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003669 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3670}
3671
3672bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3673 SyncStageAccessFlags src_access_scope) const {
3674 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003675}
3676
John Zulaufe0757ba2022-06-10 16:51:45 -06003677bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3678 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003679 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3680 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3681 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003682 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003683}
3684
John Zulaufec943ec2022-06-29 07:52:56 -06003685bool ResourceAccessState::WriteInChainedScope(VkPipelineStageFlags2KHR src_exec_scope,
3686 const SyncStageAccessFlags &src_access_scope) const {
3687 return WriteInChain(src_exec_scope) && WriteBarrierInScope(src_access_scope);
3688}
3689
John Zulaufcb7e1672022-05-04 13:46:08 -06003690bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003691 assert(IsRead(usage));
3692 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3693 // * the previous reads are not hazards, and thus last_write must be visible and available to
3694 // any reads that happen after.
3695 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3696 // 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 -07003697 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003698}
3699
John Zulaufec943ec2022-06-29 07:52:56 -06003700VkPipelineStageFlags2 ResourceAccessState::GetOrderedStages(QueueId queue_id, const OrderingBarrier &ordering) const {
3701 // At apply queue submission order limits on the effect of ordering
3702 VkPipelineStageFlags2 non_qso_stages = VK_PIPELINE_STAGE_2_NONE;
3703 if (queue_id != QueueSyncState::kQueueIdInvalid) {
3704 for (const auto &read_access : last_reads) {
3705 if (read_access.queue != queue_id) {
3706 non_qso_stages |= read_access.stage;
3707 }
3708 }
3709 }
John Zulauf4285ee92020-09-23 10:20:52 -06003710 // Whether the stage are in the ordering scope only matters if the current write is ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003711 const VkPipelineStageFlags2 read_stages_in_qso = last_read_stages & ~non_qso_stages;
3712 VkPipelineStageFlags2 ordered_stages = read_stages_in_qso & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003713 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003714 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003715 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003716 // 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 -07003717 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003718 }
3719
3720 return ordered_stages;
3721}
3722
John Zulauf14940722021-04-12 15:19:02 -06003723void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003724 // Only record until we record a write.
3725 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003726 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003727 if (0 == (usage_stage & first_read_stages_)) {
3728 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003729 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003730 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003731 if (0 == (read_execution_barriers & usage_stage)) {
3732 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3733 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3734 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003735 }
3736 }
3737}
3738
John Zulauf4fa68462021-04-26 21:04:22 -06003739void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3740 // Only call this after recording an image layout transition
3741 assert(first_accesses_.size());
3742 if (first_accesses_.back().tag == tag) {
3743 // 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 +02003744 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003745 first_write_layout_ordering_ = layout_ordering;
3746 }
3747}
3748
John Zulauf1d5f9c12022-05-13 14:51:08 -06003749ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3750 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3751 : stage(stage_),
3752 access(access_),
3753 barriers(barriers_),
3754 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3755 tag(tag_),
3756 queue(QueueSyncState::kQueueIdInvalid),
3757 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3758
John Zulaufee984022022-04-13 16:39:50 -06003759void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3760 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3761 stage = stage_;
3762 access = access_;
3763 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003764 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003765 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003766 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 -06003767}
3768
John Zulauf00119522022-05-23 19:07:42 -06003769// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3770// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3771// that have bee applied (via semaphore) to those accesses can be chained off of.
3772bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3773 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3774 return (exec_scope & effective_stages) != 0;
3775}
3776
John Zulauf697c0e12022-04-19 16:31:12 -06003777ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3778 ResourceUsageRange reserve;
3779 reserve.begin = tag_limit_.fetch_add(tag_count);
3780 reserve.end = reserve.begin + tag_count;
3781 return reserve;
3782}
3783
John Zulaufbbda4572022-04-19 16:20:45 -06003784const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3785 return GetMappedPlainFromShared(queue_sync_states_, queue);
3786}
3787
3788QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3789
3790std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3791 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3792}
3793
3794std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3795 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3796}
3797
John Zulaufe0757ba2022-06-10 16:51:45 -06003798template <typename T>
3799struct GetBatchTraits {};
3800template <>
3801struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3802 using Batch = std::shared_ptr<QueueBatchContext>;
3803 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3804};
3805
3806template <>
3807struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3808 using Batch = std::shared_ptr<QueueBatchContext>;
3809 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3810};
3811
3812template <typename BatchSet, typename Map, typename Predicate>
3813static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003814 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003815 for (auto &entry : map) {
3816 // Intentional copy
3817 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003818 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003819 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003820 return snapshot;
3821}
3822
3823template <typename Predicate>
3824QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003825 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003826}
3827
3828template <typename Predicate>
3829QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003830 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3831}
3832
3833QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3834 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3835 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3836 if (batch && !layer_data::Contains(snapshot, batch)) {
3837 snapshot.emplace(batch);
3838 }
3839 return false;
3840 };
3841 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3842 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003843}
3844
John Zulaufcb7e1672022-05-04 13:46:08 -06003845bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3846 const std::shared_ptr<QueueBatchContext> &batch,
3847 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003848 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003849 const SyncExecScope exec_scope =
3850 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3851 const VkSemaphore sem = sem_state->semaphore();
3852 auto signal_it = signaled_.find(sem);
3853 std::shared_ptr<Signal> insert_signal;
3854 if (signal_it == signaled_.end()) {
3855 if (prev_) {
3856 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3857 if (prev_sig) {
3858 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3859 insert_signal = std::make_shared<Signal>(*prev_sig);
3860 }
3861 }
3862 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3863 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003864 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003865
3866 bool success = false;
3867 if (!signal_it->second) {
3868 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3869 success = true;
3870 }
3871
3872 return success;
3873}
3874
John Zulaufecf4ac52022-06-06 10:08:42 -06003875std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3876 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06003877 const auto found_it = signaled_.find(sem);
3878 if (found_it != signaled_.end()) {
3879 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3880 // a bit.
3881 unsignaled = std::move(found_it->second);
3882 if (!prev_) {
3883 // No parent, not need to keep the entry
3884 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3885 signaled_.erase(found_it);
3886 }
3887 } else if (prev_) {
3888 // We can't unsignal prev_ because it's const * by design.
3889 // We put in an empty placeholder
3890 signaled_.emplace(sem, std::shared_ptr<Signal>());
3891 unsignaled = GetPrev(sem);
3892 }
3893 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3894 // but CoreChecks should have reported it
3895
3896 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003897 return unsignaled;
3898}
3899
John Zulaufcb7e1672022-05-04 13:46:08 -06003900void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3901 // Overwrite the s tate with the last state from this
3902 if (from) {
3903 assert(sem == from->sem_state->semaphore());
3904 signaled_[sem] = std::move(from);
3905 } else {
3906 signaled_.erase(sem);
3907 }
3908}
3909
3910void SignaledSemaphores::Reset() {
3911 signaled_.clear();
3912 prev_ = nullptr;
3913}
3914
John Zulaufea943c52022-02-22 11:05:17 -07003915std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3916 // If we don't have one, make it.
3917 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3918 assert(cb_state.get());
3919 auto queue_flags = cb_state->GetQueueFlags();
3920 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3921}
3922
John Zulaufcb7e1672022-05-04 13:46:08 -06003923std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003924 return GetMappedInsert(cb_access_state, command_buffer,
3925 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3926}
3927
3928std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3929 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3930}
3931
3932const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3933 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3934}
3935
3936CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3937 return GetAccessContextShared(command_buffer).get();
3938}
3939
3940CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3941 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3942}
3943
John Zulaufd1f85d42020-04-15 12:23:15 -06003944void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003945 auto *access_context = GetAccessContextNoInsert(command_buffer);
3946 if (access_context) {
3947 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003948 }
3949}
3950
John Zulaufd1f85d42020-04-15 12:23:15 -06003951void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3952 auto access_found = cb_access_state.find(command_buffer);
3953 if (access_found != cb_access_state.end()) {
3954 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003955 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003956 cb_access_state.erase(access_found);
3957 }
3958}
3959
John Zulauf9cb530d2019-09-30 14:14:10 -06003960bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3961 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3962 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003963 const auto *cb_context = GetAccessContext(commandBuffer);
3964 assert(cb_context);
3965 if (!cb_context) return skip;
3966 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003967
John Zulauf3d84f1b2020-03-09 13:33:25 -06003968 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003969 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3970 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003971
3972 for (uint32_t region = 0; region < regionCount; region++) {
3973 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003974 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003975 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003976 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003977 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003978 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003979 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003980 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003981 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003982 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003983 }
John Zulauf16adfc92020-04-08 10:28:33 -06003984 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003985 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003986 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003987 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003988 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003989 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003990 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003991 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003992 }
3993 }
3994 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003995 }
3996 return skip;
3997}
3998
3999void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4000 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004001 auto *cb_context = GetAccessContext(commandBuffer);
4002 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004003 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004004 auto *context = cb_context->GetCurrentAccessContext();
4005
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004006 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4007 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06004008
4009 for (uint32_t region = 0; region < regionCount; region++) {
4010 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004011 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004012 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004013 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004014 }
John Zulauf16adfc92020-04-08 10:28:33 -06004015 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004016 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004017 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004018 }
4019 }
4020}
4021
John Zulauf4a6105a2020-11-17 15:11:05 -07004022void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4023 // Clear out events from the command buffer contexts
4024 for (auto &cb_context : cb_access_state) {
4025 cb_context.second->RecordDestroyEvent(event);
4026 }
4027}
4028
Tony-LunarGef035472021-11-02 10:23:33 -06004029bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4030 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004031 bool skip = false;
4032 const auto *cb_context = GetAccessContext(commandBuffer);
4033 assert(cb_context);
4034 if (!cb_context) return skip;
4035 const auto *context = cb_context->GetCurrentAccessContext();
4036
4037 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004038 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4039 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004040
4041 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4042 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4043 if (src_buffer) {
4044 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004045 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004046 if (hazard.hazard) {
4047 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004048 skip |=
4049 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4050 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4051 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4052 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004053 }
4054 }
4055 if (dst_buffer && !skip) {
4056 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004057 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004058 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004059 skip |=
4060 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4061 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4062 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4063 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004064 }
4065 }
4066 if (skip) break;
4067 }
4068 return skip;
4069}
4070
Tony-LunarGef035472021-11-02 10:23:33 -06004071bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4072 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4073 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4074}
4075
4076bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4077 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4078}
4079
4080void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004081 auto *cb_context = GetAccessContext(commandBuffer);
4082 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004083 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004084 auto *context = cb_context->GetCurrentAccessContext();
4085
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004086 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4087 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004088
4089 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4090 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4091 if (src_buffer) {
4092 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004093 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004094 }
4095 if (dst_buffer) {
4096 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004097 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004098 }
4099 }
4100}
4101
Tony-LunarGef035472021-11-02 10:23:33 -06004102void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4103 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4104}
4105
4106void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4107 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4108}
4109
John Zulauf5c5e88d2019-12-26 11:22:02 -07004110bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4111 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4112 const VkImageCopy *pRegions) const {
4113 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004114 const auto *cb_access_context = GetAccessContext(commandBuffer);
4115 assert(cb_access_context);
4116 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004117
John Zulauf3d84f1b2020-03-09 13:33:25 -06004118 const auto *context = cb_access_context->GetCurrentAccessContext();
4119 assert(context);
4120 if (!context) return skip;
4121
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004122 auto src_image = Get<IMAGE_STATE>(srcImage);
4123 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004124 for (uint32_t region = 0; region < regionCount; region++) {
4125 const auto &copy_region = pRegions[region];
4126 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004127 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004128 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004129 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004130 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004131 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004132 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004133 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004134 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004135 }
4136
4137 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004138 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004139 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004140 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004141 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004142 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004143 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004144 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004145 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004146 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004147 }
4148 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004149
John Zulauf5c5e88d2019-12-26 11:22:02 -07004150 return skip;
4151}
4152
4153void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4154 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4155 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004156 auto *cb_access_context = GetAccessContext(commandBuffer);
4157 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004158 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004159 auto *context = cb_access_context->GetCurrentAccessContext();
4160 assert(context);
4161
Jeremy Gebben9f537102021-10-05 16:37:12 -06004162 auto src_image = Get<IMAGE_STATE>(srcImage);
4163 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004164
4165 for (uint32_t region = 0; region < regionCount; region++) {
4166 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004167 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004168 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004169 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004170 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004171 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004172 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004173 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004174 }
4175 }
4176}
4177
Tony-LunarGb61514a2021-11-02 12:36:51 -06004178bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4179 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004180 bool skip = false;
4181 const auto *cb_access_context = GetAccessContext(commandBuffer);
4182 assert(cb_access_context);
4183 if (!cb_access_context) return skip;
4184
4185 const auto *context = cb_access_context->GetCurrentAccessContext();
4186 assert(context);
4187 if (!context) return skip;
4188
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004189 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4190 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004191
Jeff Leger178b1e52020-10-05 12:22:23 -04004192 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4193 const auto &copy_region = pCopyImageInfo->pRegions[region];
4194 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004195 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004196 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004197 if (hazard.hazard) {
4198 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004199 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004200 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004201 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004202 }
4203 }
4204
4205 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004206 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004207 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004208 if (hazard.hazard) {
4209 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004210 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004211 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004212 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004213 }
4214 if (skip) break;
4215 }
4216 }
4217
4218 return skip;
4219}
4220
Tony-LunarGb61514a2021-11-02 12:36:51 -06004221bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4222 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4223 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4224}
4225
4226bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4227 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4228}
4229
4230void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004231 auto *cb_access_context = GetAccessContext(commandBuffer);
4232 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004233 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004234 auto *context = cb_access_context->GetCurrentAccessContext();
4235 assert(context);
4236
Jeremy Gebben9f537102021-10-05 16:37:12 -06004237 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4238 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004239
4240 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4241 const auto &copy_region = pCopyImageInfo->pRegions[region];
4242 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004243 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004244 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004245 }
4246 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004247 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004248 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004249 }
4250 }
4251}
4252
Tony-LunarGb61514a2021-11-02 12:36:51 -06004253void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4254 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4255}
4256
4257void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4258 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4259}
4260
John Zulauf9cb530d2019-09-30 14:14:10 -06004261bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4262 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4263 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4264 uint32_t bufferMemoryBarrierCount,
4265 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4266 uint32_t imageMemoryBarrierCount,
4267 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4268 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004269 const auto *cb_access_context = GetAccessContext(commandBuffer);
4270 assert(cb_access_context);
4271 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004272
John Zulauf36ef9282021-02-02 11:47:24 -07004273 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4274 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4275 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4276 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004277 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004278 return skip;
4279}
4280
4281void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4282 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4283 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4284 uint32_t bufferMemoryBarrierCount,
4285 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4286 uint32_t imageMemoryBarrierCount,
4287 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004288 auto *cb_access_context = GetAccessContext(commandBuffer);
4289 assert(cb_access_context);
4290 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004291
John Zulauf1bf30522021-09-03 15:39:06 -06004292 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4293 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4294 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4295 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004296}
4297
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004298bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4299 const VkDependencyInfoKHR *pDependencyInfo) const {
4300 bool skip = false;
4301 const auto *cb_access_context = GetAccessContext(commandBuffer);
4302 assert(cb_access_context);
4303 if (!cb_access_context) return skip;
4304
4305 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4306 skip = pipeline_barrier.Validate(*cb_access_context);
4307 return skip;
4308}
4309
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004310bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4311 const VkDependencyInfo *pDependencyInfo) const {
4312 bool skip = false;
4313 const auto *cb_access_context = GetAccessContext(commandBuffer);
4314 assert(cb_access_context);
4315 if (!cb_access_context) return skip;
4316
4317 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4318 skip = pipeline_barrier.Validate(*cb_access_context);
4319 return skip;
4320}
4321
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004322void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4323 auto *cb_access_context = GetAccessContext(commandBuffer);
4324 assert(cb_access_context);
4325 if (!cb_access_context) return;
4326
John Zulauf1bf30522021-09-03 15:39:06 -06004327 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4328 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004329}
4330
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004331void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4332 auto *cb_access_context = GetAccessContext(commandBuffer);
4333 assert(cb_access_context);
4334 if (!cb_access_context) return;
4335
4336 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4337 *pDependencyInfo);
4338}
4339
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004340void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004341 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004342 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004343
John Zulauf5f13a792020-03-10 07:31:21 -06004344 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4345 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004346 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004347 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4348 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004349
John Zulauf1d5f9c12022-05-13 14:51:08 -06004350 QueueId queue_id = QueueSyncState::kQueueIdBase;
4351 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004352 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004353 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004354 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4355 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004356}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004357
John Zulauf355e49b2020-04-24 15:11:15 -06004358bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004359 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004360 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004361 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004362 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004363 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004364 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004365 }
John Zulauf355e49b2020-04-24 15:11:15 -06004366 return skip;
4367}
4368
4369bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4370 VkSubpassContents contents) const {
4371 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004372 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004373 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004374 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004375 return skip;
4376}
4377
4378bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004379 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004380 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004381 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004382 return skip;
4383}
4384
4385bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4386 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004387 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004388 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004389 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004390 return skip;
4391}
4392
John Zulauf3d84f1b2020-03-09 13:33:25 -06004393void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4394 VkResult result) {
4395 // The state tracker sets up the command buffer state
4396 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4397
4398 // Create/initialize the structure that trackers accesses at the command buffer scope.
4399 auto cb_access_context = GetAccessContext(commandBuffer);
4400 assert(cb_access_context);
4401 cb_access_context->Reset();
4402}
4403
4404void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004405 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004406 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004407 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004408 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004409 }
4410}
4411
4412void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4413 VkSubpassContents contents) {
4414 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004415 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004416 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004417 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004418}
4419
4420void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4421 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4422 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004423 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004424}
4425
4426void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4427 const VkRenderPassBeginInfo *pRenderPassBegin,
4428 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4429 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004430 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004431}
4432
Mike Schuchardt2df08912020-12-15 16:28:09 -08004433bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004434 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004435 bool skip = false;
4436
4437 auto cb_context = GetAccessContext(commandBuffer);
4438 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004439 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004440 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004441 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004442}
4443
4444bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4445 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004446 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004447 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004448 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004449 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4450 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004451 return skip;
4452}
4453
Mike Schuchardt2df08912020-12-15 16:28:09 -08004454bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4455 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004456 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004457 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004458 return skip;
4459}
4460
4461bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4462 const VkSubpassEndInfo *pSubpassEndInfo) const {
4463 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004464 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004465 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004466}
4467
4468void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004469 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004470 auto cb_context = GetAccessContext(commandBuffer);
4471 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004472 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004473
sjfricke0bea06e2022-06-05 09:22:26 +09004474 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004475}
4476
4477void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4478 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004479 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004480 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004481 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004482}
4483
4484void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4485 const VkSubpassEndInfo *pSubpassEndInfo) {
4486 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004487 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004488}
4489
4490void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4491 const VkSubpassEndInfo *pSubpassEndInfo) {
4492 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004493 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004494}
4495
sfricke-samsung85584a72021-09-30 21:43:38 -07004496bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004497 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004498 bool skip = false;
4499
4500 auto cb_context = GetAccessContext(commandBuffer);
4501 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004502 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004503
sjfricke0bea06e2022-06-05 09:22:26 +09004504 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004505 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004506 return skip;
4507}
4508
4509bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4510 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004511 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004512 return skip;
4513}
4514
Mike Schuchardt2df08912020-12-15 16:28:09 -08004515bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004516 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004517 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004518 return skip;
4519}
4520
4521bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004522 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004523 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004524 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004525 return skip;
4526}
4527
sjfricke0bea06e2022-06-05 09:22:26 +09004528void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4529 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004530 // Resolve the all subpass contexts to the command buffer contexts
4531 auto cb_context = GetAccessContext(commandBuffer);
4532 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004533 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004534
sjfricke0bea06e2022-06-05 09:22:26 +09004535 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004536}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004537
John Zulauf33fc1d52020-07-17 11:01:10 -06004538// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4539// updates to a resource which do not conflict at the byte level.
4540// TODO: Revisit this rule to see if it needs to be tighter or looser
4541// TODO: Add programatic control over suppression heuristics
4542bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4543 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4544}
4545
John Zulauf3d84f1b2020-03-09 13:33:25 -06004546void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004547 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004548 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004549}
4550
4551void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004552 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004553 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004554}
4555
4556void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004557 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004558 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004559}
locke-lunarga19c71d2020-03-02 18:17:04 -07004560
sfricke-samsung71f04e32022-03-16 01:21:21 -05004561template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004562bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004563 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4564 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004565 bool skip = false;
4566 const auto *cb_access_context = GetAccessContext(commandBuffer);
4567 assert(cb_access_context);
4568 if (!cb_access_context) return skip;
4569
4570 const auto *context = cb_access_context->GetCurrentAccessContext();
4571 assert(context);
4572 if (!context) return skip;
4573
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004574 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4575 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004576
4577 for (uint32_t region = 0; region < regionCount; region++) {
4578 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004579 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004580 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004581 if (src_buffer) {
4582 ResourceAccessRange src_range =
4583 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004584 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004585 if (hazard.hazard) {
4586 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004587 skip |=
4588 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4589 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4590 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4591 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004592 }
4593 }
4594
Jeremy Gebben40a22942020-12-22 14:22:06 -07004595 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004596 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004597 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004598 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004599 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004600 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004601 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004602 }
4603 if (skip) break;
4604 }
4605 if (skip) break;
4606 }
4607 return skip;
4608}
4609
Jeff Leger178b1e52020-10-05 12:22:23 -04004610bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4611 VkImageLayout dstImageLayout, uint32_t regionCount,
4612 const VkBufferImageCopy *pRegions) const {
4613 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004614 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004615}
4616
4617bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4618 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4619 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4620 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004621 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4622}
4623
4624bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4625 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4626 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4627 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4628 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004629}
4630
sfricke-samsung71f04e32022-03-16 01:21:21 -05004631template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004632void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004633 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4634 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004635 auto *cb_access_context = GetAccessContext(commandBuffer);
4636 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004637
Jeff Leger178b1e52020-10-05 12:22:23 -04004638 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004639 auto *context = cb_access_context->GetCurrentAccessContext();
4640 assert(context);
4641
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004642 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4643 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004644
4645 for (uint32_t region = 0; region < regionCount; region++) {
4646 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004647 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004648 if (src_buffer) {
4649 ResourceAccessRange src_range =
4650 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004651 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004652 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004653 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004654 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004655 }
4656 }
4657}
4658
Jeff Leger178b1e52020-10-05 12:22:23 -04004659void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4660 VkImageLayout dstImageLayout, uint32_t regionCount,
4661 const VkBufferImageCopy *pRegions) {
4662 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004663 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004664}
4665
4666void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4667 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4668 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4669 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4670 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004671 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4672}
4673
4674void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4675 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4676 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4677 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4678 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4679 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004680}
4681
sfricke-samsung71f04e32022-03-16 01:21:21 -05004682template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004683bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004684 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4685 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004686 bool skip = false;
4687 const auto *cb_access_context = GetAccessContext(commandBuffer);
4688 assert(cb_access_context);
4689 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004690
locke-lunarga19c71d2020-03-02 18:17:04 -07004691 const auto *context = cb_access_context->GetCurrentAccessContext();
4692 assert(context);
4693 if (!context) return skip;
4694
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004695 auto src_image = Get<IMAGE_STATE>(srcImage);
4696 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004697 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004698 for (uint32_t region = 0; region < regionCount; region++) {
4699 const auto &copy_region = pRegions[region];
4700 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004701 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004702 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004703 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004704 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004705 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004706 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004707 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004708 }
John Zulauf477700e2021-01-06 11:41:49 -07004709 if (dst_mem) {
4710 ResourceAccessRange dst_range =
4711 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004712 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004713 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004714 skip |=
4715 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4716 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4717 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4718 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004719 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004720 }
4721 }
4722 if (skip) break;
4723 }
4724 return skip;
4725}
4726
Jeff Leger178b1e52020-10-05 12:22:23 -04004727bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4728 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4729 const VkBufferImageCopy *pRegions) const {
4730 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004731 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004732}
4733
4734bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4735 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4736 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4737 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004738 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4739}
4740
4741bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4742 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4743 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4744 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4745 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004746}
4747
sfricke-samsung71f04e32022-03-16 01:21:21 -05004748template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004749void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004750 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004751 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004752 auto *cb_access_context = GetAccessContext(commandBuffer);
4753 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004754
Jeff Leger178b1e52020-10-05 12:22:23 -04004755 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004756 auto *context = cb_access_context->GetCurrentAccessContext();
4757 assert(context);
4758
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004759 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004760 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004761 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004762 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004763
4764 for (uint32_t region = 0; region < regionCount; region++) {
4765 const auto &copy_region = pRegions[region];
4766 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004767 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004768 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004769 if (dst_buffer) {
4770 ResourceAccessRange dst_range =
4771 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004772 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004773 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004774 }
4775 }
4776}
4777
Jeff Leger178b1e52020-10-05 12:22:23 -04004778void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4779 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4780 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004781 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004782}
4783
4784void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4785 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4786 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4787 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4788 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004789 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4790}
4791
4792void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4793 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4794 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4795 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4796 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4797 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004798}
4799
4800template <typename RegionType>
4801bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4802 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004803 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004804 bool skip = false;
4805 const auto *cb_access_context = GetAccessContext(commandBuffer);
4806 assert(cb_access_context);
4807 if (!cb_access_context) return skip;
4808
4809 const auto *context = cb_access_context->GetCurrentAccessContext();
4810 assert(context);
4811 if (!context) return skip;
4812
sjfricke0bea06e2022-06-05 09:22:26 +09004813 const char *caller_name = CommandTypeString(cmd_type);
4814
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004815 auto src_image = Get<IMAGE_STATE>(srcImage);
4816 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004817
4818 for (uint32_t region = 0; region < regionCount; region++) {
4819 const auto &blit_region = pRegions[region];
4820 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004821 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4822 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4823 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4824 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4825 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4826 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004827 auto hazard =
4828 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004829 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004830 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004831 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004832 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004833 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004834 }
4835 }
4836
4837 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004838 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4839 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4840 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4841 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4842 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4843 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004844 auto hazard =
4845 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004846 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004847 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004848 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004849 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004850 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004851 }
4852 if (skip) break;
4853 }
4854 }
4855
4856 return skip;
4857}
4858
Jeff Leger178b1e52020-10-05 12:22:23 -04004859bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4860 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4861 const VkImageBlit *pRegions, VkFilter filter) const {
4862 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004863 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004864}
4865
4866bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4867 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4868 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4869 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004870 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004871}
4872
Tony-LunarG542ae912021-11-04 16:06:44 -06004873bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4874 const VkBlitImageInfo2 *pBlitImageInfo) const {
4875 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004876 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4877 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004878}
4879
Jeff Leger178b1e52020-10-05 12:22:23 -04004880template <typename RegionType>
4881void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4882 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4883 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004884 auto *cb_access_context = GetAccessContext(commandBuffer);
4885 assert(cb_access_context);
4886 auto *context = cb_access_context->GetCurrentAccessContext();
4887 assert(context);
4888
Jeremy Gebben9f537102021-10-05 16:37:12 -06004889 auto src_image = Get<IMAGE_STATE>(srcImage);
4890 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004891
4892 for (uint32_t region = 0; region < regionCount; region++) {
4893 const auto &blit_region = pRegions[region];
4894 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004895 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4896 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4897 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4898 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4899 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4900 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004901 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004902 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004903 }
4904 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004905 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4906 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4907 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4908 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4909 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4910 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004911 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004912 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004913 }
4914 }
4915}
locke-lunarg36ba2592020-04-03 09:42:04 -06004916
Jeff Leger178b1e52020-10-05 12:22:23 -04004917void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4918 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4919 const VkImageBlit *pRegions, VkFilter filter) {
4920 auto *cb_access_context = GetAccessContext(commandBuffer);
4921 assert(cb_access_context);
4922 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4923 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4924 pRegions, filter);
4925 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4926}
4927
4928void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4929 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4930 auto *cb_access_context = GetAccessContext(commandBuffer);
4931 assert(cb_access_context);
4932 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4933 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4934 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4935 pBlitImageInfo->filter, tag);
4936}
4937
Tony-LunarG542ae912021-11-04 16:06:44 -06004938void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4939 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4940 auto *cb_access_context = GetAccessContext(commandBuffer);
4941 assert(cb_access_context);
4942 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4943 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4944 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4945 pBlitImageInfo->filter, tag);
4946}
4947
John Zulauffaea0ee2021-01-14 14:01:32 -07004948bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4949 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4950 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09004951 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004952 bool skip = false;
4953 if (drawCount == 0) return skip;
4954
sjfricke0bea06e2022-06-05 09:22:26 +09004955 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004956 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004957 VkDeviceSize size = struct_size;
4958 if (drawCount == 1 || stride == size) {
4959 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004960 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004961 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4962 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004963 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004964 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004965 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004966 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004967 }
4968 } else {
4969 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004970 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004971 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4972 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004973 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004974 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
4975 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
4976 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004977 break;
4978 }
4979 }
4980 }
4981 return skip;
4982}
4983
John Zulauf14940722021-04-12 15:19:02 -06004984void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06004985 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4986 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004987 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004988 VkDeviceSize size = struct_size;
4989 if (drawCount == 1 || stride == size) {
4990 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004991 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004992 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004993 } else {
4994 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004995 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004996 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4997 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004998 }
4999 }
5000}
5001
John Zulauffaea0ee2021-01-14 14:01:32 -07005002bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5003 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005004 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005005 bool skip = false;
5006
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005007 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005008 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005009 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5010 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005011 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005012 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
5013 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5014 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005015 }
5016 return skip;
5017}
5018
John Zulauf14940722021-04-12 15:19:02 -06005019void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005020 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005021 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005022 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005023}
5024
locke-lunarg36ba2592020-04-03 09:42:04 -06005025bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005026 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005027 const auto *cb_access_context = GetAccessContext(commandBuffer);
5028 assert(cb_access_context);
5029 if (!cb_access_context) return skip;
5030
sjfricke0bea06e2022-06-05 09:22:26 +09005031 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005032 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005033}
5034
5035void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005036 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005037 auto *cb_access_context = GetAccessContext(commandBuffer);
5038 assert(cb_access_context);
5039 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005040
locke-lunarg61870c22020-06-09 14:51:50 -06005041 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005042}
locke-lunarge1a67022020-04-29 00:15:36 -06005043
5044bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005045 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005046 const auto *cb_access_context = GetAccessContext(commandBuffer);
5047 assert(cb_access_context);
5048 if (!cb_access_context) return skip;
5049
5050 const auto *context = cb_access_context->GetCurrentAccessContext();
5051 assert(context);
5052 if (!context) return skip;
5053
sjfricke0bea06e2022-06-05 09:22:26 +09005054 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005055 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005056 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005057 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005058}
5059
5060void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005061 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005062 auto *cb_access_context = GetAccessContext(commandBuffer);
5063 assert(cb_access_context);
5064 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5065 auto *context = cb_access_context->GetCurrentAccessContext();
5066 assert(context);
5067
locke-lunarg61870c22020-06-09 14:51:50 -06005068 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5069 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005070}
5071
5072bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5073 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005074 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005075 const auto *cb_access_context = GetAccessContext(commandBuffer);
5076 assert(cb_access_context);
5077 if (!cb_access_context) return skip;
5078
sjfricke0bea06e2022-06-05 09:22:26 +09005079 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5080 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5081 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005082 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005083}
5084
5085void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5086 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005087 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005088 auto *cb_access_context = GetAccessContext(commandBuffer);
5089 assert(cb_access_context);
5090 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005091
locke-lunarg61870c22020-06-09 14:51:50 -06005092 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5093 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5094 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005095}
5096
5097bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5098 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005099 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005100 const auto *cb_access_context = GetAccessContext(commandBuffer);
5101 assert(cb_access_context);
5102 if (!cb_access_context) return skip;
5103
sjfricke0bea06e2022-06-05 09:22:26 +09005104 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5105 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5106 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005107 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005108}
5109
5110void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5111 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005112 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005113 auto *cb_access_context = GetAccessContext(commandBuffer);
5114 assert(cb_access_context);
5115 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005116
locke-lunarg61870c22020-06-09 14:51:50 -06005117 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5118 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5119 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005120}
5121
5122bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5123 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005124 bool skip = false;
5125 if (drawCount == 0) return skip;
5126
locke-lunargff255f92020-05-13 18:53:52 -06005127 const auto *cb_access_context = GetAccessContext(commandBuffer);
5128 assert(cb_access_context);
5129 if (!cb_access_context) return skip;
5130
5131 const auto *context = cb_access_context->GetCurrentAccessContext();
5132 assert(context);
5133 if (!context) return skip;
5134
sjfricke0bea06e2022-06-05 09:22:26 +09005135 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5136 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005137 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005138 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005139
5140 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5141 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5142 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005143 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005144 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005145}
5146
5147void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5148 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005149 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005150 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005151 auto *cb_access_context = GetAccessContext(commandBuffer);
5152 assert(cb_access_context);
5153 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5154 auto *context = cb_access_context->GetCurrentAccessContext();
5155 assert(context);
5156
locke-lunarg61870c22020-06-09 14:51:50 -06005157 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5158 cb_access_context->RecordDrawSubpassAttachment(tag);
5159 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005160
5161 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5162 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5163 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005164 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005165}
5166
5167bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5168 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005169 bool skip = false;
5170 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005171 const auto *cb_access_context = GetAccessContext(commandBuffer);
5172 assert(cb_access_context);
5173 if (!cb_access_context) return skip;
5174
5175 const auto *context = cb_access_context->GetCurrentAccessContext();
5176 assert(context);
5177 if (!context) return skip;
5178
sjfricke0bea06e2022-06-05 09:22:26 +09005179 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5180 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005181 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005182 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005183
5184 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5185 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5186 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005187 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005188 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005189}
5190
5191void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5192 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005193 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005194 auto *cb_access_context = GetAccessContext(commandBuffer);
5195 assert(cb_access_context);
5196 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5197 auto *context = cb_access_context->GetCurrentAccessContext();
5198 assert(context);
5199
locke-lunarg61870c22020-06-09 14:51:50 -06005200 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5201 cb_access_context->RecordDrawSubpassAttachment(tag);
5202 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005203
5204 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5205 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5206 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005207 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005208}
5209
5210bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5211 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005212 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005213 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005214 const auto *cb_access_context = GetAccessContext(commandBuffer);
5215 assert(cb_access_context);
5216 if (!cb_access_context) return skip;
5217
5218 const auto *context = cb_access_context->GetCurrentAccessContext();
5219 assert(context);
5220 if (!context) return skip;
5221
sjfricke0bea06e2022-06-05 09:22:26 +09005222 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5223 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005224 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005225 maxDrawCount, stride, cmd_type);
5226 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005227
5228 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5229 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5230 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005231 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005232 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005233}
5234
5235bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5236 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5237 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005238 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005239 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005240}
5241
sfricke-samsung85584a72021-09-30 21:43:38 -07005242void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5243 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5244 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005245 auto *cb_access_context = GetAccessContext(commandBuffer);
5246 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005247 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005248 auto *context = cb_access_context->GetCurrentAccessContext();
5249 assert(context);
5250
locke-lunarg61870c22020-06-09 14:51:50 -06005251 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5252 cb_access_context->RecordDrawSubpassAttachment(tag);
5253 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5254 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005255
5256 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5257 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5258 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005259 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005260}
5261
sfricke-samsung85584a72021-09-30 21:43:38 -07005262void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5263 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5264 uint32_t stride) {
5265 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5266 stride);
5267 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5268 CMD_DRAWINDIRECTCOUNT);
5269}
locke-lunarge1a67022020-04-29 00:15:36 -06005270bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5271 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5272 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005273 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005274 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005275}
5276
5277void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5278 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5279 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005280 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5281 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005282 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5283 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005284}
5285
5286bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5287 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5288 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005289 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005290 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005291}
5292
5293void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5294 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5295 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005296 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5297 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005298 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5299 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005300}
5301
5302bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5303 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005304 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005305 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005306 const auto *cb_access_context = GetAccessContext(commandBuffer);
5307 assert(cb_access_context);
5308 if (!cb_access_context) return skip;
5309
5310 const auto *context = cb_access_context->GetCurrentAccessContext();
5311 assert(context);
5312 if (!context) return skip;
5313
sjfricke0bea06e2022-06-05 09:22:26 +09005314 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5315 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005316 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005317 offset, maxDrawCount, stride, cmd_type);
5318 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005319
5320 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5321 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5322 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005323 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005324 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005325}
5326
5327bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5328 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5329 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005330 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005331 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005332}
5333
sfricke-samsung85584a72021-09-30 21:43:38 -07005334void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5335 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5336 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005337 auto *cb_access_context = GetAccessContext(commandBuffer);
5338 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005339 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005340 auto *context = cb_access_context->GetCurrentAccessContext();
5341 assert(context);
5342
locke-lunarg61870c22020-06-09 14:51:50 -06005343 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5344 cb_access_context->RecordDrawSubpassAttachment(tag);
5345 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5346 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005347
5348 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5349 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005350 // We will update the index and vertex buffer in SubmitQueue in the future.
5351 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005352}
5353
sfricke-samsung85584a72021-09-30 21:43:38 -07005354void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5355 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5356 uint32_t maxDrawCount, uint32_t stride) {
5357 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5358 maxDrawCount, stride);
5359 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5360 CMD_DRAWINDEXEDINDIRECTCOUNT);
5361}
5362
locke-lunarge1a67022020-04-29 00:15:36 -06005363bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5364 VkDeviceSize offset, VkBuffer countBuffer,
5365 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5366 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005367 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005368 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005369}
5370
5371void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5372 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5373 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005374 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5375 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005376 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5377 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005378}
5379
5380bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5381 VkDeviceSize offset, VkBuffer countBuffer,
5382 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5383 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005384 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005385 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005386}
5387
5388void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5389 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5390 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005391 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5392 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005393 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5394 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005395}
5396
5397bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5398 const VkClearColorValue *pColor, uint32_t rangeCount,
5399 const VkImageSubresourceRange *pRanges) const {
5400 bool skip = false;
5401 const auto *cb_access_context = GetAccessContext(commandBuffer);
5402 assert(cb_access_context);
5403 if (!cb_access_context) return skip;
5404
5405 const auto *context = cb_access_context->GetCurrentAccessContext();
5406 assert(context);
5407 if (!context) return skip;
5408
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005409 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005410
5411 for (uint32_t index = 0; index < rangeCount; index++) {
5412 const auto &range = pRanges[index];
5413 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005414 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005415 if (hazard.hazard) {
5416 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005417 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005418 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005419 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005420 }
5421 }
5422 }
5423 return skip;
5424}
5425
5426void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5427 const VkClearColorValue *pColor, uint32_t rangeCount,
5428 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005429 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005430 auto *cb_access_context = GetAccessContext(commandBuffer);
5431 assert(cb_access_context);
5432 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5433 auto *context = cb_access_context->GetCurrentAccessContext();
5434 assert(context);
5435
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005436 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005437
5438 for (uint32_t index = 0; index < rangeCount; index++) {
5439 const auto &range = pRanges[index];
5440 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005441 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005442 }
5443 }
5444}
5445
5446bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5447 VkImageLayout imageLayout,
5448 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5449 const VkImageSubresourceRange *pRanges) const {
5450 bool skip = false;
5451 const auto *cb_access_context = GetAccessContext(commandBuffer);
5452 assert(cb_access_context);
5453 if (!cb_access_context) return skip;
5454
5455 const auto *context = cb_access_context->GetCurrentAccessContext();
5456 assert(context);
5457 if (!context) return skip;
5458
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005459 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005460
5461 for (uint32_t index = 0; index < rangeCount; index++) {
5462 const auto &range = pRanges[index];
5463 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005464 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005465 if (hazard.hazard) {
5466 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005467 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005468 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005469 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005470 }
5471 }
5472 }
5473 return skip;
5474}
5475
5476void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5477 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5478 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005479 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005480 auto *cb_access_context = GetAccessContext(commandBuffer);
5481 assert(cb_access_context);
5482 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5483 auto *context = cb_access_context->GetCurrentAccessContext();
5484 assert(context);
5485
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005486 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005487
5488 for (uint32_t index = 0; index < rangeCount; index++) {
5489 const auto &range = pRanges[index];
5490 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005491 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005492 }
5493 }
5494}
5495
5496bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5497 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5498 VkDeviceSize dstOffset, VkDeviceSize stride,
5499 VkQueryResultFlags flags) const {
5500 bool skip = false;
5501 const auto *cb_access_context = GetAccessContext(commandBuffer);
5502 assert(cb_access_context);
5503 if (!cb_access_context) return skip;
5504
5505 const auto *context = cb_access_context->GetCurrentAccessContext();
5506 assert(context);
5507 if (!context) return skip;
5508
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005509 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005510
5511 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005512 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005513 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005514 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005515 skip |=
5516 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5517 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005518 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005519 }
5520 }
locke-lunargff255f92020-05-13 18:53:52 -06005521
5522 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005523 return skip;
5524}
5525
5526void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5527 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5528 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005529 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5530 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005531 auto *cb_access_context = GetAccessContext(commandBuffer);
5532 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005533 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005534 auto *context = cb_access_context->GetCurrentAccessContext();
5535 assert(context);
5536
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005537 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005538
5539 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005540 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005541 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005542 }
locke-lunargff255f92020-05-13 18:53:52 -06005543
5544 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005545}
5546
5547bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5548 VkDeviceSize size, uint32_t data) const {
5549 bool skip = false;
5550 const auto *cb_access_context = GetAccessContext(commandBuffer);
5551 assert(cb_access_context);
5552 if (!cb_access_context) return skip;
5553
5554 const auto *context = cb_access_context->GetCurrentAccessContext();
5555 assert(context);
5556 if (!context) return skip;
5557
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005558 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005559
5560 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005561 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005562 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005563 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005564 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005565 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005566 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005567 }
5568 }
5569 return skip;
5570}
5571
5572void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5573 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005574 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005575 auto *cb_access_context = GetAccessContext(commandBuffer);
5576 assert(cb_access_context);
5577 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5578 auto *context = cb_access_context->GetCurrentAccessContext();
5579 assert(context);
5580
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005581 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005582
5583 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005584 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005585 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005586 }
5587}
5588
5589bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5590 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5591 const VkImageResolve *pRegions) const {
5592 bool skip = false;
5593 const auto *cb_access_context = GetAccessContext(commandBuffer);
5594 assert(cb_access_context);
5595 if (!cb_access_context) return skip;
5596
5597 const auto *context = cb_access_context->GetCurrentAccessContext();
5598 assert(context);
5599 if (!context) return skip;
5600
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005601 auto src_image = Get<IMAGE_STATE>(srcImage);
5602 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005603
5604 for (uint32_t region = 0; region < regionCount; region++) {
5605 const auto &resolve_region = pRegions[region];
5606 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005607 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005608 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005609 if (hazard.hazard) {
5610 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005611 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005612 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005613 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005614 }
5615 }
5616
5617 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005618 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005619 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005620 if (hazard.hazard) {
5621 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005622 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005623 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005624 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005625 }
5626 if (skip) break;
5627 }
5628 }
5629
5630 return skip;
5631}
5632
5633void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5634 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5635 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005636 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5637 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005638 auto *cb_access_context = GetAccessContext(commandBuffer);
5639 assert(cb_access_context);
5640 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5641 auto *context = cb_access_context->GetCurrentAccessContext();
5642 assert(context);
5643
Jeremy Gebben9f537102021-10-05 16:37:12 -06005644 auto src_image = Get<IMAGE_STATE>(srcImage);
5645 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005646
5647 for (uint32_t region = 0; region < regionCount; region++) {
5648 const auto &resolve_region = pRegions[region];
5649 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005650 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005651 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005652 }
5653 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005654 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005655 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005656 }
5657 }
5658}
5659
Tony-LunarG562fc102021-11-12 13:58:35 -07005660bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5661 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005662 bool skip = false;
5663 const auto *cb_access_context = GetAccessContext(commandBuffer);
5664 assert(cb_access_context);
5665 if (!cb_access_context) return skip;
5666
5667 const auto *context = cb_access_context->GetCurrentAccessContext();
5668 assert(context);
5669 if (!context) return skip;
5670
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005671 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5672 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005673
5674 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5675 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5676 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005677 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005678 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005679 if (hazard.hazard) {
5680 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005681 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005682 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005683 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005684 }
5685 }
5686
5687 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005688 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005689 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005690 if (hazard.hazard) {
5691 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005692 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005693 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005694 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005695 }
5696 if (skip) break;
5697 }
5698 }
5699
5700 return skip;
5701}
5702
Tony-LunarG562fc102021-11-12 13:58:35 -07005703bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5704 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5705 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5706}
5707
5708bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5709 const VkResolveImageInfo2 *pResolveImageInfo) const {
5710 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5711}
5712
5713void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5714 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005715 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5716 auto *cb_access_context = GetAccessContext(commandBuffer);
5717 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005718 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005719 auto *context = cb_access_context->GetCurrentAccessContext();
5720 assert(context);
5721
Jeremy Gebben9f537102021-10-05 16:37:12 -06005722 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5723 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005724
5725 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5726 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5727 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005728 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005729 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005730 }
5731 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005732 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005733 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005734 }
5735 }
5736}
5737
Tony-LunarG562fc102021-11-12 13:58:35 -07005738void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5739 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5740 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5741}
5742
5743void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5744 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5745}
5746
locke-lunarge1a67022020-04-29 00:15:36 -06005747bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5748 VkDeviceSize dataSize, const void *pData) const {
5749 bool skip = false;
5750 const auto *cb_access_context = GetAccessContext(commandBuffer);
5751 assert(cb_access_context);
5752 if (!cb_access_context) return skip;
5753
5754 const auto *context = cb_access_context->GetCurrentAccessContext();
5755 assert(context);
5756 if (!context) return skip;
5757
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005758 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005759
5760 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005761 // VK_WHOLE_SIZE not allowed
5762 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005763 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005764 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005765 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005766 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005767 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005768 }
5769 }
5770 return skip;
5771}
5772
5773void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5774 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005775 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005776 auto *cb_access_context = GetAccessContext(commandBuffer);
5777 assert(cb_access_context);
5778 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5779 auto *context = cb_access_context->GetCurrentAccessContext();
5780 assert(context);
5781
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005782 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005783
5784 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005785 // VK_WHOLE_SIZE not allowed
5786 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005787 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005788 }
5789}
locke-lunargff255f92020-05-13 18:53:52 -06005790
5791bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5792 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5793 bool skip = false;
5794 const auto *cb_access_context = GetAccessContext(commandBuffer);
5795 assert(cb_access_context);
5796 if (!cb_access_context) return skip;
5797
5798 const auto *context = cb_access_context->GetCurrentAccessContext();
5799 assert(context);
5800 if (!context) return skip;
5801
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005802 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005803
5804 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005805 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005806 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005807 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005808 skip |=
5809 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5810 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005811 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005812 }
5813 }
5814 return skip;
5815}
5816
5817void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5818 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005819 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005820 auto *cb_access_context = GetAccessContext(commandBuffer);
5821 assert(cb_access_context);
5822 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5823 auto *context = cb_access_context->GetCurrentAccessContext();
5824 assert(context);
5825
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005826 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005827
5828 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005829 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005830 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005831 }
5832}
John Zulauf49beb112020-11-04 16:06:31 -07005833
5834bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5835 bool skip = false;
5836 const auto *cb_context = GetAccessContext(commandBuffer);
5837 assert(cb_context);
5838 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005839 const auto *access_context = cb_context->GetCurrentAccessContext();
5840 assert(access_context);
5841 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005842
John Zulaufe0757ba2022-06-10 16:51:45 -06005843 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005844 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005845}
5846
5847void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5848 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5849 auto *cb_context = GetAccessContext(commandBuffer);
5850 assert(cb_context);
5851 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005852
5853 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
5854 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07005855}
5856
John Zulauf4edde622021-02-15 08:54:50 -07005857bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5858 const VkDependencyInfoKHR *pDependencyInfo) const {
5859 bool skip = false;
5860 const auto *cb_context = GetAccessContext(commandBuffer);
5861 assert(cb_context);
5862 if (!cb_context || !pDependencyInfo) return skip;
5863
John Zulaufe0757ba2022-06-10 16:51:45 -06005864 const auto *access_context = cb_context->GetCurrentAccessContext();
5865 assert(access_context);
5866 if (!access_context) return skip;
5867
5868 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07005869 return set_event_op.Validate(*cb_context);
5870}
5871
Tony-LunarGc43525f2021-11-15 16:12:38 -07005872bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5873 const VkDependencyInfo *pDependencyInfo) const {
5874 bool skip = false;
5875 const auto *cb_context = GetAccessContext(commandBuffer);
5876 assert(cb_context);
5877 if (!cb_context || !pDependencyInfo) return skip;
5878
John Zulaufe0757ba2022-06-10 16:51:45 -06005879 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07005880 return set_event_op.Validate(*cb_context);
5881}
5882
John Zulauf4edde622021-02-15 08:54:50 -07005883void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5884 const VkDependencyInfoKHR *pDependencyInfo) {
5885 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5886 auto *cb_context = GetAccessContext(commandBuffer);
5887 assert(cb_context);
5888 if (!cb_context || !pDependencyInfo) return;
5889
John Zulaufe0757ba2022-06-10 16:51:45 -06005890 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5891 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07005892}
5893
Tony-LunarGc43525f2021-11-15 16:12:38 -07005894void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5895 const VkDependencyInfo *pDependencyInfo) {
5896 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5897 auto *cb_context = GetAccessContext(commandBuffer);
5898 assert(cb_context);
5899 if (!cb_context || !pDependencyInfo) return;
5900
John Zulaufe0757ba2022-06-10 16:51:45 -06005901 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5902 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07005903}
5904
John Zulauf49beb112020-11-04 16:06:31 -07005905bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5906 VkPipelineStageFlags stageMask) const {
5907 bool skip = false;
5908 const auto *cb_context = GetAccessContext(commandBuffer);
5909 assert(cb_context);
5910 if (!cb_context) return skip;
5911
John Zulauf36ef9282021-02-02 11:47:24 -07005912 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005913 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005914}
5915
5916void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5917 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5918 auto *cb_context = GetAccessContext(commandBuffer);
5919 assert(cb_context);
5920 if (!cb_context) return;
5921
John Zulauf1bf30522021-09-03 15:39:06 -06005922 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005923}
5924
John Zulauf4edde622021-02-15 08:54:50 -07005925bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5926 VkPipelineStageFlags2KHR stageMask) const {
5927 bool skip = false;
5928 const auto *cb_context = GetAccessContext(commandBuffer);
5929 assert(cb_context);
5930 if (!cb_context) return skip;
5931
5932 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5933 return reset_event_op.Validate(*cb_context);
5934}
5935
Tony-LunarGa2662db2021-11-16 07:26:24 -07005936bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5937 VkPipelineStageFlags2 stageMask) const {
5938 bool skip = false;
5939 const auto *cb_context = GetAccessContext(commandBuffer);
5940 assert(cb_context);
5941 if (!cb_context) return skip;
5942
5943 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5944 return reset_event_op.Validate(*cb_context);
5945}
5946
John Zulauf4edde622021-02-15 08:54:50 -07005947void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5948 VkPipelineStageFlags2KHR stageMask) {
5949 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5950 auto *cb_context = GetAccessContext(commandBuffer);
5951 assert(cb_context);
5952 if (!cb_context) return;
5953
John Zulauf1bf30522021-09-03 15:39:06 -06005954 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005955}
5956
Tony-LunarGa2662db2021-11-16 07:26:24 -07005957void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5958 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5959 auto *cb_context = GetAccessContext(commandBuffer);
5960 assert(cb_context);
5961 if (!cb_context) return;
5962
5963 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5964}
5965
John Zulauf49beb112020-11-04 16:06:31 -07005966bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5967 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5968 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5969 uint32_t bufferMemoryBarrierCount,
5970 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5971 uint32_t imageMemoryBarrierCount,
5972 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5973 bool skip = false;
5974 const auto *cb_context = GetAccessContext(commandBuffer);
5975 assert(cb_context);
5976 if (!cb_context) return skip;
5977
John Zulauf36ef9282021-02-02 11:47:24 -07005978 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
5979 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5980 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07005981 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005982}
5983
5984void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5985 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5986 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5987 uint32_t bufferMemoryBarrierCount,
5988 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5989 uint32_t imageMemoryBarrierCount,
5990 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5991 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5992 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5993 imageMemoryBarrierCount, pImageMemoryBarriers);
5994
5995 auto *cb_context = GetAccessContext(commandBuffer);
5996 assert(cb_context);
5997 if (!cb_context) return;
5998
John Zulauf1bf30522021-09-03 15:39:06 -06005999 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06006000 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06006001 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07006002}
6003
John Zulauf4edde622021-02-15 08:54:50 -07006004bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6005 const VkDependencyInfoKHR *pDependencyInfos) const {
6006 bool skip = false;
6007 const auto *cb_context = GetAccessContext(commandBuffer);
6008 assert(cb_context);
6009 if (!cb_context) return skip;
6010
6011 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6012 skip |= wait_events_op.Validate(*cb_context);
6013 return skip;
6014}
6015
6016void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6017 const VkDependencyInfoKHR *pDependencyInfos) {
6018 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6019
6020 auto *cb_context = GetAccessContext(commandBuffer);
6021 assert(cb_context);
6022 if (!cb_context) return;
6023
John Zulauf1bf30522021-09-03 15:39:06 -06006024 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6025 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006026}
6027
Tony-LunarG1364cf52021-11-17 16:10:11 -07006028bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6029 const VkDependencyInfo *pDependencyInfos) const {
6030 bool skip = false;
6031 const auto *cb_context = GetAccessContext(commandBuffer);
6032 assert(cb_context);
6033 if (!cb_context) return skip;
6034
6035 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6036 skip |= wait_events_op.Validate(*cb_context);
6037 return skip;
6038}
6039
6040void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6041 const VkDependencyInfo *pDependencyInfos) {
6042 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6043
6044 auto *cb_context = GetAccessContext(commandBuffer);
6045 assert(cb_context);
6046 if (!cb_context) return;
6047
6048 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6049 pDependencyInfos);
6050}
6051
John Zulauf4a6105a2020-11-17 15:11:05 -07006052void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006053 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006054 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006055 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006056}
6057
6058// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006059SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006060 IgnoreReason reason = NotIgnored;
6061
sjfricke0bea06e2022-06-05 09:22:26 +09006062 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006063 reason = SetVsWait2;
6064 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6065 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006066 } else if (unsynchronized_set) {
6067 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006068 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006069 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006070 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006071 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006072 } else {
6073 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006074 }
6075
6076 return reason;
6077}
6078
Jeremy Gebben40a22942020-12-22 14:22:06 -07006079bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006080 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6081 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6082 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006083}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006084
John Zulaufbb890452021-12-14 11:30:18 -07006085void SyncOpBase::SetReplayContext(uint32_t subpass, ReplayContextPtr &&replay) {
6086 subpass_ = subpass;
6087 replay_context_ = std::move(replay);
6088}
6089
6090const ReplayTrackbackBarriersAction *SyncOpBase::GetReplayTrackback() const {
6091 if (replay_context_) {
6092 assert(subpass_ < replay_context_->subpass_contexts.size());
6093 return &replay_context_->subpass_contexts[subpass_];
6094 }
6095 return nullptr;
6096}
6097
sjfricke0bea06e2022-06-05 09:22:26 +09006098SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006099 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6100 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006101 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6102 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6103 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006104 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006105 auto &barrier_set = barriers_[0];
6106 barrier_set.dependency_flags = dependencyFlags;
6107 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6108 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006109 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006110 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6111 pMemoryBarriers);
6112 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6113 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6114 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6115 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006116}
6117
sjfricke0bea06e2022-06-05 09:22:26 +09006118SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006119 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006120 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006121 for (uint32_t i = 0; i < event_count; i++) {
6122 const auto &dep_info = dep_infos[i];
6123 auto &barrier_set = barriers_[i];
6124 barrier_set.dependency_flags = dep_info.dependencyFlags;
6125 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6126 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6127 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6128 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6129 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6130 dep_info.pMemoryBarriers);
6131 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6132 dep_info.pBufferMemoryBarriers);
6133 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6134 dep_info.pImageMemoryBarriers);
6135 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006136}
6137
sjfricke0bea06e2022-06-05 09:22:26 +09006138SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006139 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6140 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6141 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6142 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6143 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006144 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6145 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6146 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006147
sjfricke0bea06e2022-06-05 09:22:26 +09006148SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006149 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006150 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006151
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006152bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6153 bool skip = false;
6154 const auto *context = cb_context.GetCurrentAccessContext();
6155 assert(context);
6156 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006157 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6158
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006159 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006160 const auto &barrier_set = barriers_[0];
6161 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6162 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6163 const auto *image_state = image_barrier.image.get();
6164 if (!image_state) continue;
6165 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6166 if (hazard.hazard) {
6167 // PHASE1 TODO -- add tag information to log msg when useful.
6168 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006169 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006170 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6171 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6172 string_SyncHazard(hazard.hazard), image_barrier.index,
6173 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006174 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006175 }
6176 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006177 return skip;
6178}
6179
John Zulaufd5115702021-01-18 12:34:33 -07006180struct SyncOpPipelineBarrierFunctorFactory {
6181 using BarrierOpFunctor = PipelineBarrierOp;
6182 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6183 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6184 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6185 using BufferRange = ResourceAccessRange;
6186 using ImageRange = subresource_adapter::ImageRangeGenerator;
6187 using GlobalRange = ResourceAccessRange;
6188
John Zulauf00119522022-05-23 19:07:42 -06006189 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6190 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006191 }
John Zulauf14940722021-04-12 15:19:02 -06006192 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006193 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6194 }
John Zulauf00119522022-05-23 19:07:42 -06006195 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6196 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006197 }
6198
6199 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6200 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6201 const auto base_address = ResourceBaseAddress(buffer);
6202 return (range + base_address);
6203 }
John Zulauf110413c2021-03-20 05:38:38 -06006204 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006205 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006206
6207 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006208 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006209 return range_gen;
6210 }
6211 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6212};
6213
6214template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006215void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6216 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006217 for (const auto &barrier : barriers) {
6218 const auto *state = barrier.GetState();
6219 if (state) {
6220 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006221 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006222 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6223 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6224 }
6225 }
6226}
6227
6228template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006229void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6230 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006231 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6232 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006233 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006234 }
6235 for (const auto address_type : kAddressTypes) {
6236 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6237 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6238 }
6239}
6240
John Zulauf8eda1562021-04-13 17:06:41 -06006241ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006242 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf8eda1562021-04-13 17:06:41 -06006243 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006244 const QueueId queue_id = cb_context->GetQueueId();
sjfricke0bea06e2022-06-05 09:22:26 +09006245 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf00119522022-05-23 19:07:42 -06006246 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006247 return tag;
6248}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006249
John Zulauf00119522022-05-23 19:07:42 -06006250void SyncOpPipelineBarrier::ReplayRecord(QueueId queue_id, const ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006251 SyncEventsContext *events_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006252 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006253 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6254 assert(barriers_.size() == 1);
6255 const auto &barrier_set = barriers_[0];
John Zulauf00119522022-05-23 19:07:42 -06006256 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6257 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6258 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006259 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006260 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006261 } else {
6262 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006263 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006264 }
6265 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006266}
6267
John Zulauf8eda1562021-04-13 17:06:41 -06006268bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006269 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006270 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6271 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006272 return false;
6273}
6274
John Zulauf4edde622021-02-15 08:54:50 -07006275void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6276 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6277 const VkMemoryBarrier *barriers) {
6278 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006279 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006280 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006281 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006282 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006283 }
6284 if (0 == memory_barrier_count) {
6285 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006286 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006287 }
John Zulauf4edde622021-02-15 08:54:50 -07006288 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006289}
6290
John Zulauf4edde622021-02-15 08:54:50 -07006291void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6292 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6293 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6294 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006295 for (uint32_t index = 0; index < barrier_count; index++) {
6296 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006297 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006298 if (buffer) {
6299 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6300 const auto range = MakeRange(barrier.offset, barrier_size);
6301 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006302 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006303 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006304 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006305 }
6306 }
6307}
6308
John Zulauf4edde622021-02-15 08:54:50 -07006309void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006310 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006311 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006312 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006313 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006314 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6315 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6316 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006317 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006318 }
John Zulauf4edde622021-02-15 08:54:50 -07006319 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006320}
6321
John Zulauf4edde622021-02-15 08:54:50 -07006322void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6323 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006324 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006325 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006326 for (uint32_t index = 0; index < barrier_count; index++) {
6327 const auto &barrier = barriers[index];
6328 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6329 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006330 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006331 if (buffer) {
6332 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6333 const auto range = MakeRange(barrier.offset, barrier_size);
6334 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006335 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006336 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006337 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006338 }
6339 }
6340}
6341
John Zulauf4edde622021-02-15 08:54:50 -07006342void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6343 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6344 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6345 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006346 for (uint32_t index = 0; index < barrier_count; index++) {
6347 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006348 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006349 if (image) {
6350 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6351 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006352 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006353 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006354 image_memory_barriers.emplace_back();
6355 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006356 }
6357 }
6358}
John Zulaufd5115702021-01-18 12:34:33 -07006359
John Zulauf4edde622021-02-15 08:54:50 -07006360void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6361 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006362 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006363 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006364 for (uint32_t index = 0; index < barrier_count; index++) {
6365 const auto &barrier = barriers[index];
6366 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6367 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006368 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006369 if (image) {
6370 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6371 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006372 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006373 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006374 image_memory_barriers.emplace_back();
6375 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006376 }
6377 }
6378}
6379
sjfricke0bea06e2022-06-05 09:22:26 +09006380SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6381 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6382 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6383 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6384 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6385 const VkImageMemoryBarrier *pImageMemoryBarriers)
6386 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006387 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6388 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006389 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006390}
6391
sjfricke0bea06e2022-06-05 09:22:26 +09006392SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6393 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6394 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006395 MakeEventsList(sync_state, eventCount, pEvents);
6396 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6397}
6398
John Zulauf610e28c2021-08-03 17:46:23 -06006399const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6400
John Zulaufd5115702021-01-18 12:34:33 -07006401bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006402 bool skip = false;
6403 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006404 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006405
John Zulauf610e28c2021-08-03 17:46:23 -06006406 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006407 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6408 const auto &barrier_set = barriers_[barrier_set_index];
6409 if (barrier_set.single_exec_scope) {
6410 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6411 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6412 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6413 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6414 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6415 } else {
6416 const auto &barriers = barrier_set.memory_barriers;
6417 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6418 const auto &barrier = barriers[barrier_index];
6419 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6420 const std::string vuid =
6421 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6422 skip =
6423 sync_state.LogInfo(command_buffer_handle, vuid,
6424 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6425 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6426 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6427 }
6428 }
6429 }
6430 }
John Zulaufd5115702021-01-18 12:34:33 -07006431 }
6432
John Zulauf610e28c2021-08-03 17:46:23 -06006433 // The rest is common to record time and replay time.
6434 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6435 return skip;
6436}
6437
John Zulaufbb890452021-12-14 11:30:18 -07006438bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006439 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006440 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006441 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006442
Jeremy Gebben40a22942020-12-22 14:22:06 -07006443 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006444 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006445 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006446 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006447 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006448 size_t barrier_set_index = 0;
6449 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006450 for (const auto &event : events_) {
6451 const auto *sync_event = events_context->Get(event.get());
6452 const auto &barrier_set = barriers_[barrier_set_index];
6453 if (!sync_event) {
6454 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6455 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6456 // new validation error... wait without previously submitted set event...
6457 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 -07006458 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006459 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006460 }
John Zulauf610e28c2021-08-03 17:46:23 -06006461
6462 // For replay calls, don't revalidate "same command buffer" events
6463 if (sync_event->last_command_tag > base_tag) continue;
6464
John Zulauf78394fc2021-07-12 15:41:40 -06006465 const auto event_handle = sync_event->event->event();
6466 // TODO add "destroyed" checks
6467
John Zulaufe0757ba2022-06-10 16:51:45 -06006468 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006469 // Only accumulate barrier and event stages if there is a pending set in the current context
6470 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6471 event_stage_masks |= sync_event->scope.mask_param;
6472 }
6473
John Zulauf78394fc2021-07-12 15:41:40 -06006474 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006475
sjfricke0bea06e2022-06-05 09:22:26 +09006476 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006477 if (ignore_reason) {
6478 switch (ignore_reason) {
6479 case SyncEventState::ResetWaitRace:
6480 case SyncEventState::Reset2WaitRace: {
6481 // Four permuations of Reset and Wait calls...
6482 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006483 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006484 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006485 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6486 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006487 }
6488 const char *const message =
6489 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6490 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6491 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006492 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006493 break;
6494 }
6495 case SyncEventState::SetRace: {
6496 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6497 // this event
6498 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6499 const char *const message =
6500 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6501 const char *const reason = "First synchronization scope is undefined.";
6502 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6503 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006504 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006505 break;
6506 }
6507 case SyncEventState::MissingStageBits: {
6508 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6509 // Issue error message that event waited for is not in wait events scope
6510 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6511 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6512 ". Bits missing from srcStageMask %s. %s";
6513 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6514 sync_state.report_data->FormatHandle(event_handle).c_str(),
6515 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006516 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006517 break;
6518 }
6519 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006520 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006521 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6522 sync_state.report_data->FormatHandle(event_handle).c_str(),
6523 CommandTypeString(sync_event->last_command));
6524 break;
6525 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006526 case SyncEventState::MissingSetEvent: {
6527 // TODO: There are conditions at queue submit time where we can definitively say that
6528 // a missing set event is an error. Add those if not captured in CoreChecks
6529 break;
6530 }
John Zulauf78394fc2021-07-12 15:41:40 -06006531 default:
6532 assert(ignore_reason == SyncEventState::NotIgnored);
6533 }
6534 } else if (barrier_set.image_memory_barriers.size()) {
6535 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006536 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006537 assert(context);
6538 for (const auto &image_memory_barrier : image_memory_barriers) {
6539 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6540 const auto *image_state = image_memory_barrier.image.get();
6541 if (!image_state) continue;
6542 const auto &subresource_range = image_memory_barrier.range;
6543 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006544 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6545 src_access_scope, queue_id, *sync_event,
6546 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006547 if (hazard.hazard) {
6548 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6549 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6550 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6551 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006552 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006553 break;
6554 }
6555 }
6556 }
6557 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6558 // 03839
6559 barrier_set_index += barrier_set_incr;
6560 }
John Zulaufd5115702021-01-18 12:34:33 -07006561
6562 // 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 -07006563 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 -07006564 if (extra_stage_bits) {
6565 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006566 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6567 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006568 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006569 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006570 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006571 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006572 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006573 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006574 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006575 " vkCmdSetEvent may be in previously submitted command buffer.");
6576 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006577 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006578 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006579 }
6580 }
6581 return skip;
6582}
6583
6584struct SyncOpWaitEventsFunctorFactory {
6585 using BarrierOpFunctor = WaitEventBarrierOp;
6586 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6587 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6588 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6589 using BufferRange = EventSimpleRangeGenerator;
6590 using ImageRange = EventImageRangeGenerator;
6591 using GlobalRange = EventSimpleRangeGenerator;
6592
6593 // Need to restrict to only valid exec and access scope for this event
6594 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6595 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006596 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006597 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6598 return barrier;
6599 }
John Zulauf00119522022-05-23 19:07:42 -06006600 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006601 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006602 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006603 }
John Zulauf14940722021-04-12 15:19:02 -06006604 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006605 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6606 }
John Zulauf00119522022-05-23 19:07:42 -06006607 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006608 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006609 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006610 }
6611
6612 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6613 const AccessAddressType address_type = GetAccessAddressType(buffer);
6614 const auto base_address = ResourceBaseAddress(buffer);
6615 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6616 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6617 return filtered_range_gen;
6618 }
John Zulauf110413c2021-03-20 05:38:38 -06006619 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006620 if (!SimpleBinding(image)) return ImageRange();
6621 const auto address_type = GetAccessAddressType(image);
6622 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006623 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6624 false);
John Zulaufd5115702021-01-18 12:34:33 -07006625 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6626
6627 return filtered_range_gen;
6628 }
6629 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6630 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6631 }
6632 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6633 SyncEventState *sync_event;
6634};
6635
John Zulauf8eda1562021-04-13 17:06:41 -06006636ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006637 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006638 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf00119522022-05-23 19:07:42 -06006639 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufd5115702021-01-18 12:34:33 -07006640 assert(access_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006641 if (!access_context) return tag;
John Zulauf669dfd52021-01-27 17:15:28 -07006642 auto *events_context = cb_context->GetCurrentEventsContext();
6643 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006644 if (!events_context) return tag;
John Zulaufd5115702021-01-18 12:34:33 -07006645
John Zulauf00119522022-05-23 19:07:42 -06006646 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006647 return tag;
6648}
6649
John Zulauf00119522022-05-23 19:07:42 -06006650void SyncOpWaitEvents::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6651 SyncEventsContext *events_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006652 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6653 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6654 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
6655 access_context->ResolvePreviousAccesses();
6656
John Zulauf4edde622021-02-15 08:54:50 -07006657 size_t barrier_set_index = 0;
6658 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6659 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006660 for (auto &event_shared : events_) {
6661 if (!event_shared.get()) continue;
6662 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006663
sjfricke0bea06e2022-06-05 09:22:26 +09006664 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006665 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006666
John Zulauf4edde622021-02-15 08:54:50 -07006667 const auto &barrier_set = barriers_[barrier_set_index];
6668 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006669 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006670 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6671 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6672 // of the barriers is maintained.
6673 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006674 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6675 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6676 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006677
6678 // Apply the global barrier to the event itself (for race condition tracking)
6679 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6680 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6681 sync_event->barriers |= dst.exec_scope;
6682 } else {
6683 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6684 sync_event->barriers = 0U;
6685 }
John Zulauf4edde622021-02-15 08:54:50 -07006686 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006687 }
6688
6689 // Apply the pending barriers
6690 ResolvePendingBarrierFunctor apply_pending_action(tag);
6691 access_context->ApplyToContext(apply_pending_action);
6692}
6693
John Zulauf8eda1562021-04-13 17:06:41 -06006694bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006695 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6696 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006697}
6698
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006699bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6700 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6701 bool skip = false;
6702 const auto *cb_access_context = GetAccessContext(commandBuffer);
6703 assert(cb_access_context);
6704 if (!cb_access_context) return skip;
6705
6706 const auto *context = cb_access_context->GetCurrentAccessContext();
6707 assert(context);
6708 if (!context) return skip;
6709
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006710 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006711
6712 if (dst_buffer) {
6713 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6714 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6715 if (hazard.hazard) {
6716 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6717 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6718 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006719 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006720 }
6721 }
6722 return skip;
6723}
6724
John Zulauf669dfd52021-01-27 17:15:28 -07006725void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006726 events_.reserve(event_count);
6727 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006728 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006729 }
6730}
John Zulauf6ce24372021-01-30 05:56:25 -07006731
sjfricke0bea06e2022-06-05 09:22:26 +09006732SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006733 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006734 : SyncOpBase(cmd_type),
6735 event_(sync_state.Get<EVENT_STATE>(event)),
6736 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006737
John Zulauf1bf30522021-09-03 15:39:06 -06006738bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6739 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6740}
6741
John Zulaufbb890452021-12-14 11:30:18 -07006742bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6743 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006744 assert(events_context);
6745 bool skip = false;
6746 if (!events_context) return skip;
6747
John Zulaufbb890452021-12-14 11:30:18 -07006748 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006749 const auto *sync_event = events_context->Get(event_);
6750 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6751
John Zulauf1bf30522021-09-03 15:39:06 -06006752 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6753
John Zulauf6ce24372021-01-30 05:56:25 -07006754 const char *const set_wait =
6755 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6756 "hazards.";
6757 const char *message = set_wait; // Only one message this call.
6758 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6759 const char *vuid = nullptr;
6760 switch (sync_event->last_command) {
6761 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006762 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006763 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006764 // Needs a barrier between set and reset
6765 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6766 break;
John Zulauf4edde622021-02-15 08:54:50 -07006767 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006768 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006769 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006770 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6771 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6772 break;
6773 }
6774 default:
6775 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006776 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6777 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006778 break;
6779 }
6780 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006781 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6782 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006783 CommandTypeString(sync_event->last_command));
6784 }
6785 }
6786 return skip;
6787}
6788
John Zulauf8eda1562021-04-13 17:06:41 -06006789ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006790 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006791 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulaufe0757ba2022-06-10 16:51:45 -06006792 auto *access_context = cb_context->GetCurrentAccessContext();
6793 const QueueId queue_id = cb_context->GetQueueId();
John Zulauf6ce24372021-01-30 05:56:25 -07006794 assert(events_context);
John Zulaufe0757ba2022-06-10 16:51:45 -06006795 if (access_context && events_context) {
6796 ReplayRecord(queue_id, tag, access_context, events_context);
6797 }
John Zulauf8eda1562021-04-13 17:06:41 -06006798 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006799}
6800
John Zulauf8eda1562021-04-13 17:06:41 -06006801bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006802 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6803 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006804}
6805
John Zulauf00119522022-05-23 19:07:42 -06006806void SyncOpResetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufe0757ba2022-06-10 16:51:45 -06006807 SyncEventsContext *events_context) const {
6808 auto *sync_event = events_context->GetFromShared(event_);
6809 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6810
6811 // Update the event state
6812 sync_event->last_command = cmd_type_;
6813 sync_event->last_command_tag = tag;
6814 sync_event->unsynchronized_set = CMD_NONE;
6815 sync_event->ResetFirstScope();
6816 sync_event->barriers = 0U;
6817}
John Zulauf8eda1562021-04-13 17:06:41 -06006818
sjfricke0bea06e2022-06-05 09:22:26 +09006819SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006820 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006821 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006822 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006823 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006824 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006825 dep_info_() {
6826 // Snapshot the current access_context for later inspection at wait time.
6827 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6828 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6829 // or Submit time reference.
6830 if (access_context) {
6831 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6832 }
6833}
John Zulauf4edde622021-02-15 08:54:50 -07006834
sjfricke0bea06e2022-06-05 09:22:26 +09006835SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006836 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006837 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006838 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006839 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006840 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006841 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6842 if (access_context) {
6843 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6844 }
6845}
John Zulauf6ce24372021-01-30 05:56:25 -07006846
6847bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006848 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6849}
6850bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006851 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6852 assert(exec_context);
6853 return DoValidate(*exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006854}
6855
John Zulaufbb890452021-12-14 11:30:18 -07006856bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006857 bool skip = false;
6858
John Zulaufbb890452021-12-14 11:30:18 -07006859 const auto &sync_state = exec_context.GetSyncState();
6860 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006861 assert(events_context);
6862 if (!events_context) return skip;
6863
6864 const auto *sync_event = events_context->Get(event_);
6865 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6866
John Zulauf610e28c2021-08-03 17:46:23 -06006867 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6868
John Zulauf6ce24372021-01-30 05:56:25 -07006869 const char *const reset_set =
6870 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6871 "hazards.";
6872 const char *const wait =
6873 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6874
6875 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006876 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006877 const char *message = nullptr;
6878 switch (sync_event->last_command) {
6879 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006880 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006881 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006882 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006883 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006884 message = reset_set;
6885 break;
6886 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006887 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006888 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006889 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006890 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006891 message = reset_set;
6892 break;
6893 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006894 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006895 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006896 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006897 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006898 message = wait;
6899 break;
6900 default:
6901 // The only other valid last command that wasn't one.
6902 assert(sync_event->last_command == CMD_NONE);
6903 break;
6904 }
John Zulauf4edde622021-02-15 08:54:50 -07006905 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006906 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006907 std::string vuid("SYNC-");
6908 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006909 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6910 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006911 CommandTypeString(sync_event->last_command));
6912 }
6913 }
6914
6915 return skip;
6916}
6917
John Zulauf8eda1562021-04-13 17:06:41 -06006918ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006919 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006920 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006921 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06006922 assert(recorded_context_);
6923 if (recorded_context_ && events_context) {
6924 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006925 }
6926 return tag;
6927}
John Zulauf6ce24372021-01-30 05:56:25 -07006928
John Zulauf00119522022-05-23 19:07:42 -06006929void SyncOpSetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6930 SyncEventsContext *events_context) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06006931 // Create a copy of the current context, and merge in the state snapshot at record set event time
6932 // Note: we mustn't change the recorded context copy, as a given CB could be submitted more than once (in generaL)
6933 auto merged_context = std::make_shared<AccessContext>(*access_context);
6934 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
6935 DoRecord(queue_id, tag, merged_context, events_context);
6936}
6937
6938void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
6939 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006940 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006941 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006942
6943 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6944 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6945 // any issues caused by naive scope setting here.
6946
6947 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6948 // Given:
6949 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6950 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6951
6952 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6953 sync_event->unsynchronized_set = sync_event->last_command;
6954 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06006955 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07006956 // We only set the scope if there isn't one
6957 sync_event->scope = src_exec_scope_;
6958
John Zulaufe0757ba2022-06-10 16:51:45 -06006959 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
6960 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07006961 sync_event->unsynchronized_set = CMD_NONE;
6962 sync_event->first_scope_tag = tag;
6963 }
John Zulauf4edde622021-02-15 08:54:50 -07006964 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09006965 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006966 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006967 sync_event->barriers = 0U;
6968}
John Zulauf64ffe552021-02-06 10:25:07 -07006969
sjfricke0bea06e2022-06-05 09:22:26 +09006970SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07006971 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006972 const VkSubpassBeginInfo *pSubpassBeginInfo)
sjfricke0bea06e2022-06-05 09:22:26 +09006973 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07006974 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006975 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006976 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006977 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006978 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006979 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006980 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
6981 // Note that this a safe to presist as long as shared_attachments is not cleared
6982 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08006983 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07006984 attachments_.emplace_back(attachment.get());
6985 }
6986 }
6987 if (pSubpassBeginInfo) {
6988 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
6989 }
6990 }
6991}
6992
6993bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6994 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
6995 bool skip = false;
6996
6997 assert(rp_state_.get());
6998 if (nullptr == rp_state_.get()) return skip;
6999 auto &rp_state = *rp_state_.get();
7000
7001 const uint32_t subpass = 0;
7002
7003 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
7004 // hasn't happened yet)
7005 const std::vector<AccessContext> empty_context_vector;
7006 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
7007 cb_context.GetCurrentAccessContext());
7008
7009 // Validate attachment operations
7010 if (attachments_.size() == 0) return skip;
7011 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07007012
7013 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
7014 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
7015 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
7016 // operations (though it's currently a messy approach)
7017 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09007018 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007019
7020 // Validate load operations if there were no layout transition hazards
7021 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06007022 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09007023 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007024 }
7025
7026 return skip;
7027}
7028
John Zulauf8eda1562021-04-13 17:06:41 -06007029ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf64ffe552021-02-06 10:25:07 -07007030 // TODO PHASE2 need to have a consistent way to record to either command buffer or queue contexts
7031 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09007032 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
7033 return cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
John Zulauf64ffe552021-02-06 10:25:07 -07007034}
7035
John Zulauf8eda1562021-04-13 17:06:41 -06007036bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07007037 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007038 return false;
7039}
7040
John Zulauf00119522022-05-23 19:07:42 -06007041void SyncOpBeginRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07007042 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007043
sjfricke0bea06e2022-06-05 09:22:26 +09007044SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7045 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7046 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007047 if (pSubpassBeginInfo) {
7048 subpass_begin_info_.initialize(pSubpassBeginInfo);
7049 }
7050 if (pSubpassEndInfo) {
7051 subpass_end_info_.initialize(pSubpassEndInfo);
7052 }
7053}
7054
7055bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7056 bool skip = false;
7057 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7058 if (!renderpass_context) return skip;
7059
sjfricke0bea06e2022-06-05 09:22:26 +09007060 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007061 return skip;
7062}
7063
John Zulauf8eda1562021-04-13 17:06:41 -06007064ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09007065 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007066}
7067
7068bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07007069 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007070 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07007071}
7072
sjfricke0bea06e2022-06-05 09:22:26 +09007073SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7074 const VkSubpassEndInfo *pSubpassEndInfo)
7075 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007076 if (pSubpassEndInfo) {
7077 subpass_end_info_.initialize(pSubpassEndInfo);
7078 }
7079}
7080
John Zulauf00119522022-05-23 19:07:42 -06007081void SyncOpNextSubpass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
7082 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007083
John Zulauf64ffe552021-02-06 10:25:07 -07007084bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7085 bool skip = false;
7086 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7087
7088 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007089 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007090 return skip;
7091}
7092
John Zulauf8eda1562021-04-13 17:06:41 -06007093ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09007094 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007095}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007096
John Zulauf8eda1562021-04-13 17:06:41 -06007097bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07007098 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007099 return false;
7100}
7101
John Zulauf00119522022-05-23 19:07:42 -06007102void SyncOpEndRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07007103 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007104
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007105void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7106 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7107 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7108 auto *cb_access_context = GetAccessContext(commandBuffer);
7109 assert(cb_access_context);
7110 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7111 auto *context = cb_access_context->GetCurrentAccessContext();
7112 assert(context);
7113
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007114 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007115
7116 if (dst_buffer) {
7117 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7118 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7119 }
7120}
John Zulaufd05c5842021-03-26 11:32:16 -06007121
John Zulaufae842002021-04-15 18:20:55 -06007122bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7123 const VkCommandBuffer *pCommandBuffers) const {
7124 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007125 const auto *cb_context = GetAccessContext(commandBuffer);
7126 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007127
7128 // Heavyweight, but we need a proxy copy of the active command buffer access context
7129 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007130
7131 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007132 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007133 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7134
John Zulaufae842002021-04-15 18:20:55 -06007135 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7136 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007137
7138 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7139 assert(recorded_context);
sjfricke0bea06e2022-06-05 09:22:26 +09007140 skip |= recorded_cb_context->ValidateFirstUse(&proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007141
7142 // The barriers have already been applied in ValidatFirstUse
7143 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007144 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007145 }
7146
John Zulaufae842002021-04-15 18:20:55 -06007147 return skip;
7148}
7149
7150void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7151 const VkCommandBuffer *pCommandBuffers) {
7152 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007153 auto *cb_context = GetAccessContext(commandBuffer);
7154 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007155 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007156 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007157 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7158 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007159 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007160 }
John Zulaufae842002021-04-15 18:20:55 -06007161}
7162
John Zulauf1d5f9c12022-05-13 14:51:08 -06007163void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7164 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7165 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7166
7167 const auto queue_state = GetQueueSyncStateShared(queue);
7168 if (!queue_state) return; // Invalid queue
7169 QueueId waited_queue = queue_state->GetQueueId();
7170
7171 // We need to go through every queue batch context and clear all accesses this wait synchronizes
7172 // As usual -- two groups, the "last batch" and the signaled semaphores
7173 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
7174 // QueueBatchContext, track which we've done to avoid duplicate traversals
John Zulaufe0757ba2022-06-10 16:51:45 -06007175 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7176 for (auto &batch : queue_batch_contexts) {
7177 batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007178 }
7179
John Zulaufe0757ba2022-06-10 16:51:45 -06007180 // TODO: Fences affected by Wait
John Zulauf1d5f9c12022-05-13 14:51:08 -06007181}
7182
7183void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7184 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007185
7186 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7187 for (auto &batch : queue_batch_contexts) {
7188 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007189 }
7190
John Zulaufe0757ba2022-06-10 16:51:45 -06007191 // TODO: Update Fences affected by Wait
John Zulauf1d5f9c12022-05-13 14:51:08 -06007192}
7193
John Zulauf697c0e12022-04-19 16:31:12 -06007194struct QueueSubmitCmdState {
7195 std::shared_ptr<const QueueSyncState> queue;
7196 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007197 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007198 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007199 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7200 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007201};
7202
7203template <>
7204thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7205
John Zulaufbbda4572022-04-19 16:20:45 -06007206bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7207 VkFence fence) const {
7208 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007209
7210 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007211 if (!enabled[sync_validation_queue_submit]) return skip;
7212
John Zulauf00119522022-05-23 19:07:42 -06007213 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007214 const auto fence_state = Get<FENCE_STATE>(fence);
7215 cmd_state->queue = GetQueueSyncStateShared(queue);
7216 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007217
John Zulauf697c0e12022-04-19 16:31:12 -06007218 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7219 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7220
7221 // verify each submit batch
7222 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7223 // most recently created batch
7224 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7225 std::shared_ptr<QueueBatchContext> batch;
7226 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7227 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007228 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7229 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007230
John Zulaufe0757ba2022-06-10 16:51:45 -06007231 // Skip import and validation of empty batches
7232 if (batch->GetTagRange().size()) {
7233 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
John Zulauf697c0e12022-04-19 16:31:12 -06007234
John Zulaufe0757ba2022-06-10 16:51:45 -06007235 // For each submit in the batch...
7236 for (const auto &cb : *batch) {
7237 if (cb.cb->GetTagLimit() == 0) continue; // Skip empty CB's
7238 skip |= cb.cb->ValidateFirstUse(batch.get(), "vkQueueSubmit", cb.index);
7239
7240 // The barriers have already been applied in ValidatFirstUse
7241 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
7242 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
7243 }
John Zulauf697c0e12022-04-19 16:31:12 -06007244 }
7245
John Zulaufe0757ba2022-06-10 16:51:45 -06007246 // Empty batches could have semaphores, though.
John Zulauf697c0e12022-04-19 16:31:12 -06007247 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7248 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007249 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007250 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007251 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7252 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7253 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007254 }
7255 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7256 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7257 last_batch = batch;
7258 }
7259 // The most recently created batch will become the queue's "last batch" in the record phase
7260 if (batch) {
7261 cmd_state->last_batch = std::move(batch);
7262 }
7263
7264 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007265 return skip;
7266}
7267
7268void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7269 VkResult result) {
7270 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007271
John Zulaufcb7e1672022-05-04 13:46:08 -06007272 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007273 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7274
John Zulaufcb7e1672022-05-04 13:46:08 -06007275 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7276 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007277 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007278
7279 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007280 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7281
John Zulauf697c0e12022-04-19 16:31:12 -06007282 // Don't need to look up the queue state again, but we need a non-const version
7283 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007284
John Zulaufcb7e1672022-05-04 13:46:08 -06007285 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7286 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7287 // QBC's are those referenced by unwaited signals and the last batch.
7288 for (auto &sig_sem : cmd_state->signaled) {
7289 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007290 auto &sig_batch = sig_sem.second->batch;
7291 sig_batch->ResetAccessLog();
7292 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7293 if (sig_batch != cmd_state->last_batch) {
7294 sig_batch->ResetEventsContext();
7295 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007296 }
7297 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007298 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007299 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007300
John Zulaufcb7e1672022-05-04 13:46:08 -06007301 // Update the queue to point to the last batch from the submit
7302 if (cmd_state->last_batch) {
7303 cmd_state->last_batch->ResetAccessLog();
John Zulaufe0757ba2022-06-10 16:51:45 -06007304
7305 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7306 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7307 auto last_batch = queue_state->LastBatch();
7308 if (last_batch) {
7309 last_batch->ResetEventsContext();
7310 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007311 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007312 }
7313
7314 // Update the global access log from the one built during validation
7315 global_access_log_.MergeMove(std::move(cmd_state->logger));
7316
John Zulauf697c0e12022-04-19 16:31:12 -06007317
7318 // WIP: record information about fences
John Zulaufbbda4572022-04-19 16:20:45 -06007319}
7320
7321bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7322 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007323 bool skip = false;
7324 if (!enabled[sync_validation_queue_submit]) return skip;
7325
John Zulauf697c0e12022-04-19 16:31:12 -06007326 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007327 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007328}
7329
7330void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7331 VkFence fence, VkResult result) {
7332 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007333 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7334
7335 if (!enabled[sync_validation_queue_submit]) return;
7336
John Zulauf697c0e12022-04-19 16:31:12 -06007337 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007338}
7339
John Zulaufd0ec59f2021-03-13 14:25:08 -07007340AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7341 : view_(view), view_mask_(), gen_store_() {
7342 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7343 const IMAGE_STATE &image_state = *view_->image_state.get();
7344 const auto base_address = ResourceBaseAddress(image_state);
7345 const auto *encoder = image_state.fragment_encoder.get();
7346 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007347 // Get offset and extent for the view, accounting for possible depth slicing
7348 const VkOffset3D zero_offset = view->GetOffset();
7349 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007350 // Intentional copy
7351 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7352 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007353 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7354 view->IsDepthSliced());
7355 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007356
7357 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7358 if (depth && (depth != view_mask_)) {
7359 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007360 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007361 }
7362 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7363 if (stencil && (stencil != view_mask_)) {
7364 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007365 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7366 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007367 }
7368}
7369
7370const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7371 const ImageRangeGen *got = nullptr;
7372 switch (gen_type) {
7373 case kViewSubresource:
7374 got = &gen_store_[kViewSubresource];
7375 break;
7376 case kRenderArea:
7377 got = &gen_store_[kRenderArea];
7378 break;
7379 case kDepthOnlyRenderArea:
7380 got =
7381 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7382 break;
7383 case kStencilOnlyRenderArea:
7384 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7385 : &gen_store_[Gen::kStencilOnlyRenderArea];
7386 break;
7387 default:
7388 assert(got);
7389 }
7390 return got;
7391}
7392
7393AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7394 assert(IsValid());
7395 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7396 if (depth_op) {
7397 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7398 if (stencil_op) {
7399 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7400 return kRenderArea;
7401 }
7402 return kDepthOnlyRenderArea;
7403 }
7404 if (stencil_op) {
7405 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7406 return kStencilOnlyRenderArea;
7407 }
7408
7409 assert(depth_op || stencil_op);
7410 return kRenderArea;
7411}
7412
7413AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007414
John Zulaufe0757ba2022-06-10 16:51:45 -06007415void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007416 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7417 for (auto &event_pair : map_) {
7418 assert(event_pair.second); // Shouldn't be storing empty
7419 auto &sync_event = *event_pair.second;
7420 // 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 -06007421 // But only if occuring before the tag
7422 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007423 sync_event.barriers |= dst.exec_scope;
7424 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7425 }
7426 }
7427}
John Zulaufbb890452021-12-14 11:30:18 -07007428
John Zulaufe0757ba2022-06-10 16:51:45 -06007429void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7430 const SyncExecScope src_scope =
7431 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7432 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7433 ApplyBarrier(src_scope, dst_scope, tag);
7434}
7435
7436SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7437 // We need a deep copy of the const context to update during validation phase
7438 for (const auto &event : from.map_) {
7439 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7440 }
7441 return *this;
7442}
7443
John Zulaufbb890452021-12-14 11:30:18 -07007444ReplayTrackbackBarriersAction::ReplayTrackbackBarriersAction(VkQueueFlags queue_flags,
7445 const SubpassDependencyGraphNode &subpass_dep,
7446 const std::vector<ReplayTrackbackBarriersAction> &replay_contexts) {
7447 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
7448 trackback_barriers.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
7449 for (const auto &prev_dep : subpass_dep.prev) {
7450 const auto prev_pass = prev_dep.first->pass;
7451 const auto &prev_barriers = prev_dep.second;
7452 trackback_barriers.emplace_back(&replay_contexts[prev_pass], queue_flags, prev_barriers);
7453 }
7454 if (has_barrier_from_external) {
7455 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
7456 trackback_barriers.emplace_back(nullptr, queue_flags, subpass_dep.barrier_from_external);
7457 }
7458}
7459
7460void ReplayTrackbackBarriersAction::operator()(ResourceAccessState *access) const {
7461 if (trackback_barriers.size() == 1) {
7462 trackback_barriers[0](access);
7463 } else {
7464 ResourceAccessState resolved;
7465 for (const auto &trackback : trackback_barriers) {
7466 ResourceAccessState access_copy = *access;
7467 trackback(&access_copy);
7468 resolved.Resolve(access_copy);
7469 }
7470 *access = resolved;
7471 }
7472}
7473
7474ReplayTrackbackBarriersAction::TrackbackBarriers::TrackbackBarriers(
7475 const ReplayTrackbackBarriersAction *source_subpass_, VkQueueFlags queue_flags_,
7476 const std::vector<const VkSubpassDependency2 *> &subpass_dependencies_)
7477 : Base(source_subpass_, queue_flags_, subpass_dependencies_) {}
7478
7479void ReplayTrackbackBarriersAction::TrackbackBarriers::operator()(ResourceAccessState *access) const {
7480 if (source_subpass) {
7481 (*source_subpass)(access);
7482 }
7483 access->ApplyBarriersImmediate(barriers);
7484}
John Zulauf697c0e12022-04-19 16:31:12 -06007485
John Zulaufcb7e1672022-05-04 13:46:08 -06007486QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
7487 : CommandExecutionContext(&sync_state), queue_state_(&queue_state), tag_range_(0, 0), batch_log_(nullptr) {}
7488
John Zulauf697c0e12022-04-19 16:31:12 -06007489template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007490void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7491 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007492 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007493 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007494}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007495void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007496 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007497}
John Zulauf697c0e12022-04-19 16:31:12 -06007498
7499VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7500
John Zulauf1d5f9c12022-05-13 14:51:08 -06007501void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
7502 QueueWaitWorm wait_worm(queue_id);
7503 access_context_.ForAll(wait_worm);
7504 if (wait_worm.erase_all) {
7505 access_context_.Reset();
7506 } else {
7507 // TODO: Profiling will tell us if we need a more efficient clean up.
7508 for (const auto &address : wait_worm.erase_list) {
7509 access_context_.DeleteAccess(address);
7510 }
7511 }
John Zulaufe0757ba2022-06-10 16:51:45 -06007512
7513 if (queue_id == GetQueueId()) {
7514 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7515 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007516}
7517
7518// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007519void QueueBatchContext::ApplyDeviceWait() {
7520 access_context_.Reset();
7521 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7522}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007523
John Zulaufecf4ac52022-06-06 10:08:42 -06007524class ApplySemaphoreBarrierAction {
7525 public:
7526 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7527 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7528
7529 private:
7530 const SemaphoreScope &signal_;
7531 const SemaphoreScope wait_;
7532};
7533
7534std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7535 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007536 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007537 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007538
John Zulaufcb7e1672022-05-04 13:46:08 -06007539 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7540 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007541 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007542
John Zulaufecf4ac52022-06-06 10:08:42 -06007543 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007544
John Zulaufecf4ac52022-06-06 10:08:42 -06007545 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007546 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007547 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7548 if (signal_scope.queue == wait_scope.queue) {
7549 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7550 // valid accesses for the sync scope.
7551 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7552 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7553 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007554 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007555 } else {
7556 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7557 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007558 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007559 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7560 // enforce deep constness.
7561 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007562}
7563
7564// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7565template <>
7566class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7567 public:
7568 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7569 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7570 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7571 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7572 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7573 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7574
7575 private:
7576 const VkSubmitInfo &info_;
7577};
7578template <typename BatchInfo, typename Fn>
7579void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7580 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7581 Accessor batch(batch_info);
7582 const uint32_t wait_count = batch.WaitSemaphoreCount();
7583 for (uint32_t i = 0; i < wait_count; ++i) {
7584 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7585 }
7586}
7587
7588template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007589void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7590 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007591 // Copy in the event state from the previous batch (on this queue)
7592 if (prev) {
7593 events_context_.DeepCopy(prev->events_context_);
7594 }
7595
John Zulaufecf4ac52022-06-06 10:08:42 -06007596 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7597 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
7598 ForEachWaitSemaphore(batch_info, [this, &signaled, &batches_resolved](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7599 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(sem, wait_mask, signaled);
7600 if (resolved) {
7601 batches_resolved.emplace(std::move(resolved));
7602 }
John Zulauf697c0e12022-04-19 16:31:12 -06007603 });
7604
John Zulaufecf4ac52022-06-06 10:08:42 -06007605 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7606 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7607 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf78cb2082022-04-20 16:37:48 -06007608 }
7609
John Zulauf697c0e12022-04-19 16:31:12 -06007610 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007611 async_batches_ =
7612 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
7613 return (batch != prev) && !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007614 });
7615 for (const auto &async_batch : async_batches_) {
7616 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7617 }
7618}
7619
7620template <typename BatchInfo>
7621void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7622 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7623 Accessor batch(batch_info);
7624
7625 // Create the list of command buffers to submit
7626 const uint32_t cb_count = batch.CommandBufferCount();
7627 command_buffers_.reserve(cb_count);
7628 for (uint32_t index = 0; index < cb_count; ++index) {
7629 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7630 if (cb_context) {
7631 tag_range_.end += cb_context->GetTagLimit();
7632 command_buffers_.emplace_back(index, std::move(cb_context));
7633 }
7634 }
7635}
7636
7637// Look up the usage informaiton from the local or global logger
7638std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7639 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7640 std::stringstream out;
7641 AccessLogger::AccessRecord access = use_logger[tag];
7642 if (access.IsValid()) {
7643 const AccessLogger::BatchRecord &batch = *access.batch;
7644 const ResourceUsageRecord &record = *access.record;
7645 // Queue and Batch information
7646 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7647 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7648
7649 // Commandbuffer Usages Information
7650 out << record;
7651 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7652 out << ", reset_no: " << std::to_string(record.reset_count);
7653 }
7654 return out.str();
7655}
7656
7657VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7658
John Zulauf00119522022-05-23 19:07:42 -06007659QueueId QueueBatchContext::GetQueueId() const {
7660 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7661 return id;
7662}
7663
John Zulauf697c0e12022-04-19 16:31:12 -06007664void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7665 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7666 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7667 SetTagBias(global_tags.begin);
7668 // Add an access log for the batches range and point the batch at it.
7669 logger_ = &logger;
7670 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7671}
7672
7673void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7674 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7675 batch_log_->Append(submitted_cb.GetAccessLog());
7676}
7677
7678void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7679 const auto size = tag_range_.size();
7680 tag_range_.begin = bias;
7681 tag_range_.end = bias + size;
7682 access_context_.SetStartTag(bias);
7683}
7684
John Zulauf1d5f9c12022-05-13 14:51:08 -06007685QueueBatchContext::QueueWaitWorm::QueueWaitWorm(QueueId queue, ResourceUsageTag tag) : predicate(queue) {}
7686
7687void QueueBatchContext::QueueWaitWorm::operator()(AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) {
7688 bool erased = access.second.ApplyQueueTagWait(predicate);
7689 if (erased) {
7690 erase_list.emplace_back(address_type, access.first);
7691 } else {
7692 erase_all = false;
7693 }
7694}
7695
John Zulauf697c0e12022-04-19 16:31:12 -06007696AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7697 const ResourceUsageRange &range) {
7698 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7699 assert(inserted.second);
7700 return &inserted.first->second;
7701}
7702
7703void AccessLogger::MergeMove(AccessLogger &&child) {
7704 for (auto &range : child.access_log_map_) {
7705 BatchLog &child_batch = range.second;
7706 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7707 insert_pair.first->second = std::move(child_batch);
7708 assert(insert_pair.second);
7709 }
7710 child.Reset();
7711}
7712
7713void AccessLogger::Reset() {
7714 prev_ = nullptr;
7715 access_log_map_.clear();
7716}
7717
7718// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7719// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7720// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7721// the contexts Resolve all history from previous all contexts when created
7722void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7723 last_batch_ = std::move(last);
7724 last_batch_->ResetAccessLog();
7725}
7726
7727// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7728// scope state.
7729// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7730// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7731uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7732
7733void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7734 log_.insert(log_.end(), other.cbegin(), other.cend());
7735 for (const auto &record : other) {
7736 assert(record.cb_state);
7737 cbs_referenced_.insert(record.cb_state->shared_from_this());
7738 }
7739}
7740
7741AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7742 assert(index < log_.size());
7743 return AccessRecord{&batch_, &log_[index]};
7744}
7745
7746AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7747 AccessRecord access_record = {nullptr, nullptr};
7748
7749 auto found_range = access_log_map_.find(tag);
7750 if (found_range != access_log_map_.cend()) {
7751 const ResourceUsageTag bias = found_range->first.begin;
7752 assert(tag >= bias);
7753 access_record = found_range->second[tag - bias];
7754 } else if (prev_) {
7755 access_record = (*prev_)[tag];
7756 }
7757
7758 return access_record;
7759}
John Zulaufcb7e1672022-05-04 13:46:08 -06007760
John Zulaufecf4ac52022-06-06 10:08:42 -06007761// This is a const method, force the returned value to be const
7762std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007763 std::shared_ptr<Signal> prev_state;
7764 if (prev_) {
7765 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7766 }
7767 return prev_state;
7768}
John Zulaufecf4ac52022-06-06 10:08:42 -06007769
7770SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7771 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7772 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7773 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7774 assert(batch);
7775 assert(sem_state);
7776}