blob: 2f0c33932aed418bcc319b1b1f317e9b4f044818 [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 Zulauf8e3c3e92021-01-06 11:19:36 -07001357 return pos->second.DetectHazard(usage_index_, ordering_rule_);
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 {
1455 return pos->second.DetectBarrierHazard(usage_index_, 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();
locke-lunarg61870c22020-06-09 14:51:50 -06001997 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001998 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06001999 const auto descriptor_type = binding_it.GetType();
2000 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
2001 auto array_idx = 0;
2002
2003 if (binding_it.IsVariableDescriptorCount()) {
2004 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
2005 }
2006 SyncStageAccessIndex sync_index =
2007 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2008
2009 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2010 uint32_t index = i - index_range.start;
2011 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2012 switch (descriptor->GetClass()) {
2013 case DescriptorClass::ImageSampler:
2014 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002015 if (descriptor->Invalid()) {
2016 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002017 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002018
2019 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2020 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2021 const auto *img_view_state = image_descriptor->GetImageViewState();
2022 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2023
John Zulauf361fb532020-07-22 10:45:39 -06002024 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002025 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2026 // Descriptors, so we do not have to worry about depth slicing here.
2027 // See: VUID 00343
2028 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002029 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002030 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002031
2032 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2033 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2034 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002035 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002036 hazard =
2037 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2038 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002039 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002040 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2041 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002042 }
John Zulauf110413c2021-03-20 05:38:38 -06002043
John Zulauf33fc1d52020-07-17 11:01:10 -06002044 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002045 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002046 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002047 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2048 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002049 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002050 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2051 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2052 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002053 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2054 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002055 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002056 }
2057 break;
2058 }
2059 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002060 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2061 if (texel_descriptor->Invalid()) {
2062 continue;
2063 }
2064 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2065 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002066 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002067 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002068 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002069 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002070 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002071 "%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 +09002072 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002073 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2074 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2075 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002076 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002077 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002078 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002079 }
2080 break;
2081 }
2082 case DescriptorClass::GeneralBuffer: {
2083 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002084 if (buffer_descriptor->Invalid()) {
2085 continue;
2086 }
2087 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002088 const ResourceAccessRange range =
2089 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002090 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002091 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002092 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002093 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002094 "%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 +09002095 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002096 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2097 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2098 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002099 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002100 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002101 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002102 }
2103 break;
2104 }
2105 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2106 default:
2107 break;
2108 }
2109 }
2110 }
2111 }
2112 return skip;
2113}
2114
2115void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002116 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002117 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002118 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002119 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002120 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002121 return;
2122 }
2123
2124 using DescriptorClass = cvdescriptorset::DescriptorClass;
2125 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2126 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002127 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2128
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002129 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002130 const auto raster_state = pipe->RasterizationState();
2131 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002132 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002133 }
locke-lunarg61870c22020-06-09 14:51:50 -06002134 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002135 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002136 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002137 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06002138 const auto descriptor_type = binding_it.GetType();
2139 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
2140 auto array_idx = 0;
2141
2142 if (binding_it.IsVariableDescriptorCount()) {
2143 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
2144 }
2145 SyncStageAccessIndex sync_index =
2146 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2147
2148 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2149 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2150 switch (descriptor->GetClass()) {
2151 case DescriptorClass::ImageSampler:
2152 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002153 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2154 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2155 if (image_descriptor->Invalid()) {
2156 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002157 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002158 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002159 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2160 // Descriptors, so we do not have to worry about depth slicing here.
2161 // See: VUID 00343
2162 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002163 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002164 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002165 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2166 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2167 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2168 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002169 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002170 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2171 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002172 }
locke-lunarg61870c22020-06-09 14:51:50 -06002173 break;
2174 }
2175 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002176 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2177 if (texel_descriptor->Invalid()) {
2178 continue;
2179 }
2180 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2181 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002182 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002183 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002184 break;
2185 }
2186 case DescriptorClass::GeneralBuffer: {
2187 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002188 if (buffer_descriptor->Invalid()) {
2189 continue;
2190 }
2191 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002192 const ResourceAccessRange range =
2193 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002194 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002195 break;
2196 }
2197 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2198 default:
2199 break;
2200 }
2201 }
2202 }
2203 }
2204}
2205
sjfricke0bea06e2022-06-05 09:22:26 +09002206bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002207 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002208 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002209 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002210 return skip;
2211 }
2212
2213 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2214 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002215 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002216
2217 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002218 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002219 if (binding_description.binding < binding_buffers_size) {
2220 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002221 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002222
locke-lunarg1ae57d62020-11-18 10:49:19 -07002223 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002224 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2225 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002226 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002227 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002228 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002229 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002230 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002231 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2232 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002233 }
2234 }
2235 }
2236 return skip;
2237}
2238
John Zulauf14940722021-04-12 15:19:02 -06002239void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002240 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002241 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002242 return;
2243 }
2244 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2245 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002246 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002247
2248 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002249 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002250 if (binding_description.binding < binding_buffers_size) {
2251 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002252 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002253
locke-lunarg1ae57d62020-11-18 10:49:19 -07002254 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002255 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2256 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002257 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2258 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002259 }
2260 }
2261}
2262
sjfricke0bea06e2022-06-05 09:22:26 +09002263bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002264 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002265 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002266 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002267 }
locke-lunarg61870c22020-06-09 14:51:50 -06002268
locke-lunarg1ae57d62020-11-18 10:49:19 -07002269 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002270 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002271 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2272 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002273 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002274 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002275 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002276 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 +09002277 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2278 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002279 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002280 }
2281
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.
sjfricke0bea06e2022-06-05 09:22:26 +09002284 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002285 return skip;
2286}
2287
John Zulauf14940722021-04-12 15:19:02 -06002288void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002289 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 -06002290
locke-lunarg1ae57d62020-11-18 10:49:19 -07002291 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002292 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002293 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2294 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002295 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002296
2297 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2298 // We will detect more accurate range in the future.
2299 RecordDrawVertex(UINT32_MAX, 0, tag);
2300}
2301
sjfricke0bea06e2022-06-05 09:22:26 +09002302bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002303 bool skip = false;
2304 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002305 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002306 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002307}
2308
John Zulauf14940722021-04-12 15:19:02 -06002309void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002310 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002311 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002312 }
locke-lunarg61870c22020-06-09 14:51:50 -06002313}
2314
John Zulauf00119522022-05-23 19:07:42 -06002315QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2316
sjfricke0bea06e2022-06-05 09:22:26 +09002317ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002318 const VkRect2D &render_area,
2319 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002320 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002321 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2322 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002323 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002324 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002325 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002326 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002327 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002328}
2329
sjfricke0bea06e2022-06-05 09:22:26 +09002330ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002331 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002332 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002333
sjfricke0bea06e2022-06-05 09:22:26 +09002334 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2335 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2336 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002337
2338 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002339 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002340 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002341}
2342
sjfricke0bea06e2022-06-05 09:22:26 +09002343ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002344 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002345 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002346
sjfricke0bea06e2022-06-05 09:22:26 +09002347 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2348 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002349
2350 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002351 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002352 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002353 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002354}
2355
John Zulauf4a6105a2020-11-17 15:11:05 -07002356void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2357 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002358 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002359 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002360 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002361 }
2362}
2363
John Zulaufae842002021-04-15 18:20:55 -06002364// The is the recorded cb context
John Zulaufbb890452021-12-14 11:30:18 -07002365bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext *proxy_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002366 uint32_t index) const {
2367 assert(proxy_context);
John Zulauf00119522022-05-23 19:07:42 -06002368 SyncEventsContext *const events_context = proxy_context->GetCurrentEventsContext();
2369 AccessContext *const access_context = proxy_context->GetCurrentAccessContext();
2370 const QueueId queue_id = proxy_context->GetQueueId();
John Zulauf4fa68462021-04-26 21:04:22 -06002371 const ResourceUsageTag base_tag = proxy_context->GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002372 bool skip = false;
2373 ResourceUsageRange tag_range = {0, 0};
2374 const AccessContext *recorded_context = GetCurrentAccessContext();
2375 assert(recorded_context);
2376 HazardResult hazard;
John Zulaufbb890452021-12-14 11:30:18 -07002377 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002378 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002379 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002380 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002381 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002382 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002383 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2384 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002385 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002386 };
John Zulaufbb890452021-12-14 11:30:18 -07002387 const ReplayTrackbackBarriersAction *replay_context = nullptr;
John Zulaufae842002021-04-15 18:20:55 -06002388 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002389 // we update the range to any include layout transition first use writes,
2390 // as they are stored along with the source scope (as effective barrier) when recorded
2391 tag_range.end = sync_op.tag + 1;
John Zulauf610e28c2021-08-03 17:46:23 -06002392 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, proxy_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002393
John Zulaufbb890452021-12-14 11:30:18 -07002394 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002395 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002396 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002397 }
2398 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002399 // Record the barrier into the proxy context.
John Zulauf00119522022-05-23 19:07:42 -06002400 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulaufbb890452021-12-14 11:30:18 -07002401 replay_context = sync_op.sync_op->GetReplayTrackback();
John Zulauf4fa68462021-04-26 21:04:22 -06002402 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002403 }
2404
John Zulaufbb890452021-12-14 11:30:18 -07002405 // Renderpasses may not cross command buffer boundaries
2406 assert(replay_context == nullptr);
2407
John Zulaufae842002021-04-15 18:20:55 -06002408 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002409 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulaufbb890452021-12-14 11:30:18 -07002410 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002411 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002412 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002413 }
2414
2415 return skip;
2416}
2417
sjfricke0bea06e2022-06-05 09:22:26 +09002418void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf00119522022-05-23 19:07:42 -06002419 SyncEventsContext *const events_context = GetCurrentEventsContext();
2420 AccessContext *const access_context = GetCurrentAccessContext();
2421 const QueueId queue_id = GetQueueId();
2422
John Zulauf4fa68462021-04-26 21:04:22 -06002423 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2424 assert(recorded_context);
2425
2426 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2427 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002428 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002429 // we update the range to any include layout transition first use writes,
2430 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf00119522022-05-23 19:07:42 -06002431 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002432 }
2433
2434 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2435 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002436 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002437}
2438
John Zulauf1d5f9c12022-05-13 14:51:08 -06002439void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002440 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002441 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002442}
2443
John Zulauf3c788ef2022-02-22 12:12:30 -07002444ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002445 // The execution references ensure lifespan for the referenced child CB's...
2446 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002447 InsertRecordedAccessLogEntries(recorded_context);
2448 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002449 return tag_range;
2450}
2451
John Zulauf3c788ef2022-02-22 12:12:30 -07002452void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2453 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2454 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2455}
2456
John Zulauf41a9c7c2021-12-07 15:59:53 -07002457ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2458 ResourceUsageTag next = access_log_.size();
2459 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2460 return next;
2461}
2462
2463ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2464 command_number_++;
2465 subcommand_number_ = 0;
2466 ResourceUsageTag next = access_log_.size();
2467 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2468 return next;
2469}
2470
2471ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2472 if (index == 0) {
2473 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2474 }
2475 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2476}
2477
John Zulaufbb890452021-12-14 11:30:18 -07002478void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2479 auto tag = sync_op->Record(this);
2480 // As renderpass operations can have side effects on the command buffer access context,
2481 // update the sync operation to record these if any.
2482 if (current_renderpass_context_) {
2483 const auto &rpc = *current_renderpass_context_;
2484 sync_op->SetReplayContext(rpc.GetCurrentSubpass(), rpc.GetReplayContext());
2485 }
2486 sync_ops_.emplace_back(tag, std::move(sync_op));
2487}
2488
John Zulaufae842002021-04-15 18:20:55 -06002489class HazardDetectFirstUse {
2490 public:
John Zulaufbb890452021-12-14 11:30:18 -07002491 HazardDetectFirstUse(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
2492 const ReplayTrackbackBarriersAction *replay_barrier)
2493 : recorded_use_(recorded_use), tag_range_(tag_range), replay_barrier_(replay_barrier) {}
John Zulaufae842002021-04-15 18:20:55 -06002494 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufbb890452021-12-14 11:30:18 -07002495 if (replay_barrier_) {
2496 // Intentional copy to apply the replay barrier
2497 auto access = pos->second;
2498 (*replay_barrier_)(&access);
2499 return access.DetectHazard(recorded_use_, tag_range_);
2500 }
John Zulaufae842002021-04-15 18:20:55 -06002501 return pos->second.DetectHazard(recorded_use_, tag_range_);
2502 }
2503 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2504 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2505 }
2506
2507 private:
2508 const ResourceAccessState &recorded_use_;
2509 const ResourceUsageRange &tag_range_;
John Zulaufbb890452021-12-14 11:30:18 -07002510 const ReplayTrackbackBarriersAction *replay_barrier_;
John Zulaufae842002021-04-15 18:20:55 -06002511};
2512
2513// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2514// hazards will be detected
John Zulaufbb890452021-12-14 11:30:18 -07002515HazardResult AccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range, const AccessContext &access_context,
2516 const ReplayTrackbackBarriersAction *replay_barrier) const {
John Zulaufae842002021-04-15 18:20:55 -06002517 HazardResult hazard;
2518 for (const auto address_type : kAddressTypes) {
2519 const auto &recorded_access_map = GetAccessStateMap(address_type);
2520 for (const auto &recorded_access : recorded_access_map) {
2521 // Cull any entries not in the current tag range
2522 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulaufbb890452021-12-14 11:30:18 -07002523 HazardDetectFirstUse detector(recorded_access.second, tag_range, replay_barrier);
John Zulaufae842002021-04-15 18:20:55 -06002524 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2525 if (hazard.hazard) break;
2526 }
2527 }
2528
2529 return hazard;
2530}
2531
John Zulaufbb890452021-12-14 11:30:18 -07002532bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002533 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002534 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002535 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002536 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002537 if (!pipe) {
2538 return skip;
2539 }
2540
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002541 const auto raster_state = pipe->RasterizationState();
2542 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002543 return skip;
2544 }
sjfricke0bea06e2022-06-05 09:22:26 +09002545 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002546 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002547 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002548
John Zulauf1a224292020-06-30 14:52:13 -06002549 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002550 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002551 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2552 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002553 if (location >= subpass.colorAttachmentCount ||
2554 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002555 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002556 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002557 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2558 if (!view_gen.IsValid()) continue;
2559 HazardResult hazard =
2560 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2561 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002562 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002563 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002564 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002565 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002566 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002567 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002568 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2569 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002570 }
2571 }
2572 }
locke-lunarg37047832020-06-12 13:44:45 -06002573
2574 // PHASE1 TODO: Add layout based read/vs. write selection.
2575 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002576 const auto ds_state = pipe->DepthStencilState();
2577 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002578
2579 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2580 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2581 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002582 bool depth_write = false, stencil_write = false;
2583
2584 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002585 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002586 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2587 depth_write = true;
2588 }
2589 // PHASE1 TODO: It needs to check if stencil is writable.
2590 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2591 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2592 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002593 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002594 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2595 stencil_write = true;
2596 }
2597
2598 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2599 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002600 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2601 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2602 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002603 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002604 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002605 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002606 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002607 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002608 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002609 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002610 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002611 }
2612 }
2613 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002614 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2615 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2616 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002617 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002618 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002619 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002620 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002621 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002622 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002623 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002624 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002625 }
locke-lunarg61870c22020-06-09 14:51:50 -06002626 }
2627 }
2628 return skip;
2629}
2630
sjfricke0bea06e2022-06-05 09:22:26 +09002631void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2632 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002633 if (!pipe) {
2634 return;
2635 }
2636
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002637 const auto *raster_state = pipe->RasterizationState();
2638 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002639 return;
2640 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002641 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002642 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002643
John Zulauf1a224292020-06-30 14:52:13 -06002644 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002645 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002646 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2647 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002648 if (location >= subpass.colorAttachmentCount ||
2649 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002650 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002651 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002652 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2653 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2654 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2655 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002656 }
2657 }
locke-lunarg37047832020-06-12 13:44:45 -06002658
2659 // PHASE1 TODO: Add layout based read/vs. write selection.
2660 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002661 const auto *ds_state = pipe->DepthStencilState();
2662 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002663 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2664 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2665 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002666 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002667 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2668 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002669
2670 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002671 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2672 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002673 depth_write = true;
2674 }
2675 // PHASE1 TODO: It needs to check if stencil is writable.
2676 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2677 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2678 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002679 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002680 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2681 stencil_write = true;
2682 }
2683
John Zulaufd0ec59f2021-03-13 14:25:08 -07002684 if (depth_write || stencil_write) {
2685 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2686 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2687 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2688 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002689 }
locke-lunarg61870c22020-06-09 14:51:50 -06002690 }
2691}
2692
sjfricke0bea06e2022-06-05 09:22:26 +09002693bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002694 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002695 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002696 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002697 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002698 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002699 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002700
John Zulauf355e49b2020-04-24 15:11:15 -06002701 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002702 if (next_subpass >= subpass_contexts_.size()) {
2703 return skip;
2704 }
John Zulauf1507ee42020-05-18 11:33:09 -06002705 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002706 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002707 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002708 if (!skip) {
2709 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2710 // on a copy of the (empty) next context.
2711 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2712 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002713 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002714 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002715 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002716 }
John Zulauf7635de32020-05-29 17:14:15 -06002717 return skip;
2718}
sjfricke0bea06e2022-06-05 09:22:26 +09002719bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002720 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002721 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002722 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002723 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002724 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2725 cmd_type);
2726 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002727 return skip;
2728}
2729
John Zulauf64ffe552021-02-06 10:25:07 -07002730AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002731 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002732}
2733
John Zulaufbb890452021-12-14 11:30:18 -07002734bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002735 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002736 bool skip = false;
2737
John Zulauf7635de32020-05-29 17:14:15 -06002738 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2739 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2740 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2741 // to apply and only copy then, if this proves a hot spot.
2742 std::unique_ptr<AccessContext> proxy_for_current;
2743
John Zulauf355e49b2020-04-24 15:11:15 -06002744 // Validate the "finalLayout" transitions to external
2745 // Get them from where there we're hidding in the extra entry.
2746 const auto &final_transitions = rp_state_->subpass_transitions.back();
2747 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002748 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002749 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002750 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2751 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002752
2753 if (transition.prev_pass == current_subpass_) {
2754 if (!proxy_for_current) {
2755 // 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 -07002756 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002757 }
2758 context = proxy_for_current.get();
2759 }
2760
John Zulaufa0a98292020-09-18 09:30:10 -06002761 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2762 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002763 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002764 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002765 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002766 if (hazard.tag == kInvalidTag) {
2767 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002768 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002769 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2770 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2771 " final image layout transition (old_layout: %s, new_layout: %s).",
2772 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2773 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2774 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002775 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002776 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2777 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2778 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2779 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2780 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002781 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002782 }
John Zulauf355e49b2020-04-24 15:11:15 -06002783 }
2784 }
2785 return skip;
2786}
2787
John Zulauf14940722021-04-12 15:19:02 -06002788void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002789 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002790 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002791}
2792
John Zulauf14940722021-04-12 15:19:02 -06002793void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002794 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2795 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002796
2797 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2798 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002799 const AttachmentViewGen &view_gen = attachment_views_[i];
2800 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002801
2802 const auto &ci = attachment_ci[i];
2803 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002804 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002805 const bool is_color = !(has_depth || has_stencil);
2806
2807 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002808 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2809 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2810 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2811 SyncOrdering::kColorAttachment, tag);
2812 }
John Zulauf1507ee42020-05-18 11:33:09 -06002813 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002814 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002815 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2816 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2817 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2818 SyncOrdering::kDepthStencilAttachment, tag);
2819 }
John Zulauf1507ee42020-05-18 11:33:09 -06002820 }
2821 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002822 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2823 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2824 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2825 SyncOrdering::kDepthStencilAttachment, tag);
2826 }
John Zulauf1507ee42020-05-18 11:33:09 -06002827 }
2828 }
2829 }
2830 }
2831}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002832AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2833 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2834 AttachmentViewGenVector view_gens;
2835 VkExtent3D extent = CastTo3D(render_area.extent);
2836 VkOffset3D offset = CastTo3D(render_area.offset);
2837 view_gens.reserve(attachment_views.size());
2838 for (const auto *view : attachment_views) {
2839 view_gens.emplace_back(view, offset, extent);
2840 }
2841 return view_gens;
2842}
John Zulauf64ffe552021-02-06 10:25:07 -07002843RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2844 VkQueueFlags queue_flags,
2845 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2846 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002847 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulauf355e49b2020-04-24 15:11:15 -06002848 // Add this for all subpasses here so that they exsist during next subpass validation
John Zulauf64ffe552021-02-06 10:25:07 -07002849 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
John Zulaufbb890452021-12-14 11:30:18 -07002850 replay_context_ = std::make_shared<ReplayRenderpassContext>();
2851 auto &replay_subpass_contexts = replay_context_->subpass_contexts;
2852 replay_subpass_contexts.reserve(rp_state_->createInfo.subpassCount);
John Zulauf355e49b2020-04-24 15:11:15 -06002853 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002854 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulaufbb890452021-12-14 11:30:18 -07002855 replay_subpass_contexts.emplace_back(queue_flags, rp_state_->subpass_dependencies[pass], replay_subpass_contexts);
John Zulauf355e49b2020-04-24 15:11:15 -06002856 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002857 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002858}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002859void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002860 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002861 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2862 RecordLayoutTransitions(barrier_tag);
2863 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002864}
John Zulauf1507ee42020-05-18 11:33:09 -06002865
John Zulauf41a9c7c2021-12-07 15:59:53 -07002866void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2867 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002868 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002869 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2870 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002871
ziga-lunarg31a3e772022-03-22 11:48:46 +01002872 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2873 return;
2874 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002875 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2876 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002877 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002878 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2879 RecordLayoutTransitions(barrier_tag);
2880 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002881}
2882
John Zulauf41a9c7c2021-12-07 15:59:53 -07002883void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2884 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002885 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002886 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2887 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002888
John Zulauf355e49b2020-04-24 15:11:15 -06002889 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002890 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002891
2892 // Add the "finalLayout" transitions to external
2893 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002894 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2895 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2896 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002897 const auto &final_transitions = rp_state_->subpass_transitions.back();
2898 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002899 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002900 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002901 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002902 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002903 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002904 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002905 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002906 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002907 }
2908}
2909
John Zulauf06f6f1e2022-04-19 15:28:11 -06002910SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2911 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002912 SyncExecScope result;
2913 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002914 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002915 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002916 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002917 return result;
2918}
2919
Jeremy Gebben40a22942020-12-22 14:22:06 -07002920SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002921 SyncExecScope result;
2922 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002923 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2924 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002925 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002926 return result;
2927}
2928
John Zulaufecf4ac52022-06-06 10:08:42 -06002929SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2930 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2931
2932SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2933 : 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 -07002934
2935template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002936SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2937 : src_exec_scope(src),
2938 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2939 dst_exec_scope(dst),
2940 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002941
2942SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002943 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2944 if (barrier) {
2945 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002946 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002947 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002948
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002949 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002950 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002951 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2952
2953 } else {
2954 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002955 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002956 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2957
2958 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002959 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002960 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2961 }
2962}
2963
2964template <typename Barrier>
2965SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2966 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2967 src_exec_scope = src.exec_scope;
2968 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2969
2970 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002971 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002972 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002973}
2974
John Zulaufb02c1eb2020-10-06 16:33:36 -06002975// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2976void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002977 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002978 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002979 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002980 }
2981}
2982
John Zulauf89311b42020-09-29 16:28:47 -06002983// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2984// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2985// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002986void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002987 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002988 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002989 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002990 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002991 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002992 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002993 }
John Zulaufbb890452021-12-14 11:30:18 -07002994 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002995}
John Zulauf9cb530d2019-09-30 14:14:10 -06002996HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2997 HazardResult hazard;
2998 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002999 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06003000 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003001 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06003002 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003003 }
3004 } else {
John Zulauf361fb532020-07-22 10:45:39 -06003005 // Write operation:
3006 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
3007 // If reads exists -- test only against them because either:
3008 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
3009 // * 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
3010 // the current write happens after the reads, so just test the write against the reades
3011 // Otherwise test against last_write
3012 //
3013 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07003014 if (last_reads.size()) {
3015 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06003016 if (IsReadHazard(usage_stage, read_access)) {
3017 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3018 break;
3019 }
3020 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003021 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06003022 // Write-After-Write check -- if we have a previous write to test against
3023 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003024 }
3025 }
3026 return hazard;
3027}
3028
John Zulauf4fa68462021-04-26 21:04:22 -06003029HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003030 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf4fa68462021-04-26 21:04:22 -06003031 return DetectHazard(usage_index, ordering);
3032}
3033
3034HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering) const {
John Zulauf69133422020-05-20 14:55:53 -06003035 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3036 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003037 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003038 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003039 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
3040 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06003041 if (IsRead(usage_bit)) {
3042 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3043 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3044 if (is_raw_hazard) {
3045 // NOTE: we know last_write is non-zero
3046 // See if the ordering rules save us from the simple RAW check above
3047 // First check to see if the current usage is covered by the ordering rules
3048 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3049 const bool usage_is_ordered =
3050 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3051 if (usage_is_ordered) {
3052 // Now see of the most recent write (or a subsequent read) are ordered
3053 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
3054 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003055 }
3056 }
John Zulauf4285ee92020-09-23 10:20:52 -06003057 if (is_raw_hazard) {
3058 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3059 }
John Zulauf5c628d02021-05-04 15:46:36 -06003060 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3061 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
3062 return DetectBarrierHazard(usage_index, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003063 } else {
3064 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003065 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003066 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003067 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003068 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003069 if (usage_write_is_ordered) {
3070 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
3071 ordered_stages = GetOrderedStages(ordering);
3072 }
3073 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3074 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003075 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003076 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3077 if (IsReadHazard(usage_stage, read_access)) {
3078 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3079 break;
3080 }
John Zulaufd14743a2020-07-03 09:42:39 -06003081 }
3082 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003083 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3084 bool ilt_ilt_hazard = false;
3085 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3086 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3087 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3088 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3089 }
3090 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003091 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003092 }
John Zulauf69133422020-05-20 14:55:53 -06003093 }
3094 }
3095 return hazard;
3096}
3097
John Zulaufae842002021-04-15 18:20:55 -06003098HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range) const {
3099 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003100 using Size = FirstAccesses::size_type;
3101 const auto &recorded_accesses = recorded_use.first_accesses_;
3102 Size count = recorded_accesses.size();
3103 if (count) {
3104 const auto &last_access = recorded_accesses.back();
3105 bool do_write_last = IsWrite(last_access.usage_index);
3106 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003107
John Zulauf4fa68462021-04-26 21:04:22 -06003108 for (Size i = 0; i < count; ++count) {
3109 const auto &first = recorded_accesses[i];
3110 // Skip and quit logic
3111 if (first.tag < tag_range.begin) continue;
3112 if (first.tag >= tag_range.end) {
3113 do_write_last = false; // ignore last since we know it can't be in tag_range
3114 break;
3115 }
3116
3117 hazard = DetectHazard(first.usage_index, first.ordering_rule);
3118 if (hazard.hazard) {
3119 hazard.AddRecordedAccess(first);
3120 break;
3121 }
3122 }
3123
3124 if (do_write_last && tag_range.includes(last_access.tag)) {
3125 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3126 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3127 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3128 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3129 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3130 // the barrier that applies them
3131 barrier |= recorded_use.first_write_layout_ordering_;
3132 }
3133 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3134 // the active context
3135 if (recorded_use.first_read_stages_) {
3136 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3137 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3138 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3139 // active context.
3140 barrier.exec_scope |= recorded_use.first_read_stages_;
3141 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3142 barrier.access_scope |= FlagBit(last_access.usage_index);
3143 }
3144 hazard = DetectHazard(last_access.usage_index, barrier);
3145 if (hazard.hazard) {
3146 hazard.AddRecordedAccess(last_access);
3147 }
3148 }
John Zulaufae842002021-04-15 18:20:55 -06003149 }
3150 return hazard;
3151}
3152
John Zulauf2f952d22020-02-10 11:34:51 -07003153// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003154HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003155 HazardResult hazard;
3156 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003157 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3158 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3159 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003160 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003161 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003162 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003163 }
3164 } else {
John Zulauf14940722021-04-12 15:19:02 -06003165 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003166 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003167 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003168 // 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 -07003169 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003170 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003171 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003172 break;
3173 }
3174 }
John Zulauf2f952d22020-02-10 11:34:51 -07003175 }
3176 }
3177 return hazard;
3178}
3179
John Zulaufae842002021-04-15 18:20:55 -06003180HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3181 ResourceUsageTag start_tag) const {
3182 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003183 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003184 // Skip and quit logic
3185 if (first.tag < tag_range.begin) continue;
3186 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003187
3188 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003189 if (hazard.hazard) {
3190 hazard.AddRecordedAccess(first);
3191 break;
3192 }
John Zulaufae842002021-04-15 18:20:55 -06003193 }
3194 return hazard;
3195}
3196
Jeremy Gebben40a22942020-12-22 14:22:06 -07003197HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003198 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003199 // Only supporting image layout transitions for now
3200 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3201 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003202 // only test for WAW if there no intervening read operations.
3203 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003204 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003205 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003206 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003207 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003208 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003209 break;
3210 }
3211 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003212 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3213 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3214 }
3215
3216 return hazard;
3217}
3218
John Zulaufe0757ba2022-06-10 16:51:45 -06003219HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3220 VkPipelineStageFlags2KHR src_exec_scope,
3221 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3222 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003223 // Only supporting image layout transitions for now
3224 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3225 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003226
John Zulaufe0757ba2022-06-10 16:51:45 -06003227 if ((write_tag >= event_tag) && last_write.any()) {
3228 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3229 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3230 } else {
3231 // only test for WAW if there no intervening read operations.
3232 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3233 if (last_reads.size()) {
3234 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3235 // first scope, or they are a hazard.
3236 const ReadStates &scope_reads = scope_state.last_reads;
3237 const ReadStates::size_type scope_read_count = scope_reads.size();
3238 // Since the hasn't been a write:
3239 // * The current read state is a superset of the scoped one
3240 // * The stage order is the same.
3241 assert(last_reads.size() >= scope_read_count);
3242 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3243 const ReadState &scope_read = scope_reads[read_idx];
3244 const ReadState &current_read = last_reads[read_idx];
3245 assert(scope_read.stage == current_read.stage);
3246 if (current_read.tag > event_tag) {
3247 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3248 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3249 } else {
3250 // The read is in the events first synchronization scope, so we use a barrier hazard check
3251 // If the read stage is not in the src sync scope
3252 // *AND* not execution chained with an existing sync barrier (that's the or)
3253 // then the barrier access is unsafe (R/W after R)
3254 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3255 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3256 break;
3257 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003258 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003259 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003260 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3261 const ReadState &current_read = last_reads[scope_read_count];
3262 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3263 }
3264 } else if (last_write.any()) {
3265 // 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 -07003266 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3267 // So do a normal barrier hazard check
John Zulaufe0757ba2022-06-10 16:51:45 -06003268 if (scope_state.IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3269 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003270 }
John Zulauf361fb532020-07-22 10:45:39 -06003271 }
John Zulaufd14743a2020-07-03 09:42:39 -06003272 }
John Zulauf361fb532020-07-22 10:45:39 -06003273
John Zulauf0cb5be22020-01-23 12:18:22 -07003274 return hazard;
3275}
3276
John Zulauf5f13a792020-03-10 07:31:21 -06003277// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3278// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3279// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3280void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003281 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003282 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3283 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003284 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003285 } else if (other.write_tag == write_tag) {
3286 // 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 -06003287 // dependency chaining logic or any stage expansion)
3288 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003289 pending_write_barriers |= other.pending_write_barriers;
3290 pending_layout_transition |= other.pending_layout_transition;
3291 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003292 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003293
John Zulaufd14743a2020-07-03 09:42:39 -06003294 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003295 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003296 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003297 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003298 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003299 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003300 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003301 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3302 // but we should wait on profiling data for that.
3303 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003304 auto &my_read = last_reads[my_read_index];
3305 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003306 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003307 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003308 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003309 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003310 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003311 my_read.pending_dep_chain = other_read.pending_dep_chain;
3312 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3313 // May require tracking more than one access per stage.
3314 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003315 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003316 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003317 // Since I'm overwriting the fragement stage read, also update the input attachment info
3318 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003319 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003320 }
John Zulauf14940722021-04-12 15:19:02 -06003321 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003322 // The read tags match so merge the barriers
3323 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003324 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003325 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003326 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003327
John Zulauf5f13a792020-03-10 07:31:21 -06003328 break;
3329 }
3330 }
3331 } else {
3332 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003333 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003334 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003335 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003336 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003337 }
John Zulauf5f13a792020-03-10 07:31:21 -06003338 }
3339 }
John Zulauf361fb532020-07-22 10:45:39 -06003340 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003341 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3342 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003343
3344 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3345 // of the copy and other into this using the update first logic.
3346 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3347 // of the other first_accesses... )
3348 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3349 FirstAccesses firsts(std::move(first_accesses_));
3350 first_accesses_.clear();
3351 first_read_stages_ = 0U;
3352 auto a = firsts.begin();
3353 auto a_end = firsts.end();
3354 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003355 // TODO: Determine whether some tag offset will be needed for PHASE II
3356 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003357 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3358 ++a;
3359 }
3360 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3361 }
3362 for (; a != a_end; ++a) {
3363 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3364 }
3365 }
John Zulauf5f13a792020-03-10 07:31:21 -06003366}
3367
John Zulauf14940722021-04-12 15:19:02 -06003368void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003369 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3370 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003371 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003372 // Mulitple outstanding reads may be of interest and do dependency chains independently
3373 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3374 const auto usage_stage = PipelineStageBit(usage_index);
3375 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003376 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003377 for (auto &read_access : last_reads) {
3378 if (read_access.stage == usage_stage) {
3379 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003380 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003381 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003382 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003383 } else {
3384 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3385 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3386 // that sync_stages is a subset of barriers may not apply.
3387 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003388 }
3389 }
3390 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003391 for (auto &read_access : last_reads) {
3392 if (read_access.barriers & usage_stage) {
3393 read_access.sync_stages |= usage_stage;
3394 }
3395 }
John Zulaufab7756b2020-12-29 16:10:16 -07003396 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003397 last_read_stages |= usage_stage;
3398 }
John Zulauf4285ee92020-09-23 10:20:52 -06003399
3400 // 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 -07003401 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003402 // TODO Revisit re: multiple reads for a given stage
3403 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003404 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003405 } else {
3406 // Assume write
3407 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003408 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003409 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003410 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003411}
John Zulauf5f13a792020-03-10 07:31:21 -06003412
John Zulauf89311b42020-09-29 16:28:47 -06003413// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3414// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3415// We can overwrite them as *this* write is now after them.
3416//
3417// 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 -06003418void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003419 ClearRead();
3420 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003421 write_tag = tag;
3422 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003423}
3424
John Zulauf1d5f9c12022-05-13 14:51:08 -06003425void ResourceAccessState::ClearWrite() {
3426 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3427 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3428 write_barriers.reset();
3429 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3430 last_write.reset();
3431
3432 write_tag = 0;
3433 write_queue = QueueSyncState::kQueueIdInvalid;
3434}
3435
3436void ResourceAccessState::ClearRead() {
3437 last_reads.clear();
3438 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3439}
3440
John Zulauf89311b42020-09-29 16:28:47 -06003441// Apply the memory barrier without updating the existing barriers. The execution barrier
3442// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3443// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3444// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003445template <typename ScopeOps>
3446void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003447 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3448 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003449 // 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 -06003450 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003451 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3452 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003453 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003454 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003455 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003456 if (layout_transition) {
3457 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3458 }
John Zulaufa0a98292020-09-18 09:30:10 -06003459 }
John Zulauf89311b42020-09-29 16:28:47 -06003460 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3461 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003462
John Zulauf89311b42020-09-29 16:28:47 -06003463 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003464 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3465 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003466 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3467
John Zulaufab7756b2020-12-29 16:10:16 -07003468 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003469 // 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 -06003470 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003471 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3472 stages_in_scope |= read_access.stage;
3473 }
3474 }
3475
3476 for (auto &read_access : last_reads) {
3477 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3478 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3479 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3480 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003481 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003482 }
3483 }
John Zulaufa0a98292020-09-18 09:30:10 -06003484 }
John Zulaufa0a98292020-09-18 09:30:10 -06003485}
3486
John Zulauf14940722021-04-12 15:19:02 -06003487void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003488 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003489 // 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 -06003490 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003491 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003492 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3493 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003494 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003495 }
John Zulauf89311b42020-09-29 16:28:47 -06003496
3497 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003498 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003499 for (auto &read_access : last_reads) {
3500 read_access.barriers |= read_access.pending_dep_chain;
3501 read_execution_barriers |= read_access.barriers;
3502 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003503 }
3504
3505 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3506 write_dependency_chain |= pending_write_dep_chain;
3507 write_barriers |= pending_write_barriers;
3508 pending_write_dep_chain = 0;
3509 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003510}
3511
John Zulaufecf4ac52022-06-06 10:08:42 -06003512// Assumes signal queue != wait queue
3513void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3514 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3515 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3516 assert(signal.queue != wait.queue);
3517 for (auto &read_access : last_reads) {
3518 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3519 // Deflects WAR on wait queue
3520 read_access.barriers = wait.exec_scope;
3521 } else {
3522 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3523 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3524 }
3525 }
3526 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3527 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3528 read_execution_barriers = wait.exec_scope;
3529 write_barriers = wait.valid_accesses;
3530 } else {
3531 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3532 write_barriers.reset();
3533 }
3534 write_dependency_chain = read_execution_barriers;
3535}
3536
John Zulauf1d5f9c12022-05-13 14:51:08 -06003537bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) {
3538 return (queue == usage_queue) && (tag <= usage_tag);
3539}
3540
3541bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) { return queue == usage_queue; }
3542
3543bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) { return tag <= usage_tag; }
3544
3545// Return if the resulting state is "empty"
3546template <typename Pred>
3547bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3548 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3549
3550 // Use the predicate to build a mask of the read stages we are synchronizing
3551 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003552 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003553 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003554 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3555 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003556 }
3557 }
3558
John Zulauf434c4e62022-05-19 16:03:56 -06003559 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3560 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3561 uint32_t unsync_count = 0;
3562 for (auto &read_access : last_reads) {
3563 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3564 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3565 sync_reads |= read_access.stage;
3566 } else {
3567 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003568 }
3569 }
3570
3571 if (unsync_count) {
3572 if (sync_reads) {
3573 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3574 ReadStates unsync_reads;
3575 unsync_reads.reserve(unsync_count);
3576 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3577 for (auto &read_access : last_reads) {
3578 if (0 == (read_access.stage & sync_reads)) {
3579 unsync_reads.emplace_back(read_access);
3580 unsync_read_stages |= read_access.stage;
3581 }
3582 }
3583 last_read_stages = unsync_read_stages;
3584 last_reads = std::move(unsync_reads);
3585 }
3586 } else {
3587 // Nothing remains (or it was empty to begin with)
3588 ClearRead();
3589 }
3590
3591 bool all_clear = last_reads.size() == 0;
3592 if (last_write.any()) {
3593 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3594 // Clear any predicated write, or any the write from any any access with synchronized reads.
3595 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3596 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3597 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3598 ClearWrite();
3599 } else {
3600 all_clear = false;
3601 }
3602 }
3603 return all_clear;
3604}
3605
John Zulaufae842002021-04-15 18:20:55 -06003606bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3607 if (!first_accesses_.size()) return false;
3608 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3609 return tag_range.intersects(first_access_range);
3610}
3611
John Zulauf1d5f9c12022-05-13 14:51:08 -06003612void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3613 if (last_write.any()) write_tag += offset;
3614 for (auto &read_access : last_reads) {
3615 read_access.tag += offset;
3616 }
3617 for (auto &first : first_accesses_) {
3618 first.tag += offset;
3619 }
3620}
3621
3622ResourceAccessState::ResourceAccessState()
3623 : write_barriers(~SyncStageAccessFlags(0)),
3624 write_dependency_chain(0),
3625 write_tag(),
3626 write_queue(QueueSyncState::kQueueIdInvalid),
3627 last_write(0),
3628 input_attachment_read(false),
3629 last_read_stages(0),
3630 read_execution_barriers(0),
3631 pending_write_dep_chain(0),
3632 pending_layout_transition(false),
3633 pending_write_barriers(0),
3634 pending_layout_ordering_(),
3635 first_accesses_(),
3636 first_read_stages_(0U),
3637 first_write_layout_ordering_() {}
3638
John Zulauf59e25072020-07-17 10:55:21 -06003639// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003640VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3641 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003642
John Zulaufab7756b2020-12-29 16:10:16 -07003643 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003644 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003645 barriers = read_access.barriers;
3646 break;
John Zulauf59e25072020-07-17 10:55:21 -06003647 }
3648 }
John Zulauf4285ee92020-09-23 10:20:52 -06003649
John Zulauf59e25072020-07-17 10:55:21 -06003650 return barriers;
3651}
3652
John Zulauf1d5f9c12022-05-13 14:51:08 -06003653void ResourceAccessState::SetQueueId(QueueId id) {
3654 for (auto &read_access : last_reads) {
3655 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3656 read_access.queue = id;
3657 }
3658 }
3659 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3660 write_queue = id;
3661 }
3662}
3663
John Zulauf00119522022-05-23 19:07:42 -06003664bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3665 return 0 != (write_dependency_chain & src_exec_scope);
3666}
3667
3668bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3669 return (src_access_scope & last_write).any();
3670}
3671
John Zulaufb7578302022-05-19 13:50:18 -06003672bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3673 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003674 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3675}
3676
3677bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3678 SyncStageAccessFlags src_access_scope) const {
3679 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003680}
3681
John Zulaufe0757ba2022-06-10 16:51:45 -06003682bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3683 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003684 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3685 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3686 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003687 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003688}
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
Jeremy Gebben40a22942020-12-22 14:22:06 -07003700VkPipelineStageFlags2KHR ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003701 // Whether the stage are in the ordering scope only matters if the current write is ordered
Jeremy Gebben40a22942020-12-22 14:22:06 -07003702 VkPipelineStageFlags2KHR ordered_stages = last_read_stages & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003703 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003704 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003705 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003706 // 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 -07003707 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003708 }
3709
3710 return ordered_stages;
3711}
3712
John Zulauf14940722021-04-12 15:19:02 -06003713void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003714 // Only record until we record a write.
3715 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003716 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003717 if (0 == (usage_stage & first_read_stages_)) {
3718 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003719 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003720 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003721 if (0 == (read_execution_barriers & usage_stage)) {
3722 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3723 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3724 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003725 }
3726 }
3727}
3728
John Zulauf4fa68462021-04-26 21:04:22 -06003729void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3730 // Only call this after recording an image layout transition
3731 assert(first_accesses_.size());
3732 if (first_accesses_.back().tag == tag) {
3733 // 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 +02003734 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003735 first_write_layout_ordering_ = layout_ordering;
3736 }
3737}
3738
John Zulauf1d5f9c12022-05-13 14:51:08 -06003739ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3740 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3741 : stage(stage_),
3742 access(access_),
3743 barriers(barriers_),
3744 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3745 tag(tag_),
3746 queue(QueueSyncState::kQueueIdInvalid),
3747 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3748
John Zulaufee984022022-04-13 16:39:50 -06003749void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3750 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3751 stage = stage_;
3752 access = access_;
3753 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003754 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003755 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003756 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 -06003757}
3758
John Zulauf00119522022-05-23 19:07:42 -06003759// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3760// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3761// that have bee applied (via semaphore) to those accesses can be chained off of.
3762bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3763 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3764 return (exec_scope & effective_stages) != 0;
3765}
3766
John Zulauf697c0e12022-04-19 16:31:12 -06003767ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3768 ResourceUsageRange reserve;
3769 reserve.begin = tag_limit_.fetch_add(tag_count);
3770 reserve.end = reserve.begin + tag_count;
3771 return reserve;
3772}
3773
John Zulaufbbda4572022-04-19 16:20:45 -06003774const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3775 return GetMappedPlainFromShared(queue_sync_states_, queue);
3776}
3777
3778QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3779
3780std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3781 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3782}
3783
3784std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3785 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3786}
3787
John Zulaufe0757ba2022-06-10 16:51:45 -06003788template <typename T>
3789struct GetBatchTraits {};
3790template <>
3791struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3792 using Batch = std::shared_ptr<QueueBatchContext>;
3793 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3794};
3795
3796template <>
3797struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3798 using Batch = std::shared_ptr<QueueBatchContext>;
3799 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3800};
3801
3802template <typename BatchSet, typename Map, typename Predicate>
3803static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003804 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003805 for (auto &entry : map) {
3806 // Intentional copy
3807 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003808 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003809 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003810 return snapshot;
3811}
3812
3813template <typename Predicate>
3814QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003815 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003816}
3817
3818template <typename Predicate>
3819QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003820 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3821}
3822
3823QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3824 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3825 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3826 if (batch && !layer_data::Contains(snapshot, batch)) {
3827 snapshot.emplace(batch);
3828 }
3829 return false;
3830 };
3831 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3832 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003833}
3834
John Zulaufcb7e1672022-05-04 13:46:08 -06003835bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3836 const std::shared_ptr<QueueBatchContext> &batch,
3837 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003838 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003839 const SyncExecScope exec_scope =
3840 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3841 const VkSemaphore sem = sem_state->semaphore();
3842 auto signal_it = signaled_.find(sem);
3843 std::shared_ptr<Signal> insert_signal;
3844 if (signal_it == signaled_.end()) {
3845 if (prev_) {
3846 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3847 if (prev_sig) {
3848 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3849 insert_signal = std::make_shared<Signal>(*prev_sig);
3850 }
3851 }
3852 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3853 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003854 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003855
3856 bool success = false;
3857 if (!signal_it->second) {
3858 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3859 success = true;
3860 }
3861
3862 return success;
3863}
3864
John Zulaufecf4ac52022-06-06 10:08:42 -06003865std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3866 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06003867 const auto found_it = signaled_.find(sem);
3868 if (found_it != signaled_.end()) {
3869 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3870 // a bit.
3871 unsignaled = std::move(found_it->second);
3872 if (!prev_) {
3873 // No parent, not need to keep the entry
3874 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3875 signaled_.erase(found_it);
3876 }
3877 } else if (prev_) {
3878 // We can't unsignal prev_ because it's const * by design.
3879 // We put in an empty placeholder
3880 signaled_.emplace(sem, std::shared_ptr<Signal>());
3881 unsignaled = GetPrev(sem);
3882 }
3883 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3884 // but CoreChecks should have reported it
3885
3886 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003887 return unsignaled;
3888}
3889
John Zulaufcb7e1672022-05-04 13:46:08 -06003890void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3891 // Overwrite the s tate with the last state from this
3892 if (from) {
3893 assert(sem == from->sem_state->semaphore());
3894 signaled_[sem] = std::move(from);
3895 } else {
3896 signaled_.erase(sem);
3897 }
3898}
3899
3900void SignaledSemaphores::Reset() {
3901 signaled_.clear();
3902 prev_ = nullptr;
3903}
3904
John Zulaufea943c52022-02-22 11:05:17 -07003905std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3906 // If we don't have one, make it.
3907 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3908 assert(cb_state.get());
3909 auto queue_flags = cb_state->GetQueueFlags();
3910 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3911}
3912
John Zulaufcb7e1672022-05-04 13:46:08 -06003913std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003914 return GetMappedInsert(cb_access_state, command_buffer,
3915 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3916}
3917
3918std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3919 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3920}
3921
3922const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3923 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3924}
3925
3926CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3927 return GetAccessContextShared(command_buffer).get();
3928}
3929
3930CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3931 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3932}
3933
John Zulaufd1f85d42020-04-15 12:23:15 -06003934void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003935 auto *access_context = GetAccessContextNoInsert(command_buffer);
3936 if (access_context) {
3937 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003938 }
3939}
3940
John Zulaufd1f85d42020-04-15 12:23:15 -06003941void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3942 auto access_found = cb_access_state.find(command_buffer);
3943 if (access_found != cb_access_state.end()) {
3944 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003945 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003946 cb_access_state.erase(access_found);
3947 }
3948}
3949
John Zulauf9cb530d2019-09-30 14:14:10 -06003950bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3951 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3952 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003953 const auto *cb_context = GetAccessContext(commandBuffer);
3954 assert(cb_context);
3955 if (!cb_context) return skip;
3956 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003957
John Zulauf3d84f1b2020-03-09 13:33:25 -06003958 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003959 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3960 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003961
3962 for (uint32_t region = 0; region < regionCount; region++) {
3963 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003964 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003965 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003966 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003967 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003968 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003969 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003970 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003971 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003972 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003973 }
John Zulauf16adfc92020-04-08 10:28:33 -06003974 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003975 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003976 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003977 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003978 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003979 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003980 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003981 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003982 }
3983 }
3984 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003985 }
3986 return skip;
3987}
3988
3989void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3990 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003991 auto *cb_context = GetAccessContext(commandBuffer);
3992 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003993 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003994 auto *context = cb_context->GetCurrentAccessContext();
3995
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003996 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3997 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003998
3999 for (uint32_t region = 0; region < regionCount; region++) {
4000 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004001 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004002 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004003 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004004 }
John Zulauf16adfc92020-04-08 10:28:33 -06004005 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004006 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004007 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004008 }
4009 }
4010}
4011
John Zulauf4a6105a2020-11-17 15:11:05 -07004012void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4013 // Clear out events from the command buffer contexts
4014 for (auto &cb_context : cb_access_state) {
4015 cb_context.second->RecordDestroyEvent(event);
4016 }
4017}
4018
Tony-LunarGef035472021-11-02 10:23:33 -06004019bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4020 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004021 bool skip = false;
4022 const auto *cb_context = GetAccessContext(commandBuffer);
4023 assert(cb_context);
4024 if (!cb_context) return skip;
4025 const auto *context = cb_context->GetCurrentAccessContext();
4026
4027 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004028 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4029 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004030
4031 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4032 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4033 if (src_buffer) {
4034 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004035 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004036 if (hazard.hazard) {
4037 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004038 skip |=
4039 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4040 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4041 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4042 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004043 }
4044 }
4045 if (dst_buffer && !skip) {
4046 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004047 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004048 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004049 skip |=
4050 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4051 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4052 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4053 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004054 }
4055 }
4056 if (skip) break;
4057 }
4058 return skip;
4059}
4060
Tony-LunarGef035472021-11-02 10:23:33 -06004061bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4062 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4063 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4064}
4065
4066bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4067 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4068}
4069
4070void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004071 auto *cb_context = GetAccessContext(commandBuffer);
4072 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004073 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004074 auto *context = cb_context->GetCurrentAccessContext();
4075
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004076 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4077 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004078
4079 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4080 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4081 if (src_buffer) {
4082 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004083 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004084 }
4085 if (dst_buffer) {
4086 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004087 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004088 }
4089 }
4090}
4091
Tony-LunarGef035472021-11-02 10:23:33 -06004092void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4093 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4094}
4095
4096void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4097 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4098}
4099
John Zulauf5c5e88d2019-12-26 11:22:02 -07004100bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4101 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4102 const VkImageCopy *pRegions) const {
4103 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004104 const auto *cb_access_context = GetAccessContext(commandBuffer);
4105 assert(cb_access_context);
4106 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004107
John Zulauf3d84f1b2020-03-09 13:33:25 -06004108 const auto *context = cb_access_context->GetCurrentAccessContext();
4109 assert(context);
4110 if (!context) return skip;
4111
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004112 auto src_image = Get<IMAGE_STATE>(srcImage);
4113 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004114 for (uint32_t region = 0; region < regionCount; region++) {
4115 const auto &copy_region = pRegions[region];
4116 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004117 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004118 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004119 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004120 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004121 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004122 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004123 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004124 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004125 }
4126
4127 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004128 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004129 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004130 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004131 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004132 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004133 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004134 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004135 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004136 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004137 }
4138 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004139
John Zulauf5c5e88d2019-12-26 11:22:02 -07004140 return skip;
4141}
4142
4143void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4144 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4145 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004146 auto *cb_access_context = GetAccessContext(commandBuffer);
4147 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004148 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004149 auto *context = cb_access_context->GetCurrentAccessContext();
4150 assert(context);
4151
Jeremy Gebben9f537102021-10-05 16:37:12 -06004152 auto src_image = Get<IMAGE_STATE>(srcImage);
4153 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004154
4155 for (uint32_t region = 0; region < regionCount; region++) {
4156 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004157 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004158 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004159 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004160 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004161 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004162 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004163 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004164 }
4165 }
4166}
4167
Tony-LunarGb61514a2021-11-02 12:36:51 -06004168bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4169 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004170 bool skip = false;
4171 const auto *cb_access_context = GetAccessContext(commandBuffer);
4172 assert(cb_access_context);
4173 if (!cb_access_context) return skip;
4174
4175 const auto *context = cb_access_context->GetCurrentAccessContext();
4176 assert(context);
4177 if (!context) return skip;
4178
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004179 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4180 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004181
Jeff Leger178b1e52020-10-05 12:22:23 -04004182 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4183 const auto &copy_region = pCopyImageInfo->pRegions[region];
4184 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004185 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004186 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004187 if (hazard.hazard) {
4188 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004189 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004190 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004191 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004192 }
4193 }
4194
4195 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004196 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004197 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004198 if (hazard.hazard) {
4199 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004200 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004201 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004202 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004203 }
4204 if (skip) break;
4205 }
4206 }
4207
4208 return skip;
4209}
4210
Tony-LunarGb61514a2021-11-02 12:36:51 -06004211bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4212 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4213 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4214}
4215
4216bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4217 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4218}
4219
4220void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004221 auto *cb_access_context = GetAccessContext(commandBuffer);
4222 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004223 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004224 auto *context = cb_access_context->GetCurrentAccessContext();
4225 assert(context);
4226
Jeremy Gebben9f537102021-10-05 16:37:12 -06004227 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4228 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004229
4230 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4231 const auto &copy_region = pCopyImageInfo->pRegions[region];
4232 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004233 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004234 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004235 }
4236 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004237 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004238 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004239 }
4240 }
4241}
4242
Tony-LunarGb61514a2021-11-02 12:36:51 -06004243void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4244 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4245}
4246
4247void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4248 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4249}
4250
John Zulauf9cb530d2019-09-30 14:14:10 -06004251bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4252 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4253 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4254 uint32_t bufferMemoryBarrierCount,
4255 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4256 uint32_t imageMemoryBarrierCount,
4257 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4258 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004259 const auto *cb_access_context = GetAccessContext(commandBuffer);
4260 assert(cb_access_context);
4261 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004262
John Zulauf36ef9282021-02-02 11:47:24 -07004263 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4264 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4265 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4266 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004267 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004268 return skip;
4269}
4270
4271void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4272 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4273 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4274 uint32_t bufferMemoryBarrierCount,
4275 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4276 uint32_t imageMemoryBarrierCount,
4277 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004278 auto *cb_access_context = GetAccessContext(commandBuffer);
4279 assert(cb_access_context);
4280 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004281
John Zulauf1bf30522021-09-03 15:39:06 -06004282 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4283 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4284 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4285 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004286}
4287
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004288bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4289 const VkDependencyInfoKHR *pDependencyInfo) const {
4290 bool skip = false;
4291 const auto *cb_access_context = GetAccessContext(commandBuffer);
4292 assert(cb_access_context);
4293 if (!cb_access_context) return skip;
4294
4295 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4296 skip = pipeline_barrier.Validate(*cb_access_context);
4297 return skip;
4298}
4299
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004300bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4301 const VkDependencyInfo *pDependencyInfo) const {
4302 bool skip = false;
4303 const auto *cb_access_context = GetAccessContext(commandBuffer);
4304 assert(cb_access_context);
4305 if (!cb_access_context) return skip;
4306
4307 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4308 skip = pipeline_barrier.Validate(*cb_access_context);
4309 return skip;
4310}
4311
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004312void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4313 auto *cb_access_context = GetAccessContext(commandBuffer);
4314 assert(cb_access_context);
4315 if (!cb_access_context) return;
4316
John Zulauf1bf30522021-09-03 15:39:06 -06004317 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4318 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004319}
4320
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004321void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4322 auto *cb_access_context = GetAccessContext(commandBuffer);
4323 assert(cb_access_context);
4324 if (!cb_access_context) return;
4325
4326 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4327 *pDependencyInfo);
4328}
4329
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004330void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004331 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004332 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004333
John Zulauf5f13a792020-03-10 07:31:21 -06004334 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4335 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004336 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004337 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4338 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004339
John Zulauf1d5f9c12022-05-13 14:51:08 -06004340 QueueId queue_id = QueueSyncState::kQueueIdBase;
4341 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004342 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004343 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004344 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4345 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004346}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004347
John Zulauf355e49b2020-04-24 15:11:15 -06004348bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004349 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004350 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004351 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004352 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004353 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004354 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004355 }
John Zulauf355e49b2020-04-24 15:11:15 -06004356 return skip;
4357}
4358
4359bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4360 VkSubpassContents contents) const {
4361 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004362 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004363 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004364 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004365 return skip;
4366}
4367
4368bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004369 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004370 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004371 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004372 return skip;
4373}
4374
4375bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4376 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004377 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004378 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004379 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004380 return skip;
4381}
4382
John Zulauf3d84f1b2020-03-09 13:33:25 -06004383void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4384 VkResult result) {
4385 // The state tracker sets up the command buffer state
4386 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4387
4388 // Create/initialize the structure that trackers accesses at the command buffer scope.
4389 auto cb_access_context = GetAccessContext(commandBuffer);
4390 assert(cb_access_context);
4391 cb_access_context->Reset();
4392}
4393
4394void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004395 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004396 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004397 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004398 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004399 }
4400}
4401
4402void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4403 VkSubpassContents contents) {
4404 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004405 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004406 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004407 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004408}
4409
4410void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4411 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4412 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004413 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004414}
4415
4416void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4417 const VkRenderPassBeginInfo *pRenderPassBegin,
4418 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4419 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004420 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004421}
4422
Mike Schuchardt2df08912020-12-15 16:28:09 -08004423bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004424 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004425 bool skip = false;
4426
4427 auto cb_context = GetAccessContext(commandBuffer);
4428 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004429 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004430 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004431 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004432}
4433
4434bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4435 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004436 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004437 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004438 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004439 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4440 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004441 return skip;
4442}
4443
Mike Schuchardt2df08912020-12-15 16:28:09 -08004444bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4445 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004446 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004447 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004448 return skip;
4449}
4450
4451bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4452 const VkSubpassEndInfo *pSubpassEndInfo) const {
4453 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004454 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004455 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004456}
4457
4458void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004459 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004460 auto cb_context = GetAccessContext(commandBuffer);
4461 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004462 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004463
sjfricke0bea06e2022-06-05 09:22:26 +09004464 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004465}
4466
4467void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4468 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004469 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004470 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004471 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004472}
4473
4474void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4475 const VkSubpassEndInfo *pSubpassEndInfo) {
4476 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004477 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004478}
4479
4480void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4481 const VkSubpassEndInfo *pSubpassEndInfo) {
4482 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004483 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004484}
4485
sfricke-samsung85584a72021-09-30 21:43:38 -07004486bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004487 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004488 bool skip = false;
4489
4490 auto cb_context = GetAccessContext(commandBuffer);
4491 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004492 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004493
sjfricke0bea06e2022-06-05 09:22:26 +09004494 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004495 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004496 return skip;
4497}
4498
4499bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4500 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004501 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004502 return skip;
4503}
4504
Mike Schuchardt2df08912020-12-15 16:28:09 -08004505bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004506 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004507 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004508 return skip;
4509}
4510
4511bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004512 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004513 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004514 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004515 return skip;
4516}
4517
sjfricke0bea06e2022-06-05 09:22:26 +09004518void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4519 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004520 // Resolve the all subpass contexts to the command buffer contexts
4521 auto cb_context = GetAccessContext(commandBuffer);
4522 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004523 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004524
sjfricke0bea06e2022-06-05 09:22:26 +09004525 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004526}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004527
John Zulauf33fc1d52020-07-17 11:01:10 -06004528// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4529// updates to a resource which do not conflict at the byte level.
4530// TODO: Revisit this rule to see if it needs to be tighter or looser
4531// TODO: Add programatic control over suppression heuristics
4532bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4533 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4534}
4535
John Zulauf3d84f1b2020-03-09 13:33:25 -06004536void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004537 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004538 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004539}
4540
4541void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004542 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004543 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004544}
4545
4546void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004547 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004548 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004549}
locke-lunarga19c71d2020-03-02 18:17:04 -07004550
sfricke-samsung71f04e32022-03-16 01:21:21 -05004551template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004552bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004553 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4554 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004555 bool skip = false;
4556 const auto *cb_access_context = GetAccessContext(commandBuffer);
4557 assert(cb_access_context);
4558 if (!cb_access_context) return skip;
4559
4560 const auto *context = cb_access_context->GetCurrentAccessContext();
4561 assert(context);
4562 if (!context) return skip;
4563
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004564 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4565 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004566
4567 for (uint32_t region = 0; region < regionCount; region++) {
4568 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004569 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004570 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004571 if (src_buffer) {
4572 ResourceAccessRange src_range =
4573 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004574 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004575 if (hazard.hazard) {
4576 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004577 skip |=
4578 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4579 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4580 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4581 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004582 }
4583 }
4584
Jeremy Gebben40a22942020-12-22 14:22:06 -07004585 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004586 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004587 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004588 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004589 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004590 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004591 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004592 }
4593 if (skip) break;
4594 }
4595 if (skip) break;
4596 }
4597 return skip;
4598}
4599
Jeff Leger178b1e52020-10-05 12:22:23 -04004600bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4601 VkImageLayout dstImageLayout, uint32_t regionCount,
4602 const VkBufferImageCopy *pRegions) const {
4603 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004604 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004605}
4606
4607bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4608 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4609 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4610 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004611 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4612}
4613
4614bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4615 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4616 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4617 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4618 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004619}
4620
sfricke-samsung71f04e32022-03-16 01:21:21 -05004621template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004622void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004623 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4624 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004625 auto *cb_access_context = GetAccessContext(commandBuffer);
4626 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004627
Jeff Leger178b1e52020-10-05 12:22:23 -04004628 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004629 auto *context = cb_access_context->GetCurrentAccessContext();
4630 assert(context);
4631
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004632 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4633 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004634
4635 for (uint32_t region = 0; region < regionCount; region++) {
4636 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004637 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004638 if (src_buffer) {
4639 ResourceAccessRange src_range =
4640 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004641 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004642 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004643 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004644 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004645 }
4646 }
4647}
4648
Jeff Leger178b1e52020-10-05 12:22:23 -04004649void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4650 VkImageLayout dstImageLayout, uint32_t regionCount,
4651 const VkBufferImageCopy *pRegions) {
4652 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004653 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004654}
4655
4656void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4657 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4658 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4659 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4660 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004661 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4662}
4663
4664void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4665 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4666 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4667 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4668 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4669 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004670}
4671
sfricke-samsung71f04e32022-03-16 01:21:21 -05004672template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004673bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004674 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4675 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004676 bool skip = false;
4677 const auto *cb_access_context = GetAccessContext(commandBuffer);
4678 assert(cb_access_context);
4679 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004680
locke-lunarga19c71d2020-03-02 18:17:04 -07004681 const auto *context = cb_access_context->GetCurrentAccessContext();
4682 assert(context);
4683 if (!context) return skip;
4684
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004685 auto src_image = Get<IMAGE_STATE>(srcImage);
4686 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004687 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004688 for (uint32_t region = 0; region < regionCount; region++) {
4689 const auto &copy_region = pRegions[region];
4690 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004691 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004692 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004693 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004694 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004695 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004696 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004697 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004698 }
John Zulauf477700e2021-01-06 11:41:49 -07004699 if (dst_mem) {
4700 ResourceAccessRange dst_range =
4701 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004702 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004703 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004704 skip |=
4705 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4706 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4707 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4708 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004709 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004710 }
4711 }
4712 if (skip) break;
4713 }
4714 return skip;
4715}
4716
Jeff Leger178b1e52020-10-05 12:22:23 -04004717bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4718 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4719 const VkBufferImageCopy *pRegions) const {
4720 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004721 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004722}
4723
4724bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4725 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4726 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4727 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004728 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4729}
4730
4731bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4732 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4733 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4734 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4735 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004736}
4737
sfricke-samsung71f04e32022-03-16 01:21:21 -05004738template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004739void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004740 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004741 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004742 auto *cb_access_context = GetAccessContext(commandBuffer);
4743 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004744
Jeff Leger178b1e52020-10-05 12:22:23 -04004745 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004746 auto *context = cb_access_context->GetCurrentAccessContext();
4747 assert(context);
4748
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004749 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004750 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004751 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004752 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004753
4754 for (uint32_t region = 0; region < regionCount; region++) {
4755 const auto &copy_region = pRegions[region];
4756 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004757 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004758 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004759 if (dst_buffer) {
4760 ResourceAccessRange dst_range =
4761 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004762 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004763 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004764 }
4765 }
4766}
4767
Jeff Leger178b1e52020-10-05 12:22:23 -04004768void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4769 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4770 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004771 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004772}
4773
4774void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4775 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4776 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4777 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4778 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004779 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4780}
4781
4782void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4783 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4784 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4785 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4786 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4787 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004788}
4789
4790template <typename RegionType>
4791bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4792 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004793 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004794 bool skip = false;
4795 const auto *cb_access_context = GetAccessContext(commandBuffer);
4796 assert(cb_access_context);
4797 if (!cb_access_context) return skip;
4798
4799 const auto *context = cb_access_context->GetCurrentAccessContext();
4800 assert(context);
4801 if (!context) return skip;
4802
sjfricke0bea06e2022-06-05 09:22:26 +09004803 const char *caller_name = CommandTypeString(cmd_type);
4804
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004805 auto src_image = Get<IMAGE_STATE>(srcImage);
4806 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004807
4808 for (uint32_t region = 0; region < regionCount; region++) {
4809 const auto &blit_region = pRegions[region];
4810 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004811 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4812 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4813 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4814 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4815 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4816 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004817 auto hazard =
4818 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004819 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004820 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004821 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004822 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004823 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004824 }
4825 }
4826
4827 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004828 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4829 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4830 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4831 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4832 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4833 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004834 auto hazard =
4835 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004836 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004837 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004838 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004839 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004840 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004841 }
4842 if (skip) break;
4843 }
4844 }
4845
4846 return skip;
4847}
4848
Jeff Leger178b1e52020-10-05 12:22:23 -04004849bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4850 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4851 const VkImageBlit *pRegions, VkFilter filter) const {
4852 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004853 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004854}
4855
4856bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4857 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4858 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4859 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004860 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004861}
4862
Tony-LunarG542ae912021-11-04 16:06:44 -06004863bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4864 const VkBlitImageInfo2 *pBlitImageInfo) const {
4865 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004866 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4867 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004868}
4869
Jeff Leger178b1e52020-10-05 12:22:23 -04004870template <typename RegionType>
4871void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4872 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4873 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004874 auto *cb_access_context = GetAccessContext(commandBuffer);
4875 assert(cb_access_context);
4876 auto *context = cb_access_context->GetCurrentAccessContext();
4877 assert(context);
4878
Jeremy Gebben9f537102021-10-05 16:37:12 -06004879 auto src_image = Get<IMAGE_STATE>(srcImage);
4880 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004881
4882 for (uint32_t region = 0; region < regionCount; region++) {
4883 const auto &blit_region = pRegions[region];
4884 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004885 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4886 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4887 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4888 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4889 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4890 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004891 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004892 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004893 }
4894 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004895 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4896 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4897 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4898 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4899 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4900 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004901 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004902 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004903 }
4904 }
4905}
locke-lunarg36ba2592020-04-03 09:42:04 -06004906
Jeff Leger178b1e52020-10-05 12:22:23 -04004907void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4908 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4909 const VkImageBlit *pRegions, VkFilter filter) {
4910 auto *cb_access_context = GetAccessContext(commandBuffer);
4911 assert(cb_access_context);
4912 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4913 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4914 pRegions, filter);
4915 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4916}
4917
4918void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4919 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4920 auto *cb_access_context = GetAccessContext(commandBuffer);
4921 assert(cb_access_context);
4922 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4923 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4924 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4925 pBlitImageInfo->filter, tag);
4926}
4927
Tony-LunarG542ae912021-11-04 16:06:44 -06004928void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *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_BLITIMAGE2);
4933 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4934 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4935 pBlitImageInfo->filter, tag);
4936}
4937
John Zulauffaea0ee2021-01-14 14:01:32 -07004938bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4939 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4940 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09004941 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004942 bool skip = false;
4943 if (drawCount == 0) return skip;
4944
sjfricke0bea06e2022-06-05 09:22:26 +09004945 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004946 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004947 VkDeviceSize size = struct_size;
4948 if (drawCount == 1 || stride == size) {
4949 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004950 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004951 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4952 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004953 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004954 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004955 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004956 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004957 }
4958 } else {
4959 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004960 const ResourceAccessRange range = MakeRange(offset + i * stride, 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,
4965 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
4966 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004967 break;
4968 }
4969 }
4970 }
4971 return skip;
4972}
4973
John Zulauf14940722021-04-12 15:19:02 -06004974void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06004975 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4976 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004977 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004978 VkDeviceSize size = struct_size;
4979 if (drawCount == 1 || stride == size) {
4980 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004981 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004982 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004983 } else {
4984 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004985 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004986 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4987 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004988 }
4989 }
4990}
4991
John Zulauffaea0ee2021-01-14 14:01:32 -07004992bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4993 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09004994 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004995 bool skip = false;
4996
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004997 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004998 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004999 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5000 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005001 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005002 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
5003 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5004 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005005 }
5006 return skip;
5007}
5008
John Zulauf14940722021-04-12 15:19:02 -06005009void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005010 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005011 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005012 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005013}
5014
locke-lunarg36ba2592020-04-03 09:42:04 -06005015bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005016 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005017 const auto *cb_access_context = GetAccessContext(commandBuffer);
5018 assert(cb_access_context);
5019 if (!cb_access_context) return skip;
5020
sjfricke0bea06e2022-06-05 09:22:26 +09005021 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005022 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005023}
5024
5025void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005026 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005027 auto *cb_access_context = GetAccessContext(commandBuffer);
5028 assert(cb_access_context);
5029 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005030
locke-lunarg61870c22020-06-09 14:51:50 -06005031 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005032}
locke-lunarge1a67022020-04-29 00:15:36 -06005033
5034bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005035 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005036 const auto *cb_access_context = GetAccessContext(commandBuffer);
5037 assert(cb_access_context);
5038 if (!cb_access_context) return skip;
5039
5040 const auto *context = cb_access_context->GetCurrentAccessContext();
5041 assert(context);
5042 if (!context) return skip;
5043
sjfricke0bea06e2022-06-05 09:22:26 +09005044 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005045 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005046 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005047 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005048}
5049
5050void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005051 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005052 auto *cb_access_context = GetAccessContext(commandBuffer);
5053 assert(cb_access_context);
5054 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5055 auto *context = cb_access_context->GetCurrentAccessContext();
5056 assert(context);
5057
locke-lunarg61870c22020-06-09 14:51:50 -06005058 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5059 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005060}
5061
5062bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5063 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005064 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005065 const auto *cb_access_context = GetAccessContext(commandBuffer);
5066 assert(cb_access_context);
5067 if (!cb_access_context) return skip;
5068
sjfricke0bea06e2022-06-05 09:22:26 +09005069 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5070 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5071 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005072 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005073}
5074
5075void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5076 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005077 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005078 auto *cb_access_context = GetAccessContext(commandBuffer);
5079 assert(cb_access_context);
5080 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005081
locke-lunarg61870c22020-06-09 14:51:50 -06005082 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5083 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5084 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005085}
5086
5087bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5088 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005089 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005090 const auto *cb_access_context = GetAccessContext(commandBuffer);
5091 assert(cb_access_context);
5092 if (!cb_access_context) return skip;
5093
sjfricke0bea06e2022-06-05 09:22:26 +09005094 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5095 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5096 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005097 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005098}
5099
5100void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5101 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005102 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005103 auto *cb_access_context = GetAccessContext(commandBuffer);
5104 assert(cb_access_context);
5105 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005106
locke-lunarg61870c22020-06-09 14:51:50 -06005107 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5108 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5109 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005110}
5111
5112bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5113 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005114 bool skip = false;
5115 if (drawCount == 0) return skip;
5116
locke-lunargff255f92020-05-13 18:53:52 -06005117 const auto *cb_access_context = GetAccessContext(commandBuffer);
5118 assert(cb_access_context);
5119 if (!cb_access_context) return skip;
5120
5121 const auto *context = cb_access_context->GetCurrentAccessContext();
5122 assert(context);
5123 if (!context) return skip;
5124
sjfricke0bea06e2022-06-05 09:22:26 +09005125 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5126 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005127 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005128 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005129
5130 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5131 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5132 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005133 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005134 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005135}
5136
5137void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5138 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005139 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005140 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005141 auto *cb_access_context = GetAccessContext(commandBuffer);
5142 assert(cb_access_context);
5143 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5144 auto *context = cb_access_context->GetCurrentAccessContext();
5145 assert(context);
5146
locke-lunarg61870c22020-06-09 14:51:50 -06005147 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5148 cb_access_context->RecordDrawSubpassAttachment(tag);
5149 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005150
5151 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5152 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5153 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005154 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005155}
5156
5157bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5158 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005159 bool skip = false;
5160 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005161 const auto *cb_access_context = GetAccessContext(commandBuffer);
5162 assert(cb_access_context);
5163 if (!cb_access_context) return skip;
5164
5165 const auto *context = cb_access_context->GetCurrentAccessContext();
5166 assert(context);
5167 if (!context) return skip;
5168
sjfricke0bea06e2022-06-05 09:22:26 +09005169 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5170 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005171 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005172 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005173
5174 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5175 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5176 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005177 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005178 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005179}
5180
5181void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5182 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005183 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005184 auto *cb_access_context = GetAccessContext(commandBuffer);
5185 assert(cb_access_context);
5186 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5187 auto *context = cb_access_context->GetCurrentAccessContext();
5188 assert(context);
5189
locke-lunarg61870c22020-06-09 14:51:50 -06005190 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5191 cb_access_context->RecordDrawSubpassAttachment(tag);
5192 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005193
5194 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5195 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5196 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005197 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005198}
5199
5200bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5201 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005202 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005203 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005204 const auto *cb_access_context = GetAccessContext(commandBuffer);
5205 assert(cb_access_context);
5206 if (!cb_access_context) return skip;
5207
5208 const auto *context = cb_access_context->GetCurrentAccessContext();
5209 assert(context);
5210 if (!context) return skip;
5211
sjfricke0bea06e2022-06-05 09:22:26 +09005212 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5213 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005214 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005215 maxDrawCount, stride, cmd_type);
5216 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005217
5218 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5219 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5220 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005221 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005222 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005223}
5224
5225bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5226 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5227 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005228 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005229 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005230}
5231
sfricke-samsung85584a72021-09-30 21:43:38 -07005232void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5233 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5234 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005235 auto *cb_access_context = GetAccessContext(commandBuffer);
5236 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005237 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005238 auto *context = cb_access_context->GetCurrentAccessContext();
5239 assert(context);
5240
locke-lunarg61870c22020-06-09 14:51:50 -06005241 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5242 cb_access_context->RecordDrawSubpassAttachment(tag);
5243 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5244 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005245
5246 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5247 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5248 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005249 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005250}
5251
sfricke-samsung85584a72021-09-30 21:43:38 -07005252void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5253 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5254 uint32_t stride) {
5255 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5256 stride);
5257 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5258 CMD_DRAWINDIRECTCOUNT);
5259}
locke-lunarge1a67022020-04-29 00:15:36 -06005260bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5261 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5262 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005263 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005264 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005265}
5266
5267void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5268 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5269 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005270 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5271 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005272 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5273 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005274}
5275
5276bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5277 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5278 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005279 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005280 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005281}
5282
5283void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5284 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5285 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005286 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5287 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005288 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5289 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005290}
5291
5292bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5293 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005294 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005295 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005296 const auto *cb_access_context = GetAccessContext(commandBuffer);
5297 assert(cb_access_context);
5298 if (!cb_access_context) return skip;
5299
5300 const auto *context = cb_access_context->GetCurrentAccessContext();
5301 assert(context);
5302 if (!context) return skip;
5303
sjfricke0bea06e2022-06-05 09:22:26 +09005304 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5305 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005306 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005307 offset, maxDrawCount, stride, cmd_type);
5308 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005309
5310 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5311 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5312 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005313 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005314 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005315}
5316
5317bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5318 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5319 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005320 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005321 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005322}
5323
sfricke-samsung85584a72021-09-30 21:43:38 -07005324void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5325 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5326 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005327 auto *cb_access_context = GetAccessContext(commandBuffer);
5328 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005329 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005330 auto *context = cb_access_context->GetCurrentAccessContext();
5331 assert(context);
5332
locke-lunarg61870c22020-06-09 14:51:50 -06005333 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5334 cb_access_context->RecordDrawSubpassAttachment(tag);
5335 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5336 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005337
5338 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5339 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005340 // We will update the index and vertex buffer in SubmitQueue in the future.
5341 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005342}
5343
sfricke-samsung85584a72021-09-30 21:43:38 -07005344void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5345 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5346 uint32_t maxDrawCount, uint32_t stride) {
5347 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5348 maxDrawCount, stride);
5349 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5350 CMD_DRAWINDEXEDINDIRECTCOUNT);
5351}
5352
locke-lunarge1a67022020-04-29 00:15:36 -06005353bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5354 VkDeviceSize offset, VkBuffer countBuffer,
5355 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5356 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005357 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005358 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005359}
5360
5361void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5362 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5363 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005364 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5365 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005366 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5367 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005368}
5369
5370bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5371 VkDeviceSize offset, VkBuffer countBuffer,
5372 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5373 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005374 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005375 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005376}
5377
5378void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5379 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5380 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005381 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5382 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005383 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5384 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005385}
5386
5387bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5388 const VkClearColorValue *pColor, uint32_t rangeCount,
5389 const VkImageSubresourceRange *pRanges) const {
5390 bool skip = false;
5391 const auto *cb_access_context = GetAccessContext(commandBuffer);
5392 assert(cb_access_context);
5393 if (!cb_access_context) return skip;
5394
5395 const auto *context = cb_access_context->GetCurrentAccessContext();
5396 assert(context);
5397 if (!context) return skip;
5398
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005399 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005400
5401 for (uint32_t index = 0; index < rangeCount; index++) {
5402 const auto &range = pRanges[index];
5403 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005404 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005405 if (hazard.hazard) {
5406 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005407 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005408 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005409 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005410 }
5411 }
5412 }
5413 return skip;
5414}
5415
5416void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5417 const VkClearColorValue *pColor, uint32_t rangeCount,
5418 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005419 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005420 auto *cb_access_context = GetAccessContext(commandBuffer);
5421 assert(cb_access_context);
5422 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5423 auto *context = cb_access_context->GetCurrentAccessContext();
5424 assert(context);
5425
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005426 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005427
5428 for (uint32_t index = 0; index < rangeCount; index++) {
5429 const auto &range = pRanges[index];
5430 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005431 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005432 }
5433 }
5434}
5435
5436bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5437 VkImageLayout imageLayout,
5438 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5439 const VkImageSubresourceRange *pRanges) const {
5440 bool skip = false;
5441 const auto *cb_access_context = GetAccessContext(commandBuffer);
5442 assert(cb_access_context);
5443 if (!cb_access_context) return skip;
5444
5445 const auto *context = cb_access_context->GetCurrentAccessContext();
5446 assert(context);
5447 if (!context) return skip;
5448
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005449 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005450
5451 for (uint32_t index = 0; index < rangeCount; index++) {
5452 const auto &range = pRanges[index];
5453 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005454 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005455 if (hazard.hazard) {
5456 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005457 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005458 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005459 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005460 }
5461 }
5462 }
5463 return skip;
5464}
5465
5466void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5467 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5468 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005469 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005470 auto *cb_access_context = GetAccessContext(commandBuffer);
5471 assert(cb_access_context);
5472 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5473 auto *context = cb_access_context->GetCurrentAccessContext();
5474 assert(context);
5475
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005476 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005477
5478 for (uint32_t index = 0; index < rangeCount; index++) {
5479 const auto &range = pRanges[index];
5480 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005481 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005482 }
5483 }
5484}
5485
5486bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5487 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5488 VkDeviceSize dstOffset, VkDeviceSize stride,
5489 VkQueryResultFlags flags) const {
5490 bool skip = false;
5491 const auto *cb_access_context = GetAccessContext(commandBuffer);
5492 assert(cb_access_context);
5493 if (!cb_access_context) return skip;
5494
5495 const auto *context = cb_access_context->GetCurrentAccessContext();
5496 assert(context);
5497 if (!context) return skip;
5498
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005499 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005500
5501 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005502 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005503 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005504 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005505 skip |=
5506 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5507 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005508 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005509 }
5510 }
locke-lunargff255f92020-05-13 18:53:52 -06005511
5512 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005513 return skip;
5514}
5515
5516void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5517 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5518 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005519 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5520 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005521 auto *cb_access_context = GetAccessContext(commandBuffer);
5522 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005523 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005524 auto *context = cb_access_context->GetCurrentAccessContext();
5525 assert(context);
5526
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005527 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005528
5529 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005530 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005531 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005532 }
locke-lunargff255f92020-05-13 18:53:52 -06005533
5534 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005535}
5536
5537bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5538 VkDeviceSize size, uint32_t data) const {
5539 bool skip = false;
5540 const auto *cb_access_context = GetAccessContext(commandBuffer);
5541 assert(cb_access_context);
5542 if (!cb_access_context) return skip;
5543
5544 const auto *context = cb_access_context->GetCurrentAccessContext();
5545 assert(context);
5546 if (!context) return skip;
5547
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005548 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005549
5550 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005551 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005552 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005553 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005554 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005555 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005556 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005557 }
5558 }
5559 return skip;
5560}
5561
5562void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5563 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005564 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005565 auto *cb_access_context = GetAccessContext(commandBuffer);
5566 assert(cb_access_context);
5567 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5568 auto *context = cb_access_context->GetCurrentAccessContext();
5569 assert(context);
5570
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005571 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005572
5573 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005574 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005575 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005576 }
5577}
5578
5579bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5580 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5581 const VkImageResolve *pRegions) const {
5582 bool skip = false;
5583 const auto *cb_access_context = GetAccessContext(commandBuffer);
5584 assert(cb_access_context);
5585 if (!cb_access_context) return skip;
5586
5587 const auto *context = cb_access_context->GetCurrentAccessContext();
5588 assert(context);
5589 if (!context) return skip;
5590
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005591 auto src_image = Get<IMAGE_STATE>(srcImage);
5592 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005593
5594 for (uint32_t region = 0; region < regionCount; region++) {
5595 const auto &resolve_region = pRegions[region];
5596 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005597 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005598 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005599 if (hazard.hazard) {
5600 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005601 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005602 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005603 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005604 }
5605 }
5606
5607 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005608 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005609 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005610 if (hazard.hazard) {
5611 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005612 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005613 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005614 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005615 }
5616 if (skip) break;
5617 }
5618 }
5619
5620 return skip;
5621}
5622
5623void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5624 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5625 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005626 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5627 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005628 auto *cb_access_context = GetAccessContext(commandBuffer);
5629 assert(cb_access_context);
5630 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5631 auto *context = cb_access_context->GetCurrentAccessContext();
5632 assert(context);
5633
Jeremy Gebben9f537102021-10-05 16:37:12 -06005634 auto src_image = Get<IMAGE_STATE>(srcImage);
5635 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005636
5637 for (uint32_t region = 0; region < regionCount; region++) {
5638 const auto &resolve_region = pRegions[region];
5639 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005640 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005641 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005642 }
5643 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005644 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005645 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005646 }
5647 }
5648}
5649
Tony-LunarG562fc102021-11-12 13:58:35 -07005650bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5651 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005652 bool skip = false;
5653 const auto *cb_access_context = GetAccessContext(commandBuffer);
5654 assert(cb_access_context);
5655 if (!cb_access_context) return skip;
5656
5657 const auto *context = cb_access_context->GetCurrentAccessContext();
5658 assert(context);
5659 if (!context) return skip;
5660
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005661 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5662 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005663
5664 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5665 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5666 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005667 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005668 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005669 if (hazard.hazard) {
5670 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005671 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005672 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005673 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005674 }
5675 }
5676
5677 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005678 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005679 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005680 if (hazard.hazard) {
5681 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005682 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005683 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005684 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005685 }
5686 if (skip) break;
5687 }
5688 }
5689
5690 return skip;
5691}
5692
Tony-LunarG562fc102021-11-12 13:58:35 -07005693bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5694 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5695 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5696}
5697
5698bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5699 const VkResolveImageInfo2 *pResolveImageInfo) const {
5700 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5701}
5702
5703void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5704 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005705 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5706 auto *cb_access_context = GetAccessContext(commandBuffer);
5707 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005708 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005709 auto *context = cb_access_context->GetCurrentAccessContext();
5710 assert(context);
5711
Jeremy Gebben9f537102021-10-05 16:37:12 -06005712 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5713 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005714
5715 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5716 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5717 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005718 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005719 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005720 }
5721 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005722 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005723 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005724 }
5725 }
5726}
5727
Tony-LunarG562fc102021-11-12 13:58:35 -07005728void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5729 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5730 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5731}
5732
5733void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5734 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5735}
5736
locke-lunarge1a67022020-04-29 00:15:36 -06005737bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5738 VkDeviceSize dataSize, const void *pData) const {
5739 bool skip = false;
5740 const auto *cb_access_context = GetAccessContext(commandBuffer);
5741 assert(cb_access_context);
5742 if (!cb_access_context) return skip;
5743
5744 const auto *context = cb_access_context->GetCurrentAccessContext();
5745 assert(context);
5746 if (!context) return skip;
5747
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005748 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005749
5750 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005751 // VK_WHOLE_SIZE not allowed
5752 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005753 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005754 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005755 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005756 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005757 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005758 }
5759 }
5760 return skip;
5761}
5762
5763void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5764 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005765 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005766 auto *cb_access_context = GetAccessContext(commandBuffer);
5767 assert(cb_access_context);
5768 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5769 auto *context = cb_access_context->GetCurrentAccessContext();
5770 assert(context);
5771
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005772 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005773
5774 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005775 // VK_WHOLE_SIZE not allowed
5776 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005777 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005778 }
5779}
locke-lunargff255f92020-05-13 18:53:52 -06005780
5781bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5782 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5783 bool skip = false;
5784 const auto *cb_access_context = GetAccessContext(commandBuffer);
5785 assert(cb_access_context);
5786 if (!cb_access_context) return skip;
5787
5788 const auto *context = cb_access_context->GetCurrentAccessContext();
5789 assert(context);
5790 if (!context) return skip;
5791
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005792 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005793
5794 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005795 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005796 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005797 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005798 skip |=
5799 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5800 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005801 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005802 }
5803 }
5804 return skip;
5805}
5806
5807void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5808 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005809 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005810 auto *cb_access_context = GetAccessContext(commandBuffer);
5811 assert(cb_access_context);
5812 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5813 auto *context = cb_access_context->GetCurrentAccessContext();
5814 assert(context);
5815
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005816 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005817
5818 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005819 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005820 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005821 }
5822}
John Zulauf49beb112020-11-04 16:06:31 -07005823
5824bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5825 bool skip = false;
5826 const auto *cb_context = GetAccessContext(commandBuffer);
5827 assert(cb_context);
5828 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005829 const auto *access_context = cb_context->GetCurrentAccessContext();
5830 assert(access_context);
5831 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005832
John Zulaufe0757ba2022-06-10 16:51:45 -06005833 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005834 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005835}
5836
5837void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5838 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5839 auto *cb_context = GetAccessContext(commandBuffer);
5840 assert(cb_context);
5841 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005842
5843 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
5844 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07005845}
5846
John Zulauf4edde622021-02-15 08:54:50 -07005847bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5848 const VkDependencyInfoKHR *pDependencyInfo) const {
5849 bool skip = false;
5850 const auto *cb_context = GetAccessContext(commandBuffer);
5851 assert(cb_context);
5852 if (!cb_context || !pDependencyInfo) return skip;
5853
John Zulaufe0757ba2022-06-10 16:51:45 -06005854 const auto *access_context = cb_context->GetCurrentAccessContext();
5855 assert(access_context);
5856 if (!access_context) return skip;
5857
5858 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07005859 return set_event_op.Validate(*cb_context);
5860}
5861
Tony-LunarGc43525f2021-11-15 16:12:38 -07005862bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5863 const VkDependencyInfo *pDependencyInfo) const {
5864 bool skip = false;
5865 const auto *cb_context = GetAccessContext(commandBuffer);
5866 assert(cb_context);
5867 if (!cb_context || !pDependencyInfo) return skip;
5868
John Zulaufe0757ba2022-06-10 16:51:45 -06005869 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07005870 return set_event_op.Validate(*cb_context);
5871}
5872
John Zulauf4edde622021-02-15 08:54:50 -07005873void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5874 const VkDependencyInfoKHR *pDependencyInfo) {
5875 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5876 auto *cb_context = GetAccessContext(commandBuffer);
5877 assert(cb_context);
5878 if (!cb_context || !pDependencyInfo) return;
5879
John Zulaufe0757ba2022-06-10 16:51:45 -06005880 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5881 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07005882}
5883
Tony-LunarGc43525f2021-11-15 16:12:38 -07005884void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5885 const VkDependencyInfo *pDependencyInfo) {
5886 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5887 auto *cb_context = GetAccessContext(commandBuffer);
5888 assert(cb_context);
5889 if (!cb_context || !pDependencyInfo) return;
5890
John Zulaufe0757ba2022-06-10 16:51:45 -06005891 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5892 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07005893}
5894
John Zulauf49beb112020-11-04 16:06:31 -07005895bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5896 VkPipelineStageFlags stageMask) const {
5897 bool skip = false;
5898 const auto *cb_context = GetAccessContext(commandBuffer);
5899 assert(cb_context);
5900 if (!cb_context) return skip;
5901
John Zulauf36ef9282021-02-02 11:47:24 -07005902 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005903 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005904}
5905
5906void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5907 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5908 auto *cb_context = GetAccessContext(commandBuffer);
5909 assert(cb_context);
5910 if (!cb_context) return;
5911
John Zulauf1bf30522021-09-03 15:39:06 -06005912 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005913}
5914
John Zulauf4edde622021-02-15 08:54:50 -07005915bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5916 VkPipelineStageFlags2KHR stageMask) const {
5917 bool skip = false;
5918 const auto *cb_context = GetAccessContext(commandBuffer);
5919 assert(cb_context);
5920 if (!cb_context) return skip;
5921
5922 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5923 return reset_event_op.Validate(*cb_context);
5924}
5925
Tony-LunarGa2662db2021-11-16 07:26:24 -07005926bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5927 VkPipelineStageFlags2 stageMask) const {
5928 bool skip = false;
5929 const auto *cb_context = GetAccessContext(commandBuffer);
5930 assert(cb_context);
5931 if (!cb_context) return skip;
5932
5933 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5934 return reset_event_op.Validate(*cb_context);
5935}
5936
John Zulauf4edde622021-02-15 08:54:50 -07005937void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5938 VkPipelineStageFlags2KHR stageMask) {
5939 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5940 auto *cb_context = GetAccessContext(commandBuffer);
5941 assert(cb_context);
5942 if (!cb_context) return;
5943
John Zulauf1bf30522021-09-03 15:39:06 -06005944 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005945}
5946
Tony-LunarGa2662db2021-11-16 07:26:24 -07005947void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5948 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5949 auto *cb_context = GetAccessContext(commandBuffer);
5950 assert(cb_context);
5951 if (!cb_context) return;
5952
5953 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5954}
5955
John Zulauf49beb112020-11-04 16:06:31 -07005956bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5957 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5958 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5959 uint32_t bufferMemoryBarrierCount,
5960 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5961 uint32_t imageMemoryBarrierCount,
5962 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5963 bool skip = false;
5964 const auto *cb_context = GetAccessContext(commandBuffer);
5965 assert(cb_context);
5966 if (!cb_context) return skip;
5967
John Zulauf36ef9282021-02-02 11:47:24 -07005968 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
5969 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5970 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07005971 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005972}
5973
5974void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5975 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5976 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5977 uint32_t bufferMemoryBarrierCount,
5978 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5979 uint32_t imageMemoryBarrierCount,
5980 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5981 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5982 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5983 imageMemoryBarrierCount, pImageMemoryBarriers);
5984
5985 auto *cb_context = GetAccessContext(commandBuffer);
5986 assert(cb_context);
5987 if (!cb_context) return;
5988
John Zulauf1bf30522021-09-03 15:39:06 -06005989 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06005990 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06005991 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07005992}
5993
John Zulauf4edde622021-02-15 08:54:50 -07005994bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5995 const VkDependencyInfoKHR *pDependencyInfos) const {
5996 bool skip = false;
5997 const auto *cb_context = GetAccessContext(commandBuffer);
5998 assert(cb_context);
5999 if (!cb_context) return skip;
6000
6001 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6002 skip |= wait_events_op.Validate(*cb_context);
6003 return skip;
6004}
6005
6006void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6007 const VkDependencyInfoKHR *pDependencyInfos) {
6008 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6009
6010 auto *cb_context = GetAccessContext(commandBuffer);
6011 assert(cb_context);
6012 if (!cb_context) return;
6013
John Zulauf1bf30522021-09-03 15:39:06 -06006014 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6015 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006016}
6017
Tony-LunarG1364cf52021-11-17 16:10:11 -07006018bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6019 const VkDependencyInfo *pDependencyInfos) const {
6020 bool skip = false;
6021 const auto *cb_context = GetAccessContext(commandBuffer);
6022 assert(cb_context);
6023 if (!cb_context) return skip;
6024
6025 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6026 skip |= wait_events_op.Validate(*cb_context);
6027 return skip;
6028}
6029
6030void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6031 const VkDependencyInfo *pDependencyInfos) {
6032 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6033
6034 auto *cb_context = GetAccessContext(commandBuffer);
6035 assert(cb_context);
6036 if (!cb_context) return;
6037
6038 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6039 pDependencyInfos);
6040}
6041
John Zulauf4a6105a2020-11-17 15:11:05 -07006042void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006043 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006044 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006045 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006046}
6047
6048// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006049SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006050 IgnoreReason reason = NotIgnored;
6051
sjfricke0bea06e2022-06-05 09:22:26 +09006052 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006053 reason = SetVsWait2;
6054 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6055 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006056 } else if (unsynchronized_set) {
6057 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006058 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006059 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006060 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006061 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006062 } else {
6063 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006064 }
6065
6066 return reason;
6067}
6068
Jeremy Gebben40a22942020-12-22 14:22:06 -07006069bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006070 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6071 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6072 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006073}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006074
John Zulaufbb890452021-12-14 11:30:18 -07006075void SyncOpBase::SetReplayContext(uint32_t subpass, ReplayContextPtr &&replay) {
6076 subpass_ = subpass;
6077 replay_context_ = std::move(replay);
6078}
6079
6080const ReplayTrackbackBarriersAction *SyncOpBase::GetReplayTrackback() const {
6081 if (replay_context_) {
6082 assert(subpass_ < replay_context_->subpass_contexts.size());
6083 return &replay_context_->subpass_contexts[subpass_];
6084 }
6085 return nullptr;
6086}
6087
sjfricke0bea06e2022-06-05 09:22:26 +09006088SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006089 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6090 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006091 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6092 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6093 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006094 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006095 auto &barrier_set = barriers_[0];
6096 barrier_set.dependency_flags = dependencyFlags;
6097 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6098 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006099 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006100 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6101 pMemoryBarriers);
6102 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6103 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6104 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6105 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006106}
6107
sjfricke0bea06e2022-06-05 09:22:26 +09006108SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006109 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006110 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006111 for (uint32_t i = 0; i < event_count; i++) {
6112 const auto &dep_info = dep_infos[i];
6113 auto &barrier_set = barriers_[i];
6114 barrier_set.dependency_flags = dep_info.dependencyFlags;
6115 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6116 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6117 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6118 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6119 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6120 dep_info.pMemoryBarriers);
6121 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6122 dep_info.pBufferMemoryBarriers);
6123 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6124 dep_info.pImageMemoryBarriers);
6125 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006126}
6127
sjfricke0bea06e2022-06-05 09:22:26 +09006128SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006129 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6130 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6131 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6132 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6133 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006134 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6135 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6136 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006137
sjfricke0bea06e2022-06-05 09:22:26 +09006138SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006139 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006140 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006141
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006142bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6143 bool skip = false;
6144 const auto *context = cb_context.GetCurrentAccessContext();
6145 assert(context);
6146 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006147 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6148
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006149 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006150 const auto &barrier_set = barriers_[0];
6151 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6152 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6153 const auto *image_state = image_barrier.image.get();
6154 if (!image_state) continue;
6155 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6156 if (hazard.hazard) {
6157 // PHASE1 TODO -- add tag information to log msg when useful.
6158 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006159 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006160 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6161 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6162 string_SyncHazard(hazard.hazard), image_barrier.index,
6163 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006164 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006165 }
6166 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006167 return skip;
6168}
6169
John Zulaufd5115702021-01-18 12:34:33 -07006170struct SyncOpPipelineBarrierFunctorFactory {
6171 using BarrierOpFunctor = PipelineBarrierOp;
6172 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6173 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6174 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6175 using BufferRange = ResourceAccessRange;
6176 using ImageRange = subresource_adapter::ImageRangeGenerator;
6177 using GlobalRange = ResourceAccessRange;
6178
John Zulauf00119522022-05-23 19:07:42 -06006179 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6180 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006181 }
John Zulauf14940722021-04-12 15:19:02 -06006182 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006183 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6184 }
John Zulauf00119522022-05-23 19:07:42 -06006185 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6186 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006187 }
6188
6189 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6190 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6191 const auto base_address = ResourceBaseAddress(buffer);
6192 return (range + base_address);
6193 }
John Zulauf110413c2021-03-20 05:38:38 -06006194 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006195 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006196
6197 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006198 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006199 return range_gen;
6200 }
6201 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6202};
6203
6204template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006205void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6206 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006207 for (const auto &barrier : barriers) {
6208 const auto *state = barrier.GetState();
6209 if (state) {
6210 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006211 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006212 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6213 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6214 }
6215 }
6216}
6217
6218template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006219void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6220 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006221 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6222 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006223 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006224 }
6225 for (const auto address_type : kAddressTypes) {
6226 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6227 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6228 }
6229}
6230
John Zulauf8eda1562021-04-13 17:06:41 -06006231ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006232 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf8eda1562021-04-13 17:06:41 -06006233 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006234 const QueueId queue_id = cb_context->GetQueueId();
sjfricke0bea06e2022-06-05 09:22:26 +09006235 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf00119522022-05-23 19:07:42 -06006236 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006237 return tag;
6238}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006239
John Zulauf00119522022-05-23 19:07:42 -06006240void SyncOpPipelineBarrier::ReplayRecord(QueueId queue_id, const ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006241 SyncEventsContext *events_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006242 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006243 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6244 assert(barriers_.size() == 1);
6245 const auto &barrier_set = barriers_[0];
John Zulauf00119522022-05-23 19:07:42 -06006246 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6247 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6248 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006249 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006250 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006251 } else {
6252 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006253 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006254 }
6255 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006256}
6257
John Zulauf8eda1562021-04-13 17:06:41 -06006258bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006259 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006260 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6261 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006262 return false;
6263}
6264
John Zulauf4edde622021-02-15 08:54:50 -07006265void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6266 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6267 const VkMemoryBarrier *barriers) {
6268 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006269 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006270 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006271 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006272 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006273 }
6274 if (0 == memory_barrier_count) {
6275 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006276 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006277 }
John Zulauf4edde622021-02-15 08:54:50 -07006278 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006279}
6280
John Zulauf4edde622021-02-15 08:54:50 -07006281void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6282 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6283 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6284 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006285 for (uint32_t index = 0; index < barrier_count; index++) {
6286 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006287 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006288 if (buffer) {
6289 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6290 const auto range = MakeRange(barrier.offset, barrier_size);
6291 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006292 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006293 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006294 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006295 }
6296 }
6297}
6298
John Zulauf4edde622021-02-15 08:54:50 -07006299void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006300 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006301 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006302 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006303 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006304 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6305 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6306 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006307 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006308 }
John Zulauf4edde622021-02-15 08:54:50 -07006309 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006310}
6311
John Zulauf4edde622021-02-15 08:54:50 -07006312void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6313 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006314 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006315 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006316 for (uint32_t index = 0; index < barrier_count; index++) {
6317 const auto &barrier = barriers[index];
6318 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6319 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006320 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006321 if (buffer) {
6322 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6323 const auto range = MakeRange(barrier.offset, barrier_size);
6324 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006325 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006326 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006327 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006328 }
6329 }
6330}
6331
John Zulauf4edde622021-02-15 08:54:50 -07006332void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6333 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6334 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6335 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006336 for (uint32_t index = 0; index < barrier_count; index++) {
6337 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006338 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006339 if (image) {
6340 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6341 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006342 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006343 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006344 image_memory_barriers.emplace_back();
6345 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006346 }
6347 }
6348}
John Zulaufd5115702021-01-18 12:34:33 -07006349
John Zulauf4edde622021-02-15 08:54:50 -07006350void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6351 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006352 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006353 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006354 for (uint32_t index = 0; index < barrier_count; index++) {
6355 const auto &barrier = barriers[index];
6356 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6357 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006358 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006359 if (image) {
6360 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6361 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006362 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006363 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006364 image_memory_barriers.emplace_back();
6365 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006366 }
6367 }
6368}
6369
sjfricke0bea06e2022-06-05 09:22:26 +09006370SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6371 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6372 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6373 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6374 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6375 const VkImageMemoryBarrier *pImageMemoryBarriers)
6376 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006377 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6378 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006379 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006380}
6381
sjfricke0bea06e2022-06-05 09:22:26 +09006382SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6383 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6384 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006385 MakeEventsList(sync_state, eventCount, pEvents);
6386 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6387}
6388
John Zulauf610e28c2021-08-03 17:46:23 -06006389const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6390
John Zulaufd5115702021-01-18 12:34:33 -07006391bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006392 bool skip = false;
6393 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006394 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006395
John Zulauf610e28c2021-08-03 17:46:23 -06006396 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006397 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6398 const auto &barrier_set = barriers_[barrier_set_index];
6399 if (barrier_set.single_exec_scope) {
6400 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6401 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6402 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6403 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6404 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6405 } else {
6406 const auto &barriers = barrier_set.memory_barriers;
6407 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6408 const auto &barrier = barriers[barrier_index];
6409 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6410 const std::string vuid =
6411 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6412 skip =
6413 sync_state.LogInfo(command_buffer_handle, vuid,
6414 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6415 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6416 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6417 }
6418 }
6419 }
6420 }
John Zulaufd5115702021-01-18 12:34:33 -07006421 }
6422
John Zulauf610e28c2021-08-03 17:46:23 -06006423 // The rest is common to record time and replay time.
6424 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6425 return skip;
6426}
6427
John Zulaufbb890452021-12-14 11:30:18 -07006428bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006429 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006430 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006431 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006432
Jeremy Gebben40a22942020-12-22 14:22:06 -07006433 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006434 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006435 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006436 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006437 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006438 size_t barrier_set_index = 0;
6439 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006440 for (const auto &event : events_) {
6441 const auto *sync_event = events_context->Get(event.get());
6442 const auto &barrier_set = barriers_[barrier_set_index];
6443 if (!sync_event) {
6444 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6445 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6446 // new validation error... wait without previously submitted set event...
6447 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 -07006448 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006449 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006450 }
John Zulauf610e28c2021-08-03 17:46:23 -06006451
6452 // For replay calls, don't revalidate "same command buffer" events
6453 if (sync_event->last_command_tag > base_tag) continue;
6454
John Zulauf78394fc2021-07-12 15:41:40 -06006455 const auto event_handle = sync_event->event->event();
6456 // TODO add "destroyed" checks
6457
John Zulaufe0757ba2022-06-10 16:51:45 -06006458 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006459 // Only accumulate barrier and event stages if there is a pending set in the current context
6460 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6461 event_stage_masks |= sync_event->scope.mask_param;
6462 }
6463
John Zulauf78394fc2021-07-12 15:41:40 -06006464 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006465
sjfricke0bea06e2022-06-05 09:22:26 +09006466 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006467 if (ignore_reason) {
6468 switch (ignore_reason) {
6469 case SyncEventState::ResetWaitRace:
6470 case SyncEventState::Reset2WaitRace: {
6471 // Four permuations of Reset and Wait calls...
6472 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006473 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006474 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006475 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6476 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006477 }
6478 const char *const message =
6479 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6480 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6481 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006482 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006483 break;
6484 }
6485 case SyncEventState::SetRace: {
6486 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6487 // this event
6488 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6489 const char *const message =
6490 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6491 const char *const reason = "First synchronization scope is undefined.";
6492 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6493 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006494 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006495 break;
6496 }
6497 case SyncEventState::MissingStageBits: {
6498 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6499 // Issue error message that event waited for is not in wait events scope
6500 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6501 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6502 ". Bits missing from srcStageMask %s. %s";
6503 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6504 sync_state.report_data->FormatHandle(event_handle).c_str(),
6505 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006506 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006507 break;
6508 }
6509 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006510 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006511 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6512 sync_state.report_data->FormatHandle(event_handle).c_str(),
6513 CommandTypeString(sync_event->last_command));
6514 break;
6515 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006516 case SyncEventState::MissingSetEvent: {
6517 // TODO: There are conditions at queue submit time where we can definitively say that
6518 // a missing set event is an error. Add those if not captured in CoreChecks
6519 break;
6520 }
John Zulauf78394fc2021-07-12 15:41:40 -06006521 default:
6522 assert(ignore_reason == SyncEventState::NotIgnored);
6523 }
6524 } else if (barrier_set.image_memory_barriers.size()) {
6525 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006526 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006527 assert(context);
6528 for (const auto &image_memory_barrier : image_memory_barriers) {
6529 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6530 const auto *image_state = image_memory_barrier.image.get();
6531 if (!image_state) continue;
6532 const auto &subresource_range = image_memory_barrier.range;
6533 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006534 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6535 src_access_scope, queue_id, *sync_event,
6536 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006537 if (hazard.hazard) {
6538 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6539 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6540 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6541 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006542 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006543 break;
6544 }
6545 }
6546 }
6547 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6548 // 03839
6549 barrier_set_index += barrier_set_incr;
6550 }
John Zulaufd5115702021-01-18 12:34:33 -07006551
6552 // 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 -07006553 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 -07006554 if (extra_stage_bits) {
6555 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006556 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6557 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006558 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006559 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006560 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006561 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006562 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006563 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006564 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006565 " vkCmdSetEvent may be in previously submitted command buffer.");
6566 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006567 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006568 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006569 }
6570 }
6571 return skip;
6572}
6573
6574struct SyncOpWaitEventsFunctorFactory {
6575 using BarrierOpFunctor = WaitEventBarrierOp;
6576 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6577 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6578 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6579 using BufferRange = EventSimpleRangeGenerator;
6580 using ImageRange = EventImageRangeGenerator;
6581 using GlobalRange = EventSimpleRangeGenerator;
6582
6583 // Need to restrict to only valid exec and access scope for this event
6584 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6585 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006586 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006587 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6588 return barrier;
6589 }
John Zulauf00119522022-05-23 19:07:42 -06006590 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006591 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006592 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006593 }
John Zulauf14940722021-04-12 15:19:02 -06006594 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006595 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6596 }
John Zulauf00119522022-05-23 19:07:42 -06006597 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006598 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006599 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006600 }
6601
6602 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6603 const AccessAddressType address_type = GetAccessAddressType(buffer);
6604 const auto base_address = ResourceBaseAddress(buffer);
6605 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6606 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6607 return filtered_range_gen;
6608 }
John Zulauf110413c2021-03-20 05:38:38 -06006609 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006610 if (!SimpleBinding(image)) return ImageRange();
6611 const auto address_type = GetAccessAddressType(image);
6612 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006613 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6614 false);
John Zulaufd5115702021-01-18 12:34:33 -07006615 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6616
6617 return filtered_range_gen;
6618 }
6619 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6620 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6621 }
6622 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6623 SyncEventState *sync_event;
6624};
6625
John Zulauf8eda1562021-04-13 17:06:41 -06006626ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006627 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006628 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf00119522022-05-23 19:07:42 -06006629 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufd5115702021-01-18 12:34:33 -07006630 assert(access_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006631 if (!access_context) return tag;
John Zulauf669dfd52021-01-27 17:15:28 -07006632 auto *events_context = cb_context->GetCurrentEventsContext();
6633 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006634 if (!events_context) return tag;
John Zulaufd5115702021-01-18 12:34:33 -07006635
John Zulauf00119522022-05-23 19:07:42 -06006636 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006637 return tag;
6638}
6639
John Zulauf00119522022-05-23 19:07:42 -06006640void SyncOpWaitEvents::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6641 SyncEventsContext *events_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006642 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6643 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6644 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
6645 access_context->ResolvePreviousAccesses();
6646
John Zulauf4edde622021-02-15 08:54:50 -07006647 size_t barrier_set_index = 0;
6648 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6649 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006650 for (auto &event_shared : events_) {
6651 if (!event_shared.get()) continue;
6652 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006653
sjfricke0bea06e2022-06-05 09:22:26 +09006654 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006655 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006656
John Zulauf4edde622021-02-15 08:54:50 -07006657 const auto &barrier_set = barriers_[barrier_set_index];
6658 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006659 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006660 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6661 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6662 // of the barriers is maintained.
6663 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006664 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6665 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6666 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006667
6668 // Apply the global barrier to the event itself (for race condition tracking)
6669 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6670 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6671 sync_event->barriers |= dst.exec_scope;
6672 } else {
6673 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6674 sync_event->barriers = 0U;
6675 }
John Zulauf4edde622021-02-15 08:54:50 -07006676 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006677 }
6678
6679 // Apply the pending barriers
6680 ResolvePendingBarrierFunctor apply_pending_action(tag);
6681 access_context->ApplyToContext(apply_pending_action);
6682}
6683
John Zulauf8eda1562021-04-13 17:06:41 -06006684bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006685 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6686 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006687}
6688
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006689bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6690 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6691 bool skip = false;
6692 const auto *cb_access_context = GetAccessContext(commandBuffer);
6693 assert(cb_access_context);
6694 if (!cb_access_context) return skip;
6695
6696 const auto *context = cb_access_context->GetCurrentAccessContext();
6697 assert(context);
6698 if (!context) return skip;
6699
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006700 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006701
6702 if (dst_buffer) {
6703 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6704 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6705 if (hazard.hazard) {
6706 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6707 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6708 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006709 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006710 }
6711 }
6712 return skip;
6713}
6714
John Zulauf669dfd52021-01-27 17:15:28 -07006715void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006716 events_.reserve(event_count);
6717 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006718 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006719 }
6720}
John Zulauf6ce24372021-01-30 05:56:25 -07006721
sjfricke0bea06e2022-06-05 09:22:26 +09006722SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006723 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006724 : SyncOpBase(cmd_type),
6725 event_(sync_state.Get<EVENT_STATE>(event)),
6726 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006727
John Zulauf1bf30522021-09-03 15:39:06 -06006728bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6729 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6730}
6731
John Zulaufbb890452021-12-14 11:30:18 -07006732bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6733 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006734 assert(events_context);
6735 bool skip = false;
6736 if (!events_context) return skip;
6737
John Zulaufbb890452021-12-14 11:30:18 -07006738 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006739 const auto *sync_event = events_context->Get(event_);
6740 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6741
John Zulauf1bf30522021-09-03 15:39:06 -06006742 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6743
John Zulauf6ce24372021-01-30 05:56:25 -07006744 const char *const set_wait =
6745 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6746 "hazards.";
6747 const char *message = set_wait; // Only one message this call.
6748 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6749 const char *vuid = nullptr;
6750 switch (sync_event->last_command) {
6751 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006752 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006753 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006754 // Needs a barrier between set and reset
6755 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6756 break;
John Zulauf4edde622021-02-15 08:54:50 -07006757 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006758 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006759 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006760 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6761 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6762 break;
6763 }
6764 default:
6765 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006766 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6767 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006768 break;
6769 }
6770 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006771 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6772 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006773 CommandTypeString(sync_event->last_command));
6774 }
6775 }
6776 return skip;
6777}
6778
John Zulauf8eda1562021-04-13 17:06:41 -06006779ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006780 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006781 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulaufe0757ba2022-06-10 16:51:45 -06006782 auto *access_context = cb_context->GetCurrentAccessContext();
6783 const QueueId queue_id = cb_context->GetQueueId();
John Zulauf6ce24372021-01-30 05:56:25 -07006784 assert(events_context);
John Zulaufe0757ba2022-06-10 16:51:45 -06006785 if (access_context && events_context) {
6786 ReplayRecord(queue_id, tag, access_context, events_context);
6787 }
John Zulauf8eda1562021-04-13 17:06:41 -06006788 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006789}
6790
John Zulauf8eda1562021-04-13 17:06:41 -06006791bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006792 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6793 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006794}
6795
John Zulauf00119522022-05-23 19:07:42 -06006796void SyncOpResetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufe0757ba2022-06-10 16:51:45 -06006797 SyncEventsContext *events_context) const {
6798 auto *sync_event = events_context->GetFromShared(event_);
6799 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6800
6801 // Update the event state
6802 sync_event->last_command = cmd_type_;
6803 sync_event->last_command_tag = tag;
6804 sync_event->unsynchronized_set = CMD_NONE;
6805 sync_event->ResetFirstScope();
6806 sync_event->barriers = 0U;
6807}
John Zulauf8eda1562021-04-13 17:06:41 -06006808
sjfricke0bea06e2022-06-05 09:22:26 +09006809SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006810 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006811 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006812 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006813 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006814 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006815 dep_info_() {
6816 // Snapshot the current access_context for later inspection at wait time.
6817 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6818 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6819 // or Submit time reference.
6820 if (access_context) {
6821 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6822 }
6823}
John Zulauf4edde622021-02-15 08:54:50 -07006824
sjfricke0bea06e2022-06-05 09:22:26 +09006825SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006826 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006827 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006828 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006829 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006830 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006831 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6832 if (access_context) {
6833 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6834 }
6835}
John Zulauf6ce24372021-01-30 05:56:25 -07006836
6837bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006838 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6839}
6840bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006841 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6842 assert(exec_context);
6843 return DoValidate(*exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006844}
6845
John Zulaufbb890452021-12-14 11:30:18 -07006846bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006847 bool skip = false;
6848
John Zulaufbb890452021-12-14 11:30:18 -07006849 const auto &sync_state = exec_context.GetSyncState();
6850 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006851 assert(events_context);
6852 if (!events_context) return skip;
6853
6854 const auto *sync_event = events_context->Get(event_);
6855 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6856
John Zulauf610e28c2021-08-03 17:46:23 -06006857 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6858
John Zulauf6ce24372021-01-30 05:56:25 -07006859 const char *const reset_set =
6860 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6861 "hazards.";
6862 const char *const wait =
6863 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6864
6865 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006866 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006867 const char *message = nullptr;
6868 switch (sync_event->last_command) {
6869 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006870 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006871 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006872 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006873 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006874 message = reset_set;
6875 break;
6876 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006877 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006878 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006879 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006880 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006881 message = reset_set;
6882 break;
6883 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006884 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006885 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006886 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006887 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006888 message = wait;
6889 break;
6890 default:
6891 // The only other valid last command that wasn't one.
6892 assert(sync_event->last_command == CMD_NONE);
6893 break;
6894 }
John Zulauf4edde622021-02-15 08:54:50 -07006895 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006896 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006897 std::string vuid("SYNC-");
6898 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006899 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6900 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006901 CommandTypeString(sync_event->last_command));
6902 }
6903 }
6904
6905 return skip;
6906}
6907
John Zulauf8eda1562021-04-13 17:06:41 -06006908ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006909 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006910 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006911 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06006912 assert(recorded_context_);
6913 if (recorded_context_ && events_context) {
6914 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006915 }
6916 return tag;
6917}
John Zulauf6ce24372021-01-30 05:56:25 -07006918
John Zulauf00119522022-05-23 19:07:42 -06006919void SyncOpSetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6920 SyncEventsContext *events_context) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06006921 // Create a copy of the current context, and merge in the state snapshot at record set event time
6922 // Note: we mustn't change the recorded context copy, as a given CB could be submitted more than once (in generaL)
6923 auto merged_context = std::make_shared<AccessContext>(*access_context);
6924 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
6925 DoRecord(queue_id, tag, merged_context, events_context);
6926}
6927
6928void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
6929 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006930 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006931 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006932
6933 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6934 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6935 // any issues caused by naive scope setting here.
6936
6937 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6938 // Given:
6939 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6940 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6941
6942 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6943 sync_event->unsynchronized_set = sync_event->last_command;
6944 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06006945 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07006946 // We only set the scope if there isn't one
6947 sync_event->scope = src_exec_scope_;
6948
John Zulaufe0757ba2022-06-10 16:51:45 -06006949 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
6950 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07006951 sync_event->unsynchronized_set = CMD_NONE;
6952 sync_event->first_scope_tag = tag;
6953 }
John Zulauf4edde622021-02-15 08:54:50 -07006954 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09006955 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006956 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006957 sync_event->barriers = 0U;
6958}
John Zulauf64ffe552021-02-06 10:25:07 -07006959
sjfricke0bea06e2022-06-05 09:22:26 +09006960SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07006961 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006962 const VkSubpassBeginInfo *pSubpassBeginInfo)
sjfricke0bea06e2022-06-05 09:22:26 +09006963 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07006964 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006965 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006966 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006967 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006968 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006969 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006970 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
6971 // Note that this a safe to presist as long as shared_attachments is not cleared
6972 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08006973 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07006974 attachments_.emplace_back(attachment.get());
6975 }
6976 }
6977 if (pSubpassBeginInfo) {
6978 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
6979 }
6980 }
6981}
6982
6983bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6984 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
6985 bool skip = false;
6986
6987 assert(rp_state_.get());
6988 if (nullptr == rp_state_.get()) return skip;
6989 auto &rp_state = *rp_state_.get();
6990
6991 const uint32_t subpass = 0;
6992
6993 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
6994 // hasn't happened yet)
6995 const std::vector<AccessContext> empty_context_vector;
6996 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
6997 cb_context.GetCurrentAccessContext());
6998
6999 // Validate attachment operations
7000 if (attachments_.size() == 0) return skip;
7001 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07007002
7003 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
7004 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
7005 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
7006 // operations (though it's currently a messy approach)
7007 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09007008 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007009
7010 // Validate load operations if there were no layout transition hazards
7011 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06007012 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09007013 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007014 }
7015
7016 return skip;
7017}
7018
John Zulauf8eda1562021-04-13 17:06:41 -06007019ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf64ffe552021-02-06 10:25:07 -07007020 // TODO PHASE2 need to have a consistent way to record to either command buffer or queue contexts
7021 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09007022 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
7023 return cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
John Zulauf64ffe552021-02-06 10:25:07 -07007024}
7025
John Zulauf8eda1562021-04-13 17:06:41 -06007026bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07007027 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007028 return false;
7029}
7030
John Zulauf00119522022-05-23 19:07:42 -06007031void SyncOpBeginRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07007032 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007033
sjfricke0bea06e2022-06-05 09:22:26 +09007034SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7035 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7036 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007037 if (pSubpassBeginInfo) {
7038 subpass_begin_info_.initialize(pSubpassBeginInfo);
7039 }
7040 if (pSubpassEndInfo) {
7041 subpass_end_info_.initialize(pSubpassEndInfo);
7042 }
7043}
7044
7045bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7046 bool skip = false;
7047 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7048 if (!renderpass_context) return skip;
7049
sjfricke0bea06e2022-06-05 09:22:26 +09007050 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007051 return skip;
7052}
7053
John Zulauf8eda1562021-04-13 17:06:41 -06007054ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09007055 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007056}
7057
7058bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07007059 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007060 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07007061}
7062
sjfricke0bea06e2022-06-05 09:22:26 +09007063SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7064 const VkSubpassEndInfo *pSubpassEndInfo)
7065 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007066 if (pSubpassEndInfo) {
7067 subpass_end_info_.initialize(pSubpassEndInfo);
7068 }
7069}
7070
John Zulauf00119522022-05-23 19:07:42 -06007071void SyncOpNextSubpass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
7072 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007073
John Zulauf64ffe552021-02-06 10:25:07 -07007074bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7075 bool skip = false;
7076 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7077
7078 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007079 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007080 return skip;
7081}
7082
John Zulauf8eda1562021-04-13 17:06:41 -06007083ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09007084 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007085}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007086
John Zulauf8eda1562021-04-13 17:06:41 -06007087bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07007088 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007089 return false;
7090}
7091
John Zulauf00119522022-05-23 19:07:42 -06007092void SyncOpEndRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07007093 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007094
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007095void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7096 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7097 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7098 auto *cb_access_context = GetAccessContext(commandBuffer);
7099 assert(cb_access_context);
7100 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7101 auto *context = cb_access_context->GetCurrentAccessContext();
7102 assert(context);
7103
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007104 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007105
7106 if (dst_buffer) {
7107 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7108 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7109 }
7110}
John Zulaufd05c5842021-03-26 11:32:16 -06007111
John Zulaufae842002021-04-15 18:20:55 -06007112bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7113 const VkCommandBuffer *pCommandBuffers) const {
7114 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007115 const auto *cb_context = GetAccessContext(commandBuffer);
7116 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007117
7118 // Heavyweight, but we need a proxy copy of the active command buffer access context
7119 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007120
7121 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007122 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007123 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7124
John Zulaufae842002021-04-15 18:20:55 -06007125 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7126 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007127
7128 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7129 assert(recorded_context);
sjfricke0bea06e2022-06-05 09:22:26 +09007130 skip |= recorded_cb_context->ValidateFirstUse(&proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007131
7132 // The barriers have already been applied in ValidatFirstUse
7133 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007134 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007135 }
7136
John Zulaufae842002021-04-15 18:20:55 -06007137 return skip;
7138}
7139
7140void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7141 const VkCommandBuffer *pCommandBuffers) {
7142 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007143 auto *cb_context = GetAccessContext(commandBuffer);
7144 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007145 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007146 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007147 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7148 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007149 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007150 }
John Zulaufae842002021-04-15 18:20:55 -06007151}
7152
John Zulauf1d5f9c12022-05-13 14:51:08 -06007153void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7154 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7155 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7156
7157 const auto queue_state = GetQueueSyncStateShared(queue);
7158 if (!queue_state) return; // Invalid queue
7159 QueueId waited_queue = queue_state->GetQueueId();
7160
7161 // We need to go through every queue batch context and clear all accesses this wait synchronizes
7162 // As usual -- two groups, the "last batch" and the signaled semaphores
7163 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
7164 // QueueBatchContext, track which we've done to avoid duplicate traversals
John Zulaufe0757ba2022-06-10 16:51:45 -06007165 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7166 for (auto &batch : queue_batch_contexts) {
7167 batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007168 }
7169
John Zulaufe0757ba2022-06-10 16:51:45 -06007170 // TODO: Fences affected by Wait
John Zulauf1d5f9c12022-05-13 14:51:08 -06007171}
7172
7173void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7174 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007175
7176 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7177 for (auto &batch : queue_batch_contexts) {
7178 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007179 }
7180
John Zulaufe0757ba2022-06-10 16:51:45 -06007181 // TODO: Update Fences affected by Wait
John Zulauf1d5f9c12022-05-13 14:51:08 -06007182}
7183
John Zulauf697c0e12022-04-19 16:31:12 -06007184struct QueueSubmitCmdState {
7185 std::shared_ptr<const QueueSyncState> queue;
7186 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007187 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007188 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007189 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7190 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007191};
7192
7193template <>
7194thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7195
John Zulaufbbda4572022-04-19 16:20:45 -06007196bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7197 VkFence fence) const {
7198 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007199
7200 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007201 if (!enabled[sync_validation_queue_submit]) return skip;
7202
John Zulauf00119522022-05-23 19:07:42 -06007203 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007204 const auto fence_state = Get<FENCE_STATE>(fence);
7205 cmd_state->queue = GetQueueSyncStateShared(queue);
7206 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007207
John Zulauf697c0e12022-04-19 16:31:12 -06007208 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7209 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7210
7211 // verify each submit batch
7212 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7213 // most recently created batch
7214 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7215 std::shared_ptr<QueueBatchContext> batch;
7216 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7217 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007218 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7219 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007220
John Zulaufe0757ba2022-06-10 16:51:45 -06007221 // Skip import and validation of empty batches
7222 if (batch->GetTagRange().size()) {
7223 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
John Zulauf697c0e12022-04-19 16:31:12 -06007224
John Zulaufe0757ba2022-06-10 16:51:45 -06007225 // For each submit in the batch...
7226 for (const auto &cb : *batch) {
7227 if (cb.cb->GetTagLimit() == 0) continue; // Skip empty CB's
7228 skip |= cb.cb->ValidateFirstUse(batch.get(), "vkQueueSubmit", cb.index);
7229
7230 // The barriers have already been applied in ValidatFirstUse
7231 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
7232 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
7233 }
John Zulauf697c0e12022-04-19 16:31:12 -06007234 }
7235
John Zulaufe0757ba2022-06-10 16:51:45 -06007236 // Empty batches could have semaphores, though.
John Zulauf697c0e12022-04-19 16:31:12 -06007237 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7238 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007239 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007240 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007241 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7242 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7243 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007244 }
7245 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7246 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7247 last_batch = batch;
7248 }
7249 // The most recently created batch will become the queue's "last batch" in the record phase
7250 if (batch) {
7251 cmd_state->last_batch = std::move(batch);
7252 }
7253
7254 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007255 return skip;
7256}
7257
7258void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7259 VkResult result) {
7260 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007261
John Zulaufcb7e1672022-05-04 13:46:08 -06007262 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007263 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7264
John Zulaufcb7e1672022-05-04 13:46:08 -06007265 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7266 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007267 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007268
7269 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007270 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7271
John Zulauf697c0e12022-04-19 16:31:12 -06007272 // Don't need to look up the queue state again, but we need a non-const version
7273 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007274
John Zulaufcb7e1672022-05-04 13:46:08 -06007275 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7276 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7277 // QBC's are those referenced by unwaited signals and the last batch.
7278 for (auto &sig_sem : cmd_state->signaled) {
7279 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007280 auto &sig_batch = sig_sem.second->batch;
7281 sig_batch->ResetAccessLog();
7282 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7283 if (sig_batch != cmd_state->last_batch) {
7284 sig_batch->ResetEventsContext();
7285 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007286 }
7287 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007288 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007289 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007290
John Zulaufcb7e1672022-05-04 13:46:08 -06007291 // Update the queue to point to the last batch from the submit
7292 if (cmd_state->last_batch) {
7293 cmd_state->last_batch->ResetAccessLog();
John Zulaufe0757ba2022-06-10 16:51:45 -06007294
7295 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7296 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7297 auto last_batch = queue_state->LastBatch();
7298 if (last_batch) {
7299 last_batch->ResetEventsContext();
7300 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007301 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007302 }
7303
7304 // Update the global access log from the one built during validation
7305 global_access_log_.MergeMove(std::move(cmd_state->logger));
7306
John Zulauf697c0e12022-04-19 16:31:12 -06007307
7308 // WIP: record information about fences
John Zulaufbbda4572022-04-19 16:20:45 -06007309}
7310
7311bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7312 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007313 bool skip = false;
7314 if (!enabled[sync_validation_queue_submit]) return skip;
7315
John Zulauf697c0e12022-04-19 16:31:12 -06007316 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007317 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007318}
7319
7320void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7321 VkFence fence, VkResult result) {
7322 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007323 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7324
7325 if (!enabled[sync_validation_queue_submit]) return;
7326
John Zulauf697c0e12022-04-19 16:31:12 -06007327 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007328}
7329
John Zulaufd0ec59f2021-03-13 14:25:08 -07007330AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7331 : view_(view), view_mask_(), gen_store_() {
7332 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7333 const IMAGE_STATE &image_state = *view_->image_state.get();
7334 const auto base_address = ResourceBaseAddress(image_state);
7335 const auto *encoder = image_state.fragment_encoder.get();
7336 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007337 // Get offset and extent for the view, accounting for possible depth slicing
7338 const VkOffset3D zero_offset = view->GetOffset();
7339 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007340 // Intentional copy
7341 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7342 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007343 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7344 view->IsDepthSliced());
7345 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007346
7347 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7348 if (depth && (depth != view_mask_)) {
7349 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007350 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007351 }
7352 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7353 if (stencil && (stencil != view_mask_)) {
7354 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007355 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7356 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007357 }
7358}
7359
7360const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7361 const ImageRangeGen *got = nullptr;
7362 switch (gen_type) {
7363 case kViewSubresource:
7364 got = &gen_store_[kViewSubresource];
7365 break;
7366 case kRenderArea:
7367 got = &gen_store_[kRenderArea];
7368 break;
7369 case kDepthOnlyRenderArea:
7370 got =
7371 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7372 break;
7373 case kStencilOnlyRenderArea:
7374 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7375 : &gen_store_[Gen::kStencilOnlyRenderArea];
7376 break;
7377 default:
7378 assert(got);
7379 }
7380 return got;
7381}
7382
7383AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7384 assert(IsValid());
7385 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7386 if (depth_op) {
7387 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7388 if (stencil_op) {
7389 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7390 return kRenderArea;
7391 }
7392 return kDepthOnlyRenderArea;
7393 }
7394 if (stencil_op) {
7395 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7396 return kStencilOnlyRenderArea;
7397 }
7398
7399 assert(depth_op || stencil_op);
7400 return kRenderArea;
7401}
7402
7403AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007404
John Zulaufe0757ba2022-06-10 16:51:45 -06007405void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007406 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7407 for (auto &event_pair : map_) {
7408 assert(event_pair.second); // Shouldn't be storing empty
7409 auto &sync_event = *event_pair.second;
7410 // 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 -06007411 // But only if occuring before the tag
7412 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007413 sync_event.barriers |= dst.exec_scope;
7414 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7415 }
7416 }
7417}
John Zulaufbb890452021-12-14 11:30:18 -07007418
John Zulaufe0757ba2022-06-10 16:51:45 -06007419void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7420 const SyncExecScope src_scope =
7421 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7422 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7423 ApplyBarrier(src_scope, dst_scope, tag);
7424}
7425
7426SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7427 // We need a deep copy of the const context to update during validation phase
7428 for (const auto &event : from.map_) {
7429 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7430 }
7431 return *this;
7432}
7433
John Zulaufbb890452021-12-14 11:30:18 -07007434ReplayTrackbackBarriersAction::ReplayTrackbackBarriersAction(VkQueueFlags queue_flags,
7435 const SubpassDependencyGraphNode &subpass_dep,
7436 const std::vector<ReplayTrackbackBarriersAction> &replay_contexts) {
7437 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
7438 trackback_barriers.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
7439 for (const auto &prev_dep : subpass_dep.prev) {
7440 const auto prev_pass = prev_dep.first->pass;
7441 const auto &prev_barriers = prev_dep.second;
7442 trackback_barriers.emplace_back(&replay_contexts[prev_pass], queue_flags, prev_barriers);
7443 }
7444 if (has_barrier_from_external) {
7445 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
7446 trackback_barriers.emplace_back(nullptr, queue_flags, subpass_dep.barrier_from_external);
7447 }
7448}
7449
7450void ReplayTrackbackBarriersAction::operator()(ResourceAccessState *access) const {
7451 if (trackback_barriers.size() == 1) {
7452 trackback_barriers[0](access);
7453 } else {
7454 ResourceAccessState resolved;
7455 for (const auto &trackback : trackback_barriers) {
7456 ResourceAccessState access_copy = *access;
7457 trackback(&access_copy);
7458 resolved.Resolve(access_copy);
7459 }
7460 *access = resolved;
7461 }
7462}
7463
7464ReplayTrackbackBarriersAction::TrackbackBarriers::TrackbackBarriers(
7465 const ReplayTrackbackBarriersAction *source_subpass_, VkQueueFlags queue_flags_,
7466 const std::vector<const VkSubpassDependency2 *> &subpass_dependencies_)
7467 : Base(source_subpass_, queue_flags_, subpass_dependencies_) {}
7468
7469void ReplayTrackbackBarriersAction::TrackbackBarriers::operator()(ResourceAccessState *access) const {
7470 if (source_subpass) {
7471 (*source_subpass)(access);
7472 }
7473 access->ApplyBarriersImmediate(barriers);
7474}
John Zulauf697c0e12022-04-19 16:31:12 -06007475
John Zulaufcb7e1672022-05-04 13:46:08 -06007476QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
7477 : CommandExecutionContext(&sync_state), queue_state_(&queue_state), tag_range_(0, 0), batch_log_(nullptr) {}
7478
John Zulauf697c0e12022-04-19 16:31:12 -06007479template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007480void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7481 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007482 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007483 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007484}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007485void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007486 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007487}
John Zulauf697c0e12022-04-19 16:31:12 -06007488
7489VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7490
John Zulauf1d5f9c12022-05-13 14:51:08 -06007491void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
7492 QueueWaitWorm wait_worm(queue_id);
7493 access_context_.ForAll(wait_worm);
7494 if (wait_worm.erase_all) {
7495 access_context_.Reset();
7496 } else {
7497 // TODO: Profiling will tell us if we need a more efficient clean up.
7498 for (const auto &address : wait_worm.erase_list) {
7499 access_context_.DeleteAccess(address);
7500 }
7501 }
John Zulaufe0757ba2022-06-10 16:51:45 -06007502
7503 if (queue_id == GetQueueId()) {
7504 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7505 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007506}
7507
7508// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007509void QueueBatchContext::ApplyDeviceWait() {
7510 access_context_.Reset();
7511 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7512}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007513
John Zulaufecf4ac52022-06-06 10:08:42 -06007514class ApplySemaphoreBarrierAction {
7515 public:
7516 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7517 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7518
7519 private:
7520 const SemaphoreScope &signal_;
7521 const SemaphoreScope wait_;
7522};
7523
7524std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7525 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007526 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007527 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007528
John Zulaufcb7e1672022-05-04 13:46:08 -06007529 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7530 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007531 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007532
John Zulaufecf4ac52022-06-06 10:08:42 -06007533 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007534
John Zulaufecf4ac52022-06-06 10:08:42 -06007535 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007536 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007537 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7538 if (signal_scope.queue == wait_scope.queue) {
7539 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7540 // valid accesses for the sync scope.
7541 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7542 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7543 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007544 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007545 } else {
7546 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7547 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007548 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007549 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7550 // enforce deep constness.
7551 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007552}
7553
7554// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7555template <>
7556class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7557 public:
7558 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7559 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7560 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7561 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7562 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7563 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7564
7565 private:
7566 const VkSubmitInfo &info_;
7567};
7568template <typename BatchInfo, typename Fn>
7569void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7570 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7571 Accessor batch(batch_info);
7572 const uint32_t wait_count = batch.WaitSemaphoreCount();
7573 for (uint32_t i = 0; i < wait_count; ++i) {
7574 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7575 }
7576}
7577
7578template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007579void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7580 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007581 // Copy in the event state from the previous batch (on this queue)
7582 if (prev) {
7583 events_context_.DeepCopy(prev->events_context_);
7584 }
7585
John Zulaufecf4ac52022-06-06 10:08:42 -06007586 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7587 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
7588 ForEachWaitSemaphore(batch_info, [this, &signaled, &batches_resolved](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7589 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(sem, wait_mask, signaled);
7590 if (resolved) {
7591 batches_resolved.emplace(std::move(resolved));
7592 }
John Zulauf697c0e12022-04-19 16:31:12 -06007593 });
7594
John Zulaufecf4ac52022-06-06 10:08:42 -06007595 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7596 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7597 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf78cb2082022-04-20 16:37:48 -06007598 }
7599
John Zulauf697c0e12022-04-19 16:31:12 -06007600 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007601 async_batches_ =
7602 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
7603 return (batch != prev) && !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007604 });
7605 for (const auto &async_batch : async_batches_) {
7606 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7607 }
7608}
7609
7610template <typename BatchInfo>
7611void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7612 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7613 Accessor batch(batch_info);
7614
7615 // Create the list of command buffers to submit
7616 const uint32_t cb_count = batch.CommandBufferCount();
7617 command_buffers_.reserve(cb_count);
7618 for (uint32_t index = 0; index < cb_count; ++index) {
7619 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7620 if (cb_context) {
7621 tag_range_.end += cb_context->GetTagLimit();
7622 command_buffers_.emplace_back(index, std::move(cb_context));
7623 }
7624 }
7625}
7626
7627// Look up the usage informaiton from the local or global logger
7628std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7629 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7630 std::stringstream out;
7631 AccessLogger::AccessRecord access = use_logger[tag];
7632 if (access.IsValid()) {
7633 const AccessLogger::BatchRecord &batch = *access.batch;
7634 const ResourceUsageRecord &record = *access.record;
7635 // Queue and Batch information
7636 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7637 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7638
7639 // Commandbuffer Usages Information
7640 out << record;
7641 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7642 out << ", reset_no: " << std::to_string(record.reset_count);
7643 }
7644 return out.str();
7645}
7646
7647VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7648
John Zulauf00119522022-05-23 19:07:42 -06007649QueueId QueueBatchContext::GetQueueId() const {
7650 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7651 return id;
7652}
7653
John Zulauf697c0e12022-04-19 16:31:12 -06007654void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7655 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7656 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7657 SetTagBias(global_tags.begin);
7658 // Add an access log for the batches range and point the batch at it.
7659 logger_ = &logger;
7660 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7661}
7662
7663void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7664 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7665 batch_log_->Append(submitted_cb.GetAccessLog());
7666}
7667
7668void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7669 const auto size = tag_range_.size();
7670 tag_range_.begin = bias;
7671 tag_range_.end = bias + size;
7672 access_context_.SetStartTag(bias);
7673}
7674
John Zulauf1d5f9c12022-05-13 14:51:08 -06007675QueueBatchContext::QueueWaitWorm::QueueWaitWorm(QueueId queue, ResourceUsageTag tag) : predicate(queue) {}
7676
7677void QueueBatchContext::QueueWaitWorm::operator()(AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) {
7678 bool erased = access.second.ApplyQueueTagWait(predicate);
7679 if (erased) {
7680 erase_list.emplace_back(address_type, access.first);
7681 } else {
7682 erase_all = false;
7683 }
7684}
7685
John Zulauf697c0e12022-04-19 16:31:12 -06007686AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7687 const ResourceUsageRange &range) {
7688 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7689 assert(inserted.second);
7690 return &inserted.first->second;
7691}
7692
7693void AccessLogger::MergeMove(AccessLogger &&child) {
7694 for (auto &range : child.access_log_map_) {
7695 BatchLog &child_batch = range.second;
7696 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7697 insert_pair.first->second = std::move(child_batch);
7698 assert(insert_pair.second);
7699 }
7700 child.Reset();
7701}
7702
7703void AccessLogger::Reset() {
7704 prev_ = nullptr;
7705 access_log_map_.clear();
7706}
7707
7708// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7709// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7710// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7711// the contexts Resolve all history from previous all contexts when created
7712void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7713 last_batch_ = std::move(last);
7714 last_batch_->ResetAccessLog();
7715}
7716
7717// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7718// scope state.
7719// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7720// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7721uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7722
7723void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7724 log_.insert(log_.end(), other.cbegin(), other.cend());
7725 for (const auto &record : other) {
7726 assert(record.cb_state);
7727 cbs_referenced_.insert(record.cb_state->shared_from_this());
7728 }
7729}
7730
7731AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7732 assert(index < log_.size());
7733 return AccessRecord{&batch_, &log_[index]};
7734}
7735
7736AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7737 AccessRecord access_record = {nullptr, nullptr};
7738
7739 auto found_range = access_log_map_.find(tag);
7740 if (found_range != access_log_map_.cend()) {
7741 const ResourceUsageTag bias = found_range->first.begin;
7742 assert(tag >= bias);
7743 access_record = found_range->second[tag - bias];
7744 } else if (prev_) {
7745 access_record = (*prev_)[tag];
7746 }
7747
7748 return access_record;
7749}
John Zulaufcb7e1672022-05-04 13:46:08 -06007750
John Zulaufecf4ac52022-06-06 10:08:42 -06007751// This is a const method, force the returned value to be const
7752std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007753 std::shared_ptr<Signal> prev_state;
7754 if (prev_) {
7755 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7756 }
7757 return prev_state;
7758}
John Zulaufecf4ac52022-06-06 10:08:42 -06007759
7760SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7761 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7762 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7763 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7764 assert(batch);
7765 assert(sem_state);
7766}