blob: c8085fe45d9572f03d1249d931caed91e6333512 [file] [log] [blame]
John Zulaufab7756b2020-12-29 16:10:16 -07001/* Copyright (c) 2019-2021 The Khronos Group Inc.
2 * Copyright (c) 2019-2021 Valve Corporation
3 * Copyright (c) 2019-2021 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"
27
John Zulauf43cc7462020-12-03 12:33:12 -070028const static std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
29 AccessAddressType::kLinear, AccessAddressType::kIdealized};
30
John Zulaufd5115702021-01-18 12:34:33 -070031static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
32static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) { return AccessContext::ImageAddressType(image); }
33
John Zulauf9cb530d2019-09-30 14:14:10 -060034static const char *string_SyncHazardVUID(SyncHazard hazard) {
35 switch (hazard) {
36 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070037 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060038 break;
39 case SyncHazard::READ_AFTER_WRITE:
40 return "SYNC-HAZARD-READ_AFTER_WRITE";
41 break;
42 case SyncHazard::WRITE_AFTER_READ:
43 return "SYNC-HAZARD-WRITE_AFTER_READ";
44 break;
45 case SyncHazard::WRITE_AFTER_WRITE:
46 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
47 break;
John Zulauf2f952d22020-02-10 11:34:51 -070048 case SyncHazard::READ_RACING_WRITE:
49 return "SYNC-HAZARD-READ-RACING-WRITE";
50 break;
51 case SyncHazard::WRITE_RACING_WRITE:
52 return "SYNC-HAZARD-WRITE-RACING-WRITE";
53 break;
54 case SyncHazard::WRITE_RACING_READ:
55 return "SYNC-HAZARD-WRITE-RACING-READ";
56 break;
John Zulauf9cb530d2019-09-30 14:14:10 -060057 default:
58 assert(0);
59 }
60 return "SYNC-HAZARD-INVALID";
61}
62
John Zulauf59e25072020-07-17 10:55:21 -060063static bool IsHazardVsRead(SyncHazard hazard) {
64 switch (hazard) {
65 case SyncHazard::NONE:
66 return false;
67 break;
68 case SyncHazard::READ_AFTER_WRITE:
69 return false;
70 break;
71 case SyncHazard::WRITE_AFTER_READ:
72 return true;
73 break;
74 case SyncHazard::WRITE_AFTER_WRITE:
75 return false;
76 break;
77 case SyncHazard::READ_RACING_WRITE:
78 return false;
79 break;
80 case SyncHazard::WRITE_RACING_WRITE:
81 return false;
82 break;
83 case SyncHazard::WRITE_RACING_READ:
84 return true;
85 break;
86 default:
87 assert(0);
88 }
89 return false;
90}
91
John Zulauf9cb530d2019-09-30 14:14:10 -060092static const char *string_SyncHazard(SyncHazard hazard) {
93 switch (hazard) {
94 case SyncHazard::NONE:
95 return "NONR";
96 break;
97 case SyncHazard::READ_AFTER_WRITE:
98 return "READ_AFTER_WRITE";
99 break;
100 case SyncHazard::WRITE_AFTER_READ:
101 return "WRITE_AFTER_READ";
102 break;
103 case SyncHazard::WRITE_AFTER_WRITE:
104 return "WRITE_AFTER_WRITE";
105 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700106 case SyncHazard::READ_RACING_WRITE:
107 return "READ_RACING_WRITE";
108 break;
109 case SyncHazard::WRITE_RACING_WRITE:
110 return "WRITE_RACING_WRITE";
111 break;
112 case SyncHazard::WRITE_RACING_READ:
113 return "WRITE_RACING_READ";
114 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600115 default:
116 assert(0);
117 }
118 return "INVALID HAZARD";
119}
120
John Zulauf37ceaed2020-07-03 16:18:15 -0600121static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
122 // Return the info for the first bit found
123 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700124 for (size_t i = 0; i < flags.size(); i++) {
125 if (flags.test(i)) {
126 info = &syncStageAccessInfoByStageAccessIndex[i];
127 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600128 }
129 }
130 return info;
131}
132
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700133static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600134 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700135 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600136 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700137 } else {
138 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
139 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
140 if ((flags & info.stage_access_bit).any()) {
141 if (!out_str.empty()) {
142 out_str.append(sep);
143 }
144 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600145 }
John Zulauf59e25072020-07-17 10:55:21 -0600146 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700147 if (out_str.length() == 0) {
148 out_str.append("Unhandled SyncStageAccess");
149 }
John Zulauf59e25072020-07-17 10:55:21 -0600150 }
151 return out_str;
152}
153
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700154static std::string string_UsageTag(const ResourceUsageTag &tag) {
155 std::stringstream out;
156
John Zulauffaea0ee2021-01-14 14:01:32 -0700157 out << "command: " << CommandTypeString(tag.command);
158 out << ", seq_no: " << tag.seq_num;
159 if (tag.sub_command != 0) {
160 out << ", subcmd: " << tag.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700161 }
162 return out.str();
163}
164
John Zulauffaea0ee2021-01-14 14:01:32 -0700165std::string CommandBufferAccessContext::FormatUsage(const HazardResult &hazard) const {
John Zulauf37ceaed2020-07-03 16:18:15 -0600166 const auto &tag = hazard.tag;
John Zulauf59e25072020-07-17 10:55:21 -0600167 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
168 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
John Zulauf1dae9192020-06-16 15:46:44 -0600169 std::stringstream out;
John Zulauf37ceaed2020-07-03 16:18:15 -0600170 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
171 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
John Zulauf59e25072020-07-17 10:55:21 -0600172 out << "(usage: " << usage_info.name << ", prior_usage: " << stage_access_name;
173 if (IsHazardVsRead(hazard.hazard)) {
174 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
175 out << ", read_barriers: " << string_VkPipelineStageFlags(barriers);
176 } else {
177 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
178 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
179 }
180
John Zulauffaea0ee2021-01-14 14:01:32 -0700181 // PHASE2 TODO -- add comand buffer and reset from secondary if applicable
182 out << ", " << string_UsageTag(tag) << ", reset_no: " << reset_count_;
John Zulauf1dae9192020-06-16 15:46:44 -0600183 return out.str();
184}
185
John Zulaufd14743a2020-07-03 09:42:39 -0600186// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
187// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
188// also reflects this special case for read hazard detection (using access instead of exec scope)
John Zulaufb027cdb2020-05-21 14:25:22 -0600189static constexpr VkPipelineStageFlags kColorAttachmentExecScope = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700190static const SyncStageAccessFlags kColorAttachmentAccessScope =
191 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
192 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
193 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
194 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulaufb027cdb2020-05-21 14:25:22 -0600195static constexpr VkPipelineStageFlags kDepthStencilAttachmentExecScope =
196 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700197static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
198 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
199 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
200 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulauf8e3c3e92021-01-06 11:19:36 -0700201static constexpr VkPipelineStageFlags kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
202static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600203
John Zulauf8e3c3e92021-01-06 11:19:36 -0700204ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
205 {{0U, SyncStageAccessFlags()},
206 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
207 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
208 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
209
John Zulauf7635de32020-05-29 17:14:15 -0600210// Sometimes we have an internal access conflict, and we using the kCurrentCommandTag to set and detect in temporary/proxy contexts
John Zulauffaea0ee2021-01-14 14:01:32 -0700211static const ResourceUsageTag kCurrentCommandTag(ResourceUsageTag::kMaxIndex, ResourceUsageTag::kMaxCount,
212 ResourceUsageTag::kMaxCount, CMD_NONE);
John Zulaufb027cdb2020-05-21 14:25:22 -0600213
John Zulaufb02c1eb2020-10-06 16:33:36 -0600214static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) {
215 return bindable.binding.offset + bindable.binding.mem_state->fake_base_address;
216}
217
218static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.binding.mem_state; }
219
locke-lunarg3c038002020-04-30 23:08:08 -0600220inline VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
221 if (size == VK_WHOLE_SIZE) {
222 return (whole_size - offset);
223 }
224 return size;
225}
226
John Zulauf3e86bf02020-09-12 10:47:57 -0600227static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
228 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
229}
230
John Zulauf16adfc92020-04-08 10:28:33 -0600231template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600232static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600233 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
234}
235
John Zulauf355e49b2020-04-24 15:11:15 -0600236static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600237
John Zulauf3e86bf02020-09-12 10:47:57 -0600238static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
239 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
240}
241
242static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
243 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
244}
245
John Zulauf4a6105a2020-11-17 15:11:05 -0700246// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
247//
John Zulauf10f1f522020-12-18 12:00:35 -0700248// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
249//
John Zulauf4a6105a2020-11-17 15:11:05 -0700250// Usage:
251// Constructor() -- initializes the generator to point to the begin of the space declared.
252// * -- the current range of the generator empty signfies end
253// ++ -- advance to the next non-empty range (or end)
254
255// A wrapper for a single range with the same semantics as the actual generators below
256template <typename KeyType>
257class SingleRangeGenerator {
258 public:
259 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700260 const KeyType &operator*() const { return current_; }
261 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700262 SingleRangeGenerator &operator++() {
263 current_ = KeyType(); // just one real range
264 return *this;
265 }
266
267 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
268
269 private:
270 SingleRangeGenerator() = default;
271 const KeyType range_;
272 KeyType current_;
273};
274
275// Generate the ranges that are the intersection of range and the entries in the FilterMap
276template <typename FilterMap, typename KeyType = typename FilterMap::key_type>
277class FilteredRangeGenerator {
278 public:
John Zulaufd5115702021-01-18 12:34:33 -0700279 // Default constructed is safe to dereference for "empty" test, but for no other operation.
280 FilteredRangeGenerator() : range_(), filter_(nullptr), filter_pos_(), current_() {
281 // Default construction for KeyType *must* be empty range
282 assert(current_.empty());
283 }
John Zulauf4a6105a2020-11-17 15:11:05 -0700284 FilteredRangeGenerator(const FilterMap &filter, const KeyType &range)
285 : range_(range), filter_(&filter), filter_pos_(), current_() {
286 SeekBegin();
287 }
John Zulaufd5115702021-01-18 12:34:33 -0700288 FilteredRangeGenerator(const FilteredRangeGenerator &from) = default;
289
John Zulauf4a6105a2020-11-17 15:11:05 -0700290 const KeyType &operator*() const { return current_; }
291 const KeyType *operator->() const { return &current_; }
292 FilteredRangeGenerator &operator++() {
293 ++filter_pos_;
294 UpdateCurrent();
295 return *this;
296 }
297
298 bool operator==(const FilteredRangeGenerator &other) const { return current_ == other.current_; }
299
300 private:
John Zulauf4a6105a2020-11-17 15:11:05 -0700301 void UpdateCurrent() {
302 if (filter_pos_ != filter_->cend()) {
303 current_ = range_ & filter_pos_->first;
304 } else {
305 current_ = KeyType();
306 }
307 }
308 void SeekBegin() {
309 filter_pos_ = filter_->lower_bound(range_);
310 UpdateCurrent();
311 }
312 const KeyType range_;
313 const FilterMap *filter_;
314 typename FilterMap::const_iterator filter_pos_;
315 KeyType current_;
316};
John Zulaufd5115702021-01-18 12:34:33 -0700317using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700318using EventSimpleRangeGenerator = FilteredRangeGenerator<SyncEventState::ScopeMap>;
319
320// Templated to allow for different Range generators or map sources...
321
322// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulauf4a6105a2020-11-17 15:11:05 -0700323template <typename FilterMap, typename RangeGen, typename KeyType = typename FilterMap::key_type>
324class FilteredGeneratorGenerator {
325 public:
John Zulaufd5115702021-01-18 12:34:33 -0700326 // Default constructed is safe to dereference for "empty" test, but for no other operation.
327 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
328 // Default construction for KeyType *must* be empty range
329 assert(current_.empty());
330 }
331 FilteredGeneratorGenerator(const FilterMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700332 SeekBegin();
333 }
John Zulaufd5115702021-01-18 12:34:33 -0700334 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700335 const KeyType &operator*() const { return current_; }
336 const KeyType *operator->() const { return &current_; }
337 FilteredGeneratorGenerator &operator++() {
338 KeyType gen_range = GenRange();
339 KeyType filter_range = FilterRange();
340 current_ = KeyType();
341 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
342 if (gen_range.end > filter_range.end) {
343 // if the generated range is beyond the filter_range, advance the filter range
344 filter_range = AdvanceFilter();
345 } else {
346 gen_range = AdvanceGen();
347 }
348 current_ = gen_range & filter_range;
349 }
350 return *this;
351 }
352
353 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
354
355 private:
356 KeyType AdvanceFilter() {
357 ++filter_pos_;
358 auto filter_range = FilterRange();
359 if (filter_range.valid()) {
360 FastForwardGen(filter_range);
361 }
362 return filter_range;
363 }
364 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700365 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700366 auto gen_range = GenRange();
367 if (gen_range.valid()) {
368 FastForwardFilter(gen_range);
369 }
370 return gen_range;
371 }
372
373 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700374 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700375
376 KeyType FastForwardFilter(const KeyType &range) {
377 auto filter_range = FilterRange();
378 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700379 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700380 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
381 if (retry_count < kRetryLimit) {
382 ++filter_pos_;
383 filter_range = FilterRange();
384 retry_count++;
385 } else {
386 // Okay we've tried walking, do a seek.
387 filter_pos_ = filter_->lower_bound(range);
388 break;
389 }
390 }
391 return FilterRange();
392 }
393
394 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
395 // faster.
396 KeyType FastForwardGen(const KeyType &range) {
397 auto gen_range = GenRange();
398 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700399 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700400 gen_range = GenRange();
401 }
402 return gen_range;
403 }
404
405 void SeekBegin() {
406 auto gen_range = GenRange();
407 if (gen_range.empty()) {
408 current_ = KeyType();
409 filter_pos_ = filter_->cend();
410 } else {
411 filter_pos_ = filter_->lower_bound(gen_range);
412 current_ = gen_range & FilterRange();
413 }
414 }
415
John Zulauf4a6105a2020-11-17 15:11:05 -0700416 const FilterMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700417 RangeGen gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700418 typename FilterMap::const_iterator filter_pos_;
419 KeyType current_;
420};
421
422using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
423
John Zulauf0cb5be22020-01-23 12:18:22 -0700424// Expand the pipeline stage without regard to whether the are valid w.r.t. queue or extension
425VkPipelineStageFlags ExpandPipelineStages(VkQueueFlags queue_flags, VkPipelineStageFlags stage_mask) {
426 VkPipelineStageFlags expanded = stage_mask;
427 if (VK_PIPELINE_STAGE_ALL_COMMANDS_BIT & stage_mask) {
428 expanded = expanded & ~VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
429 for (const auto &all_commands : syncAllCommandStagesByQueueFlags) {
430 if (all_commands.first & queue_flags) {
431 expanded |= all_commands.second;
432 }
433 }
434 }
435 if (VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT & stage_mask) {
436 expanded = expanded & ~VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
437 expanded |= syncAllCommandStagesByQueueFlags.at(VK_QUEUE_GRAPHICS_BIT) & ~VK_PIPELINE_STAGE_HOST_BIT;
438 }
439 return expanded;
440}
441
John Zulauf36bcf6a2020-02-03 15:12:52 -0700442VkPipelineStageFlags RelatedPipelineStages(VkPipelineStageFlags stage_mask,
Jeremy Gebben91c36902020-11-09 08:17:08 -0700443 const std::map<VkPipelineStageFlagBits, VkPipelineStageFlags> &map) {
John Zulauf36bcf6a2020-02-03 15:12:52 -0700444 VkPipelineStageFlags unscanned = stage_mask;
445 VkPipelineStageFlags related = 0;
Jonah Ryan-Davis185189c2020-07-14 10:28:52 -0400446 for (const auto &entry : map) {
447 const auto &stage = entry.first;
John Zulauf36bcf6a2020-02-03 15:12:52 -0700448 if (stage & unscanned) {
449 related = related | entry.second;
450 unscanned = unscanned & ~stage;
451 if (!unscanned) break;
452 }
453 }
454 return related;
455}
456
457VkPipelineStageFlags WithEarlierPipelineStages(VkPipelineStageFlags stage_mask) {
458 return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyEarlierStages);
459}
460
461VkPipelineStageFlags WithLaterPipelineStages(VkPipelineStageFlags stage_mask) {
462 return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyLaterStages);
463}
464
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700465static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
John Zulauf5c5e88d2019-12-26 11:22:02 -0700466
John Zulauf3e86bf02020-09-12 10:47:57 -0600467ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
468 VkDeviceSize stride) {
469 VkDeviceSize range_start = offset + first_index * stride;
470 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600471 if (count == UINT32_MAX) {
472 range_size = buf_whole_size - range_start;
473 } else {
474 range_size = count * stride;
475 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600476 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600477}
478
locke-lunarg654e3692020-06-04 17:19:15 -0600479SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
480 VkShaderStageFlagBits stage_flag) {
481 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
482 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
483 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
484 }
485 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
486 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
487 assert(0);
488 }
489 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
490 return stage_access->second.uniform_read;
491 }
492
493 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
494 // Because if write hazard happens, read hazard might or might not happen.
495 // But if write hazard doesn't happen, read hazard is impossible to happen.
496 if (descriptor_data.is_writable) {
497 return stage_access->second.shader_write;
498 }
499 return stage_access->second.shader_read;
500}
501
locke-lunarg37047832020-06-12 13:44:45 -0600502bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
503 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
504 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
505 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
506 ? true
507 : false;
508}
509
510bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
511 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
512 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
513 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
514 ? true
515 : false;
516}
517
John Zulauf355e49b2020-04-24 15:11:15 -0600518// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600519template <typename Action>
520static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
521 Action &action) {
522 // At this point the "apply over range" logic only supports a single memory binding
523 if (!SimpleBinding(image_state)) return;
524 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600525 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700526 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
527 image_state.createInfo.extent, base_address);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600528 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700529 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600530 }
531}
532
John Zulauf7635de32020-05-29 17:14:15 -0600533// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
534// Used by both validation and record operations
535//
536// The signature for Action() reflect the needs of both uses.
537template <typename Action>
538void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
539 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass) {
540 VkExtent3D extent = CastTo3D(render_area.extent);
541 VkOffset3D offset = CastTo3D(render_area.offset);
542 const auto &rp_ci = rp_state.createInfo;
543 const auto *attachment_ci = rp_ci.pAttachments;
544 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
545
546 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
547 const auto *color_attachments = subpass_ci.pColorAttachments;
548 const auto *color_resolve = subpass_ci.pResolveAttachments;
549 if (color_resolve && color_attachments) {
550 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
551 const auto &color_attach = color_attachments[i].attachment;
552 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
553 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
554 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700555 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kColorAttachment, offset, extent, 0);
John Zulauf7635de32020-05-29 17:14:15 -0600556 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700557 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment, offset, extent, 0);
John Zulauf7635de32020-05-29 17:14:15 -0600558 }
559 }
560 }
561
562 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700563 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600564 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
565 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
566 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
567 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
568 const auto src_ci = attachment_ci[src_at];
569 // The formats are required to match so we can pick either
570 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
571 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
572 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
573 VkImageAspectFlags aspect_mask = 0u;
574
575 // Figure out which aspects are actually touched during resolve operations
576 const char *aspect_string = nullptr;
577 if (resolve_depth && resolve_stencil) {
578 // Validate all aspects together
579 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
580 aspect_string = "depth/stencil";
581 } else if (resolve_depth) {
582 // Validate depth only
583 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
584 aspect_string = "depth";
585 } else if (resolve_stencil) {
586 // Validate all stencil only
587 aspect_mask = VK_IMAGE_ASPECT_STENCIL_BIT;
588 aspect_string = "stencil";
589 }
590
591 if (aspect_mask) {
592 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700593 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600594 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700595 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600596 }
597 }
598}
599
600// Action for validating resolve operations
601class ValidateResolveAction {
602 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700603 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
604 const CommandBufferAccessContext &cb_context, const char *func_name)
John Zulauf7635de32020-05-29 17:14:15 -0600605 : render_pass_(render_pass),
606 subpass_(subpass),
607 context_(context),
John Zulauffaea0ee2021-01-14 14:01:32 -0700608 cb_context_(cb_context),
John Zulauf7635de32020-05-29 17:14:15 -0600609 func_name_(func_name),
610 skip_(false) {}
611 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
John Zulauf8e3c3e92021-01-06 11:19:36 -0700612 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf7635de32020-05-29 17:14:15 -0600613 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
614 HazardResult hazard;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700615 hazard = context_.DetectHazard(view, current_usage, ordering_rule, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600616 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -0700617 skip_ |=
618 cb_context_.GetSyncState().LogError(render_pass_, string_SyncHazardVUID(hazard.hazard),
619 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32
620 " to resolve attachment %" PRIu32 ". Access info %s.",
621 func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name,
622 attachment_name, src_at, dst_at, cb_context_.FormatUsage(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600623 }
624 }
625 // Providing a mechanism for the constructing caller to get the result of the validation
626 bool GetSkip() const { return skip_; }
627
628 private:
629 VkRenderPass render_pass_;
630 const uint32_t subpass_;
631 const AccessContext &context_;
John Zulauffaea0ee2021-01-14 14:01:32 -0700632 const CommandBufferAccessContext &cb_context_;
John Zulauf7635de32020-05-29 17:14:15 -0600633 const char *func_name_;
634 bool skip_;
635};
636
637// Update action for resolve operations
638class UpdateStateResolveAction {
639 public:
640 UpdateStateResolveAction(AccessContext &context, const ResourceUsageTag &tag) : context_(context), tag_(tag) {}
641 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
John Zulauf8e3c3e92021-01-06 11:19:36 -0700642 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf7635de32020-05-29 17:14:15 -0600643 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
644 // Ignores validation only arguments...
John Zulauf8e3c3e92021-01-06 11:19:36 -0700645 context_.UpdateAccessState(view, current_usage, ordering_rule, offset, extent, aspect_mask, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600646 }
647
648 private:
649 AccessContext &context_;
650 const ResourceUsageTag &tag_;
651};
652
John Zulauf59e25072020-07-17 10:55:21 -0600653void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700654 const SyncStageAccessFlags &prior_, const ResourceUsageTag &tag_) {
John Zulauf59e25072020-07-17 10:55:21 -0600655 access_state = std::unique_ptr<const ResourceAccessState>(new ResourceAccessState(*access_state_));
656 usage_index = usage_index_;
657 hazard = hazard_;
658 prior_access = prior_;
659 tag = tag_;
660}
661
John Zulauf540266b2020-04-06 18:54:53 -0600662AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
663 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600664 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600665 Reset();
666 const auto &subpass_dep = dependencies[subpass];
667 prev_.reserve(subpass_dep.prev.size());
John Zulauf355e49b2020-04-24 15:11:15 -0600668 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600669 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600670 const auto prev_pass = prev_dep.first->pass;
671 const auto &prev_barriers = prev_dep.second;
672 assert(prev_dep.second.size());
673 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
674 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700675 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600676
677 async_.reserve(subpass_dep.async.size());
678 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700679 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600680 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600681 if (subpass_dep.barrier_from_external.size()) {
682 src_external_ = TrackBack(external_context, queue_flags, subpass_dep.barrier_from_external);
John Zulaufe5da6e52020-03-18 15:32:18 -0600683 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600684 if (subpass_dep.barrier_to_external.size()) {
685 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600686 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700687}
688
John Zulauf5f13a792020-03-10 07:31:21 -0600689template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700690HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, const Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600691 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600692 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600693 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600694
695 HazardResult hazard;
696 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
697 hazard = detector.Detect(prev);
698 }
699 return hazard;
700}
701
John Zulauf4a6105a2020-11-17 15:11:05 -0700702template <typename Action>
703void AccessContext::ForAll(Action &&action) {
704 for (const auto address_type : kAddressTypes) {
705 auto &accesses = GetAccessStateMap(address_type);
706 for (const auto &access : accesses) {
707 action(address_type, access);
708 }
709 }
710}
711
John Zulauf3d84f1b2020-03-09 13:33:25 -0600712// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
713// the DAG of the contexts (for example subpasses)
714template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700715HazardResult AccessContext::DetectHazard(AccessAddressType type, const Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600716 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600717 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600718
John Zulauf1a224292020-06-30 14:52:13 -0600719 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600720 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
721 // so we'll check these first
722 for (const auto &async_context : async_) {
723 hazard = async_context->DetectAsyncHazard(type, detector, range);
724 if (hazard.hazard) return hazard;
725 }
John Zulauf5f13a792020-03-10 07:31:21 -0600726 }
727
John Zulauf1a224292020-06-30 14:52:13 -0600728 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600729
John Zulauf69133422020-05-20 14:55:53 -0600730 const auto &accesses = GetAccessStateMap(type);
731 const auto from = accesses.lower_bound(range);
732 const auto to = accesses.upper_bound(range);
733 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600734
John Zulauf69133422020-05-20 14:55:53 -0600735 for (auto pos = from; pos != to; ++pos) {
736 // Cover any leading gap, or gap between entries
737 if (detect_prev) {
738 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
739 // Cover any leading gap, or gap between entries
740 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600741 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600742 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600743 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600744 if (hazard.hazard) return hazard;
745 }
John Zulauf69133422020-05-20 14:55:53 -0600746 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
747 gap.begin = pos->first.end;
748 }
749
750 hazard = detector.Detect(pos);
751 if (hazard.hazard) return hazard;
752 }
753
754 if (detect_prev) {
755 // Detect in the trailing empty as needed
756 gap.end = range.end;
757 if (gap.non_empty()) {
758 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600759 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600760 }
761
762 return hazard;
763}
764
765// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
766template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700767HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
768 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600769 auto &accesses = GetAccessStateMap(type);
770 const auto from = accesses.lower_bound(range);
771 const auto to = accesses.upper_bound(range);
772
John Zulauf3d84f1b2020-03-09 13:33:25 -0600773 HazardResult hazard;
John Zulauf16adfc92020-04-08 10:28:33 -0600774 for (auto pos = from; pos != to && !hazard.hazard; ++pos) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700775 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600776 }
John Zulauf16adfc92020-04-08 10:28:33 -0600777
John Zulauf3d84f1b2020-03-09 13:33:25 -0600778 return hazard;
779}
780
John Zulaufb02c1eb2020-10-06 16:33:36 -0600781struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700782 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600783 void operator()(ResourceAccessState *access) const {
784 assert(access);
785 access->ApplyBarriers(barriers, true);
786 }
787 const std::vector<SyncBarrier> &barriers;
788};
789
790struct ApplyTrackbackBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700791 explicit ApplyTrackbackBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600792 void operator()(ResourceAccessState *access) const {
793 assert(access);
794 assert(!access->HasPendingState());
795 access->ApplyBarriers(barriers, false);
796 access->ApplyPendingBarriers(kCurrentCommandTag);
797 }
798 const std::vector<SyncBarrier> &barriers;
799};
800
801// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
802// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
803// *different* map from dest.
804// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
805// range [first, last)
806template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600807static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
808 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600809 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600810 auto at = entry;
811 for (auto pos = first; pos != last; ++pos) {
812 // Every member of the input iterator range must fit within the remaining portion of entry
813 assert(at->first.includes(pos->first));
814 assert(at != dest->end());
815 // Trim up at to the same size as the entry to resolve
816 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600817 auto access = pos->second; // intentional copy
818 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600819 at->second.Resolve(access);
820 ++at; // Go to the remaining unused section of entry
821 }
822}
823
John Zulaufa0a98292020-09-18 09:30:10 -0600824static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
825 SyncBarrier merged = {};
826 for (const auto &barrier : barriers) {
827 merged.Merge(barrier);
828 }
829 return merged;
830}
831
John Zulaufb02c1eb2020-10-06 16:33:36 -0600832template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700833void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600834 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
835 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600836 if (!range.non_empty()) return;
837
John Zulauf355e49b2020-04-24 15:11:15 -0600838 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
839 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600840 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -0600841 if (current->pos_B->valid) {
842 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600843 auto access = src_pos->second; // intentional copy
844 barrier_action(&access);
845
John Zulauf16adfc92020-04-08 10:28:33 -0600846 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600847 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
848 trimmed->second.Resolve(access);
849 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -0600850 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600851 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -0600852 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -0600853 }
John Zulauf16adfc92020-04-08 10:28:33 -0600854 } else {
855 // we have to descend to fill this gap
856 if (recur_to_infill) {
John Zulauf355e49b2020-04-24 15:11:15 -0600857 if (current->pos_A->valid) {
858 // Dest is valid, so we need to accumulate along the DAG and then resolve... in an N-to-1 resolve operation
859 ResourceAccessRangeMap gap_map;
John Zulauf3bcab5e2020-06-19 14:42:32 -0600860 ResolvePreviousAccess(type, current_range, &gap_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600861 ResolveMapToEntry(resolve_map, current->pos_A->lower_bound, gap_map.begin(), gap_map.end(), barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -0600862 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600863 // There isn't anything in dest in current)range, so we can accumulate directly into it.
864 ResolvePreviousAccess(type, current_range, resolve_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600865 // Need to apply the barrier to the accesses we accumulated, noting that we haven't updated current
866 for (auto pos = resolve_map->lower_bound(current_range); pos != current->pos_A->lower_bound; ++pos) {
867 barrier_action(&pos->second);
John Zulauf355e49b2020-04-24 15:11:15 -0600868 }
869 }
870 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
871 // iterator of the outer while.
872
873 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
874 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
875 // we stepped on the dest map
locke-lunarg88dbb542020-06-23 22:05:42 -0600876 const auto seek_to = current_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
877 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -0600878 current.seek(seek_to);
879 } else if (!current->pos_A->valid && infill_state) {
880 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
881 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
882 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -0600883 }
John Zulauf5f13a792020-03-10 07:31:21 -0600884 }
John Zulauf16adfc92020-04-08 10:28:33 -0600885 ++current;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600886 }
John Zulauf1a224292020-06-30 14:52:13 -0600887
888 // Infill if range goes passed both the current and resolve map prior contents
889 if (recur_to_infill && (current->range.end < range.end)) {
890 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
891 ResourceAccessRangeMap gap_map;
892 const auto the_end = resolve_map->end();
893 ResolvePreviousAccess(type, trailing_fill_range, &gap_map, infill_state);
894 for (auto &access : gap_map) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600895 barrier_action(&access.second);
John Zulauf1a224292020-06-30 14:52:13 -0600896 resolve_map->insert(the_end, access);
897 }
898 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600899}
900
John Zulauf43cc7462020-12-03 12:33:12 -0700901void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
902 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufe5da6e52020-03-18 15:32:18 -0600903 if ((prev_.size() == 0) && (src_external_.context == nullptr)) {
John Zulauf5f13a792020-03-10 07:31:21 -0600904 if (range.non_empty() && infill_state) {
905 descent_map->insert(std::make_pair(range, *infill_state));
906 }
907 } else {
908 // Look for something to fill the gap further along.
909 for (const auto &prev_dep : prev_) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600910 const ApplyTrackbackBarriersAction barrier_action(prev_dep.barriers);
911 prev_dep.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600912 }
913
John Zulaufe5da6e52020-03-18 15:32:18 -0600914 if (src_external_.context) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600915 const ApplyTrackbackBarriersAction barrier_action(src_external_.barriers);
916 src_external_.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600917 }
918 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600919}
920
John Zulauf4a6105a2020-11-17 15:11:05 -0700921// Non-lazy import of all accesses, WaitEvents needs this.
922void AccessContext::ResolvePreviousAccesses() {
923 ResourceAccessState default_state;
924 for (const auto address_type : kAddressTypes) {
925 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
926 }
927}
928
John Zulauf43cc7462020-12-03 12:33:12 -0700929AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
930 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -0600931}
932
John Zulauf1507ee42020-05-18 11:33:09 -0600933static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
934 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
935 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE;
936 return stage_access;
937}
938static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
939 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
940 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE;
941 return stage_access;
942}
943
John Zulauf7635de32020-05-29 17:14:15 -0600944// Caller must manage returned pointer
945static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
946 uint32_t subpass, const VkRect2D &render_area,
947 std::vector<const IMAGE_VIEW_STATE *> attachment_views) {
948 auto *proxy = new AccessContext(context);
949 proxy->UpdateAttachmentResolveAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulaufaff20662020-06-01 14:07:58 -0600950 proxy->UpdateAttachmentStoreAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulauf7635de32020-05-29 17:14:15 -0600951 return proxy;
952}
953
John Zulaufb02c1eb2020-10-06 16:33:36 -0600954template <typename BarrierAction>
John Zulauf52446eb2020-10-22 16:40:08 -0600955class ResolveAccessRangeFunctor {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600956 public:
John Zulauf43cc7462020-12-03 12:33:12 -0700957 ResolveAccessRangeFunctor(const AccessContext &context, AccessAddressType address_type, ResourceAccessRangeMap *descent_map,
958 const ResourceAccessState *infill_state, BarrierAction &barrier_action)
John Zulauf52446eb2020-10-22 16:40:08 -0600959 : context_(context),
960 address_type_(address_type),
961 descent_map_(descent_map),
962 infill_state_(infill_state),
963 barrier_action_(barrier_action) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600964 ResolveAccessRangeFunctor() = delete;
965 void operator()(const ResourceAccessRange &range) const {
966 context_.ResolveAccessRange(address_type_, range, barrier_action_, descent_map_, infill_state_);
967 }
968
969 private:
John Zulauf52446eb2020-10-22 16:40:08 -0600970 const AccessContext &context_;
John Zulauf43cc7462020-12-03 12:33:12 -0700971 const AccessAddressType address_type_;
John Zulauf52446eb2020-10-22 16:40:08 -0600972 ResourceAccessRangeMap *const descent_map_;
973 const ResourceAccessState *infill_state_;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600974 BarrierAction &barrier_action_;
975};
976
John Zulaufb02c1eb2020-10-06 16:33:36 -0600977template <typename BarrierAction>
978void AccessContext::ResolveAccessRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -0700979 BarrierAction &barrier_action, AccessAddressType address_type,
980 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600981 const ResolveAccessRangeFunctor<BarrierAction> action(*this, address_type, descent_map, infill_state, barrier_action);
982 ApplyOverImageRange(image_state, subresource_range, action);
John Zulauf62f10592020-04-03 12:20:02 -0600983}
984
John Zulauf7635de32020-05-29 17:14:15 -0600985// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulauffaea0ee2021-01-14 14:01:32 -0700986bool AccessContext::ValidateLayoutTransitions(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -0600987 const VkRect2D &render_area, uint32_t subpass,
988 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
989 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -0600990 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -0600991 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
992 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
993 // those affects have not been recorded yet.
994 //
995 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
996 // to apply and only copy then, if this proves a hot spot.
997 std::unique_ptr<AccessContext> proxy_for_prev;
998 TrackBack proxy_track_back;
999
John Zulauf355e49b2020-04-24 15:11:15 -06001000 const auto &transitions = rp_state.subpass_transitions[subpass];
1001 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001002 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1003
1004 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
1005 if (prev_needs_proxy) {
1006 if (!proxy_for_prev) {
1007 proxy_for_prev.reset(CreateStoreResolveProxyContext(*track_back->context, rp_state, transition.prev_pass,
1008 render_area, attachment_views));
1009 proxy_track_back = *track_back;
1010 proxy_track_back.context = proxy_for_prev.get();
1011 }
1012 track_back = &proxy_track_back;
1013 }
1014 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001015 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -07001016 skip |= cb_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1017 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1018 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1019 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1020 string_VkImageLayout(transition.old_layout),
1021 string_VkImageLayout(transition.new_layout),
1022 cb_context.FormatUsage(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -06001023 }
1024 }
1025 return skip;
1026}
1027
John Zulauffaea0ee2021-01-14 14:01:32 -07001028bool AccessContext::ValidateLoadOperation(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001029 const VkRect2D &render_area, uint32_t subpass,
1030 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1031 const char *func_name) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001032 bool skip = false;
1033 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1034 VkExtent3D extent = CastTo3D(render_area.extent);
1035 VkOffset3D offset = CastTo3D(render_area.offset);
John Zulaufa0a98292020-09-18 09:30:10 -06001036
John Zulauf1507ee42020-05-18 11:33:09 -06001037 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1038 if (subpass == rp_state.attachment_first_subpass[i]) {
1039 if (attachment_views[i] == nullptr) continue;
1040 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1041 const IMAGE_STATE *image = view.image_state.get();
1042 if (image == nullptr) continue;
1043 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001044
1045 // Need check in the following way
1046 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1047 // vs. transition
1048 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1049 // for each aspect loaded.
1050
1051 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001052 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001053 const bool is_color = !(has_depth || has_stencil);
1054
1055 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001056 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001057
John Zulaufaff20662020-06-01 14:07:58 -06001058 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001059 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001060
John Zulaufb02c1eb2020-10-06 16:33:36 -06001061 auto hazard_range = view.normalized_subresource_range;
1062 bool checked_stencil = false;
1063 if (is_color) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001064 hazard = DetectHazard(*image, load_index, view.normalized_subresource_range, SyncOrdering::kColorAttachment, offset,
John Zulauf859089b2020-10-29 17:37:03 -06001065 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001066 aspect = "color";
1067 } else {
1068 if (has_depth) {
1069 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001070 hazard = DetectHazard(*image, load_index, hazard_range, SyncOrdering::kDepthStencilAttachment, offset, extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001071 aspect = "depth";
1072 }
1073 if (!hazard.hazard && has_stencil) {
1074 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001075 hazard = DetectHazard(*image, stencil_load_index, hazard_range, SyncOrdering::kDepthStencilAttachment, offset,
1076 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001077 aspect = "stencil";
1078 checked_stencil = true;
1079 }
1080 }
1081
1082 if (hazard.hazard) {
1083 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulauffaea0ee2021-01-14 14:01:32 -07001084 const auto &sync_state = cb_context.GetSyncState();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001085 if (hazard.tag == kCurrentCommandTag) {
1086 // Hazard vs. ILT
1087 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1088 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1089 " aspect %s during load with loadOp %s.",
1090 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1091 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06001092 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1093 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001094 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001095 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauffaea0ee2021-01-14 14:01:32 -07001096 cb_context.FormatUsage(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001097 }
1098 }
1099 }
1100 }
1101 return skip;
1102}
1103
John Zulaufaff20662020-06-01 14:07:58 -06001104// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1105// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1106// store is part of the same Next/End operation.
1107// The latter is handled in layout transistion validation directly
John Zulauffaea0ee2021-01-14 14:01:32 -07001108bool AccessContext::ValidateStoreOperation(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001109 const VkRect2D &render_area, uint32_t subpass,
1110 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1111 const char *func_name) const {
1112 bool skip = false;
1113 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1114 VkExtent3D extent = CastTo3D(render_area.extent);
1115 VkOffset3D offset = CastTo3D(render_area.offset);
1116
1117 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1118 if (subpass == rp_state.attachment_last_subpass[i]) {
1119 if (attachment_views[i] == nullptr) continue;
1120 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1121 const IMAGE_STATE *image = view.image_state.get();
1122 if (image == nullptr) continue;
1123 const auto &ci = attachment_ci[i];
1124
1125 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1126 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1127 // sake, we treat DONT_CARE as writing.
1128 const bool has_depth = FormatHasDepth(ci.format);
1129 const bool has_stencil = FormatHasStencil(ci.format);
1130 const bool is_color = !(has_depth || has_stencil);
1131 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1132 if (!has_stencil && !store_op_stores) continue;
1133
1134 HazardResult hazard;
1135 const char *aspect = nullptr;
1136 bool checked_stencil = false;
1137 if (is_color) {
1138 hazard = DetectHazard(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001139 view.normalized_subresource_range, SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001140 aspect = "color";
1141 } else {
1142 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1143 auto hazard_range = view.normalized_subresource_range;
1144 if (has_depth && store_op_stores) {
1145 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1146 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001147 SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001148 aspect = "depth";
1149 }
1150 if (!hazard.hazard && has_stencil && stencil_op_stores) {
1151 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
1152 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001153 SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001154 aspect = "stencil";
1155 checked_stencil = true;
1156 }
1157 }
1158
1159 if (hazard.hazard) {
1160 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1161 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauffaea0ee2021-01-14 14:01:32 -07001162 skip |= cb_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1163 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1164 " %s aspect during store with %s %s. Access info %s",
1165 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect,
1166 op_type_string, store_op_string, cb_context.FormatUsage(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001167 }
1168 }
1169 }
1170 return skip;
1171}
1172
John Zulauffaea0ee2021-01-14 14:01:32 -07001173bool AccessContext::ValidateResolveOperations(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulaufb027cdb2020-05-21 14:25:22 -06001174 const VkRect2D &render_area,
1175 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name,
1176 uint32_t subpass) const {
John Zulauffaea0ee2021-01-14 14:01:32 -07001177 ValidateResolveAction validate_action(rp_state.renderPass, subpass, *this, cb_context, func_name);
John Zulauf7635de32020-05-29 17:14:15 -06001178 ResolveOperation(validate_action, rp_state, render_area, attachment_views, subpass);
1179 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001180}
1181
John Zulauf3d84f1b2020-03-09 13:33:25 -06001182class HazardDetector {
1183 SyncStageAccessIndex usage_index_;
1184
1185 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001186 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001187 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1188 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001189 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001190 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001191};
1192
John Zulauf69133422020-05-20 14:55:53 -06001193class HazardDetectorWithOrdering {
1194 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001195 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001196
1197 public:
1198 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001199 return pos->second.DetectHazard(usage_index_, ordering_rule_);
John Zulauf69133422020-05-20 14:55:53 -06001200 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001201 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1202 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001203 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001204 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001205};
1206
John Zulauf16adfc92020-04-08 10:28:33 -06001207HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001208 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001209 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001210 const auto base_address = ResourceBaseAddress(buffer);
1211 HazardDetector detector(usage_index);
1212 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001213}
1214
John Zulauf69133422020-05-20 14:55:53 -06001215template <typename Detector>
1216HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1217 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1218 const VkExtent3D &extent, DetectOptions options) const {
1219 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001220 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001221 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1222 base_address);
1223 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001224 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001225 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001226 if (hazard.hazard) return hazard;
1227 }
1228 return HazardResult();
1229}
1230
John Zulauf540266b2020-04-06 18:54:53 -06001231HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1232 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1233 const VkExtent3D &extent) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001234 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1235 subresource.layerCount};
John Zulauf1507ee42020-05-18 11:33:09 -06001236 return DetectHazard(image, current_usage, subresource_range, offset, extent);
1237}
1238
1239HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1240 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1241 const VkExtent3D &extent) const {
John Zulauf69133422020-05-20 14:55:53 -06001242 HazardDetector detector(current_usage);
1243 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
1244}
1245
1246HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001247 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
John Zulauf69133422020-05-20 14:55:53 -06001248 const VkOffset3D &offset, const VkExtent3D &extent) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001249 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06001250 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001251}
1252
John Zulaufb027cdb2020-05-21 14:25:22 -06001253// Some common code for looking at attachments, if there's anything wrong, we return no hazard, core validation
1254// should have reported the issue regarding an invalid attachment entry
1255HazardResult AccessContext::DetectHazard(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001256 SyncOrdering ordering_rule, const VkOffset3D &offset, const VkExtent3D &extent,
John Zulaufb027cdb2020-05-21 14:25:22 -06001257 VkImageAspectFlags aspect_mask) const {
1258 if (view != nullptr) {
1259 const IMAGE_STATE *image = view->image_state.get();
1260 if (image != nullptr) {
1261 auto *detect_range = &view->normalized_subresource_range;
1262 VkImageSubresourceRange masked_range;
1263 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1264 masked_range = view->normalized_subresource_range;
1265 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1266 detect_range = &masked_range;
1267 }
1268
1269 // NOTE: The range encoding code is not robust to invalid ranges, so we protect it from our change
1270 if (detect_range->aspectMask) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001271 return DetectHazard(*image, current_usage, *detect_range, ordering_rule, offset, extent);
John Zulaufb027cdb2020-05-21 14:25:22 -06001272 }
1273 }
1274 }
1275 return HazardResult();
1276}
John Zulauf43cc7462020-12-03 12:33:12 -07001277
John Zulauf3d84f1b2020-03-09 13:33:25 -06001278class BarrierHazardDetector {
1279 public:
1280 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1281 SyncStageAccessFlags src_access_scope)
1282 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1283
John Zulauf5f13a792020-03-10 07:31:21 -06001284 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1285 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001286 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001287 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001288 // 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 -07001289 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001290 }
1291
1292 private:
1293 SyncStageAccessIndex usage_index_;
1294 VkPipelineStageFlags src_exec_scope_;
1295 SyncStageAccessFlags src_access_scope_;
1296};
1297
John Zulauf4a6105a2020-11-17 15:11:05 -07001298class EventBarrierHazardDetector {
1299 public:
1300 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1301 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
1302 const ResourceUsageTag &scope_tag)
1303 : usage_index_(usage_index),
1304 src_exec_scope_(src_exec_scope),
1305 src_access_scope_(src_access_scope),
1306 event_scope_(event_scope),
1307 scope_pos_(event_scope.cbegin()),
1308 scope_end_(event_scope.cend()),
1309 scope_tag_(scope_tag) {}
1310
1311 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1312 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1313 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1314 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1315 if (scope_pos_ == scope_end_) return HazardResult();
1316 if (!scope_pos_->first.intersects(pos->first)) {
1317 event_scope_.lower_bound(pos->first);
1318 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1319 }
1320
1321 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1322 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1323 }
1324 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1325 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1326 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1327 }
1328
1329 private:
1330 SyncStageAccessIndex usage_index_;
1331 VkPipelineStageFlags src_exec_scope_;
1332 SyncStageAccessFlags src_access_scope_;
1333 const SyncEventState::ScopeMap &event_scope_;
1334 SyncEventState::ScopeMap::const_iterator scope_pos_;
1335 SyncEventState::ScopeMap::const_iterator scope_end_;
1336 const ResourceUsageTag &scope_tag_;
1337};
1338
1339HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
1340 const SyncStageAccessFlags &src_access_scope,
1341 const VkImageSubresourceRange &subresource_range,
1342 const SyncEventState &sync_event, DetectOptions options) const {
1343 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1344 // first access scope map to use, and there's no easy way to plumb it in below.
1345 const auto address_type = ImageAddressType(image);
1346 const auto &event_scope = sync_event.FirstScope(address_type);
1347
1348 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1349 event_scope, sync_event.first_scope_tag);
1350 VkOffset3D zero_offset = {0, 0, 0};
1351 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
1352}
1353
John Zulauf16adfc92020-04-08 10:28:33 -06001354HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001355 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001356 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001357 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001358 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
1359 VkOffset3D zero_offset = {0, 0, 0};
1360 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001361}
1362
John Zulauf355e49b2020-04-24 15:11:15 -06001363HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001364 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001365 const VkImageMemoryBarrier &barrier) const {
1366 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1367 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1368 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1369}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001370HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
1371 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope,
John Zulaufd5115702021-01-18 12:34:33 -07001372 image_barrier.barrier.src_access_scope, image_barrier.range.subresource_range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001373}
John Zulauf355e49b2020-04-24 15:11:15 -06001374
John Zulauf9cb530d2019-09-30 14:14:10 -06001375template <typename Flags, typename Map>
1376SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1377 SyncStageAccessFlags scope = 0;
1378 for (const auto &bit_scope : map) {
1379 if (flag_mask < bit_scope.first) break;
1380
1381 if (flag_mask & bit_scope.first) {
1382 scope |= bit_scope.second;
1383 }
1384 }
1385 return scope;
1386}
1387
1388SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags stages) {
1389 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1390}
1391
1392SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags accesses) {
1393 return AccessScopeImpl(accesses, syncStageAccessMaskByAccessBit);
1394}
1395
1396// Getting from stage mask and access mask to stage/acess masks is something we need to be good at...
1397SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags stages, VkAccessFlags accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001398 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1399 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1400 // 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 -06001401 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1402}
1403
1404template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001405void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001406 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1407 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001408 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001409 auto pos = accesses->lower_bound(range);
1410 if (pos == accesses->end() || !pos->first.intersects(range)) {
1411 // The range is empty, fill it with a default value.
1412 pos = action.Infill(accesses, pos, range);
1413 } else if (range.begin < pos->first.begin) {
1414 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001415 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001416 } else if (pos->first.begin < range.begin) {
1417 // Trim the beginning if needed
1418 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1419 ++pos;
1420 }
1421
1422 const auto the_end = accesses->end();
1423 while ((pos != the_end) && pos->first.intersects(range)) {
1424 if (pos->first.end > range.end) {
1425 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1426 }
1427
1428 pos = action(accesses, pos);
1429 if (pos == the_end) break;
1430
1431 auto next = pos;
1432 ++next;
1433 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1434 // Need to infill if next is disjoint
1435 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001436 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001437 next = action.Infill(accesses, next, new_range);
1438 }
1439 pos = next;
1440 }
1441}
John Zulaufd5115702021-01-18 12:34:33 -07001442
1443// Give a comparable interface for range generators and ranges
1444template <typename Action>
1445inline void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
1446 assert(range);
1447 UpdateMemoryAccessState(accesses, *range, action);
1448}
1449
John Zulauf4a6105a2020-11-17 15:11:05 -07001450template <typename Action, typename RangeGen>
1451void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1452 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001453 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 -07001454 for (; range_gen->non_empty(); ++range_gen) {
1455 UpdateMemoryAccessState(accesses, *range_gen, action);
1456 }
1457}
John Zulauf9cb530d2019-09-30 14:14:10 -06001458
1459struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001460 using Iterator = ResourceAccessRangeMap::iterator;
1461 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001462 // this is only called on gaps, and never returns a gap.
1463 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001464 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001465 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001466 }
John Zulauf5f13a792020-03-10 07:31:21 -06001467
John Zulauf5c5e88d2019-12-26 11:22:02 -07001468 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001469 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001470 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001471 return pos;
1472 }
1473
John Zulauf43cc7462020-12-03 12:33:12 -07001474 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001475 SyncOrdering ordering_rule_, const ResourceUsageTag &tag_)
1476 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001477 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001478 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001479 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001480 const SyncOrdering ordering_rule;
John Zulauf9cb530d2019-09-30 14:14:10 -06001481 const ResourceUsageTag &tag;
1482};
1483
John Zulauf4a6105a2020-11-17 15:11:05 -07001484// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001485struct PipelineBarrierOp {
1486 SyncBarrier barrier;
1487 bool layout_transition;
1488 PipelineBarrierOp(const SyncBarrier &barrier_, bool layout_transition_)
1489 : barrier(barrier_), layout_transition(layout_transition_) {}
1490 PipelineBarrierOp() = default;
John Zulaufd5115702021-01-18 12:34:33 -07001491 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf1e331ec2020-12-04 18:29:38 -07001492 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(barrier, layout_transition); }
1493};
John Zulauf4a6105a2020-11-17 15:11:05 -07001494// The barrier operation for wait events
1495struct WaitEventBarrierOp {
1496 const ResourceUsageTag *scope_tag;
1497 SyncBarrier barrier;
1498 bool layout_transition;
1499 WaitEventBarrierOp(const ResourceUsageTag &scope_tag_, const SyncBarrier &barrier_, bool layout_transition_)
1500 : scope_tag(&scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1501 WaitEventBarrierOp() = default;
1502 void operator()(ResourceAccessState *access_state) const {
1503 assert(scope_tag); // Not valid to have a non-scope op executed, default construct included for std::vector support
1504 access_state->ApplyBarrier(*scope_tag, barrier, layout_transition);
1505 }
1506};
John Zulauf1e331ec2020-12-04 18:29:38 -07001507
John Zulauf4a6105a2020-11-17 15:11:05 -07001508// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1509// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1510// of a collection is known/present.
John Zulauf1e331ec2020-12-04 18:29:38 -07001511template <typename BarrierOp>
John Zulauf89311b42020-09-29 16:28:47 -06001512class ApplyBarrierOpsFunctor {
1513 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001514 using Iterator = ResourceAccessRangeMap::iterator;
1515 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
John Zulauf9cb530d2019-09-30 14:14:10 -06001516
John Zulauf5c5e88d2019-12-26 11:22:02 -07001517 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001518 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001519 for (const auto &op : barrier_ops_) {
1520 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001521 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001522
John Zulauf89311b42020-09-29 16:28:47 -06001523 if (resolve_) {
1524 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1525 // another walk
1526 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001527 }
1528 return pos;
1529 }
1530
John Zulauf89311b42020-09-29 16:28:47 -06001531 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulaufd5115702021-01-18 12:34:33 -07001532 ApplyBarrierOpsFunctor(bool resolve, size_t size_hint, const ResourceUsageTag &tag)
1533 : resolve_(resolve), barrier_ops_(), tag_(tag) {
1534 barrier_ops_.reserve(size_hint);
1535 }
1536 void EmplaceBack(const BarrierOp &op) { barrier_ops_.emplace_back(op); }
John Zulauf89311b42020-09-29 16:28:47 -06001537
1538 private:
1539 bool resolve_;
John Zulaufd5115702021-01-18 12:34:33 -07001540 std::vector<BarrierOp> barrier_ops_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001541 const ResourceUsageTag &tag_;
1542};
1543
John Zulauf4a6105a2020-11-17 15:11:05 -07001544// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1545// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1546template <typename BarrierOp>
1547class ApplyBarrierFunctor {
1548 public:
1549 using Iterator = ResourceAccessRangeMap::iterator;
1550 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1551
1552 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1553 auto &access_state = pos->second;
1554 barrier_op_(&access_state);
1555 return pos;
1556 }
1557
1558 ApplyBarrierFunctor(const BarrierOp &barrier_op) : barrier_op_(barrier_op) {}
1559
1560 private:
John Zulaufd5115702021-01-18 12:34:33 -07001561 BarrierOp barrier_op_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001562};
1563
John Zulauf1e331ec2020-12-04 18:29:38 -07001564// This functor resolves the pendinging state.
1565class ResolvePendingBarrierFunctor {
1566 public:
1567 using Iterator = ResourceAccessRangeMap::iterator;
1568 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1569
1570 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1571 auto &access_state = pos->second;
1572 access_state.ApplyPendingBarriers(tag_);
1573 return pos;
1574 }
1575
1576 ResolvePendingBarrierFunctor(const ResourceUsageTag &tag) : tag_(tag) {}
1577
1578 private:
John Zulauf89311b42020-09-29 16:28:47 -06001579 const ResourceUsageTag &tag_;
John Zulauf9cb530d2019-09-30 14:14:10 -06001580};
1581
John Zulauf8e3c3e92021-01-06 11:19:36 -07001582void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
1583 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
1584 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001585 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001586}
1587
John Zulauf8e3c3e92021-01-06 11:19:36 -07001588void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001589 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001590 if (!SimpleBinding(buffer)) return;
1591 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001592 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001593}
John Zulauf355e49b2020-04-24 15:11:15 -06001594
John Zulauf8e3c3e92021-01-06 11:19:36 -07001595void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001596 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf540266b2020-04-06 18:54:53 -06001597 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001598 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001599 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001600 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1601 base_address);
1602 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001603 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf5f13a792020-03-10 07:31:21 -06001604 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001605 UpdateMemoryAccessState(&GetAccessStateMap(address_type), *range_gen, action);
John Zulauf5f13a792020-03-10 07:31:21 -06001606 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001607}
John Zulauf8e3c3e92021-01-06 11:19:36 -07001608void AccessContext::UpdateAccessState(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
1609 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask,
1610 const ResourceUsageTag &tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001611 if (view != nullptr) {
1612 const IMAGE_STATE *image = view->image_state.get();
1613 if (image != nullptr) {
1614 auto *update_range = &view->normalized_subresource_range;
1615 VkImageSubresourceRange masked_range;
1616 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1617 masked_range = view->normalized_subresource_range;
1618 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1619 update_range = &masked_range;
1620 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001621 UpdateAccessState(*image, current_usage, ordering_rule, *update_range, offset, extent, tag);
John Zulauf7635de32020-05-29 17:14:15 -06001622 }
1623 }
1624}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001625
John Zulauf8e3c3e92021-01-06 11:19:36 -07001626void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001627 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1628 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001629 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1630 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001631 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001632}
1633
John Zulauf540266b2020-04-06 18:54:53 -06001634template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001635void AccessContext::UpdateResourceAccess(const BUFFER_STATE &buffer, const ResourceAccessRange &range, const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001636 if (!SimpleBinding(buffer)) return;
1637 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf43cc7462020-12-03 12:33:12 -07001638 UpdateMemoryAccessState(&GetAccessStateMap(AccessAddressType::kLinear), (range + base_address), action);
John Zulauf540266b2020-04-06 18:54:53 -06001639}
1640
1641template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001642void AccessContext::UpdateResourceAccess(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1643 const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001644 if (!SimpleBinding(image)) return;
1645 const auto address_type = ImageAddressType(image);
1646 auto *accesses = &GetAccessStateMap(address_type);
John Zulauf540266b2020-04-06 18:54:53 -06001647
John Zulauf16adfc92020-04-08 10:28:33 -06001648 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001649 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, {0, 0, 0},
1650 image.createInfo.extent, base_address);
1651
John Zulauf540266b2020-04-06 18:54:53 -06001652 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001653 UpdateMemoryAccessState(accesses, *range_gen, action);
John Zulauf540266b2020-04-06 18:54:53 -06001654 }
1655}
1656
John Zulauf7635de32020-05-29 17:14:15 -06001657void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1658 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1659 const ResourceUsageTag &tag) {
1660 UpdateStateResolveAction update(*this, tag);
1661 ResolveOperation(update, rp_state, render_area, attachment_views, subpass);
1662}
1663
John Zulaufaff20662020-06-01 14:07:58 -06001664void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1665 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1666 const ResourceUsageTag &tag) {
1667 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1668 VkExtent3D extent = CastTo3D(render_area.extent);
1669 VkOffset3D offset = CastTo3D(render_area.offset);
1670
1671 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1672 if (rp_state.attachment_last_subpass[i] == subpass) {
1673 if (attachment_views[i] == nullptr) continue; // UNUSED
1674 const auto &view = *attachment_views[i];
1675 const IMAGE_STATE *image = view.image_state.get();
1676 if (image == nullptr) continue;
1677
1678 const auto &ci = attachment_ci[i];
1679 const bool has_depth = FormatHasDepth(ci.format);
1680 const bool has_stencil = FormatHasStencil(ci.format);
1681 const bool is_color = !(has_depth || has_stencil);
1682 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1683
1684 if (is_color && store_op_stores) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001685 UpdateAccessState(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1686 view.normalized_subresource_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001687 } else {
1688 auto update_range = view.normalized_subresource_range;
1689 if (has_depth && store_op_stores) {
1690 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001691 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1692 update_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001693 }
1694 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1695 if (has_stencil && stencil_op_stores) {
1696 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001697 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1698 update_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001699 }
1700 }
1701 }
1702 }
1703}
1704
John Zulauf540266b2020-04-06 18:54:53 -06001705template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001706void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001707 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001708 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001709 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001710 }
1711}
1712
1713void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001714 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1715 auto &context = contexts[subpass_index];
John Zulaufb02c1eb2020-10-06 16:33:36 -06001716 ApplyTrackbackBarriersAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001717 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001718 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001719 }
1720 }
1721}
1722
John Zulauf355e49b2020-04-24 15:11:15 -06001723// Suitable only for *subpass* access contexts
John Zulauf7635de32020-05-29 17:14:15 -06001724HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const IMAGE_VIEW_STATE *attach_view) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001725 if (!attach_view) return HazardResult();
1726 const auto image_state = attach_view->image_state.get();
1727 if (!image_state) return HazardResult();
1728
John Zulauf355e49b2020-04-24 15:11:15 -06001729 // We should never ask for a transition from a context we don't have
John Zulauf7635de32020-05-29 17:14:15 -06001730 assert(track_back.context);
John Zulauf355e49b2020-04-24 15:11:15 -06001731
1732 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001733 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1734 const auto merged_barrier = MergeBarriers(track_back.barriers);
1735 HazardResult hazard =
1736 track_back.context->DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
1737 attach_view->normalized_subresource_range, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001738 if (!hazard.hazard) {
1739 // The Async hazard check is against the current context's async set.
John Zulaufa0a98292020-09-18 09:30:10 -06001740 hazard = DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001741 attach_view->normalized_subresource_range, kDetectAsync);
1742 }
John Zulaufa0a98292020-09-18 09:30:10 -06001743
John Zulauf355e49b2020-04-24 15:11:15 -06001744 return hazard;
1745}
1746
John Zulaufb02c1eb2020-10-06 16:33:36 -06001747void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
1748 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1749 const ResourceUsageTag &tag) {
1750 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001751 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001752 for (const auto &transition : transitions) {
1753 const auto prev_pass = transition.prev_pass;
1754 const auto attachment_view = attachment_views[transition.attachment];
1755 if (!attachment_view) continue;
1756 const auto *image = attachment_view->image_state.get();
1757 if (!image) continue;
1758 if (!SimpleBinding(*image)) continue;
1759
1760 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1761 assert(trackback);
1762
1763 // Import the attachments into the current context
1764 const auto *prev_context = trackback->context;
1765 assert(prev_context);
1766 const auto address_type = ImageAddressType(*image);
1767 auto &target_map = GetAccessStateMap(address_type);
1768 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
1769 prev_context->ResolveAccessRange(*image, attachment_view->normalized_subresource_range, barrier_action, address_type,
John Zulauf646cc292020-10-23 09:16:45 -06001770 &target_map, &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001771 }
1772
John Zulauf86356ca2020-10-19 11:46:41 -06001773 // If there were no transitions skip this global map walk
1774 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001775 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001776 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001777 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001778}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001779
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001780void CommandBufferAccessContext::ApplyGlobalBarriersToEvents(const SyncExecScope &src, const SyncExecScope &dst) {
1781 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
John Zulauf669dfd52021-01-27 17:15:28 -07001782
1783 auto *events_context = GetCurrentEventsContext();
1784 assert(events_context);
1785 for (auto &event_pair : *events_context) {
John Zulauf4a6105a2020-11-17 15:11:05 -07001786 assert(event_pair.second); // Shouldn't be storing empty
1787 auto &sync_event = *event_pair.second;
1788 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001789 if ((sync_event.barriers & src.exec_scope) || all_commands_bit) {
1790 sync_event.barriers |= dst.exec_scope;
1791 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
John Zulauf4a6105a2020-11-17 15:11:05 -07001792 }
1793 }
1794}
1795
John Zulauf355e49b2020-04-24 15:11:15 -06001796// Class CommandBufferAccessContext: Keep track of resource access state information for a specific command buffer
1797bool CommandBufferAccessContext::ValidateBeginRenderPass(const RENDER_PASS_STATE &rp_state,
1798
1799 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001800 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001801 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
1802 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06001803
John Zulauf86356ca2020-10-19 11:46:41 -06001804 assert(pRenderPassBegin);
1805 if (nullptr == pRenderPassBegin) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06001806
John Zulauf86356ca2020-10-19 11:46:41 -06001807 const uint32_t subpass = 0;
John Zulauf355e49b2020-04-24 15:11:15 -06001808
John Zulauf86356ca2020-10-19 11:46:41 -06001809 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
1810 // hasn't happened yet)
1811 const std::vector<AccessContext> empty_context_vector;
1812 AccessContext temp_context(subpass, queue_flags_, rp_state.subpass_dependencies, empty_context_vector,
1813 const_cast<AccessContext *>(&cb_access_context_));
John Zulauf355e49b2020-04-24 15:11:15 -06001814
John Zulauf86356ca2020-10-19 11:46:41 -06001815 // Create a view list
1816 const auto fb_state = sync_state_->Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
1817 assert(fb_state);
1818 if (nullptr == fb_state) return skip;
1819 // NOTE: Must not use COMMAND_BUFFER_STATE variant of this as RecordCmdBeginRenderPass hasn't run and thus
1820 // the activeRenderPass.* fields haven't been set.
1821 const auto views = sync_state_->GetAttachmentViews(*pRenderPassBegin, *fb_state);
1822
1823 // Validate transitions
John Zulauffaea0ee2021-01-14 14:01:32 -07001824 skip |= temp_context.ValidateLayoutTransitions(*this, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf86356ca2020-10-19 11:46:41 -06001825
1826 // Validate load operations if there were no layout transition hazards
1827 if (!skip) {
1828 temp_context.RecordLayoutTransitions(rp_state, subpass, views, kCurrentCommandTag);
John Zulauffaea0ee2021-01-14 14:01:32 -07001829 skip |= temp_context.ValidateLoadOperation(*this, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06001830 }
John Zulauf86356ca2020-10-19 11:46:41 -06001831
John Zulauf355e49b2020-04-24 15:11:15 -06001832 return skip;
1833}
1834
locke-lunarg61870c22020-06-09 14:51:50 -06001835bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1836 const char *func_name) const {
1837 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001838 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001839 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001840 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1841 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001842 return skip;
1843 }
1844
1845 using DescriptorClass = cvdescriptorset::DescriptorClass;
1846 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1847 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1848 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1849 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1850
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001851 for (const auto &stage_state : pipe->stage_state) {
1852 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1853 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001854 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001855 }
locke-lunarg61870c22020-06-09 14:51:50 -06001856 for (const auto &set_binding : stage_state.descriptor_uses) {
1857 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1858 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1859 set_binding.first.second);
1860 const auto descriptor_type = binding_it.GetType();
1861 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1862 auto array_idx = 0;
1863
1864 if (binding_it.IsVariableDescriptorCount()) {
1865 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1866 }
1867 SyncStageAccessIndex sync_index =
1868 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1869
1870 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1871 uint32_t index = i - index_range.start;
1872 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1873 switch (descriptor->GetClass()) {
1874 case DescriptorClass::ImageSampler:
1875 case DescriptorClass::Image: {
1876 const IMAGE_VIEW_STATE *img_view_state = nullptr;
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001877 VkImageLayout image_layout;
locke-lunarg61870c22020-06-09 14:51:50 -06001878 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001879 const auto image_sampler_descriptor = static_cast<const ImageSamplerDescriptor *>(descriptor);
1880 img_view_state = image_sampler_descriptor->GetImageViewState();
1881 image_layout = image_sampler_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001882 } else {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001883 const auto image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1884 img_view_state = image_descriptor->GetImageViewState();
1885 image_layout = image_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001886 }
1887 if (!img_view_state) continue;
1888 const IMAGE_STATE *img_state = img_view_state->image_state.get();
1889 VkExtent3D extent = {};
1890 VkOffset3D offset = {};
1891 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1892 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1893 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
1894 } else {
1895 extent = img_state->createInfo.extent;
1896 }
John Zulauf361fb532020-07-22 10:45:39 -06001897 HazardResult hazard;
1898 const auto &subresource_range = img_view_state->normalized_subresource_range;
1899 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
1900 // Input attachments are subject to raster ordering rules
1901 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001902 SyncOrdering::kRaster, offset, extent);
John Zulauf361fb532020-07-22 10:45:39 -06001903 } else {
1904 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range, offset, extent);
1905 }
John Zulauf33fc1d52020-07-17 11:01:10 -06001906 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001907 skip |= sync_state_->LogError(
1908 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001909 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1910 ", index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06001911 func_name, string_SyncHazard(hazard.hazard),
1912 sync_state_->report_data->FormatHandle(img_view_state->image_view).c_str(),
1913 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001914 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001915 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1916 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauffaea0ee2021-01-14 14:01:32 -07001917 set_binding.first.second, index, FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001918 }
1919 break;
1920 }
1921 case DescriptorClass::TexelBuffer: {
1922 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
1923 if (!buf_view_state) continue;
1924 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06001925 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06001926 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06001927 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001928 skip |= sync_state_->LogError(
1929 buf_view_state->buffer_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001930 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1931 func_name, string_SyncHazard(hazard.hazard),
locke-lunarg88dbb542020-06-23 22:05:42 -06001932 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view).c_str(),
1933 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001934 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001935 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1936 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
John Zulauffaea0ee2021-01-14 14:01:32 -07001937 FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001938 }
1939 break;
1940 }
1941 case DescriptorClass::GeneralBuffer: {
1942 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
1943 auto buf_state = buffer_descriptor->GetBufferState();
1944 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06001945 const ResourceAccessRange range =
1946 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06001947 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06001948 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001949 skip |= sync_state_->LogError(
1950 buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001951 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1952 func_name, string_SyncHazard(hazard.hazard),
1953 sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
locke-lunarg88dbb542020-06-23 22:05:42 -06001954 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001955 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001956 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1957 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
John Zulauffaea0ee2021-01-14 14:01:32 -07001958 FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001959 }
1960 break;
1961 }
1962 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
1963 default:
1964 break;
1965 }
1966 }
1967 }
1968 }
1969 return skip;
1970}
1971
1972void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1973 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001974 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001975 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001976 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1977 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001978 return;
1979 }
1980
1981 using DescriptorClass = cvdescriptorset::DescriptorClass;
1982 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1983 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1984 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1985 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1986
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001987 for (const auto &stage_state : pipe->stage_state) {
1988 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1989 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001990 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001991 }
locke-lunarg61870c22020-06-09 14:51:50 -06001992 for (const auto &set_binding : stage_state.descriptor_uses) {
1993 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1994 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1995 set_binding.first.second);
1996 const auto descriptor_type = binding_it.GetType();
1997 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1998 auto array_idx = 0;
1999
2000 if (binding_it.IsVariableDescriptorCount()) {
2001 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
2002 }
2003 SyncStageAccessIndex sync_index =
2004 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2005
2006 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2007 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2008 switch (descriptor->GetClass()) {
2009 case DescriptorClass::ImageSampler:
2010 case DescriptorClass::Image: {
2011 const IMAGE_VIEW_STATE *img_view_state = nullptr;
2012 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
2013 img_view_state = static_cast<const ImageSamplerDescriptor *>(descriptor)->GetImageViewState();
2014 } else {
2015 img_view_state = static_cast<const ImageDescriptor *>(descriptor)->GetImageViewState();
2016 }
2017 if (!img_view_state) continue;
2018 const IMAGE_STATE *img_state = img_view_state->image_state.get();
2019 VkExtent3D extent = {};
2020 VkOffset3D offset = {};
2021 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2022 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2023 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2024 } else {
2025 extent = img_state->createInfo.extent;
2026 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07002027 SyncOrdering ordering_rule = (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)
2028 ? SyncOrdering::kRaster
2029 : SyncOrdering::kNonAttachment;
2030 current_context_->UpdateAccessState(*img_state, sync_index, ordering_rule,
2031 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002032 break;
2033 }
2034 case DescriptorClass::TexelBuffer: {
2035 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
2036 if (!buf_view_state) continue;
2037 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002038 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002039 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002040 break;
2041 }
2042 case DescriptorClass::GeneralBuffer: {
2043 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
2044 auto buf_state = buffer_descriptor->GetBufferState();
2045 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06002046 const ResourceAccessRange range =
2047 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002048 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002049 break;
2050 }
2051 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2052 default:
2053 break;
2054 }
2055 }
2056 }
2057 }
2058}
2059
2060bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const {
2061 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002062 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2063 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002064 return skip;
2065 }
2066
2067 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2068 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002069 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002070
2071 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002072 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002073 if (binding_description.binding < binding_buffers_size) {
2074 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002075 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002076
locke-lunarg1ae57d62020-11-18 10:49:19 -07002077 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002078 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2079 vertexCount, binding_description.stride);
locke-lunarg61870c22020-06-09 14:51:50 -06002080 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, range);
2081 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002082 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002083 buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002084 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07002085 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002086 }
2087 }
2088 }
2089 return skip;
2090}
2091
2092void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002093 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2094 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002095 return;
2096 }
2097 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2098 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002099 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002100
2101 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002102 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002103 if (binding_description.binding < binding_buffers_size) {
2104 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002105 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002106
locke-lunarg1ae57d62020-11-18 10:49:19 -07002107 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002108 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2109 vertexCount, binding_description.stride);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002110 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, SyncOrdering::kNonAttachment,
2111 range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002112 }
2113 }
2114}
2115
2116bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const {
2117 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002118 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->destroyed) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002119 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002120 }
locke-lunarg61870c22020-06-09 14:51:50 -06002121
locke-lunarg1ae57d62020-11-18 10:49:19 -07002122 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002123 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002124 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2125 firstIndex, indexCount, index_size);
locke-lunarg61870c22020-06-09 14:51:50 -06002126 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, range);
2127 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002128 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002129 index_buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002130 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07002131 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002132 }
2133
2134 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2135 // We will detect more accurate range in the future.
2136 skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name);
2137 return skip;
2138}
2139
2140void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag &tag) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002141 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 -06002142
locke-lunarg1ae57d62020-11-18 10:49:19 -07002143 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002144 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002145 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2146 firstIndex, indexCount, index_size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002147 current_context_->UpdateAccessState(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002148
2149 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2150 // We will detect more accurate range in the future.
2151 RecordDrawVertex(UINT32_MAX, 0, tag);
2152}
2153
2154bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002155 bool skip = false;
2156 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002157 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(*this, *cb_state_.get(),
locke-lunarg7077d502020-06-18 21:37:26 -06002158 cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
2159 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002160}
2161
2162void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002163 if (current_renderpass_context_) {
locke-lunarg7077d502020-06-18 21:37:26 -06002164 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), cb_state_->activeRenderPassBeginInfo.renderArea,
2165 tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002166 }
locke-lunarg61870c22020-06-09 14:51:50 -06002167}
2168
John Zulauf355e49b2020-04-24 15:11:15 -06002169bool CommandBufferAccessContext::ValidateNextSubpass(const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002170 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002171 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002172 skip |= current_renderpass_context_->ValidateNextSubpass(*this, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002173
2174 return skip;
2175}
2176
2177bool CommandBufferAccessContext::ValidateEndRenderpass(const char *func_name) const {
2178 // TODO: Things to add here.
John Zulauf7635de32020-05-29 17:14:15 -06002179 // Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002180 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002181 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002182 skip |= current_renderpass_context_->ValidateEndRenderPass(*this, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002183
2184 return skip;
2185}
2186
2187void CommandBufferAccessContext::RecordBeginRenderPass(const ResourceUsageTag &tag) {
2188 assert(sync_state_);
2189 if (!cb_state_) return;
2190
2191 // Create an access context the current renderpass.
John Zulauf1a224292020-06-30 14:52:13 -06002192 render_pass_contexts_.emplace_back();
John Zulauf16adfc92020-04-08 10:28:33 -06002193 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf1a224292020-06-30 14:52:13 -06002194 current_renderpass_context_->RecordBeginRenderPass(*sync_state_, *cb_state_, &cb_access_context_, queue_flags_, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002195 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf16adfc92020-04-08 10:28:33 -06002196}
2197
John Zulauffaea0ee2021-01-14 14:01:32 -07002198void CommandBufferAccessContext::RecordNextSubpass(const RENDER_PASS_STATE &rp_state, CMD_TYPE command) {
John Zulauf16adfc92020-04-08 10:28:33 -06002199 assert(current_renderpass_context_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002200 auto prev_tag = NextCommandTag(command);
2201 auto next_tag = NextSubcommandTag(command);
2202 current_renderpass_context_->RecordNextSubpass(cb_state_->activeRenderPassBeginInfo.renderArea, prev_tag, next_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002203 current_context_ = &current_renderpass_context_->CurrentContext();
2204}
2205
John Zulauffaea0ee2021-01-14 14:01:32 -07002206void CommandBufferAccessContext::RecordEndRenderPass(const RENDER_PASS_STATE &render_pass, CMD_TYPE command) {
John Zulauf16adfc92020-04-08 10:28:33 -06002207 assert(current_renderpass_context_);
2208 if (!current_renderpass_context_) return;
2209
John Zulauffaea0ee2021-01-14 14:01:32 -07002210 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, cb_state_->activeRenderPassBeginInfo.renderArea,
2211 NextCommandTag(command));
John Zulauf355e49b2020-04-24 15:11:15 -06002212 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002213 current_renderpass_context_ = nullptr;
2214}
2215
John Zulauf49beb112020-11-04 16:06:31 -07002216bool CommandBufferAccessContext::ValidateSetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2217 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002218 // I'll put this here just in case we need to pass this in for future extension support
2219 const auto cmd = CMD_SETEVENT;
2220 bool skip = false;
John Zulauf669dfd52021-01-27 17:15:28 -07002221 const auto *event_state = sync_state_->Get<EVENT_STATE>(event);
2222 if (!event_state) return skip;
2223
2224 const auto *sync_event = GetCurrentEventsContext()->Get(event_state);
John Zulauf4a6105a2020-11-17 15:11:05 -07002225 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2226
2227 const char *const reset_set =
2228 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2229 "hazards.";
2230 const char *const wait =
2231 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
2232
2233 const auto exec_scope = WithEarlierPipelineStages(ExpandPipelineStages(GetQueueFlags(), stageMask));
2234 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2235 const char *vuid = nullptr;
2236 const char *message = nullptr;
2237 switch (sync_event->last_command) {
2238 case CMD_RESETEVENT:
2239 // Needs a barrier between reset and set
2240 vuid = "SYNC-vkCmdSetEvent-missingbarrier-reset";
2241 message = reset_set;
2242 break;
2243 case CMD_SETEVENT:
2244 // Needs a barrier between set and set
2245 vuid = "SYNC-vkCmdSetEvent-missingbarrier-set";
2246 message = reset_set;
2247 break;
2248 case CMD_WAITEVENTS:
2249 // Needs a barrier or is in second execution scope
2250 vuid = "SYNC-vkCmdSetEvent-missingbarrier-wait";
2251 message = wait;
2252 break;
2253 default:
2254 // The only other valid last command that wasn't one.
2255 assert(sync_event->last_command == CMD_NONE);
2256 break;
2257 }
2258 if (vuid) {
2259 assert(nullptr != message);
2260 const char *const cmd_name = CommandTypeString(cmd);
2261 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2262 cmd_name, CommandTypeString(sync_event->last_command));
2263 }
2264 }
2265
2266 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002267}
2268
John Zulauf4a6105a2020-11-17 15:11:05 -07002269void CommandBufferAccessContext::RecordSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask,
2270 const ResourceUsageTag &tag) {
John Zulauf669dfd52021-01-27 17:15:28 -07002271 auto event_state_shared = sync_state_->GetShared<EVENT_STATE>(event);
2272 if (!event_state_shared.get()) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2273
2274 auto *sync_event = GetCurrentEventsContext()->GetFromShared(event_state_shared);
John Zulauf4a6105a2020-11-17 15:11:05 -07002275 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2276
2277 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
2278 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
2279 // any issues caused by naive scope setting here.
2280
2281 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
2282 // Given:
2283 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
2284 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002285 auto scope = SyncExecScope::MakeSrc(GetQueueFlags(), stageMask);
John Zulauf4a6105a2020-11-17 15:11:05 -07002286
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002287 if (!sync_event->HasBarrier(stageMask, scope.exec_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002288 sync_event->unsynchronized_set = sync_event->last_command;
2289 sync_event->ResetFirstScope();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002290 } else if (sync_event->scope.exec_scope == 0) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002291 // We only set the scope if there isn't one
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002292 sync_event->scope = scope;
John Zulauf4a6105a2020-11-17 15:11:05 -07002293
2294 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
2295 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002296 if (access.second.InSourceScopeOrChain(sync_event->scope.exec_scope, sync_event->scope.valid_accesses)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002297 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
2298 }
2299 };
2300 GetCurrentAccessContext()->ForAll(set_scope);
2301 sync_event->unsynchronized_set = CMD_NONE;
2302 sync_event->first_scope_tag = tag;
2303 }
2304 sync_event->last_command = CMD_SETEVENT;
2305 sync_event->barriers = 0U;
2306}
John Zulauf49beb112020-11-04 16:06:31 -07002307
2308bool CommandBufferAccessContext::ValidateResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2309 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002310 // I'll put this here just in case we need to pass this in for future extension support
2311 const auto cmd = CMD_RESETEVENT;
2312
2313 bool skip = false;
2314 // TODO: EVENTS:
2315 // What is it we need to check... that we've had a reset since a set? Set/Set seems ill formed...
John Zulauf669dfd52021-01-27 17:15:28 -07002316 auto event_state = sync_state_->Get<EVENT_STATE>(event);
2317 if (!event_state) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
2318
2319 const auto *sync_event = GetCurrentEventsContext()->Get(event_state);
John Zulauf4a6105a2020-11-17 15:11:05 -07002320 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2321
2322 const char *const set_wait =
2323 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2324 "hazards.";
2325 const char *message = set_wait; // Only one message this call.
2326 const auto exec_scope = WithEarlierPipelineStages(ExpandPipelineStages(GetQueueFlags(), stageMask));
2327 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2328 const char *vuid = nullptr;
2329 switch (sync_event->last_command) {
2330 case CMD_SETEVENT:
2331 // Needs a barrier between set and reset
2332 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
2333 break;
2334 case CMD_WAITEVENTS: {
2335 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
2336 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
2337 break;
2338 }
2339 default:
2340 // The only other valid last command that wasn't one.
2341 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT));
2342 break;
2343 }
2344 if (vuid) {
2345 const char *const cmd_name = CommandTypeString(cmd);
2346 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2347 cmd_name, CommandTypeString(sync_event->last_command));
2348 }
2349 }
2350 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002351}
2352
John Zulauf4a6105a2020-11-17 15:11:05 -07002353void CommandBufferAccessContext::RecordResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
2354 const auto cmd = CMD_RESETEVENT;
John Zulauf669dfd52021-01-27 17:15:28 -07002355 auto event_state_shared = sync_state_->GetShared<EVENT_STATE>(event);
2356 if (!event_state_shared.get()) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2357
2358 auto *sync_event = GetCurrentEventsContext()->GetFromShared(event_state_shared);
John Zulauf4a6105a2020-11-17 15:11:05 -07002359 if (!sync_event) return;
John Zulauf49beb112020-11-04 16:06:31 -07002360
John Zulauf4a6105a2020-11-17 15:11:05 -07002361 // Clear out the first sync scope, any races vs. wait or set are reported, so we'll keep the bookkeeping simple assuming
2362 // the safe case
2363 for (const auto address_type : kAddressTypes) {
2364 sync_event->first_scope[static_cast<size_t>(address_type)].clear();
2365 }
2366
2367 // Update the event state
2368 sync_event->last_command = cmd;
2369 sync_event->unsynchronized_set = CMD_NONE;
2370 sync_event->ResetFirstScope();
2371 sync_event->barriers = 0U;
2372}
2373
John Zulauf4a6105a2020-11-17 15:11:05 -07002374void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2375 // Erase is okay with the key not being
John Zulauf669dfd52021-01-27 17:15:28 -07002376 const auto *event_state = sync_state_->Get<EVENT_STATE>(event);
2377 if (event_state) {
2378 GetCurrentEventsContext()->Destroy(event_state);
John Zulaufd5115702021-01-18 12:34:33 -07002379 }
2380}
2381
John Zulauffaea0ee2021-01-14 14:01:32 -07002382bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandBufferAccessContext &cb_context,
2383 const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2384 const char *func_name) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002385 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002386 const auto &sync_state = cb_context.GetSyncState();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002387 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2388 if (!pipe ||
2389 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002390 return skip;
2391 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002392 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002393 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2394 VkExtent3D extent = CastTo3D(render_area.extent);
2395 VkOffset3D offset = CastTo3D(render_area.offset);
locke-lunarg37047832020-06-12 13:44:45 -06002396
John Zulauf1a224292020-06-30 14:52:13 -06002397 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002398 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002399 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2400 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002401 if (location >= subpass.colorAttachmentCount ||
2402 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002403 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002404 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002405 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf1a224292020-06-30 14:52:13 -06002406 HazardResult hazard = current_context.DetectHazard(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002407 SyncOrdering::kColorAttachment, offset, extent);
locke-lunarg96dc9632020-06-10 17:22:18 -06002408 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002409 skip |= sync_state.LogError(img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002410 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002411 func_name, string_SyncHazard(hazard.hazard),
2412 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2413 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002414 location, cb_context.FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002415 }
2416 }
2417 }
locke-lunarg37047832020-06-12 13:44:45 -06002418
2419 // PHASE1 TODO: Add layout based read/vs. write selection.
2420 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002421 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002422 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002423 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002424 bool depth_write = false, stencil_write = false;
2425
2426 // PHASE1 TODO: These validation should be in core_checks.
2427 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002428 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2429 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002430 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2431 depth_write = true;
2432 }
2433 // PHASE1 TODO: It needs to check if stencil is writable.
2434 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2435 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2436 // PHASE1 TODO: These validation should be in core_checks.
2437 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002438 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002439 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2440 stencil_write = true;
2441 }
2442
2443 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2444 if (depth_write) {
2445 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002446 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002447 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002448 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002449 skip |= sync_state.LogError(
2450 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002451 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002452 func_name, string_SyncHazard(hazard.hazard),
2453 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2454 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002455 cb_context.FormatUsage(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002456 }
2457 }
2458 if (stencil_write) {
2459 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002460 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002461 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002462 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002463 skip |= sync_state.LogError(
2464 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002465 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002466 func_name, string_SyncHazard(hazard.hazard),
2467 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2468 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002469 cb_context.FormatUsage(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002470 }
locke-lunarg61870c22020-06-09 14:51:50 -06002471 }
2472 }
2473 return skip;
2474}
2475
locke-lunarg96dc9632020-06-10 17:22:18 -06002476void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2477 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002478 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2479 if (!pipe ||
2480 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002481 return;
2482 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002483 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002484 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2485 VkExtent3D extent = CastTo3D(render_area.extent);
2486 VkOffset3D offset = CastTo3D(render_area.offset);
2487
John Zulauf1a224292020-06-30 14:52:13 -06002488 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002489 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002490 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2491 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002492 if (location >= subpass.colorAttachmentCount ||
2493 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002494 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002495 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002496 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf8e3c3e92021-01-06 11:19:36 -07002497 current_context.UpdateAccessState(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
2498 SyncOrdering::kColorAttachment, offset, extent, 0, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002499 }
2500 }
locke-lunarg37047832020-06-12 13:44:45 -06002501
2502 // PHASE1 TODO: Add layout based read/vs. write selection.
2503 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002504 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002505 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002506 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002507 bool depth_write = false, stencil_write = false;
2508
2509 // PHASE1 TODO: These validation should be in core_checks.
2510 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002511 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2512 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002513 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2514 depth_write = true;
2515 }
2516 // PHASE1 TODO: It needs to check if stencil is writable.
2517 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2518 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2519 // PHASE1 TODO: These validation should be in core_checks.
2520 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002521 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002522 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2523 stencil_write = true;
2524 }
2525
2526 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2527 if (depth_write) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002528 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2529 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT,
2530 tag);
locke-lunarg37047832020-06-12 13:44:45 -06002531 }
2532 if (stencil_write) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002533 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2534 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT,
2535 tag);
locke-lunarg37047832020-06-12 13:44:45 -06002536 }
locke-lunarg61870c22020-06-09 14:51:50 -06002537 }
2538}
2539
John Zulauffaea0ee2021-01-14 14:01:32 -07002540bool RenderPassAccessContext::ValidateNextSubpass(const CommandBufferAccessContext &cb_context, const VkRect2D &render_area,
John Zulauf1507ee42020-05-18 11:33:09 -06002541 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002542 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002543 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002544 skip |= CurrentContext().ValidateResolveOperations(cb_context, *rp_state_, render_area, attachment_views_, func_name,
John Zulaufb027cdb2020-05-21 14:25:22 -06002545 current_subpass_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002546 skip |= CurrentContext().ValidateStoreOperation(cb_context, *rp_state_, render_area, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002547 func_name);
2548
John Zulauf355e49b2020-04-24 15:11:15 -06002549 const auto next_subpass = current_subpass_ + 1;
John Zulauf1507ee42020-05-18 11:33:09 -06002550 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauffaea0ee2021-01-14 14:01:32 -07002551 skip |= next_context.ValidateLayoutTransitions(cb_context, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002552 if (!skip) {
2553 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2554 // on a copy of the (empty) next context.
2555 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2556 AccessContext temp_context(next_context);
2557 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kCurrentCommandTag);
John Zulauffaea0ee2021-01-14 14:01:32 -07002558 skip |= temp_context.ValidateLoadOperation(cb_context, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002559 }
John Zulauf7635de32020-05-29 17:14:15 -06002560 return skip;
2561}
John Zulauffaea0ee2021-01-14 14:01:32 -07002562bool RenderPassAccessContext::ValidateEndRenderPass(const CommandBufferAccessContext &cb_context, const VkRect2D &render_area,
John Zulauf7635de32020-05-29 17:14:15 -06002563 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002564 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002565 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002566 skip |= CurrentContext().ValidateResolveOperations(cb_context, *rp_state_, render_area, attachment_views_, func_name,
John Zulauf7635de32020-05-29 17:14:15 -06002567 current_subpass_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002568 skip |= CurrentContext().ValidateStoreOperation(cb_context, *rp_state_, render_area, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002569 func_name);
John Zulauffaea0ee2021-01-14 14:01:32 -07002570 skip |= ValidateFinalSubpassLayoutTransitions(cb_context, render_area, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002571 return skip;
2572}
2573
John Zulauf7635de32020-05-29 17:14:15 -06002574AccessContext *RenderPassAccessContext::CreateStoreResolveProxy(const VkRect2D &render_area) const {
2575 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, render_area, attachment_views_);
2576}
2577
John Zulauffaea0ee2021-01-14 14:01:32 -07002578bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandBufferAccessContext &cb_context,
2579 const VkRect2D &render_area, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002580 bool skip = false;
2581
John Zulauf7635de32020-05-29 17:14:15 -06002582 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2583 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2584 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2585 // to apply and only copy then, if this proves a hot spot.
2586 std::unique_ptr<AccessContext> proxy_for_current;
2587
John Zulauf355e49b2020-04-24 15:11:15 -06002588 // Validate the "finalLayout" transitions to external
2589 // Get them from where there we're hidding in the extra entry.
2590 const auto &final_transitions = rp_state_->subpass_transitions.back();
2591 for (const auto &transition : final_transitions) {
2592 const auto &attach_view = attachment_views_[transition.attachment];
2593 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
2594 assert(trackback.context); // Transitions are given implicit transitions if the StateTracker is working correctly
John Zulauf7635de32020-05-29 17:14:15 -06002595 auto *context = trackback.context;
2596
2597 if (transition.prev_pass == current_subpass_) {
2598 if (!proxy_for_current) {
2599 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
2600 proxy_for_current.reset(CreateStoreResolveProxy(render_area));
2601 }
2602 context = proxy_for_current.get();
2603 }
2604
John Zulaufa0a98292020-09-18 09:30:10 -06002605 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2606 const auto merged_barrier = MergeBarriers(trackback.barriers);
2607 auto hazard = context->DetectImageBarrierHazard(*attach_view->image_state, merged_barrier.src_exec_scope,
2608 merged_barrier.src_access_scope, attach_view->normalized_subresource_range,
2609 AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002610 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -07002611 skip |= cb_context.GetSyncState().LogError(
2612 rp_state_->renderPass, string_SyncHazardVUID(hazard.hazard),
2613 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2614 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2615 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2616 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
2617 cb_context.FormatUsage(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -06002618 }
2619 }
2620 return skip;
2621}
2622
2623void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag &tag) {
2624 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002625 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002626}
2627
John Zulauf1507ee42020-05-18 11:33:09 -06002628void RenderPassAccessContext::RecordLoadOperations(const VkRect2D &render_area, const ResourceUsageTag &tag) {
2629 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2630 auto &subpass_context = subpass_contexts_[current_subpass_];
2631 VkExtent3D extent = CastTo3D(render_area.extent);
2632 VkOffset3D offset = CastTo3D(render_area.offset);
2633
2634 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2635 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
2636 if (attachment_views_[i] == nullptr) continue; // UNUSED
2637 const auto &view = *attachment_views_[i];
2638 const IMAGE_STATE *image = view.image_state.get();
2639 if (image == nullptr) continue;
2640
2641 const auto &ci = attachment_ci[i];
2642 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002643 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002644 const bool is_color = !(has_depth || has_stencil);
2645
2646 if (is_color) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002647 subpass_context.UpdateAccessState(*image, ColorLoadUsage(ci.loadOp), SyncOrdering::kColorAttachment,
2648 view.normalized_subresource_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002649 } else {
2650 auto update_range = view.normalized_subresource_range;
2651 if (has_depth) {
2652 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07002653 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.loadOp),
2654 SyncOrdering::kDepthStencilAttachment, update_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002655 }
2656 if (has_stencil) {
2657 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07002658 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.stencilLoadOp),
2659 SyncOrdering::kDepthStencilAttachment, update_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002660 }
2661 }
2662 }
2663 }
2664}
2665
John Zulauf355e49b2020-04-24 15:11:15 -06002666void RenderPassAccessContext::RecordBeginRenderPass(const SyncValidator &state, const CMD_BUFFER_STATE &cb_state,
John Zulauf1a224292020-06-30 14:52:13 -06002667 const AccessContext *external_context, VkQueueFlags queue_flags,
2668 const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002669 current_subpass_ = 0;
locke-lunargaecf2152020-05-12 17:15:41 -06002670 rp_state_ = cb_state.activeRenderPass.get();
John Zulauf355e49b2020-04-24 15:11:15 -06002671 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
2672 // Add this for all subpasses here so that they exsist during next subpass validation
2673 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002674 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulauf355e49b2020-04-24 15:11:15 -06002675 }
2676 attachment_views_ = state.GetCurrentAttachmentViews(cb_state);
2677
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002678 subpass_contexts_[current_subpass_].SetStartTag(tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002679 RecordLayoutTransitions(tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002680 RecordLoadOperations(cb_state.activeRenderPassBeginInfo.renderArea, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002681}
John Zulauf1507ee42020-05-18 11:33:09 -06002682
John Zulauffaea0ee2021-01-14 14:01:32 -07002683void RenderPassAccessContext::RecordNextSubpass(const VkRect2D &render_area, const ResourceUsageTag &prev_subpass_tag,
2684 const ResourceUsageTag &next_subpass_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002685 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauffaea0ee2021-01-14 14:01:32 -07002686 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, prev_subpass_tag);
2687 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, prev_subpass_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002688
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002689 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2690 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002691 current_subpass_++;
2692 assert(current_subpass_ < subpass_contexts_.size());
John Zulauffaea0ee2021-01-14 14:01:32 -07002693 subpass_contexts_[current_subpass_].SetStartTag(next_subpass_tag);
2694 RecordLayoutTransitions(next_subpass_tag);
2695 RecordLoadOperations(render_area, next_subpass_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002696}
2697
John Zulauf1a224292020-06-30 14:52:13 -06002698void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const VkRect2D &render_area,
2699 const ResourceUsageTag &tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002700 // Add the resolve and store accesses
John Zulauf7635de32020-05-29 17:14:15 -06002701 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulaufaff20662020-06-01 14:07:58 -06002702 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulauf7635de32020-05-29 17:14:15 -06002703
John Zulauf355e49b2020-04-24 15:11:15 -06002704 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002705 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002706
2707 // Add the "finalLayout" transitions to external
2708 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002709 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2710 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2711 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002712 const auto &final_transitions = rp_state_->subpass_transitions.back();
2713 for (const auto &transition : final_transitions) {
2714 const auto &attachment = attachment_views_[transition.attachment];
2715 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufaa97d8b2020-07-14 10:58:13 -06002716 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.context);
John Zulaufd5115702021-01-18 12:34:33 -07002717 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002718 for (const auto &barrier : last_trackback.barriers) {
John Zulaufd5115702021-01-18 12:34:33 -07002719 barrier_action.EmplaceBack(PipelineBarrierOp(barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002720 }
John Zulauf1e331ec2020-12-04 18:29:38 -07002721 external_context->UpdateResourceAccess(*attachment->image_state, attachment->normalized_subresource_range, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002722 }
2723}
2724
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002725SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags mask_param) {
2726 SyncExecScope result;
2727 result.mask_param = mask_param;
2728 result.expanded_mask = ExpandPipelineStages(queue_flags, mask_param);
2729 result.exec_scope = WithEarlierPipelineStages(result.expanded_mask);
2730 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2731 return result;
2732}
2733
2734SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags mask_param) {
2735 SyncExecScope result;
2736 result.mask_param = mask_param;
2737 result.expanded_mask = ExpandPipelineStages(queue_flags, mask_param);
2738 result.exec_scope = WithLaterPipelineStages(result.expanded_mask);
2739 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2740 return result;
2741}
2742
2743SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
2744 src_exec_scope = src.exec_scope;
2745 src_access_scope = 0;
2746 dst_exec_scope = dst.exec_scope;
2747 dst_access_scope = 0;
2748}
2749
2750template <typename Barrier>
2751SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst) {
2752 src_exec_scope = src.exec_scope;
2753 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2754 dst_exec_scope = dst.exec_scope;
2755 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
2756}
2757
2758SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
2759 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
2760 src_exec_scope = src.exec_scope;
2761 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2762
2763 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
2764 dst_exec_scope = dst.exec_scope;
2765 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002766}
2767
John Zulaufb02c1eb2020-10-06 16:33:36 -06002768// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2769void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
2770 for (const auto &barrier : barriers) {
2771 ApplyBarrier(barrier, layout_transition);
2772 }
2773}
2774
John Zulauf89311b42020-09-29 16:28:47 -06002775// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2776// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2777// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufb02c1eb2020-10-06 16:33:36 -06002778void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, const ResourceUsageTag &tag) {
2779 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002780 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002781 assert(!pending_write_dep_chain);
John Zulaufa0a98292020-09-18 09:30:10 -06002782 for (const auto &barrier : barriers) {
John Zulauf89311b42020-09-29 16:28:47 -06002783 ApplyBarrier(barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002784 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002785 ApplyPendingBarriers(tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002786}
John Zulauf9cb530d2019-09-30 14:14:10 -06002787HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2788 HazardResult hazard;
2789 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002790 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002791 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002792 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002793 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002794 }
2795 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002796 // Write operation:
2797 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2798 // If reads exists -- test only against them because either:
2799 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2800 // * 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
2801 // the current write happens after the reads, so just test the write against the reades
2802 // Otherwise test against last_write
2803 //
2804 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002805 if (last_reads.size()) {
2806 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002807 if (IsReadHazard(usage_stage, read_access)) {
2808 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2809 break;
2810 }
2811 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002812 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002813 // Write-After-Write check -- if we have a previous write to test against
2814 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002815 }
2816 }
2817 return hazard;
2818}
2819
John Zulauf8e3c3e92021-01-06 11:19:36 -07002820HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering &ordering_rule) const {
2821 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06002822 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2823 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002824 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002825 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002826 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2827 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002828 if (IsRead(usage_bit)) {
2829 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2830 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2831 if (is_raw_hazard) {
2832 // NOTE: we know last_write is non-zero
2833 // See if the ordering rules save us from the simple RAW check above
2834 // First check to see if the current usage is covered by the ordering rules
2835 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
2836 const bool usage_is_ordered =
2837 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
2838 if (usage_is_ordered) {
2839 // Now see of the most recent write (or a subsequent read) are ordered
2840 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
2841 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06002842 }
2843 }
John Zulauf4285ee92020-09-23 10:20:52 -06002844 if (is_raw_hazard) {
2845 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
2846 }
John Zulauf361fb532020-07-22 10:45:39 -06002847 } else {
2848 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002849 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07002850 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06002851 // Look for any WAR hazards outside the ordered set of stages
John Zulauf4285ee92020-09-23 10:20:52 -06002852 VkPipelineStageFlags ordered_stages = 0;
2853 if (usage_write_is_ordered) {
2854 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
2855 ordered_stages = GetOrderedStages(ordering);
2856 }
2857 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
2858 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07002859 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06002860 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
2861 if (IsReadHazard(usage_stage, read_access)) {
2862 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2863 break;
2864 }
John Zulaufd14743a2020-07-03 09:42:39 -06002865 }
2866 }
John Zulauf4285ee92020-09-23 10:20:52 -06002867 } else if (!(last_write_is_ordered && usage_write_is_ordered)) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002868 if (last_write.any() && IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002869 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06002870 }
John Zulauf69133422020-05-20 14:55:53 -06002871 }
2872 }
2873 return hazard;
2874}
2875
John Zulauf2f952d22020-02-10 11:34:51 -07002876// Asynchronous Hazards occur between subpasses with no connection through the DAG
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002877HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag &start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07002878 HazardResult hazard;
2879 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002880 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
2881 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
2882 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07002883 if (IsRead(usage)) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002884 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06002885 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07002886 }
2887 } else {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002888 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06002889 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07002890 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002891 // 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 -07002892 for (const auto &read_access : last_reads) {
2893 if (read_access.tag.index >= start_tag.index) {
2894 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002895 break;
2896 }
2897 }
John Zulauf2f952d22020-02-10 11:34:51 -07002898 }
2899 }
2900 return hazard;
2901}
2902
John Zulauf36bcf6a2020-02-03 15:12:52 -07002903HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002904 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07002905 // Only supporting image layout transitions for now
2906 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
2907 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06002908 // only test for WAW if there no intervening read operations.
2909 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07002910 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06002911 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07002912 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002913 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06002914 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07002915 break;
2916 }
2917 }
John Zulauf4a6105a2020-11-17 15:11:05 -07002918 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
2919 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2920 }
2921
2922 return hazard;
2923}
2924
2925HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
2926 const SyncStageAccessFlags &src_access_scope,
2927 const ResourceUsageTag &event_tag) const {
2928 // Only supporting image layout transitions for now
2929 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
2930 HazardResult hazard;
2931 // only test for WAW if there no intervening read operations.
2932 // See DetectHazard(SyncStagetAccessIndex) above for more details.
2933
John Zulaufab7756b2020-12-29 16:10:16 -07002934 if (last_reads.size()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002935 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
2936 // first scope, or they are a hazard.
John Zulaufab7756b2020-12-29 16:10:16 -07002937 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002938 if (read_access.tag.IsBefore(event_tag)) {
2939 // The read is in the events first synchronization scope, so we use a barrier hazard check
2940 // If the read stage is not in the src sync scope
2941 // *AND* not execution chained with an existing sync barrier (that's the or)
2942 // then the barrier access is unsafe (R/W after R)
2943 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
2944 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2945 break;
2946 }
2947 } else {
2948 // The read not in the event first sync scope and so is a hazard vs. the layout transition
2949 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2950 }
2951 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002952 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002953 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
2954 if (write_tag.IsBefore(event_tag)) {
2955 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
2956 // So do a normal barrier hazard check
2957 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
2958 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2959 }
2960 } else {
2961 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06002962 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2963 }
John Zulaufd14743a2020-07-03 09:42:39 -06002964 }
John Zulauf361fb532020-07-22 10:45:39 -06002965
John Zulauf0cb5be22020-01-23 12:18:22 -07002966 return hazard;
2967}
2968
John Zulauf5f13a792020-03-10 07:31:21 -06002969// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
2970// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
2971// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
2972void ResourceAccessState::Resolve(const ResourceAccessState &other) {
2973 if (write_tag.IsBefore(other.write_tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002974 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
2975 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06002976 *this = other;
2977 } else if (!other.write_tag.IsBefore(write_tag)) {
2978 // This is the *equals* case for write operations, we merged the write barriers and the read state (but without the
2979 // dependency chaining logic or any stage expansion)
2980 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002981 pending_write_barriers |= other.pending_write_barriers;
2982 pending_layout_transition |= other.pending_layout_transition;
2983 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06002984
John Zulaufd14743a2020-07-03 09:42:39 -06002985 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07002986 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06002987 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07002988 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06002989 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06002990 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06002991 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06002992 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
2993 // but we should wait on profiling data for that.
2994 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06002995 auto &my_read = last_reads[my_read_index];
2996 if (other_read.stage == my_read.stage) {
2997 if (my_read.tag.IsBefore(other_read.tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002998 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06002999 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003000 my_read.tag = other_read.tag;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003001 my_read.pending_dep_chain = other_read.pending_dep_chain;
3002 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3003 // May require tracking more than one access per stage.
3004 my_read.barriers = other_read.barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003005 if (my_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
3006 // Since I'm overwriting the fragement stage read, also update the input attachment info
3007 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003008 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003009 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003010 } else if (other_read.tag.IsBefore(my_read.tag)) {
3011 // The read tags match so merge the barriers
3012 my_read.barriers |= other_read.barriers;
3013 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003014 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003015
John Zulauf5f13a792020-03-10 07:31:21 -06003016 break;
3017 }
3018 }
3019 } else {
3020 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003021 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003022 last_read_stages |= other_read.stage;
John Zulauf4285ee92020-09-23 10:20:52 -06003023 if (other_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06003024 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003025 }
John Zulauf5f13a792020-03-10 07:31:21 -06003026 }
3027 }
John Zulauf361fb532020-07-22 10:45:39 -06003028 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003029 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3030 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003031
3032 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3033 // of the copy and other into this using the update first logic.
3034 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3035 // of the other first_accesses... )
3036 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3037 FirstAccesses firsts(std::move(first_accesses_));
3038 first_accesses_.clear();
3039 first_read_stages_ = 0U;
3040 auto a = firsts.begin();
3041 auto a_end = firsts.end();
3042 for (auto &b : other.first_accesses_) {
3043 // TODO: Determine whether "IsBefore" or "IsGloballyBefore" is needed...
3044 while (a != a_end && a->tag.IsBefore(b.tag)) {
3045 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3046 ++a;
3047 }
3048 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3049 }
3050 for (; a != a_end; ++a) {
3051 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3052 }
3053 }
John Zulauf5f13a792020-03-10 07:31:21 -06003054}
3055
John Zulauf8e3c3e92021-01-06 11:19:36 -07003056void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag &tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003057 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3058 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003059 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003060 // Mulitple outstanding reads may be of interest and do dependency chains independently
3061 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3062 const auto usage_stage = PipelineStageBit(usage_index);
3063 if (usage_stage & last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003064 for (auto &read_access : last_reads) {
3065 if (read_access.stage == usage_stage) {
3066 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003067 break;
3068 }
3069 }
3070 } else {
John Zulaufab7756b2020-12-29 16:10:16 -07003071 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003072 last_read_stages |= usage_stage;
3073 }
John Zulauf4285ee92020-09-23 10:20:52 -06003074
3075 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
3076 if (usage_stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06003077 // TODO Revisit re: multiple reads for a given stage
3078 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003079 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003080 } else {
3081 // Assume write
3082 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003083 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003084 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003085 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003086}
John Zulauf5f13a792020-03-10 07:31:21 -06003087
John Zulauf89311b42020-09-29 16:28:47 -06003088// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3089// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3090// We can overwrite them as *this* write is now after them.
3091//
3092// Note: intentionally ignore pending barriers and chains (i.e. don't apply or clear them), let ApplyPendingBarriers handle them.
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003093void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag &tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003094 last_reads.clear();
John Zulauf89311b42020-09-29 16:28:47 -06003095 last_read_stages = 0;
3096 read_execution_barriers = 0;
John Zulauff51fbb62020-10-02 14:43:24 -06003097 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
John Zulauf89311b42020-09-29 16:28:47 -06003098
3099 write_barriers = 0;
3100 write_dependency_chain = 0;
3101 write_tag = tag;
3102 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003103}
3104
John Zulauf89311b42020-09-29 16:28:47 -06003105// Apply the memory barrier without updating the existing barriers. The execution barrier
3106// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3107// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3108// replace the current write barriers or add to them, so accumulate to pending as well.
3109void ResourceAccessState::ApplyBarrier(const SyncBarrier &barrier, bool layout_transition) {
3110 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3111 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003112 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
3113 // transistion, under the theory of "most recent access". If the read/write *isn't* safe
3114 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3115 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulauf4a6105a2020-11-17 15:11:05 -07003116 if (layout_transition || WriteInSourceScopeOrChain(barrier.src_exec_scope, barrier.src_access_scope)) {
John Zulauf89311b42020-09-29 16:28:47 -06003117 pending_write_barriers |= barrier.dst_access_scope;
3118 pending_write_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003119 }
John Zulauf89311b42020-09-29 16:28:47 -06003120 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3121 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003122
John Zulauf89311b42020-09-29 16:28:47 -06003123 if (!pending_layout_transition) {
3124 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3125 // don't need to be tracked as we're just going to zero them.
John Zulaufab7756b2020-12-29 16:10:16 -07003126 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003127 // The | implements the "dependency chain" logic for this access, as the barriers field stores the second sync scope
John Zulaufab7756b2020-12-29 16:10:16 -07003128 if (barrier.src_exec_scope & (read_access.stage | read_access.barriers)) {
3129 read_access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003130 }
3131 }
John Zulaufa0a98292020-09-18 09:30:10 -06003132 }
John Zulaufa0a98292020-09-18 09:30:10 -06003133}
3134
John Zulauf4a6105a2020-11-17 15:11:05 -07003135// Apply the tag scoped memory barrier without updating the existing barriers. The execution barrier
3136// changes the "chaining" state, but to keep barriers independent. See discussion above.
3137void ResourceAccessState::ApplyBarrier(const ResourceUsageTag &scope_tag, const SyncBarrier &barrier, bool layout_transition) {
3138 // The scope logic for events is, if we're here, the resource usage was flagged as "in the first execution scope" at
3139 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3140 // in order to know if it's in the excecution scope
3141 // Notice that the layout transition sets the pending barriers *regardless*, as any lack of src_access_scope to
3142 // guard against the layout transition should be reported in the detect barrier hazard phase, and we only report
3143 // errors w.r.t. "most recent" accesses.
3144 if (layout_transition || ((write_tag.IsBefore(scope_tag)) && (barrier.src_access_scope & last_write).any())) {
3145 pending_write_barriers |= barrier.dst_access_scope;
3146 pending_write_dep_chain |= barrier.dst_exec_scope;
3147 }
3148 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3149 pending_layout_transition |= layout_transition;
3150
3151 if (!pending_layout_transition) {
3152 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3153 // don't need to be tracked as we're just going to zero them.
John Zulaufab7756b2020-12-29 16:10:16 -07003154 for (auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003155 // If this read is the same one we included in the set event and in scope, then apply the execution barrier...
3156 // NOTE: That's not really correct... this read stage might *not* have been included in the setevent, and the barriers
3157 // representing the chain might have changed since then (that would be an odd usage), so as a first approximation
3158 // we'll assume the barriers *haven't* been changed since (if the tag hasn't), and while this could be a false
3159 // positive in the case of Set; SomeBarrier; Wait; we'll live with it until we can add more state to the first scope
3160 // capture (the specific write and read stages that *were* in scope at the moment of SetEvents.
3161 // TODO: eliminate the false positive by including write/read-stages "in scope" information in SetEvents first_scope
John Zulaufab7756b2020-12-29 16:10:16 -07003162 if (read_access.tag.IsBefore(scope_tag) && (barrier.src_exec_scope & (read_access.stage | read_access.barriers))) {
3163 read_access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulauf4a6105a2020-11-17 15:11:05 -07003164 }
3165 }
3166 }
3167}
John Zulauf89311b42020-09-29 16:28:47 -06003168void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag &tag) {
3169 if (pending_layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003170 // SetWrite clobbers the read count, and thus we don't have to clear the read_state out.
3171 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003172 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf89311b42020-09-29 16:28:47 -06003173 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003174 }
John Zulauf89311b42020-09-29 16:28:47 -06003175
3176 // Apply the accumulate execution barriers (and thus update chaining information)
3177 // for layout transition, read count is zeroed by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003178 for (auto &read_access : last_reads) {
3179 read_access.barriers |= read_access.pending_dep_chain;
3180 read_execution_barriers |= read_access.barriers;
3181 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003182 }
3183
3184 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3185 write_dependency_chain |= pending_write_dep_chain;
3186 write_barriers |= pending_write_barriers;
3187 pending_write_dep_chain = 0;
3188 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003189}
3190
John Zulauf59e25072020-07-17 10:55:21 -06003191// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003192VkPipelineStageFlags ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
John Zulauf59e25072020-07-17 10:55:21 -06003193 VkPipelineStageFlags barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003194
John Zulaufab7756b2020-12-29 16:10:16 -07003195 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003196 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003197 barriers = read_access.barriers;
3198 break;
John Zulauf59e25072020-07-17 10:55:21 -06003199 }
3200 }
John Zulauf4285ee92020-09-23 10:20:52 -06003201
John Zulauf59e25072020-07-17 10:55:21 -06003202 return barriers;
3203}
3204
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003205inline bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlagBits usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003206 assert(IsRead(usage));
3207 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3208 // * the previous reads are not hazards, and thus last_write must be visible and available to
3209 // any reads that happen after.
3210 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3211 // 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 -07003212 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003213}
3214
John Zulauf8e3c3e92021-01-06 11:19:36 -07003215VkPipelineStageFlags ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003216 // Whether the stage are in the ordering scope only matters if the current write is ordered
3217 VkPipelineStageFlags ordered_stages = last_read_stages & ordering.exec_scope;
3218 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003219 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003220 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003221 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
3222 ordered_stages |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
3223 }
3224
3225 return ordered_stages;
3226}
3227
John Zulauffaea0ee2021-01-14 14:01:32 -07003228void ResourceAccessState::UpdateFirst(const ResourceUsageTag &tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
3229 // Only record until we record a write.
3230 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003231 const VkPipelineStageFlags usage_stage =
3232 IsRead(usage_index) ? static_cast<VkPipelineStageFlags>(PipelineStageBit(usage_index)) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003233 if (0 == (usage_stage & first_read_stages_)) {
3234 // If this is a read we haven't seen or a write, record.
3235 first_read_stages_ |= usage_stage;
3236 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3237 }
3238 }
3239}
3240
John Zulaufd1f85d42020-04-15 12:23:15 -06003241void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003242 auto *access_context = GetAccessContextNoInsert(command_buffer);
3243 if (access_context) {
3244 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003245 }
3246}
3247
John Zulaufd1f85d42020-04-15 12:23:15 -06003248void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3249 auto access_found = cb_access_state.find(command_buffer);
3250 if (access_found != cb_access_state.end()) {
3251 access_found->second->Reset();
3252 cb_access_state.erase(access_found);
3253 }
3254}
3255
John Zulauf9cb530d2019-09-30 14:14:10 -06003256bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3257 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3258 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003259 const auto *cb_context = GetAccessContext(commandBuffer);
3260 assert(cb_context);
3261 if (!cb_context) return skip;
3262 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003263
John Zulauf3d84f1b2020-03-09 13:33:25 -06003264 // If we have no previous accesses, we have no hazards
John Zulauf3d84f1b2020-03-09 13:33:25 -06003265 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003266 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003267
3268 for (uint32_t region = 0; region < regionCount; region++) {
3269 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003270 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003271 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf16adfc92020-04-08 10:28:33 -06003272 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003273 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003274 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003275 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003276 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003277 cb_context->FormatUsage(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003278 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003279 }
John Zulauf16adfc92020-04-08 10:28:33 -06003280 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003281 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf355e49b2020-04-24 15:11:15 -06003282 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003283 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003284 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003285 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003286 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003287 cb_context->FormatUsage(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003288 }
3289 }
3290 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003291 }
3292 return skip;
3293}
3294
3295void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3296 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003297 auto *cb_context = GetAccessContext(commandBuffer);
3298 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003299 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003300 auto *context = cb_context->GetCurrentAccessContext();
3301
John Zulauf9cb530d2019-09-30 14:14:10 -06003302 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003303 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003304
3305 for (uint32_t region = 0; region < regionCount; region++) {
3306 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003307 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003308 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003309 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003310 }
John Zulauf16adfc92020-04-08 10:28:33 -06003311 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003312 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003313 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003314 }
3315 }
3316}
3317
John Zulauf4a6105a2020-11-17 15:11:05 -07003318void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3319 // Clear out events from the command buffer contexts
3320 for (auto &cb_context : cb_access_state) {
3321 cb_context.second->RecordDestroyEvent(event);
3322 }
3323}
3324
Jeff Leger178b1e52020-10-05 12:22:23 -04003325bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3326 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3327 bool skip = false;
3328 const auto *cb_context = GetAccessContext(commandBuffer);
3329 assert(cb_context);
3330 if (!cb_context) return skip;
3331 const auto *context = cb_context->GetCurrentAccessContext();
3332
3333 // If we have no previous accesses, we have no hazards
3334 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3335 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3336
3337 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3338 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3339 if (src_buffer) {
3340 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
3341 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3342 if (hazard.hazard) {
3343 // TODO -- add tag information to log msg when useful.
3344 skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
3345 "vkCmdCopyBuffer2KHR(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
3346 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003347 region, cb_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003348 }
3349 }
3350 if (dst_buffer && !skip) {
3351 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
3352 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3353 if (hazard.hazard) {
3354 skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
3355 "vkCmdCopyBuffer2KHR(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
3356 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003357 region, cb_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003358 }
3359 }
3360 if (skip) break;
3361 }
3362 return skip;
3363}
3364
3365void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3366 auto *cb_context = GetAccessContext(commandBuffer);
3367 assert(cb_context);
3368 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER2KHR);
3369 auto *context = cb_context->GetCurrentAccessContext();
3370
3371 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3372 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3373
3374 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3375 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3376 if (src_buffer) {
3377 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003378 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003379 }
3380 if (dst_buffer) {
3381 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003382 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003383 }
3384 }
3385}
3386
John Zulauf5c5e88d2019-12-26 11:22:02 -07003387bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3388 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3389 const VkImageCopy *pRegions) const {
3390 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003391 const auto *cb_access_context = GetAccessContext(commandBuffer);
3392 assert(cb_access_context);
3393 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003394
John Zulauf3d84f1b2020-03-09 13:33:25 -06003395 const auto *context = cb_access_context->GetCurrentAccessContext();
3396 assert(context);
3397 if (!context) return skip;
3398
3399 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3400 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003401 for (uint32_t region = 0; region < regionCount; region++) {
3402 const auto &copy_region = pRegions[region];
3403 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003404 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
John Zulauf3d84f1b2020-03-09 13:33:25 -06003405 copy_region.srcOffset, copy_region.extent);
3406 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003407 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003408 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003409 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003410 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003411 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003412 }
3413
3414 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003415 VkExtent3D dst_copy_extent =
3416 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf540266b2020-04-06 18:54:53 -06003417 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
locke-lunarg1df1f882020-03-02 16:42:08 -07003418 copy_region.dstOffset, dst_copy_extent);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003419 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003420 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003421 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003422 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003423 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003424 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07003425 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003426 }
3427 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003428
John Zulauf5c5e88d2019-12-26 11:22:02 -07003429 return skip;
3430}
3431
3432void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3433 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3434 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003435 auto *cb_access_context = GetAccessContext(commandBuffer);
3436 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003437 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003438 auto *context = cb_access_context->GetCurrentAccessContext();
3439 assert(context);
3440
John Zulauf5c5e88d2019-12-26 11:22:02 -07003441 auto *src_image = Get<IMAGE_STATE>(srcImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003442 auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003443
3444 for (uint32_t region = 0; region < regionCount; region++) {
3445 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06003446 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003447 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3448 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003449 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003450 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003451 VkExtent3D dst_copy_extent =
3452 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003453 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3454 copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003455 }
3456 }
3457}
3458
Jeff Leger178b1e52020-10-05 12:22:23 -04003459bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
3460 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
3461 bool skip = false;
3462 const auto *cb_access_context = GetAccessContext(commandBuffer);
3463 assert(cb_access_context);
3464 if (!cb_access_context) return skip;
3465
3466 const auto *context = cb_access_context->GetCurrentAccessContext();
3467 assert(context);
3468 if (!context) return skip;
3469
3470 const auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3471 const auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3472 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3473 const auto &copy_region = pCopyImageInfo->pRegions[region];
3474 if (src_image) {
3475 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
3476 copy_region.srcOffset, copy_region.extent);
3477 if (hazard.hazard) {
3478 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
3479 "vkCmdCopyImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
3480 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003481 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003482 }
3483 }
3484
3485 if (dst_image) {
3486 VkExtent3D dst_copy_extent =
3487 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
3488 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
3489 copy_region.dstOffset, dst_copy_extent);
3490 if (hazard.hazard) {
3491 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
3492 "vkCmdCopyImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
3493 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003494 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003495 }
3496 if (skip) break;
3497 }
3498 }
3499
3500 return skip;
3501}
3502
3503void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
3504 auto *cb_access_context = GetAccessContext(commandBuffer);
3505 assert(cb_access_context);
3506 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE2KHR);
3507 auto *context = cb_access_context->GetCurrentAccessContext();
3508 assert(context);
3509
3510 auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3511 auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3512
3513 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3514 const auto &copy_region = pCopyImageInfo->pRegions[region];
3515 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003516 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3517 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003518 }
3519 if (dst_image) {
3520 VkExtent3D dst_copy_extent =
3521 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003522 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3523 copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003524 }
3525 }
3526}
3527
John Zulauf9cb530d2019-09-30 14:14:10 -06003528bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3529 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3530 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3531 uint32_t bufferMemoryBarrierCount,
3532 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3533 uint32_t imageMemoryBarrierCount,
3534 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
3535 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003536 const auto *cb_access_context = GetAccessContext(commandBuffer);
3537 assert(cb_access_context);
3538 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07003539
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003540 SyncOpPipelineBarrier pipeline_barrier(*this, cb_access_context->GetQueueFlags(), srcStageMask, dstStageMask, dependencyFlags,
3541 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
3542 imageMemoryBarrierCount, pImageMemoryBarriers);
3543 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06003544 return skip;
3545}
3546
3547void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3548 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3549 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3550 uint32_t bufferMemoryBarrierCount,
3551 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3552 uint32_t imageMemoryBarrierCount,
3553 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003554 auto *cb_access_context = GetAccessContext(commandBuffer);
3555 assert(cb_access_context);
3556 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06003557
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003558 SyncOpPipelineBarrier pipeline_barrier(*this, cb_access_context->GetQueueFlags(), srcStageMask, dstStageMask, dependencyFlags,
3559 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
3560 imageMemoryBarrierCount, pImageMemoryBarriers);
3561 pipeline_barrier.Record(cb_access_context, cb_access_context->NextCommandTag(CMD_PIPELINEBARRIER));
John Zulauf9cb530d2019-09-30 14:14:10 -06003562}
3563
3564void SyncValidator::PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
3565 const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) {
3566 // The state tracker sets up the device state
3567 StateTracker::PostCallRecordCreateDevice(gpu, pCreateInfo, pAllocator, pDevice, result);
3568
John Zulauf5f13a792020-03-10 07:31:21 -06003569 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
3570 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06003571 // TODO: Find a good way to do this hooklessly.
3572 ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map);
3573 ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeSyncValidation);
3574 SyncValidator *sync_device_state = static_cast<SyncValidator *>(validation_data);
3575
John Zulaufd1f85d42020-04-15 12:23:15 -06003576 sync_device_state->SetCommandBufferResetCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3577 sync_device_state->ResetCommandBufferCallback(command_buffer);
3578 });
3579 sync_device_state->SetCommandBufferFreeCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3580 sync_device_state->FreeCommandBufferCallback(command_buffer);
3581 });
John Zulauf9cb530d2019-09-30 14:14:10 -06003582}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003583
John Zulauf355e49b2020-04-24 15:11:15 -06003584bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003585 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003586 bool skip = false;
3587 const auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
3588 auto cb_context = GetAccessContext(commandBuffer);
3589
3590 if (rp_state && cb_context) {
3591 skip |= cb_context->ValidateBeginRenderPass(*rp_state, pRenderPassBegin, pSubpassBeginInfo, func_name);
3592 }
3593
3594 return skip;
3595}
3596
3597bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3598 VkSubpassContents contents) const {
3599 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003600 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06003601 subpass_begin_info.contents = contents;
3602 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, "vkCmdBeginRenderPass");
3603 return skip;
3604}
3605
3606bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003607 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003608 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3609 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2");
3610 return skip;
3611}
3612
3613bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3614 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003615 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003616 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3617 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2KHR");
3618 return skip;
3619}
3620
John Zulauf3d84f1b2020-03-09 13:33:25 -06003621void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
3622 VkResult result) {
3623 // The state tracker sets up the command buffer state
3624 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
3625
3626 // Create/initialize the structure that trackers accesses at the command buffer scope.
3627 auto cb_access_context = GetAccessContext(commandBuffer);
3628 assert(cb_access_context);
3629 cb_access_context->Reset();
3630}
3631
3632void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
John Zulauf355e49b2020-04-24 15:11:15 -06003633 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003634 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06003635 if (cb_context) {
3636 cb_context->RecordBeginRenderPass(cb_context->NextCommandTag(command));
John Zulauf3d84f1b2020-03-09 13:33:25 -06003637 }
3638}
3639
3640void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3641 VkSubpassContents contents) {
3642 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003643 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06003644 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003645 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003646}
3647
3648void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3649 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3650 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003651 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003652}
3653
3654void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3655 const VkRenderPassBeginInfo *pRenderPassBegin,
3656 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3657 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003658 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
3659}
3660
Mike Schuchardt2df08912020-12-15 16:28:09 -08003661bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3662 const VkSubpassEndInfo *pSubpassEndInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003663 bool skip = false;
3664
3665 auto cb_context = GetAccessContext(commandBuffer);
3666 assert(cb_context);
3667 auto cb_state = cb_context->GetCommandBufferState();
3668 if (!cb_state) return skip;
3669
3670 auto rp_state = cb_state->activeRenderPass;
3671 if (!rp_state) return skip;
3672
3673 skip |= cb_context->ValidateNextSubpass(func_name);
3674
3675 return skip;
3676}
3677
3678bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
3679 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003680 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06003681 subpass_begin_info.contents = contents;
3682 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, "vkCmdNextSubpass");
3683 return skip;
3684}
3685
Mike Schuchardt2df08912020-12-15 16:28:09 -08003686bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3687 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003688 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3689 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2KHR");
3690 return skip;
3691}
3692
3693bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3694 const VkSubpassEndInfo *pSubpassEndInfo) const {
3695 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3696 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2");
3697 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003698}
3699
3700void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003701 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003702 auto cb_context = GetAccessContext(commandBuffer);
3703 assert(cb_context);
3704 auto cb_state = cb_context->GetCommandBufferState();
3705 if (!cb_state) return;
3706
3707 auto rp_state = cb_state->activeRenderPass;
3708 if (!rp_state) return;
3709
John Zulauffaea0ee2021-01-14 14:01:32 -07003710 cb_context->RecordNextSubpass(*rp_state, command);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003711}
3712
3713void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
3714 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003715 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06003716 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003717 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003718}
3719
3720void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3721 const VkSubpassEndInfo *pSubpassEndInfo) {
3722 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003723 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003724}
3725
3726void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3727 const VkSubpassEndInfo *pSubpassEndInfo) {
3728 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003729 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003730}
3731
Mike Schuchardt2df08912020-12-15 16:28:09 -08003732bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003733 const char *func_name) const {
3734 bool skip = false;
3735
3736 auto cb_context = GetAccessContext(commandBuffer);
3737 assert(cb_context);
3738 auto cb_state = cb_context->GetCommandBufferState();
3739 if (!cb_state) return skip;
3740
3741 auto rp_state = cb_state->activeRenderPass;
3742 if (!rp_state) return skip;
3743
3744 skip |= cb_context->ValidateEndRenderpass(func_name);
3745 return skip;
3746}
3747
3748bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3749 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
3750 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, "vkEndRenderPass");
3751 return skip;
3752}
3753
Mike Schuchardt2df08912020-12-15 16:28:09 -08003754bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003755 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3756 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2");
3757 return skip;
3758}
3759
3760bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003761 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003762 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
3763 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2KHR");
3764 return skip;
3765}
3766
3767void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
3768 CMD_TYPE command) {
John Zulaufe5da6e52020-03-18 15:32:18 -06003769 // Resolve the all subpass contexts to the command buffer contexts
3770 auto cb_context = GetAccessContext(commandBuffer);
3771 assert(cb_context);
3772 auto cb_state = cb_context->GetCommandBufferState();
3773 if (!cb_state) return;
3774
locke-lunargaecf2152020-05-12 17:15:41 -06003775 const auto *rp_state = cb_state->activeRenderPass.get();
John Zulaufe5da6e52020-03-18 15:32:18 -06003776 if (!rp_state) return;
3777
John Zulauffaea0ee2021-01-14 14:01:32 -07003778 cb_context->RecordEndRenderPass(*rp_state, command);
John Zulaufe5da6e52020-03-18 15:32:18 -06003779}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003780
John Zulauf33fc1d52020-07-17 11:01:10 -06003781// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
3782// updates to a resource which do not conflict at the byte level.
3783// TODO: Revisit this rule to see if it needs to be tighter or looser
3784// TODO: Add programatic control over suppression heuristics
3785bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
3786 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
3787}
3788
John Zulauf3d84f1b2020-03-09 13:33:25 -06003789void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06003790 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06003791 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003792}
3793
3794void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06003795 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06003796 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003797}
3798
3799void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06003800 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06003801 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003802}
locke-lunarga19c71d2020-03-02 18:17:04 -07003803
Jeff Leger178b1e52020-10-05 12:22:23 -04003804template <typename BufferImageCopyRegionType>
3805bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3806 VkImageLayout dstImageLayout, uint32_t regionCount,
3807 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003808 bool skip = false;
3809 const auto *cb_access_context = GetAccessContext(commandBuffer);
3810 assert(cb_access_context);
3811 if (!cb_access_context) return skip;
3812
Jeff Leger178b1e52020-10-05 12:22:23 -04003813 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3814 const char *func_name = is_2khr ? "vkCmdCopyBufferToImage2KHR()" : "vkCmdCopyBufferToImage()";
3815
locke-lunarga19c71d2020-03-02 18:17:04 -07003816 const auto *context = cb_access_context->GetCurrentAccessContext();
3817 assert(context);
3818 if (!context) return skip;
3819
3820 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
locke-lunarga19c71d2020-03-02 18:17:04 -07003821 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
3822
3823 for (uint32_t region = 0; region < regionCount; region++) {
3824 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07003825 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07003826 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07003827 if (src_buffer) {
3828 ResourceAccessRange src_range =
3829 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
3830 hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3831 if (hazard.hazard) {
3832 // PHASE1 TODO -- add tag information to log msg when useful.
3833 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
3834 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
3835 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003836 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07003837 }
3838 }
3839
3840 hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.imageSubresource,
3841 copy_region.imageOffset, copy_region.imageExtent);
locke-lunarga19c71d2020-03-02 18:17:04 -07003842 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003843 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04003844 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06003845 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003846 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07003847 }
3848 if (skip) break;
3849 }
3850 if (skip) break;
3851 }
3852 return skip;
3853}
3854
Jeff Leger178b1e52020-10-05 12:22:23 -04003855bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3856 VkImageLayout dstImageLayout, uint32_t regionCount,
3857 const VkBufferImageCopy *pRegions) const {
3858 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
3859 COPY_COMMAND_VERSION_1);
3860}
3861
3862bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
3863 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
3864 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
3865 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
3866 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
3867}
3868
3869template <typename BufferImageCopyRegionType>
3870void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3871 VkImageLayout dstImageLayout, uint32_t regionCount,
3872 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07003873 auto *cb_access_context = GetAccessContext(commandBuffer);
3874 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04003875
3876 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3877 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYBUFFERTOIMAGE2KHR : CMD_COPYBUFFERTOIMAGE;
3878
3879 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07003880 auto *context = cb_access_context->GetCurrentAccessContext();
3881 assert(context);
3882
3883 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf16adfc92020-04-08 10:28:33 -06003884 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07003885
3886 for (uint32_t region = 0; region < regionCount; region++) {
3887 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07003888 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07003889 if (src_buffer) {
3890 ResourceAccessRange src_range =
3891 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
3892 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
3893 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07003894 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3895 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07003896 }
3897 }
3898}
3899
Jeff Leger178b1e52020-10-05 12:22:23 -04003900void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3901 VkImageLayout dstImageLayout, uint32_t regionCount,
3902 const VkBufferImageCopy *pRegions) {
3903 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
3904 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, COPY_COMMAND_VERSION_1);
3905}
3906
3907void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
3908 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
3909 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
3910 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
3911 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
3912 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
3913}
3914
3915template <typename BufferImageCopyRegionType>
3916bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3917 VkBuffer dstBuffer, uint32_t regionCount,
3918 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003919 bool skip = false;
3920 const auto *cb_access_context = GetAccessContext(commandBuffer);
3921 assert(cb_access_context);
3922 if (!cb_access_context) return skip;
3923
Jeff Leger178b1e52020-10-05 12:22:23 -04003924 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3925 const char *func_name = is_2khr ? "vkCmdCopyImageToBuffer2KHR()" : "vkCmdCopyImageToBuffer()";
3926
locke-lunarga19c71d2020-03-02 18:17:04 -07003927 const auto *context = cb_access_context->GetCurrentAccessContext();
3928 assert(context);
3929 if (!context) return skip;
3930
3931 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3932 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
3933 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE;
3934 for (uint32_t region = 0; region < regionCount; region++) {
3935 const auto &copy_region = pRegions[region];
3936 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003937 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.imageSubresource,
locke-lunarga19c71d2020-03-02 18:17:04 -07003938 copy_region.imageOffset, copy_region.imageExtent);
3939 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003940 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04003941 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06003942 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003943 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07003944 }
John Zulauf477700e2021-01-06 11:41:49 -07003945 if (dst_mem) {
3946 ResourceAccessRange dst_range =
3947 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
3948 hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3949 if (hazard.hazard) {
3950 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
3951 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
3952 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003953 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07003954 }
locke-lunarga19c71d2020-03-02 18:17:04 -07003955 }
3956 }
3957 if (skip) break;
3958 }
3959 return skip;
3960}
3961
Jeff Leger178b1e52020-10-05 12:22:23 -04003962bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
3963 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
3964 const VkBufferImageCopy *pRegions) const {
3965 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
3966 COPY_COMMAND_VERSION_1);
3967}
3968
3969bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
3970 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
3971 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
3972 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
3973 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
3974}
3975
3976template <typename BufferImageCopyRegionType>
3977void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3978 VkBuffer dstBuffer, uint32_t regionCount, const BufferImageCopyRegionType *pRegions,
3979 CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07003980 auto *cb_access_context = GetAccessContext(commandBuffer);
3981 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04003982
3983 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3984 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYIMAGETOBUFFER2KHR : CMD_COPYIMAGETOBUFFER;
3985
3986 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07003987 auto *context = cb_access_context->GetCurrentAccessContext();
3988 assert(context);
3989
3990 const auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07003991 auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
3992 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06003993 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07003994
3995 for (uint32_t region = 0; region < regionCount; region++) {
3996 const auto &copy_region = pRegions[region];
3997 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003998 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3999 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004000 if (dst_buffer) {
4001 ResourceAccessRange dst_range =
4002 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
4003 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
4004 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004005 }
4006 }
4007}
4008
Jeff Leger178b1e52020-10-05 12:22:23 -04004009void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4010 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4011 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
4012 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, COPY_COMMAND_VERSION_1);
4013}
4014
4015void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4016 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4017 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4018 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4019 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4020 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
4021}
4022
4023template <typename RegionType>
4024bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4025 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4026 const RegionType *pRegions, VkFilter filter, const char *apiName) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004027 bool skip = false;
4028 const auto *cb_access_context = GetAccessContext(commandBuffer);
4029 assert(cb_access_context);
4030 if (!cb_access_context) return skip;
4031
4032 const auto *context = cb_access_context->GetCurrentAccessContext();
4033 assert(context);
4034 if (!context) return skip;
4035
4036 const auto *src_image = Get<IMAGE_STATE>(srcImage);
4037 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4038
4039 for (uint32_t region = 0; region < regionCount; region++) {
4040 const auto &blit_region = pRegions[region];
4041 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004042 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4043 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4044 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4045 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4046 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4047 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
4048 auto hazard =
4049 context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, blit_region.srcSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004050 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004051 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004052 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004053 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004054 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004055 }
4056 }
4057
4058 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004059 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4060 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4061 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4062 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4063 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4064 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
4065 auto hazard =
4066 context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004067 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004068 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004069 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004070 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004071 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004072 }
4073 if (skip) break;
4074 }
4075 }
4076
4077 return skip;
4078}
4079
Jeff Leger178b1e52020-10-05 12:22:23 -04004080bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4081 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4082 const VkImageBlit *pRegions, VkFilter filter) const {
4083 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
4084 "vkCmdBlitImage");
4085}
4086
4087bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4088 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4089 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4090 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4091 pBlitImageInfo->filter, "vkCmdBlitImage2KHR");
4092}
4093
4094template <typename RegionType>
4095void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4096 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4097 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004098 auto *cb_access_context = GetAccessContext(commandBuffer);
4099 assert(cb_access_context);
4100 auto *context = cb_access_context->GetCurrentAccessContext();
4101 assert(context);
4102
4103 auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004104 auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004105
4106 for (uint32_t region = 0; region < regionCount; region++) {
4107 const auto &blit_region = pRegions[region];
4108 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004109 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4110 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4111 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4112 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4113 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4114 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
John Zulauf8e3c3e92021-01-06 11:19:36 -07004115 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4116 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004117 }
4118 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004119 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4120 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4121 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4122 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4123 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4124 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
John Zulauf8e3c3e92021-01-06 11:19:36 -07004125 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4126 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004127 }
4128 }
4129}
locke-lunarg36ba2592020-04-03 09:42:04 -06004130
Jeff Leger178b1e52020-10-05 12:22:23 -04004131void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4132 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4133 const VkImageBlit *pRegions, VkFilter filter) {
4134 auto *cb_access_context = GetAccessContext(commandBuffer);
4135 assert(cb_access_context);
4136 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4137 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4138 pRegions, filter);
4139 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4140}
4141
4142void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4143 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4144 auto *cb_access_context = GetAccessContext(commandBuffer);
4145 assert(cb_access_context);
4146 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4147 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4148 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4149 pBlitImageInfo->filter, tag);
4150}
4151
John Zulauffaea0ee2021-01-14 14:01:32 -07004152bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4153 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4154 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
4155 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004156 bool skip = false;
4157 if (drawCount == 0) return skip;
4158
4159 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4160 VkDeviceSize size = struct_size;
4161 if (drawCount == 1 || stride == size) {
4162 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004163 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004164 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4165 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004166 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004167 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004168 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004169 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004170 }
4171 } else {
4172 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004173 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004174 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4175 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004176 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004177 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
4178 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004179 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004180 break;
4181 }
4182 }
4183 }
4184 return skip;
4185}
4186
locke-lunarg61870c22020-06-09 14:51:50 -06004187void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag &tag, const VkDeviceSize struct_size,
4188 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4189 uint32_t stride) {
locke-lunargff255f92020-05-13 18:53:52 -06004190 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4191 VkDeviceSize size = struct_size;
4192 if (drawCount == 1 || stride == size) {
4193 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004194 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004195 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004196 } else {
4197 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004198 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004199 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4200 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004201 }
4202 }
4203}
4204
John Zulauffaea0ee2021-01-14 14:01:32 -07004205bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4206 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4207 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004208 bool skip = false;
4209
4210 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004211 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004212 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4213 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004214 skip |= LogError(count_buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004215 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004216 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004217 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004218 }
4219 return skip;
4220}
4221
locke-lunarg61870c22020-06-09 14:51:50 -06004222void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag &tag, VkBuffer buffer, VkDeviceSize offset) {
locke-lunargff255f92020-05-13 18:53:52 -06004223 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004224 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004225 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004226}
4227
locke-lunarg36ba2592020-04-03 09:42:04 -06004228bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004229 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004230 const auto *cb_access_context = GetAccessContext(commandBuffer);
4231 assert(cb_access_context);
4232 if (!cb_access_context) return skip;
4233
locke-lunarg61870c22020-06-09 14:51:50 -06004234 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch");
locke-lunargff255f92020-05-13 18:53:52 -06004235 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004236}
4237
4238void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004239 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004240 auto *cb_access_context = GetAccessContext(commandBuffer);
4241 assert(cb_access_context);
4242 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004243
locke-lunarg61870c22020-06-09 14:51:50 -06004244 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004245}
locke-lunarge1a67022020-04-29 00:15:36 -06004246
4247bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004248 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004249 const auto *cb_access_context = GetAccessContext(commandBuffer);
4250 assert(cb_access_context);
4251 if (!cb_access_context) return skip;
4252
4253 const auto *context = cb_access_context->GetCurrentAccessContext();
4254 assert(context);
4255 if (!context) return skip;
4256
locke-lunarg61870c22020-06-09 14:51:50 -06004257 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004258 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
4259 1, sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004260 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004261}
4262
4263void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004264 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004265 auto *cb_access_context = GetAccessContext(commandBuffer);
4266 assert(cb_access_context);
4267 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4268 auto *context = cb_access_context->GetCurrentAccessContext();
4269 assert(context);
4270
locke-lunarg61870c22020-06-09 14:51:50 -06004271 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4272 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004273}
4274
4275bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4276 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004277 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004278 const auto *cb_access_context = GetAccessContext(commandBuffer);
4279 assert(cb_access_context);
4280 if (!cb_access_context) return skip;
4281
locke-lunarg61870c22020-06-09 14:51:50 -06004282 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw");
4283 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw");
4284 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004285 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004286}
4287
4288void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4289 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004290 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004291 auto *cb_access_context = GetAccessContext(commandBuffer);
4292 assert(cb_access_context);
4293 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004294
locke-lunarg61870c22020-06-09 14:51:50 -06004295 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4296 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4297 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004298}
4299
4300bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4301 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004302 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004303 const auto *cb_access_context = GetAccessContext(commandBuffer);
4304 assert(cb_access_context);
4305 if (!cb_access_context) return skip;
4306
locke-lunarg61870c22020-06-09 14:51:50 -06004307 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed");
4308 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed");
4309 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004310 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004311}
4312
4313void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4314 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004315 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004316 auto *cb_access_context = GetAccessContext(commandBuffer);
4317 assert(cb_access_context);
4318 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004319
locke-lunarg61870c22020-06-09 14:51:50 -06004320 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4321 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4322 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004323}
4324
4325bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4326 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004327 bool skip = false;
4328 if (drawCount == 0) return skip;
4329
locke-lunargff255f92020-05-13 18:53:52 -06004330 const auto *cb_access_context = GetAccessContext(commandBuffer);
4331 assert(cb_access_context);
4332 if (!cb_access_context) return skip;
4333
4334 const auto *context = cb_access_context->GetCurrentAccessContext();
4335 assert(context);
4336 if (!context) return skip;
4337
locke-lunarg61870c22020-06-09 14:51:50 -06004338 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect");
4339 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004340 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4341 drawCount, stride, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004342
4343 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4344 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4345 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004346 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004347 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004348}
4349
4350void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4351 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004352 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004353 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06004354 auto *cb_access_context = GetAccessContext(commandBuffer);
4355 assert(cb_access_context);
4356 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
4357 auto *context = cb_access_context->GetCurrentAccessContext();
4358 assert(context);
4359
locke-lunarg61870c22020-06-09 14:51:50 -06004360 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4361 cb_access_context->RecordDrawSubpassAttachment(tag);
4362 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004363
4364 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4365 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4366 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004367 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004368}
4369
4370bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4371 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004372 bool skip = false;
4373 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06004374 const auto *cb_access_context = GetAccessContext(commandBuffer);
4375 assert(cb_access_context);
4376 if (!cb_access_context) return skip;
4377
4378 const auto *context = cb_access_context->GetCurrentAccessContext();
4379 assert(context);
4380 if (!context) return skip;
4381
locke-lunarg61870c22020-06-09 14:51:50 -06004382 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect");
4383 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004384 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
4385 offset, drawCount, stride, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004386
4387 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4388 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4389 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004390 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004391 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004392}
4393
4394void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4395 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004396 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004397 auto *cb_access_context = GetAccessContext(commandBuffer);
4398 assert(cb_access_context);
4399 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
4400 auto *context = cb_access_context->GetCurrentAccessContext();
4401 assert(context);
4402
locke-lunarg61870c22020-06-09 14:51:50 -06004403 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4404 cb_access_context->RecordDrawSubpassAttachment(tag);
4405 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004406
4407 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4408 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4409 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004410 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004411}
4412
4413bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4414 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4415 uint32_t stride, const char *function) const {
4416 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004417 const auto *cb_access_context = GetAccessContext(commandBuffer);
4418 assert(cb_access_context);
4419 if (!cb_access_context) return skip;
4420
4421 const auto *context = cb_access_context->GetCurrentAccessContext();
4422 assert(context);
4423 if (!context) return skip;
4424
locke-lunarg61870c22020-06-09 14:51:50 -06004425 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4426 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07004427 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4428 maxDrawCount, stride, function);
4429 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004430
4431 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4432 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4433 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004434 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004435 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004436}
4437
4438bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4439 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4440 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004441 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4442 "vkCmdDrawIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004443}
4444
4445void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4446 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4447 uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004448 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4449 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004450 auto *cb_access_context = GetAccessContext(commandBuffer);
4451 assert(cb_access_context);
4452 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECTCOUNT);
4453 auto *context = cb_access_context->GetCurrentAccessContext();
4454 assert(context);
4455
locke-lunarg61870c22020-06-09 14:51:50 -06004456 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4457 cb_access_context->RecordDrawSubpassAttachment(tag);
4458 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
4459 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004460
4461 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4462 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4463 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004464 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004465}
4466
4467bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4468 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4469 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004470 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4471 "vkCmdDrawIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004472}
4473
4474void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4475 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4476 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004477 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4478 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004479 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004480}
4481
4482bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4483 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4484 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004485 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4486 "vkCmdDrawIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004487}
4488
4489void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4490 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4491 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004492 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4493 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004494 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4495}
4496
4497bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4498 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4499 uint32_t stride, const char *function) const {
4500 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004501 const auto *cb_access_context = GetAccessContext(commandBuffer);
4502 assert(cb_access_context);
4503 if (!cb_access_context) return skip;
4504
4505 const auto *context = cb_access_context->GetCurrentAccessContext();
4506 assert(context);
4507 if (!context) return skip;
4508
locke-lunarg61870c22020-06-09 14:51:50 -06004509 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4510 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07004511 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
4512 offset, maxDrawCount, stride, function);
4513 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004514
4515 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4516 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4517 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004518 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004519 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004520}
4521
4522bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4523 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4524 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004525 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4526 "vkCmdDrawIndexedIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004527}
4528
4529void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4530 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4531 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004532 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4533 maxDrawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004534 auto *cb_access_context = GetAccessContext(commandBuffer);
4535 assert(cb_access_context);
4536 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECTCOUNT);
4537 auto *context = cb_access_context->GetCurrentAccessContext();
4538 assert(context);
4539
locke-lunarg61870c22020-06-09 14:51:50 -06004540 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4541 cb_access_context->RecordDrawSubpassAttachment(tag);
4542 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
4543 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004544
4545 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4546 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06004547 // We will update the index and vertex buffer in SubmitQueue in the future.
4548 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004549}
4550
4551bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
4552 VkDeviceSize offset, VkBuffer countBuffer,
4553 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4554 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004555 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4556 "vkCmdDrawIndexedIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004557}
4558
4559void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4560 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4561 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004562 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4563 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004564 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4565}
4566
4567bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
4568 VkDeviceSize offset, VkBuffer countBuffer,
4569 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4570 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004571 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4572 "vkCmdDrawIndexedIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004573}
4574
4575void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4576 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4577 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004578 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4579 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004580 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4581}
4582
4583bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4584 const VkClearColorValue *pColor, uint32_t rangeCount,
4585 const VkImageSubresourceRange *pRanges) const {
4586 bool skip = false;
4587 const auto *cb_access_context = GetAccessContext(commandBuffer);
4588 assert(cb_access_context);
4589 if (!cb_access_context) return skip;
4590
4591 const auto *context = cb_access_context->GetCurrentAccessContext();
4592 assert(context);
4593 if (!context) return skip;
4594
4595 const auto *image_state = Get<IMAGE_STATE>(image);
4596
4597 for (uint32_t index = 0; index < rangeCount; index++) {
4598 const auto &range = pRanges[index];
4599 if (image_state) {
4600 auto hazard =
4601 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4602 if (hazard.hazard) {
4603 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004604 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004605 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauffaea0ee2021-01-14 14:01:32 -07004606 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004607 }
4608 }
4609 }
4610 return skip;
4611}
4612
4613void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4614 const VkClearColorValue *pColor, uint32_t rangeCount,
4615 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004616 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004617 auto *cb_access_context = GetAccessContext(commandBuffer);
4618 assert(cb_access_context);
4619 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
4620 auto *context = cb_access_context->GetCurrentAccessContext();
4621 assert(context);
4622
4623 const auto *image_state = Get<IMAGE_STATE>(image);
4624
4625 for (uint32_t index = 0; index < rangeCount; index++) {
4626 const auto &range = pRanges[index];
4627 if (image_state) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004628 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, {0, 0, 0},
4629 image_state->createInfo.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004630 }
4631 }
4632}
4633
4634bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4635 VkImageLayout imageLayout,
4636 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4637 const VkImageSubresourceRange *pRanges) const {
4638 bool skip = false;
4639 const auto *cb_access_context = GetAccessContext(commandBuffer);
4640 assert(cb_access_context);
4641 if (!cb_access_context) return skip;
4642
4643 const auto *context = cb_access_context->GetCurrentAccessContext();
4644 assert(context);
4645 if (!context) return skip;
4646
4647 const auto *image_state = Get<IMAGE_STATE>(image);
4648
4649 for (uint32_t index = 0; index < rangeCount; index++) {
4650 const auto &range = pRanges[index];
4651 if (image_state) {
4652 auto hazard =
4653 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4654 if (hazard.hazard) {
4655 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004656 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004657 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauffaea0ee2021-01-14 14:01:32 -07004658 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004659 }
4660 }
4661 }
4662 return skip;
4663}
4664
4665void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4666 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4667 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004668 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004669 auto *cb_access_context = GetAccessContext(commandBuffer);
4670 assert(cb_access_context);
4671 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
4672 auto *context = cb_access_context->GetCurrentAccessContext();
4673 assert(context);
4674
4675 const auto *image_state = Get<IMAGE_STATE>(image);
4676
4677 for (uint32_t index = 0; index < rangeCount; index++) {
4678 const auto &range = pRanges[index];
4679 if (image_state) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004680 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, {0, 0, 0},
4681 image_state->createInfo.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004682 }
4683 }
4684}
4685
4686bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
4687 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
4688 VkDeviceSize dstOffset, VkDeviceSize stride,
4689 VkQueryResultFlags flags) const {
4690 bool skip = false;
4691 const auto *cb_access_context = GetAccessContext(commandBuffer);
4692 assert(cb_access_context);
4693 if (!cb_access_context) return skip;
4694
4695 const auto *context = cb_access_context->GetCurrentAccessContext();
4696 assert(context);
4697 if (!context) return skip;
4698
4699 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4700
4701 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004702 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
locke-lunarge1a67022020-04-29 00:15:36 -06004703 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4704 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06004705 skip |=
4706 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4707 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004708 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004709 }
4710 }
locke-lunargff255f92020-05-13 18:53:52 -06004711
4712 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004713 return skip;
4714}
4715
4716void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
4717 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4718 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004719 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
4720 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06004721 auto *cb_access_context = GetAccessContext(commandBuffer);
4722 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06004723 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06004724 auto *context = cb_access_context->GetCurrentAccessContext();
4725 assert(context);
4726
4727 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4728
4729 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004730 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004731 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004732 }
locke-lunargff255f92020-05-13 18:53:52 -06004733
4734 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004735}
4736
4737bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4738 VkDeviceSize size, uint32_t data) const {
4739 bool skip = false;
4740 const auto *cb_access_context = GetAccessContext(commandBuffer);
4741 assert(cb_access_context);
4742 if (!cb_access_context) return skip;
4743
4744 const auto *context = cb_access_context->GetCurrentAccessContext();
4745 assert(context);
4746 if (!context) return skip;
4747
4748 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4749
4750 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004751 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
locke-lunarge1a67022020-04-29 00:15:36 -06004752 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4753 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004754 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004755 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004756 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004757 }
4758 }
4759 return skip;
4760}
4761
4762void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4763 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004764 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06004765 auto *cb_access_context = GetAccessContext(commandBuffer);
4766 assert(cb_access_context);
4767 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
4768 auto *context = cb_access_context->GetCurrentAccessContext();
4769 assert(context);
4770
4771 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4772
4773 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004774 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004775 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004776 }
4777}
4778
4779bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4780 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4781 const VkImageResolve *pRegions) const {
4782 bool skip = false;
4783 const auto *cb_access_context = GetAccessContext(commandBuffer);
4784 assert(cb_access_context);
4785 if (!cb_access_context) return skip;
4786
4787 const auto *context = cb_access_context->GetCurrentAccessContext();
4788 assert(context);
4789 if (!context) return skip;
4790
4791 const auto *src_image = Get<IMAGE_STATE>(srcImage);
4792 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4793
4794 for (uint32_t region = 0; region < regionCount; region++) {
4795 const auto &resolve_region = pRegions[region];
4796 if (src_image) {
4797 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
4798 resolve_region.srcOffset, resolve_region.extent);
4799 if (hazard.hazard) {
4800 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004801 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004802 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004803 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004804 }
4805 }
4806
4807 if (dst_image) {
4808 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
4809 resolve_region.dstOffset, resolve_region.extent);
4810 if (hazard.hazard) {
4811 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004812 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004813 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004814 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004815 }
4816 if (skip) break;
4817 }
4818 }
4819
4820 return skip;
4821}
4822
4823void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4824 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4825 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004826 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4827 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06004828 auto *cb_access_context = GetAccessContext(commandBuffer);
4829 assert(cb_access_context);
4830 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
4831 auto *context = cb_access_context->GetCurrentAccessContext();
4832 assert(context);
4833
4834 auto *src_image = Get<IMAGE_STATE>(srcImage);
4835 auto *dst_image = Get<IMAGE_STATE>(dstImage);
4836
4837 for (uint32_t region = 0; region < regionCount; region++) {
4838 const auto &resolve_region = pRegions[region];
4839 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004840 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4841 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004842 }
4843 if (dst_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004844 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4845 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004846 }
4847 }
4848}
4849
Jeff Leger178b1e52020-10-05 12:22:23 -04004850bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4851 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
4852 bool skip = false;
4853 const auto *cb_access_context = GetAccessContext(commandBuffer);
4854 assert(cb_access_context);
4855 if (!cb_access_context) return skip;
4856
4857 const auto *context = cb_access_context->GetCurrentAccessContext();
4858 assert(context);
4859 if (!context) return skip;
4860
4861 const auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
4862 const auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
4863
4864 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
4865 const auto &resolve_region = pResolveImageInfo->pRegions[region];
4866 if (src_image) {
4867 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
4868 resolve_region.srcOffset, resolve_region.extent);
4869 if (hazard.hazard) {
4870 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
4871 "vkCmdResolveImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
4872 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004873 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004874 }
4875 }
4876
4877 if (dst_image) {
4878 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
4879 resolve_region.dstOffset, resolve_region.extent);
4880 if (hazard.hazard) {
4881 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
4882 "vkCmdResolveImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
4883 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004884 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004885 }
4886 if (skip) break;
4887 }
4888 }
4889
4890 return skip;
4891}
4892
4893void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4894 const VkResolveImageInfo2KHR *pResolveImageInfo) {
4895 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
4896 auto *cb_access_context = GetAccessContext(commandBuffer);
4897 assert(cb_access_context);
4898 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE2KHR);
4899 auto *context = cb_access_context->GetCurrentAccessContext();
4900 assert(context);
4901
4902 auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
4903 auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
4904
4905 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
4906 const auto &resolve_region = pResolveImageInfo->pRegions[region];
4907 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004908 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4909 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004910 }
4911 if (dst_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004912 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4913 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004914 }
4915 }
4916}
4917
locke-lunarge1a67022020-04-29 00:15:36 -06004918bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4919 VkDeviceSize dataSize, const void *pData) const {
4920 bool skip = false;
4921 const auto *cb_access_context = GetAccessContext(commandBuffer);
4922 assert(cb_access_context);
4923 if (!cb_access_context) return skip;
4924
4925 const auto *context = cb_access_context->GetCurrentAccessContext();
4926 assert(context);
4927 if (!context) return skip;
4928
4929 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4930
4931 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004932 // VK_WHOLE_SIZE not allowed
4933 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
locke-lunarge1a67022020-04-29 00:15:36 -06004934 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4935 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004936 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004937 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004938 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004939 }
4940 }
4941 return skip;
4942}
4943
4944void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4945 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004946 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06004947 auto *cb_access_context = GetAccessContext(commandBuffer);
4948 assert(cb_access_context);
4949 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
4950 auto *context = cb_access_context->GetCurrentAccessContext();
4951 assert(context);
4952
4953 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4954
4955 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004956 // VK_WHOLE_SIZE not allowed
4957 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004958 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004959 }
4960}
locke-lunargff255f92020-05-13 18:53:52 -06004961
4962bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
4963 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
4964 bool skip = false;
4965 const auto *cb_access_context = GetAccessContext(commandBuffer);
4966 assert(cb_access_context);
4967 if (!cb_access_context) return skip;
4968
4969 const auto *context = cb_access_context->GetCurrentAccessContext();
4970 assert(context);
4971 if (!context) return skip;
4972
4973 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4974
4975 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004976 const ResourceAccessRange range = MakeRange(dstOffset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004977 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4978 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06004979 skip |=
4980 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4981 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004982 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004983 }
4984 }
4985 return skip;
4986}
4987
4988void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
4989 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004990 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06004991 auto *cb_access_context = GetAccessContext(commandBuffer);
4992 assert(cb_access_context);
4993 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
4994 auto *context = cb_access_context->GetCurrentAccessContext();
4995 assert(context);
4996
4997 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4998
4999 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005000 const ResourceAccessRange range = MakeRange(dstOffset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005001 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005002 }
5003}
John Zulauf49beb112020-11-04 16:06:31 -07005004
5005bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5006 bool skip = false;
5007 const auto *cb_context = GetAccessContext(commandBuffer);
5008 assert(cb_context);
5009 if (!cb_context) return skip;
5010
5011 return cb_context->ValidateSetEvent(commandBuffer, event, stageMask);
5012}
5013
5014void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5015 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5016 auto *cb_context = GetAccessContext(commandBuffer);
5017 assert(cb_context);
5018 if (!cb_context) return;
John Zulauf4a6105a2020-11-17 15:11:05 -07005019 const auto tag = cb_context->NextCommandTag(CMD_SETEVENT);
5020 cb_context->RecordSetEvent(commandBuffer, event, stageMask, tag);
John Zulauf49beb112020-11-04 16:06:31 -07005021}
5022
5023bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5024 VkPipelineStageFlags stageMask) const {
5025 bool skip = false;
5026 const auto *cb_context = GetAccessContext(commandBuffer);
5027 assert(cb_context);
5028 if (!cb_context) return skip;
5029
5030 return cb_context->ValidateResetEvent(commandBuffer, event, stageMask);
5031}
5032
5033void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5034 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5035 auto *cb_context = GetAccessContext(commandBuffer);
5036 assert(cb_context);
5037 if (!cb_context) return;
5038
5039 cb_context->RecordResetEvent(commandBuffer, event, stageMask);
5040}
5041
5042bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5043 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5044 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5045 uint32_t bufferMemoryBarrierCount,
5046 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5047 uint32_t imageMemoryBarrierCount,
5048 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5049 bool skip = false;
5050 const auto *cb_context = GetAccessContext(commandBuffer);
5051 assert(cb_context);
5052 if (!cb_context) return skip;
5053
John Zulauf669dfd52021-01-27 17:15:28 -07005054 SyncOpWaitEvents wait_events_op(*this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask,
John Zulaufd5115702021-01-18 12:34:33 -07005055 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5056 imageMemoryBarrierCount, pImageMemoryBarriers);
5057 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005058}
5059
5060void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5061 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5062 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5063 uint32_t bufferMemoryBarrierCount,
5064 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5065 uint32_t imageMemoryBarrierCount,
5066 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5067 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5068 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5069 imageMemoryBarrierCount, pImageMemoryBarriers);
5070
5071 auto *cb_context = GetAccessContext(commandBuffer);
5072 assert(cb_context);
5073 if (!cb_context) return;
5074
John Zulauf4a6105a2020-11-17 15:11:05 -07005075 const auto tag = cb_context->NextCommandTag(CMD_WAITEVENTS);
John Zulauf669dfd52021-01-27 17:15:28 -07005076 SyncOpWaitEvents wait_events_op(*this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask,
John Zulaufd5115702021-01-18 12:34:33 -07005077 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5078 imageMemoryBarrierCount, pImageMemoryBarriers);
5079 return wait_events_op.Record(cb_context, tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07005080}
5081
5082void SyncEventState::ResetFirstScope() {
5083 for (const auto address_type : kAddressTypes) {
5084 first_scope[static_cast<size_t>(address_type)].clear();
5085 }
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005086 scope = SyncExecScope();
John Zulauf4a6105a2020-11-17 15:11:05 -07005087}
5088
5089// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
5090SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(VkPipelineStageFlags srcStageMask) const {
5091 IgnoreReason reason = NotIgnored;
5092
5093 if (last_command == CMD_RESETEVENT && !HasBarrier(0U, 0U)) {
5094 reason = ResetWaitRace;
5095 } else if (unsynchronized_set) {
5096 reason = SetRace;
5097 } else {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005098 const VkPipelineStageFlags missing_bits = scope.mask_param & ~srcStageMask;
John Zulauf4a6105a2020-11-17 15:11:05 -07005099 if (missing_bits) reason = MissingStageBits;
5100 }
5101
5102 return reason;
5103}
5104
5105bool SyncEventState::HasBarrier(VkPipelineStageFlags stageMask, VkPipelineStageFlags exec_scope_arg) const {
5106 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5107 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5108 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005109}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005110
John Zulaufd5115702021-01-18 12:34:33 -07005111SyncOpBarriers::SyncOpBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags, VkPipelineStageFlags srcStageMask,
5112 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5113 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5114 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5115 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005116 : dependency_flags_(dependencyFlags),
5117 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, srcStageMask)),
5118 dst_exec_scope_(SyncExecScope::MakeDst(queue_flags, dstStageMask)) {
5119 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
5120 MakeMemoryBarriers(src_exec_scope_, dst_exec_scope_, dependencyFlags, memoryBarrierCount, pMemoryBarriers);
5121 MakeBufferMemoryBarriers(sync_state, src_exec_scope_, dst_exec_scope_, dependencyFlags, bufferMemoryBarrierCount,
5122 pBufferMemoryBarriers);
5123 MakeImageMemoryBarriers(sync_state, src_exec_scope_, dst_exec_scope_, dependencyFlags, imageMemoryBarrierCount,
5124 pImageMemoryBarriers);
5125}
5126
John Zulaufd5115702021-01-18 12:34:33 -07005127SyncOpPipelineBarrier::SyncOpPipelineBarrier(const SyncValidator &sync_state, VkQueueFlags queue_flags,
5128 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5129 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5130 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5131 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5132 const VkImageMemoryBarrier *pImageMemoryBarriers)
5133 : SyncOpBarriers(sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
5134 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers) {}
5135
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005136bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
5137 bool skip = false;
5138 const auto *context = cb_context.GetCurrentAccessContext();
5139 assert(context);
5140 if (!context) return skip;
5141 // Validate Image Layout transitions
5142 for (const auto image_barrier : image_memory_barriers_) {
5143 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
5144 const auto *image_state = image_barrier.image.get();
5145 if (!image_state) continue;
5146 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
5147 if (hazard.hazard) {
5148 // PHASE1 TODO -- add tag information to log msg when useful.
5149 const auto &sync_state = cb_context.GetSyncState();
5150 const auto image_handle = image_state->image;
5151 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
5152 "vkCmdPipelineBarrier: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.",
5153 string_SyncHazard(hazard.hazard), image_barrier.index,
5154 sync_state.report_data->FormatHandle(image_handle).c_str(),
5155 cb_context.FormatUsage(hazard).c_str());
5156 }
5157 }
5158
5159 return skip;
5160}
5161
John Zulaufd5115702021-01-18 12:34:33 -07005162struct SyncOpPipelineBarrierFunctorFactory {
5163 using BarrierOpFunctor = PipelineBarrierOp;
5164 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
5165 using GlobalBarrierOpFunctor = PipelineBarrierOp;
5166 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
5167 using BufferRange = ResourceAccessRange;
5168 using ImageRange = subresource_adapter::ImageRangeGenerator;
5169 using GlobalRange = ResourceAccessRange;
5170
5171 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier, bool layout_transition) const {
5172 return ApplyFunctor(BarrierOpFunctor(barrier, layout_transition));
5173 }
5174 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, const ResourceUsageTag &tag) const {
5175 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
5176 }
5177 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier) const {
5178 return GlobalBarrierOpFunctor(barrier, false);
5179 }
5180
5181 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
5182 if (!SimpleBinding(buffer)) return ResourceAccessRange();
5183 const auto base_address = ResourceBaseAddress(buffer);
5184 return (range + base_address);
5185 }
5186 ImageRange MakeRangeGen(const IMAGE_STATE &image, const SyncImageMemoryBarrier::SubImageRange &range) const {
5187 if (!SimpleBinding(image)) subresource_adapter::ImageRangeGenerator();
5188
5189 const auto base_address = ResourceBaseAddress(image);
5190 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), range.subresource_range, range.offset,
5191 range.extent, base_address);
5192 return range_gen;
5193 }
5194 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
5195};
5196
5197template <typename Barriers, typename FunctorFactory>
5198void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag &tag,
5199 AccessContext *context) {
5200 for (const auto &barrier : barriers) {
5201 const auto *state = barrier.GetState();
5202 if (state) {
5203 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
5204 auto update_action = factory.MakeApplyFunctor(barrier.barrier, barrier.IsLayoutTransition());
5205 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
5206 UpdateMemoryAccessState(accesses, update_action, &range_gen);
5207 }
5208 }
5209}
5210
5211template <typename Barriers, typename FunctorFactory>
5212void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag &tag,
5213 AccessContext *access_context) {
5214 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
5215 for (const auto &barrier : barriers) {
5216 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(barrier));
5217 }
5218 for (const auto address_type : kAddressTypes) {
5219 auto range_gen = factory.MakeGlobalRangeGen(address_type);
5220 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
5221 }
5222}
5223
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005224void SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context, const ResourceUsageTag &tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07005225 SyncOpPipelineBarrierFunctorFactory factory;
5226 auto *access_context = cb_context->GetCurrentAccessContext();
5227 ApplyBarriers(buffer_memory_barriers_, factory, tag, access_context);
5228 ApplyBarriers(image_memory_barriers_, factory, tag, access_context);
5229 ApplyGlobalBarriers(memory_barriers_, factory, tag, access_context);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005230
5231 cb_context->ApplyGlobalBarriersToEvents(src_exec_scope_, dst_exec_scope_);
5232}
5233
John Zulaufd5115702021-01-18 12:34:33 -07005234void SyncOpBarriers::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst, VkDependencyFlags dependency_flags,
5235 uint32_t memory_barrier_count, const VkMemoryBarrier *memory_barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005236 memory_barriers_.reserve(std::min<uint32_t>(1, memory_barrier_count));
5237 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
5238 const auto &barrier = memory_barriers[barrier_index];
5239 SyncBarrier sync_barrier(barrier, src, dst);
5240 memory_barriers_.emplace_back(sync_barrier);
5241 }
5242 if (0 == memory_barrier_count) {
5243 // If there are no global memory barriers, force an exec barrier
5244 memory_barriers_.emplace_back(SyncBarrier(src, dst));
5245 }
5246}
5247
John Zulaufd5115702021-01-18 12:34:33 -07005248void SyncOpBarriers::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src, const SyncExecScope &dst,
5249 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
5250 const VkBufferMemoryBarrier *barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005251 buffer_memory_barriers_.reserve(barrier_count);
5252 for (uint32_t index = 0; index < barrier_count; index++) {
5253 const auto &barrier = barriers[index];
5254 auto buffer = sync_state.GetShared<BUFFER_STATE>(barrier.buffer);
5255 if (buffer) {
5256 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
5257 const auto range = MakeRange(barrier.offset, barrier_size);
5258 const SyncBarrier sync_barrier(barrier, src, dst);
5259 buffer_memory_barriers_.emplace_back(buffer, sync_barrier, range);
5260 } else {
5261 buffer_memory_barriers_.emplace_back();
5262 }
5263 }
5264}
5265
John Zulaufd5115702021-01-18 12:34:33 -07005266void SyncOpBarriers::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src, const SyncExecScope &dst,
5267 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
5268 const VkImageMemoryBarrier *barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005269 image_memory_barriers_.reserve(barrier_count);
5270 for (uint32_t index = 0; index < barrier_count; index++) {
5271 const auto &barrier = barriers[index];
5272 const auto image = sync_state.GetShared<IMAGE_STATE>(barrier.image);
5273 if (image) {
5274 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
5275 const SyncBarrier sync_barrier(barrier, src, dst);
5276 image_memory_barriers_.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout,
5277 subresource_range);
5278 } else {
5279 image_memory_barriers_.emplace_back();
5280 image_memory_barriers_.back().index = index; // Just in case we're interested in the ones we skipped.
5281 }
5282 }
5283}
John Zulaufd5115702021-01-18 12:34:33 -07005284
John Zulauf669dfd52021-01-27 17:15:28 -07005285SyncOpWaitEvents::SyncOpWaitEvents(const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
John Zulaufd5115702021-01-18 12:34:33 -07005286 const VkEvent *pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5287 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5288 uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5289 uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf669dfd52021-01-27 17:15:28 -07005290 : SyncOpBarriers(sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07005291 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
5292 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07005293 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07005294}
5295
5296bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
5297 const auto cmd = CMD_WAITEVENTS;
5298 const char *const ignored = "Wait operation is ignored for this event.";
5299 bool skip = false;
5300 const auto &sync_state = cb_context.GetSyncState();
5301 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer;
5302
5303 if (src_exec_scope_.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
5304 const char *const cmd_name = CommandTypeString(cmd);
5305 const char *const vuid = "SYNC-vkCmdWaitEvents-hostevent-unsupported";
5306 skip = sync_state.LogInfo(command_buffer_handle, vuid,
5307 "%s, srcStageMask includes %s, unsupported by synchronization validaton.", cmd_name,
5308 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT), ignored);
5309 }
5310
5311 VkPipelineStageFlags event_stage_masks = 0U;
5312 bool events_not_found = false;
John Zulauf669dfd52021-01-27 17:15:28 -07005313 const auto *events_context = cb_context.GetCurrentEventsContext();
5314 assert(events_context);
5315 for (const auto &sync_event_pair : *events_context) {
5316 const auto *sync_event = sync_event_pair.second.get();
John Zulaufd5115702021-01-18 12:34:33 -07005317 if (!sync_event) {
5318 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
John Zulauf669dfd52021-01-27 17:15:28 -07005319 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
5320 // new validation error... wait without previously submitted set event...
5321 events_not_found = true; // Demote "extra_stage_bits" error to warning, to avoid false positives at *record time*
John Zulaufd5115702021-01-18 12:34:33 -07005322
5323 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
5324 }
5325 const auto event = sync_event->event->event;
5326 // TODO add "destroyed" checks
5327
5328 event_stage_masks |= sync_event->scope.mask_param;
5329 const auto ignore_reason = sync_event->IsIgnoredByWait(src_exec_scope_.mask_param);
5330 if (ignore_reason) {
5331 switch (ignore_reason) {
5332 case SyncEventState::ResetWaitRace: {
5333 const char *const cmd_name = CommandTypeString(cmd);
5334 const char *const vuid = "SYNC-vkCmdWaitEvents-missingbarrier-reset";
5335 const char *const message =
5336 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
5337 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5338 cmd_name, CommandTypeString(sync_event->last_command), ignored);
5339 break;
5340 }
5341 case SyncEventState::SetRace: {
5342 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for this
5343 // event
5344 const char *const cmd_name = CommandTypeString(cmd);
5345 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
5346 const char *const message =
5347 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, % %s";
5348 const char *const reason = "First synchronization scope is undefined.";
5349 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5350 CommandTypeString(sync_event->last_command), reason, ignored);
5351 break;
5352 }
5353 case SyncEventState::MissingStageBits: {
5354 const VkPipelineStageFlags missing_bits = sync_event->scope.mask_param & ~src_exec_scope_.mask_param;
5355 // Issue error message that event waited for is not in wait events scope
5356 const char *const cmd_name = CommandTypeString(cmd);
5357 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
5358 const char *const message =
5359 "%s: %s stageMask 0x%" PRIx32 " includes bits not present in srcStageMask 0x%" PRIx32
5360 ". Bits missing from srcStageMask %s. %s";
5361 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5362 sync_event->scope.mask_param, src_exec_scope_.mask_param,
5363 string_VkPipelineStageFlags(missing_bits).c_str(), ignored);
5364 break;
5365 }
5366 default:
5367 assert(ignore_reason == SyncEventState::NotIgnored);
5368 }
5369 } else if (image_memory_barriers_.size()) {
5370 const auto *context = cb_context.GetCurrentAccessContext();
5371 assert(context);
5372 for (const auto &image_memory_barrier : image_memory_barriers_) {
5373 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
5374 const auto *image_state = image_memory_barrier.image.get();
5375 if (!image_state) continue;
5376 const auto &subresource_range = image_memory_barrier.range.subresource_range;
5377 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
5378 const auto hazard =
5379 context->DetectImageBarrierHazard(*image_state, sync_event->scope.exec_scope, src_access_scope,
5380 subresource_range, *sync_event, AccessContext::DetectOptions::kDetectAll);
5381 if (hazard.hazard) {
5382 const char *const cmd_name = CommandTypeString(cmd);
5383 skip |= sync_state.LogError(image_state->image, string_SyncHazardVUID(hazard.hazard),
5384 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", cmd_name,
5385 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
5386 sync_state.report_data->FormatHandle(image_state->image).c_str(),
5387 cb_context.FormatUsage(hazard).c_str());
5388 break;
5389 }
5390 }
5391 }
5392 }
5393
5394 // Note that we can't check for HOST in pEvents as we don't track that set event type
5395 const auto extra_stage_bits = (src_exec_scope_.mask_param & ~VK_PIPELINE_STAGE_HOST_BIT) & ~event_stage_masks;
5396 if (extra_stage_bits) {
5397 // Issue error message that event waited for is not in wait events scope
5398 const char *const cmd_name = CommandTypeString(cmd);
5399 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
5400 const char *const message =
5401 "%s: srcStageMask 0x%" PRIx32 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
5402 if (events_not_found) {
5403 skip |= sync_state.LogInfo(command_buffer_handle, vuid, message, cmd_name, src_exec_scope_.mask_param,
5404 string_VkPipelineStageFlags(extra_stage_bits).c_str(),
5405 " vkCmdSetEvent may be in previously submitted command buffer.");
5406 } else {
5407 skip |= sync_state.LogError(command_buffer_handle, vuid, message, cmd_name, src_exec_scope_.mask_param,
5408 string_VkPipelineStageFlags(extra_stage_bits).c_str(), "");
5409 }
5410 }
5411 return skip;
5412}
5413
5414struct SyncOpWaitEventsFunctorFactory {
5415 using BarrierOpFunctor = WaitEventBarrierOp;
5416 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
5417 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
5418 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
5419 using BufferRange = EventSimpleRangeGenerator;
5420 using ImageRange = EventImageRangeGenerator;
5421 using GlobalRange = EventSimpleRangeGenerator;
5422
5423 // Need to restrict to only valid exec and access scope for this event
5424 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
5425 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
5426 barrier.src_exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope;
5427 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
5428 return barrier;
5429 }
5430 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier_arg, bool layout_transition) const {
5431 auto barrier = RestrictToEvent(barrier_arg);
5432 return ApplyFunctor(BarrierOpFunctor(sync_event->first_scope_tag, barrier, layout_transition));
5433 }
5434 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, const ResourceUsageTag &tag) const {
5435 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
5436 }
5437 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier_arg) const {
5438 auto barrier = RestrictToEvent(barrier_arg);
5439 return GlobalBarrierOpFunctor(sync_event->first_scope_tag, barrier, false);
5440 }
5441
5442 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
5443 const AccessAddressType address_type = GetAccessAddressType(buffer);
5444 const auto base_address = ResourceBaseAddress(buffer);
5445 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
5446 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
5447 return filtered_range_gen;
5448 }
5449 ImageRange MakeRangeGen(const IMAGE_STATE &image, const SyncImageMemoryBarrier::SubImageRange &range) const {
5450 if (!SimpleBinding(image)) return ImageRange();
5451 const auto address_type = GetAccessAddressType(image);
5452 const auto base_address = ResourceBaseAddress(image);
5453 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), range.subresource_range,
5454 range.offset, range.extent, base_address);
5455 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
5456
5457 return filtered_range_gen;
5458 }
5459 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
5460 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
5461 }
5462 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
5463 SyncEventState *sync_event;
5464};
5465
5466void SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context, const ResourceUsageTag &tag) const {
5467 auto *access_context = cb_context->GetCurrentAccessContext();
5468 assert(access_context);
5469 if (!access_context) return;
John Zulauf669dfd52021-01-27 17:15:28 -07005470 auto *events_context = cb_context->GetCurrentEventsContext();
5471 assert(events_context);
5472 if (!events_context) return;
John Zulaufd5115702021-01-18 12:34:33 -07005473
5474 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
5475 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
5476 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
5477 access_context->ResolvePreviousAccesses();
5478
5479 const auto &dst = dst_exec_scope_;
5480 // TODO... this needs change the SyncEventContext it's using depending on whether this is replay... the recorded
5481 // sync_event will be in the recorded context, but we need to update the sync_events in the current context....
John Zulauf669dfd52021-01-27 17:15:28 -07005482 for (auto &event_shared : events_) {
5483 if (!event_shared.get()) continue;
5484 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07005485
5486 sync_event->last_command = CMD_WAITEVENTS;
5487
5488 if (!sync_event->IsIgnoredByWait(src_exec_scope_.mask_param)) {
5489 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
5490 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
5491 // of the barriers is maintained.
5492 SyncOpWaitEventsFunctorFactory factory(sync_event);
5493 ApplyBarriers(buffer_memory_barriers_, factory, tag, access_context);
5494 ApplyBarriers(image_memory_barriers_, factory, tag, access_context);
5495 ApplyGlobalBarriers(memory_barriers_, factory, tag, access_context);
5496
5497 // Apply the global barrier to the event itself (for race condition tracking)
5498 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
5499 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
5500 sync_event->barriers |= dst.exec_scope;
5501 } else {
5502 // We ignored this wait, so we don't have any effective synchronization barriers for it.
5503 sync_event->barriers = 0U;
5504 }
5505 }
5506
5507 // Apply the pending barriers
5508 ResolvePendingBarrierFunctor apply_pending_action(tag);
5509 access_context->ApplyToContext(apply_pending_action);
5510}
5511
John Zulauf669dfd52021-01-27 17:15:28 -07005512void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07005513 events_.reserve(event_count);
5514 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
John Zulauf669dfd52021-01-27 17:15:28 -07005515 events_.emplace_back(sync_state.GetShared<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07005516 }
5517}