blob: 04c0e582999f449fd5f351a9d2135ebf3b496bde [file] [log] [blame]
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
4 * Copyright (C) 2015-2021 Google Inc.
5 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * Author: Courtney Goeltzenleuchter <courtneygo@google.com>
20 * Author: Tobin Ehlis <tobine@google.com>
21 * Author: Chris Forbes <chrisf@ijw.co.nz>
22 * Author: Mark Lobodzinski <mark@lunarg.com>
23 * Author: Dave Houlton <daveh@lunarg.com>
24 * Author: John Zulauf <jzulauf@lunarg.com>
25 * Author: Tobias Hector <tobias.hector@amd.com>
26 */
27#include "cmd_buffer_state.h"
28#include "render_pass_state.h"
Jeremy Gebben1ec89332021-08-05 13:51:49 -060029#include "state_tracker.h"
30#include "image_state.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060031
32const char *CommandTypeString(CMD_TYPE type) {
33 // Autogenerated as part of the command_validation.h codegen
34 return kGeneratedCommandNameList[type];
35}
36
37VkDynamicState ConvertToDynamicState(CBStatusFlagBits flag) {
38 switch (flag) {
39 case CBSTATUS_LINE_WIDTH_SET:
40 return VK_DYNAMIC_STATE_LINE_WIDTH;
41 case CBSTATUS_DEPTH_BIAS_SET:
42 return VK_DYNAMIC_STATE_DEPTH_BIAS;
43 case CBSTATUS_BLEND_CONSTANTS_SET:
44 return VK_DYNAMIC_STATE_BLEND_CONSTANTS;
45 case CBSTATUS_DEPTH_BOUNDS_SET:
46 return VK_DYNAMIC_STATE_DEPTH_BOUNDS;
47 case CBSTATUS_STENCIL_READ_MASK_SET:
48 return VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK;
49 case CBSTATUS_STENCIL_WRITE_MASK_SET:
50 return VK_DYNAMIC_STATE_STENCIL_WRITE_MASK;
51 case CBSTATUS_STENCIL_REFERENCE_SET:
52 return VK_DYNAMIC_STATE_STENCIL_REFERENCE;
53 case CBSTATUS_VIEWPORT_SET:
54 return VK_DYNAMIC_STATE_VIEWPORT;
55 case CBSTATUS_SCISSOR_SET:
56 return VK_DYNAMIC_STATE_SCISSOR;
57 case CBSTATUS_EXCLUSIVE_SCISSOR_SET:
58 return VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV;
59 case CBSTATUS_SHADING_RATE_PALETTE_SET:
60 return VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV;
61 case CBSTATUS_LINE_STIPPLE_SET:
62 return VK_DYNAMIC_STATE_LINE_STIPPLE_EXT;
63 case CBSTATUS_VIEWPORT_W_SCALING_SET:
64 return VK_DYNAMIC_STATE_VIEWPORT_W_SCALING_NV;
65 case CBSTATUS_CULL_MODE_SET:
66 return VK_DYNAMIC_STATE_CULL_MODE_EXT;
67 case CBSTATUS_FRONT_FACE_SET:
68 return VK_DYNAMIC_STATE_FRONT_FACE_EXT;
69 case CBSTATUS_PRIMITIVE_TOPOLOGY_SET:
70 return VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT;
71 case CBSTATUS_VIEWPORT_WITH_COUNT_SET:
72 return VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT;
73 case CBSTATUS_SCISSOR_WITH_COUNT_SET:
74 return VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT;
75 case CBSTATUS_VERTEX_INPUT_BINDING_STRIDE_SET:
76 return VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT;
77 case CBSTATUS_DEPTH_TEST_ENABLE_SET:
78 return VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE_EXT;
79 case CBSTATUS_DEPTH_WRITE_ENABLE_SET:
80 return VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT;
81 case CBSTATUS_DEPTH_COMPARE_OP_SET:
82 return VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT;
83 case CBSTATUS_DEPTH_BOUNDS_TEST_ENABLE_SET:
84 return VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE_EXT;
85 case CBSTATUS_STENCIL_TEST_ENABLE_SET:
86 return VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE_EXT;
87 case CBSTATUS_STENCIL_OP_SET:
88 return VK_DYNAMIC_STATE_STENCIL_OP_EXT;
89 case CBSTATUS_DISCARD_RECTANGLE_SET:
90 return VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT;
91 case CBSTATUS_SAMPLE_LOCATIONS_SET:
92 return VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT;
93 case CBSTATUS_COARSE_SAMPLE_ORDER_SET:
94 return VK_DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV;
95 case CBSTATUS_PATCH_CONTROL_POINTS_SET:
96 return VK_DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT;
97 case CBSTATUS_RASTERIZER_DISCARD_ENABLE_SET:
98 return VK_DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE_EXT;
99 case CBSTATUS_DEPTH_BIAS_ENABLE_SET:
100 return VK_DYNAMIC_STATE_DEPTH_BIAS_ENABLE_EXT;
101 case CBSTATUS_LOGIC_OP_SET:
102 return VK_DYNAMIC_STATE_LOGIC_OP_EXT;
103 case CBSTATUS_PRIMITIVE_RESTART_ENABLE_SET:
104 return VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE_EXT;
105 case CBSTATUS_VERTEX_INPUT_SET:
106 return VK_DYNAMIC_STATE_VERTEX_INPUT_EXT;
107 default:
108 // CBSTATUS_INDEX_BUFFER_BOUND is not in VkDynamicState
109 return VK_DYNAMIC_STATE_MAX_ENUM;
110 }
111 return VK_DYNAMIC_STATE_MAX_ENUM;
112}
113
114CBStatusFlagBits ConvertToCBStatusFlagBits(VkDynamicState state) {
115 switch (state) {
116 case VK_DYNAMIC_STATE_VIEWPORT:
117 return CBSTATUS_VIEWPORT_SET;
118 case VK_DYNAMIC_STATE_SCISSOR:
119 return CBSTATUS_SCISSOR_SET;
120 case VK_DYNAMIC_STATE_LINE_WIDTH:
121 return CBSTATUS_LINE_WIDTH_SET;
122 case VK_DYNAMIC_STATE_DEPTH_BIAS:
123 return CBSTATUS_DEPTH_BIAS_SET;
124 case VK_DYNAMIC_STATE_BLEND_CONSTANTS:
125 return CBSTATUS_BLEND_CONSTANTS_SET;
126 case VK_DYNAMIC_STATE_DEPTH_BOUNDS:
127 return CBSTATUS_DEPTH_BOUNDS_SET;
128 case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK:
129 return CBSTATUS_STENCIL_READ_MASK_SET;
130 case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK:
131 return CBSTATUS_STENCIL_WRITE_MASK_SET;
132 case VK_DYNAMIC_STATE_STENCIL_REFERENCE:
133 return CBSTATUS_STENCIL_REFERENCE_SET;
134 case VK_DYNAMIC_STATE_VIEWPORT_W_SCALING_NV:
135 return CBSTATUS_VIEWPORT_W_SCALING_SET;
136 case VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT:
137 return CBSTATUS_DISCARD_RECTANGLE_SET;
138 case VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT:
139 return CBSTATUS_SAMPLE_LOCATIONS_SET;
140 case VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV:
141 return CBSTATUS_SHADING_RATE_PALETTE_SET;
142 case VK_DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV:
143 return CBSTATUS_COARSE_SAMPLE_ORDER_SET;
144 case VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV:
145 return CBSTATUS_EXCLUSIVE_SCISSOR_SET;
146 case VK_DYNAMIC_STATE_LINE_STIPPLE_EXT:
147 return CBSTATUS_LINE_STIPPLE_SET;
148 case VK_DYNAMIC_STATE_CULL_MODE_EXT:
149 return CBSTATUS_CULL_MODE_SET;
150 case VK_DYNAMIC_STATE_FRONT_FACE_EXT:
151 return CBSTATUS_FRONT_FACE_SET;
152 case VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT:
153 return CBSTATUS_PRIMITIVE_TOPOLOGY_SET;
154 case VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT:
155 return CBSTATUS_VIEWPORT_WITH_COUNT_SET;
156 case VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT:
157 return CBSTATUS_SCISSOR_WITH_COUNT_SET;
158 case VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT:
159 return CBSTATUS_VERTEX_INPUT_BINDING_STRIDE_SET;
160 case VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE_EXT:
161 return CBSTATUS_DEPTH_TEST_ENABLE_SET;
162 case VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT:
163 return CBSTATUS_DEPTH_WRITE_ENABLE_SET;
164 case VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT:
165 return CBSTATUS_DEPTH_COMPARE_OP_SET;
166 case VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE_EXT:
167 return CBSTATUS_DEPTH_BOUNDS_TEST_ENABLE_SET;
168 case VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE_EXT:
169 return CBSTATUS_STENCIL_TEST_ENABLE_SET;
170 case VK_DYNAMIC_STATE_STENCIL_OP_EXT:
171 return CBSTATUS_STENCIL_OP_SET;
172 case VK_DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT:
173 return CBSTATUS_PATCH_CONTROL_POINTS_SET;
174 case VK_DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE_EXT:
175 return CBSTATUS_RASTERIZER_DISCARD_ENABLE_SET;
176 case VK_DYNAMIC_STATE_DEPTH_BIAS_ENABLE_EXT:
177 return CBSTATUS_DEPTH_BIAS_ENABLE_SET;
178 case VK_DYNAMIC_STATE_LOGIC_OP_EXT:
179 return CBSTATUS_LOGIC_OP_SET;
180 case VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE_EXT:
181 return CBSTATUS_PRIMITIVE_RESTART_ENABLE_SET;
182 case VK_DYNAMIC_STATE_VERTEX_INPUT_EXT:
183 return CBSTATUS_VERTEX_INPUT_SET;
184 default:
185 return CBSTATUS_NONE;
186 }
187 return CBSTATUS_NONE;
188}
189
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600190CMD_BUFFER_STATE::CMD_BUFFER_STATE(ValidationStateTracker *dd, VkCommandBuffer cb, const VkCommandBufferAllocateInfo *pCreateInfo,
191 std::shared_ptr<COMMAND_POOL_STATE> &pool)
192 : REFCOUNTED_NODE(cb, kVulkanObjectTypeCommandBuffer),
193 createInfo(*pCreateInfo),
194 command_pool(pool),
195 dev_data(dd),
196 unprotected(pool->unprotected) {
197 Reset();
198}
199
Jeremy Gebben159b3cc2021-06-03 09:09:03 -0600200// Get the image viewstate for a given framebuffer attachment
201IMAGE_VIEW_STATE *CMD_BUFFER_STATE::GetActiveAttachmentImageViewState(uint32_t index) {
202 assert(active_attachments && index != VK_ATTACHMENT_UNUSED && (index < active_attachments->size()));
203 return active_attachments->at(index);
204}
205
206// Get the image viewstate for a given framebuffer attachment
207const IMAGE_VIEW_STATE *CMD_BUFFER_STATE::GetActiveAttachmentImageViewState(uint32_t index) const {
ziga-lunarg452a5f92021-09-08 15:33:03 +0200208 if (!active_attachments || index == VK_ATTACHMENT_UNUSED || (index >= active_attachments->size())) {
209 return nullptr;
210 }
Jeremy Gebben159b3cc2021-06-03 09:09:03 -0600211 return active_attachments->at(index);
212}
213
214void CMD_BUFFER_STATE::AddChild(BASE_NODE *child_node) {
215 if (child_node->AddParent(this)) {
216 object_bindings.insert(child_node->Handle());
217 }
218}
219
220void CMD_BUFFER_STATE::RemoveChild(BASE_NODE *child_node) {
221 child_node->RemoveParent(this);
222 object_bindings.erase(child_node->Handle());
223}
224
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600225// Reset the command buffer state
226// Maintain the createInfo and set state to CB_NEW, but clear all other state
Jeremy Gebben159b3cc2021-06-03 09:09:03 -0600227void CMD_BUFFER_STATE::Reset() {
228 ResetUse();
229 // Reset CB state (note that createInfo is not cleared)
230 memset(&beginInfo, 0, sizeof(VkCommandBufferBeginInfo));
231 memset(&inheritanceInfo, 0, sizeof(VkCommandBufferInheritanceInfo));
232 hasDrawCmd = false;
233 hasTraceRaysCmd = false;
234 hasBuildAccelerationStructureCmd = false;
235 hasDispatchCmd = false;
236 state = CB_NEW;
237 commandCount = 0;
238 submitCount = 0;
239 image_layout_change_count = 1; // Start at 1. 0 is insert value for validation cache versions, s.t. new == dirty
240 status = 0;
241 static_status = 0;
242 inheritedViewportDepths.clear();
243 usedViewportScissorCount = 0;
244 pipelineStaticViewportCount = 0;
245 pipelineStaticScissorCount = 0;
246 viewportMask = 0;
247 viewportWithCountMask = 0;
248 viewportWithCountCount = 0;
249 scissorMask = 0;
250 scissorWithCountMask = 0;
251 scissorWithCountCount = 0;
252 trashedViewportMask = 0;
253 trashedScissorMask = 0;
254 trashedViewportCount = false;
255 trashedScissorCount = false;
256 usedDynamicViewportCount = false;
257 usedDynamicScissorCount = false;
258 primitiveTopology = VK_PRIMITIVE_TOPOLOGY_MAX_ENUM;
259
260 activeRenderPassBeginInfo = safe_VkRenderPassBeginInfo();
261 activeRenderPass = nullptr;
262 active_attachments = nullptr;
263 active_subpasses = nullptr;
264 attachments_view_states.clear();
265 activeSubpassContents = VK_SUBPASS_CONTENTS_INLINE;
266 activeSubpass = 0;
267 broken_bindings.clear();
268 waitedEvents.clear();
269 events.clear();
270 writeEventsBeforeWait.clear();
271 activeQueries.clear();
272 startedQueries.clear();
273 image_layout_map.clear();
274 current_vertex_buffer_binding_info.vertex_buffer_bindings.clear();
275 vertex_buffer_used = false;
276 primaryCommandBuffer = VK_NULL_HANDLE;
277
278 linkedCommandBuffers.clear();
279 // Remove reverse command buffer links.
280 Invalidate(true);
281
282 queue_submit_functions.clear();
Hans-Kristian Arntzen59c2c3f2021-06-14 11:40:12 +0200283 queue_submit_functions_after_render_pass.clear();
Jeremy Gebben159b3cc2021-06-03 09:09:03 -0600284 cmd_execute_commands_functions.clear();
285 eventUpdates.clear();
286 queryUpdates.clear();
287
288 // Remove object bindings
289 for (const auto &obj : object_bindings) {
290 if (obj.node) {
291 obj.node->RemoveParent(this);
292 }
293 }
294 object_bindings.clear();
295
296 for (auto &item : lastBound) {
297 item.Reset();
298 }
299 // Remove this cmdBuffer's reference from each FrameBuffer's CB ref list
300 for (auto &framebuffer : framebuffers) {
301 framebuffer->RemoveParent(this);
302 }
303 framebuffers.clear();
304 activeFramebuffer = VK_NULL_HANDLE;
305 index_buffer_binding.reset();
306
307 qfo_transfer_image_barriers.Reset();
308 qfo_transfer_buffer_barriers.Reset();
309
310 // Clean up the label data
311 debug_label.Reset();
312 validate_descriptorsets_in_queuesubmit.clear();
313
314 // Best practices info
315 small_indexed_draw_call_count = 0;
316
317 transform_feedback_active = false;
318
319 // Remove object bindings
320 for (const auto &obj : object_bindings) {
321 BASE_NODE *base_obj = obj.node;
322 if (base_obj) RemoveChild(base_obj);
323 }
324 object_bindings.clear();
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600325
326 // Clean up the label data
327 ResetCmdDebugUtilsLabel(dev_data->report_data, commandBuffer());
328
329 if (dev_data->command_buffer_reset_callback) {
330 (*dev_data->command_buffer_reset_callback)(commandBuffer());
331 }
332}
333
334// Track which resources are in-flight by atomically incrementing their "in_use" count
335void CMD_BUFFER_STATE::IncrementResources() {
336 submitCount++;
337
338 // TODO : We should be able to remove the NULL look-up checks from the code below as long as
339 // all the corresponding cases are verified to cause CB_INVALID state and the CB_INVALID state
340 // should then be flagged prior to calling this function
341 for (auto event : writeEventsBeforeWait) {
342 auto event_state = dev_data->GetEventState(event);
343 if (event_state) event_state->write_in_use++;
344 }
345}
346
347// Discussed in details in https://github.com/KhronosGroup/Vulkan-Docs/issues/1081
348// Internal discussion and CTS were written to prove that this is not called after an incompatible vkCmdBindPipeline
349// "Binding a pipeline with a layout that is not compatible with the push constant layout does not disturb the push constant values"
350//
351// vkCmdBindDescriptorSet has nothing to do with push constants and don't need to call this after neither
352//
353// Part of this assumes apps at draw/dispath/traceRays/etc time will have it properly compatabile or else other VU will be triggered
354void CMD_BUFFER_STATE::ResetPushConstantDataIfIncompatible(const PIPELINE_LAYOUT_STATE *pipeline_layout_state) {
355 if (pipeline_layout_state == nullptr) {
356 return;
357 }
358 if (push_constant_data_ranges == pipeline_layout_state->push_constant_ranges) {
359 return;
360 }
361
362 push_constant_data_ranges = pipeline_layout_state->push_constant_ranges;
363 push_constant_data.clear();
364 push_constant_data_update.clear();
365 uint32_t size_needed = 0;
366 for (const auto &push_constant_range : *push_constant_data_ranges) {
367 auto size = push_constant_range.offset + push_constant_range.size;
368 size_needed = std::max(size_needed, size);
369
370 auto stage_flags = push_constant_range.stageFlags;
371 uint32_t bit_shift = 0;
372 while (stage_flags) {
373 if (stage_flags & 1) {
374 VkShaderStageFlagBits flag = static_cast<VkShaderStageFlagBits>(1 << bit_shift);
375 const auto it = push_constant_data_update.find(flag);
376
377 if (it != push_constant_data_update.end()) {
378 if (it->second.size() < push_constant_range.offset) {
379 it->second.resize(push_constant_range.offset, PC_Byte_Not_Set);
380 }
381 if (it->second.size() < size) {
382 it->second.resize(size, PC_Byte_Not_Updated);
383 }
384 } else {
385 std::vector<uint8_t> bytes;
386 bytes.resize(push_constant_range.offset, PC_Byte_Not_Set);
387 bytes.resize(size, PC_Byte_Not_Updated);
388 push_constant_data_update[flag] = bytes;
389 }
390 }
391 stage_flags = stage_flags >> 1;
392 ++bit_shift;
393 }
394 }
395 push_constant_data.resize(size_needed, 0);
Jeremy Gebben159b3cc2021-06-03 09:09:03 -0600396}
397
398void CMD_BUFFER_STATE::Destroy() {
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600399 // Allow any derived class to clean up command buffer state
400 if (dev_data->command_buffer_reset_callback) {
401 (*dev_data->command_buffer_reset_callback)(commandBuffer());
402 }
403 if (dev_data->command_buffer_free_callback) {
404 (*dev_data->command_buffer_free_callback)(commandBuffer());
405 }
406
407 // Remove the cb debug labels
408 EraseCmdDebugUtilsLabel(dev_data->report_data, commandBuffer());
Jeremy Gebben159b3cc2021-06-03 09:09:03 -0600409 Reset();
410 BASE_NODE::Destroy();
411}
412
413void CMD_BUFFER_STATE::NotifyInvalidate(const LogObjectList &invalid_handles, bool unlink) {
414 if (state == CB_RECORDING) {
415 state = CB_INVALID_INCOMPLETE;
416 } else if (state == CB_RECORDED) {
417 state = CB_INVALID_COMPLETE;
418 }
419 assert(!invalid_handles.object_list.empty());
420 broken_bindings.emplace(invalid_handles.object_list[0], invalid_handles);
421
422 if (unlink) {
423 for (auto &obj : invalid_handles.object_list) {
424 object_bindings.erase(obj);
425 if (obj.type == kVulkanObjectTypeCommandBuffer) {
426 linkedCommandBuffers.erase(static_cast<CMD_BUFFER_STATE *>(obj.node));
427 }
428 }
429 }
430 BASE_NODE::NotifyInvalidate(invalid_handles, unlink);
431}
432
433// The const variant only need the image as it is the key for the map
434const ImageSubresourceLayoutMap *CMD_BUFFER_STATE::GetImageSubresourceLayoutMap(VkImage image) const {
435 auto it = image_layout_map.find(image);
436 if (it == image_layout_map.cend()) {
437 return nullptr;
438 }
439 return &it->second;
440}
441
442// The non-const variant only needs the image state, as the factory requires it to construct a new entry
443ImageSubresourceLayoutMap *CMD_BUFFER_STATE::GetImageSubresourceLayoutMap(const IMAGE_STATE &image_state) {
444 auto &layout_map = image_layout_map[image_state.image()];
445 if (!layout_map) {
446 // Was an empty slot... fill it in.
447 layout_map.emplace(image_state);
448 }
449 return &layout_map;
450}
451
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600452static bool SetQueryState(QueryObject object, QueryState value, QueryMap *localQueryToStateMap) {
453 (*localQueryToStateMap)[object] = value;
454 return false;
455}
456
457void CMD_BUFFER_STATE::BeginQuery(const QueryObject &query_obj) {
458 activeQueries.insert(query_obj);
459 startedQueries.insert(query_obj);
460 queryUpdates.emplace_back([query_obj](const ValidationStateTracker *device_data, bool do_validate,
461 VkQueryPool &firstPerfQueryPool, uint32_t perfQueryPass, QueryMap *localQueryToStateMap) {
462 SetQueryState(QueryObject(query_obj, perfQueryPass), QUERYSTATE_RUNNING, localQueryToStateMap);
463 return false;
464 });
465}
466
467void CMD_BUFFER_STATE::EndQuery(const QueryObject &query_obj) {
468 activeQueries.erase(query_obj);
469 queryUpdates.emplace_back([query_obj](const ValidationStateTracker *device_data, bool do_validate,
470 VkQueryPool &firstPerfQueryPool, uint32_t perfQueryPass, QueryMap *localQueryToStateMap) {
471 return SetQueryState(QueryObject(query_obj, perfQueryPass), QUERYSTATE_ENDED, localQueryToStateMap);
472 });
473}
474
475static bool SetQueryStateMulti(VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, uint32_t perfPass, QueryState value,
476 QueryMap *localQueryToStateMap) {
477 for (uint32_t i = 0; i < queryCount; i++) {
478 QueryObject object = QueryObject(QueryObject(queryPool, firstQuery + i), perfPass);
479 (*localQueryToStateMap)[object] = value;
480 }
481 return false;
482}
483
484void CMD_BUFFER_STATE::EndQueries(VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) {
485 for (uint32_t slot = firstQuery; slot < (firstQuery + queryCount); slot++) {
486 QueryObject query = {queryPool, slot};
487 activeQueries.erase(query);
488 }
489 queryUpdates.emplace_back([queryPool, firstQuery, queryCount](const ValidationStateTracker *device_data, bool do_validate,
490 VkQueryPool &firstPerfQueryPool, uint32_t perfQueryPass,
491 QueryMap *localQueryToStateMap) {
492 return SetQueryStateMulti(queryPool, firstQuery, queryCount, perfQueryPass, QUERYSTATE_RESET, localQueryToStateMap);
493 });
494}
495
496void CMD_BUFFER_STATE::ResetQueryPool(VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) {
497 for (uint32_t slot = firstQuery; slot < (firstQuery + queryCount); slot++) {
498 QueryObject query = {queryPool, slot};
499 resetQueries.insert(query);
500 }
501
502 queryUpdates.emplace_back([queryPool, firstQuery, queryCount](const ValidationStateTracker *device_data, bool do_validate,
503 VkQueryPool &firstPerfQueryPool, uint32_t perfQueryPass,
504 QueryMap *localQueryToStateMap) {
505 return SetQueryStateMulti(queryPool, firstQuery, queryCount, perfQueryPass, QUERYSTATE_RESET, localQueryToStateMap);
506 });
507}
508
509void UpdateSubpassAttachments(const safe_VkSubpassDescription2 &subpass, std::vector<SUBPASS_INFO> &subpasses) {
510 for (uint32_t index = 0; index < subpass.inputAttachmentCount; ++index) {
511 const uint32_t attachment_index = subpass.pInputAttachments[index].attachment;
512 if (attachment_index != VK_ATTACHMENT_UNUSED) {
513 subpasses[attachment_index].used = true;
514 subpasses[attachment_index].usage = VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
515 subpasses[attachment_index].layout = subpass.pInputAttachments[index].layout;
516 }
517 }
518
519 for (uint32_t index = 0; index < subpass.colorAttachmentCount; ++index) {
520 const uint32_t attachment_index = subpass.pColorAttachments[index].attachment;
521 if (attachment_index != VK_ATTACHMENT_UNUSED) {
522 subpasses[attachment_index].used = true;
523 subpasses[attachment_index].usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
524 subpasses[attachment_index].layout = subpass.pColorAttachments[index].layout;
525 }
526 if (subpass.pResolveAttachments) {
527 const uint32_t attachment_index2 = subpass.pResolveAttachments[index].attachment;
528 if (attachment_index2 != VK_ATTACHMENT_UNUSED) {
529 subpasses[attachment_index2].used = true;
530 subpasses[attachment_index2].usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
531 subpasses[attachment_index2].layout = subpass.pResolveAttachments[index].layout;
532 }
533 }
534 }
535
536 if (subpass.pDepthStencilAttachment) {
537 const uint32_t attachment_index = subpass.pDepthStencilAttachment->attachment;
538 if (attachment_index != VK_ATTACHMENT_UNUSED) {
539 subpasses[attachment_index].used = true;
540 subpasses[attachment_index].usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
541 subpasses[attachment_index].layout = subpass.pDepthStencilAttachment->layout;
542 }
543 }
544}
545
546void CMD_BUFFER_STATE::UpdateAttachmentsView(const VkRenderPassBeginInfo *pRenderPassBegin) {
547 auto &attachments = *(active_attachments.get());
548 const bool imageless = (activeFramebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) ? true : false;
549 const VkRenderPassAttachmentBeginInfo *attachment_info_struct = nullptr;
550 if (pRenderPassBegin) attachment_info_struct = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
551
552 for (uint32_t i = 0; i < attachments.size(); ++i) {
553 if (imageless) {
554 if (attachment_info_struct && i < attachment_info_struct->attachmentCount) {
555 auto res =
556 attachments_view_states.insert(dev_data->GetShared<IMAGE_VIEW_STATE>(attachment_info_struct->pAttachments[i]));
557 attachments[i] = res.first->get();
558 }
559 } else {
560 auto res = attachments_view_states.insert(activeFramebuffer->attachments_view_state[i]);
561 attachments[i] = res.first->get();
562 }
563 }
564}
565
Jeremy Gebben10a0ed12021-08-17 09:54:29 -0600566void CMD_BUFFER_STATE::BeginRenderPass(CMD_TYPE cmd_type, const VkRenderPassBeginInfo *pRenderPassBegin,
567 const VkSubpassContents contents) {
568 RecordCmd(cmd_type);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600569 activeFramebuffer = dev_data->GetShared<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
570 activeRenderPass = dev_data->GetShared<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
571 activeRenderPassBeginInfo = safe_VkRenderPassBeginInfo(pRenderPassBegin);
572 activeSubpass = 0;
573 activeSubpassContents = contents;
574
575 // Connect this RP to cmdBuffer
576 if (!dev_data->disabled[command_buffer_state] && activeRenderPass) {
577 AddChild(activeRenderPass.get());
578 }
579
580 auto chained_device_group_struct = LvlFindInChain<VkDeviceGroupRenderPassBeginInfo>(pRenderPassBegin->pNext);
581 if (chained_device_group_struct) {
582 active_render_pass_device_mask = chained_device_group_struct->deviceMask;
583 } else {
584 active_render_pass_device_mask = initial_device_mask;
585 }
586
587 active_subpasses = nullptr;
588 active_attachments = nullptr;
589
590 if (activeFramebuffer) {
591 framebuffers.insert(activeFramebuffer);
592
593 // Set cb_state->active_subpasses
594 active_subpasses = std::make_shared<std::vector<SUBPASS_INFO>>(activeFramebuffer->createInfo.attachmentCount);
595 const auto &subpass = activeRenderPass->createInfo.pSubpasses[activeSubpass];
596 UpdateSubpassAttachments(subpass, *active_subpasses);
597
598 // Set cb_state->active_attachments & cb_state->attachments_view_states
599 active_attachments = std::make_shared<std::vector<IMAGE_VIEW_STATE *>>(activeFramebuffer->createInfo.attachmentCount);
600 UpdateAttachmentsView(pRenderPassBegin);
601
602 // Connect this framebuffer and its children to this cmdBuffer
603 AddChild(activeFramebuffer.get());
604 }
605}
606
Jeremy Gebben10a0ed12021-08-17 09:54:29 -0600607void CMD_BUFFER_STATE::NextSubpass(CMD_TYPE cmd_type, VkSubpassContents contents) {
608 RecordCmd(cmd_type);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600609 activeSubpass++;
610 activeSubpassContents = contents;
611
612 // Update cb_state->active_subpasses
613 if (activeRenderPass && activeFramebuffer) {
614 active_subpasses = nullptr;
615 active_subpasses = std::make_shared<std::vector<SUBPASS_INFO>>(activeFramebuffer->createInfo.attachmentCount);
616
617 const auto &subpass = activeRenderPass->createInfo.pSubpasses[activeSubpass];
618 UpdateSubpassAttachments(subpass, *active_subpasses);
619 }
620}
621
Jeremy Gebben10a0ed12021-08-17 09:54:29 -0600622void CMD_BUFFER_STATE::EndRenderPass(CMD_TYPE cmd_type) {
623 RecordCmd(cmd_type);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600624 activeRenderPass = nullptr;
625 active_attachments = nullptr;
626 active_subpasses = nullptr;
627 activeSubpass = 0;
628 activeFramebuffer = VK_NULL_HANDLE;
629}
630
631void CMD_BUFFER_STATE::Begin(const VkCommandBufferBeginInfo *pBeginInfo) {
632 if (CB_RECORDED == state || CB_INVALID_COMPLETE == state) {
633 Reset();
634 }
635 // Set updated state here in case implicit reset occurs above
636 state = CB_RECORDING;
637 beginInfo = *pBeginInfo;
638 if (beginInfo.pInheritanceInfo && (createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY)) {
639 inheritanceInfo = *(beginInfo.pInheritanceInfo);
640 beginInfo.pInheritanceInfo = &inheritanceInfo;
641 // If we are a secondary command-buffer and inheriting. Update the items we should inherit.
642 if ((createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) &&
643 (beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) {
644 activeRenderPass = dev_data->GetShared<RENDER_PASS_STATE>(beginInfo.pInheritanceInfo->renderPass);
645 activeSubpass = beginInfo.pInheritanceInfo->subpass;
646
647 if (beginInfo.pInheritanceInfo->framebuffer) {
648 activeFramebuffer = dev_data->GetShared<FRAMEBUFFER_STATE>(beginInfo.pInheritanceInfo->framebuffer);
649 active_subpasses = nullptr;
650 active_attachments = nullptr;
651
652 if (activeFramebuffer) {
653 framebuffers.insert(activeFramebuffer);
654
655 // Set active_subpasses
656 active_subpasses = std::make_shared<std::vector<SUBPASS_INFO>>(activeFramebuffer->createInfo.attachmentCount);
657 const auto &subpass = activeRenderPass->createInfo.pSubpasses[activeSubpass];
658 UpdateSubpassAttachments(subpass, *active_subpasses);
659
660 // Set active_attachments & attachments_view_states
661 active_attachments =
662 std::make_shared<std::vector<IMAGE_VIEW_STATE *>>(activeFramebuffer->createInfo.attachmentCount);
663 UpdateAttachmentsView(nullptr);
664
665 // Connect this framebuffer and its children to this cmdBuffer
666 if (!dev_data->disabled[command_buffer_state]) {
667 AddChild(activeFramebuffer.get());
668 }
669 }
670 }
671
672 // Check for VkCommandBufferInheritanceViewportScissorInfoNV (VK_NV_inherited_viewport_scissor)
673 auto p_inherited_viewport_scissor_info =
674 LvlFindInChain<VkCommandBufferInheritanceViewportScissorInfoNV>(beginInfo.pInheritanceInfo->pNext);
675 if (p_inherited_viewport_scissor_info != nullptr && p_inherited_viewport_scissor_info->viewportScissor2D) {
676 auto pViewportDepths = p_inherited_viewport_scissor_info->pViewportDepths;
677 inheritedViewportDepths.assign(pViewportDepths,
678 pViewportDepths + p_inherited_viewport_scissor_info->viewportDepthCount);
679 }
680 }
681 }
682
683 auto chained_device_group_struct = LvlFindInChain<VkDeviceGroupCommandBufferBeginInfo>(pBeginInfo->pNext);
684 if (chained_device_group_struct) {
685 initial_device_mask = chained_device_group_struct->deviceMask;
686 } else {
687 initial_device_mask = (1 << dev_data->physical_device_count) - 1;
688 }
689 performance_lock_acquired = dev_data->performance_lock_acquired;
690}
691
692void CMD_BUFFER_STATE::End(VkResult result) {
693 // Cached validation is specific to a specific recording of a specific command buffer.
694 for (auto *descriptor_set : validated_descriptor_sets) {
695 descriptor_set->ClearCachedValidation(this);
696 }
697 validated_descriptor_sets.clear();
698 if (VK_SUCCESS == result) {
699 state = CB_RECORDED;
700 }
701}
702
703void CMD_BUFFER_STATE::ExecuteCommands(uint32_t commandBuffersCount, const VkCommandBuffer *pCommandBuffers) {
Jeremy Gebben10a0ed12021-08-17 09:54:29 -0600704 RecordCmd(CMD_EXECUTECOMMANDS);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600705 CMD_BUFFER_STATE *sub_cb_state = NULL;
706 for (uint32_t i = 0; i < commandBuffersCount; i++) {
Jeremy Gebben3d22d582021-08-11 15:37:58 -0600707 sub_cb_state = dev_data->Get<CMD_BUFFER_STATE>(pCommandBuffers[i]);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600708 assert(sub_cb_state);
709 if (!(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) {
710 if (beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
711 // TODO: Because this is a state change, clearing the VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT needs to be moved
712 // from the validation step to the recording step
713 beginInfo.flags &= ~VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
714 }
715 }
716
717 // Propagate inital layout and current layout state to the primary cmd buffer
718 // NOTE: The update/population of the image_layout_map is done in CoreChecks, but for other classes derived from
719 // ValidationStateTracker these maps will be empty, so leaving the propagation in the the state tracker should be a no-op
720 // for those other classes.
721 for (const auto &sub_layout_map_entry : sub_cb_state->image_layout_map) {
722 const auto image = sub_layout_map_entry.first;
723 const IMAGE_STATE *image_state = dev_data->GetImageState(image);
724 if (!image_state) continue; // Can't set layouts of a dead image
725
726 auto *cb_subres_map = GetImageSubresourceLayoutMap(*image_state);
727 const auto *sub_cb_subres_map = &sub_layout_map_entry.second;
728 assert(cb_subres_map && sub_cb_subres_map); // Non const get and map traversal should never be null
729 cb_subres_map->UpdateFrom(*sub_cb_subres_map);
730 }
731
732 sub_cb_state->primaryCommandBuffer = commandBuffer();
733 linkedCommandBuffers.insert(sub_cb_state);
734 AddChild(sub_cb_state);
735 for (auto &function : sub_cb_state->queryUpdates) {
736 queryUpdates.push_back(function);
737 }
738 for (auto &function : sub_cb_state->queue_submit_functions) {
739 queue_submit_functions.push_back(function);
740 }
741
742 // State is trashed after executing secondary command buffers.
743 // Importantly, this function runs after CoreChecks::PreCallValidateCmdExecuteCommands.
744 trashedViewportMask = ~uint32_t(0);
745 trashedScissorMask = ~uint32_t(0);
746 trashedViewportCount = true;
747 trashedScissorCount = true;
748 }
749}
750
751void CMD_BUFFER_STATE::PushDescriptorSetState(VkPipelineBindPoint pipelineBindPoint, PIPELINE_LAYOUT_STATE *pipeline_layout,
752 uint32_t set, uint32_t descriptorWriteCount,
753 const VkWriteDescriptorSet *pDescriptorWrites) {
754 // Short circuit invalid updates
755 if (!pipeline_layout || (set >= pipeline_layout->set_layouts.size()) || !pipeline_layout->set_layouts[set] ||
756 !pipeline_layout->set_layouts[set]->IsPushDescriptor()) {
757 return;
758 }
759
760 // We need a descriptor set to update the bindings with, compatible with the passed layout
761 const auto &dsl = pipeline_layout->set_layouts[set];
762 const auto lv_bind_point = ConvertToLvlBindPoint(pipelineBindPoint);
763 auto &last_bound = lastBound[lv_bind_point];
764 auto &push_descriptor_set = last_bound.push_descriptor_set;
765 // If we are disturbing the current push_desriptor_set clear it
766 if (!push_descriptor_set || !CompatForSet(set, last_bound, pipeline_layout->compat_for_set)) {
767 last_bound.UnbindAndResetPushDescriptorSet(this, new cvdescriptorset::DescriptorSet(0, nullptr, dsl, 0, dev_data));
768 }
769
770 UpdateLastBoundDescriptorSets(pipelineBindPoint, pipeline_layout, set, 1, nullptr, push_descriptor_set.get(), 0, nullptr);
771 last_bound.pipeline_layout = pipeline_layout->layout();
772
773 // Now that we have either the new or extant push_descriptor set ... do the write updates against it
774 push_descriptor_set->PerformPushDescriptorsUpdate(dev_data, descriptorWriteCount, pDescriptorWrites);
775}
776
777// Generic function to handle state update for all CmdDraw* and CmdDispatch* type functions
sfricke-samsung85584a72021-09-30 21:43:38 -0700778void CMD_BUFFER_STATE::UpdateStateCmdDrawDispatchType(CMD_TYPE cmd_type, VkPipelineBindPoint bind_point) {
779 UpdateDrawState(cmd_type, bind_point);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600780 hasDispatchCmd = true;
781}
782
783// Generic function to handle state update for all CmdDraw* type functions
sfricke-samsung85584a72021-09-30 21:43:38 -0700784void CMD_BUFFER_STATE::UpdateStateCmdDrawType(CMD_TYPE cmd_type, VkPipelineBindPoint bind_point) {
785 UpdateStateCmdDrawDispatchType(cmd_type, bind_point);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600786 hasDrawCmd = true;
787
788 // Update the consumed viewport/scissor count.
789 uint32_t &used = usedViewportScissorCount;
790 used = std::max(used, pipelineStaticViewportCount);
791 used = std::max(used, pipelineStaticScissorCount);
792 usedDynamicViewportCount |= !!(dynamic_status & CBSTATUS_VIEWPORT_WITH_COUNT_SET); // !! silences MSVC warn
793 usedDynamicScissorCount |= !!(dynamic_status & CBSTATUS_SCISSOR_WITH_COUNT_SET);
794}
795
sfricke-samsung85584a72021-09-30 21:43:38 -0700796void CMD_BUFFER_STATE::UpdateDrawState(CMD_TYPE cmd_type, const VkPipelineBindPoint bind_point) {
Jeremy Gebben10a0ed12021-08-17 09:54:29 -0600797 RecordCmd(cmd_type);
798
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600799 const auto lv_bind_point = ConvertToLvlBindPoint(bind_point);
800 auto &state = lastBound[lv_bind_point];
801 PIPELINE_STATE *pipe = state.pipeline_state;
802 if (VK_NULL_HANDLE != state.pipeline_layout) {
803 for (const auto &set_binding_pair : pipe->active_slots) {
804 uint32_t set_index = set_binding_pair.first;
805 // Pull the set node
806 cvdescriptorset::DescriptorSet *descriptor_set = state.per_set[set_index].bound_descriptor_set;
807
808 // For the "bindless" style resource usage with many descriptors, need to optimize command <-> descriptor binding
809
810 // TODO: If recreating the reduced_map here shows up in profilinging, need to find a way of sharing with the
811 // Validate pass. Though in the case of "many" descriptors, typically the descriptor count >> binding count
812 cvdescriptorset::PrefilterBindRequestMap reduced_map(*descriptor_set, set_binding_pair.second);
813 const auto &binding_req_map = reduced_map.FilteredMap(*this, *pipe);
814
815 if (reduced_map.IsManyDescriptors()) {
816 // Only update validate binding tags if we meet the "many" criteria in the Prefilter class
817 descriptor_set->UpdateValidationCache(*this, *pipe, binding_req_map);
818 }
819
820 // We can skip updating the state if "nothing" has changed since the last validation.
821 // See CoreChecks::ValidateCmdBufDrawState for more details.
822 bool descriptor_set_changed =
823 !reduced_map.IsManyDescriptors() ||
824 // Update if descriptor set (or contents) has changed
825 state.per_set[set_index].validated_set != descriptor_set ||
826 state.per_set[set_index].validated_set_change_count != descriptor_set->GetChangeCount() ||
827 (!dev_data->disabled[image_layout_validation] &&
828 state.per_set[set_index].validated_set_image_layout_change_count != image_layout_change_count);
829 bool need_update = descriptor_set_changed ||
830 // Update if previous bindingReqMap doesn't include new bindingReqMap
831 !std::includes(state.per_set[set_index].validated_set_binding_req_map.begin(),
832 state.per_set[set_index].validated_set_binding_req_map.end(), binding_req_map.begin(),
833 binding_req_map.end());
834
835 if (need_update) {
836 // Bind this set and its active descriptor resources to the command buffer
837 if (!descriptor_set_changed && reduced_map.IsManyDescriptors()) {
838 // Only record the bindings that haven't already been recorded
839 BindingReqMap delta_reqs;
840 std::set_difference(binding_req_map.begin(), binding_req_map.end(),
841 state.per_set[set_index].validated_set_binding_req_map.begin(),
842 state.per_set[set_index].validated_set_binding_req_map.end(),
843 layer_data::insert_iterator<BindingReqMap>(delta_reqs, delta_reqs.begin()));
sfricke-samsung85584a72021-09-30 21:43:38 -0700844 descriptor_set->UpdateDrawState(dev_data, this, cmd_type, pipe, delta_reqs);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600845 } else {
sfricke-samsung85584a72021-09-30 21:43:38 -0700846 descriptor_set->UpdateDrawState(dev_data, this, cmd_type, pipe, binding_req_map);
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600847 }
848
849 state.per_set[set_index].validated_set = descriptor_set;
850 state.per_set[set_index].validated_set_change_count = descriptor_set->GetChangeCount();
851 state.per_set[set_index].validated_set_image_layout_change_count = image_layout_change_count;
852 if (reduced_map.IsManyDescriptors()) {
853 // Check whether old == new before assigning, the equality check is much cheaper than
854 // freeing and reallocating the map.
855 if (state.per_set[set_index].validated_set_binding_req_map != set_binding_pair.second) {
856 state.per_set[set_index].validated_set_binding_req_map = set_binding_pair.second;
857 }
858 } else {
859 state.per_set[set_index].validated_set_binding_req_map = BindingReqMap();
860 }
861 }
862 }
863 }
ziga-lunarg4898e4f2021-10-03 13:57:48 +0200864 if (pipe && !pipe->vertex_binding_descriptions_.empty()) {
Jeremy Gebben1ec89332021-08-05 13:51:49 -0600865 vertex_buffer_used = true;
866 }
867}
868
869// Update pipeline_layout bind points applying the "Pipeline Layout Compatibility" rules.
870// One of pDescriptorSets or push_descriptor_set should be nullptr, indicating whether this
871// is called for CmdBindDescriptorSets or CmdPushDescriptorSet.
872void CMD_BUFFER_STATE::UpdateLastBoundDescriptorSets(VkPipelineBindPoint pipeline_bind_point,
873 const PIPELINE_LAYOUT_STATE *pipeline_layout, uint32_t first_set,
874 uint32_t set_count, const VkDescriptorSet *pDescriptorSets,
875 cvdescriptorset::DescriptorSet *push_descriptor_set,
876 uint32_t dynamic_offset_count, const uint32_t *p_dynamic_offsets) {
877 assert((pDescriptorSets == nullptr) ^ (push_descriptor_set == nullptr));
878 // Defensive
879 assert(pipeline_layout);
880 if (!pipeline_layout) return;
881
882 uint32_t required_size = first_set + set_count;
883 const uint32_t last_binding_index = required_size - 1;
884 assert(last_binding_index < pipeline_layout->compat_for_set.size());
885
886 // Some useful shorthand
887 const auto lv_bind_point = ConvertToLvlBindPoint(pipeline_bind_point);
888 auto &last_bound = lastBound[lv_bind_point];
889 auto &pipe_compat_ids = pipeline_layout->compat_for_set;
890 const uint32_t current_size = static_cast<uint32_t>(last_bound.per_set.size());
891
892 // We need this three times in this function, but nowhere else
893 auto push_descriptor_cleanup = [&last_bound](const cvdescriptorset::DescriptorSet *ds) -> bool {
894 if (ds && ds->IsPushDescriptor()) {
895 assert(ds == last_bound.push_descriptor_set.get());
896 last_bound.push_descriptor_set = nullptr;
897 return true;
898 }
899 return false;
900 };
901
902 // Clean up the "disturbed" before and after the range to be set
903 if (required_size < current_size) {
904 if (last_bound.per_set[last_binding_index].compat_id_for_set != pipe_compat_ids[last_binding_index]) {
905 // We're disturbing those after last, we'll shrink below, but first need to check for and cleanup the push_descriptor
906 for (auto set_idx = required_size; set_idx < current_size; ++set_idx) {
907 if (push_descriptor_cleanup(last_bound.per_set[set_idx].bound_descriptor_set)) break;
908 }
909 } else {
910 // We're not disturbing past last, so leave the upper binding data alone.
911 required_size = current_size;
912 }
913 }
914
915 // We resize if we need more set entries or if those past "last" are disturbed
916 if (required_size != current_size) {
917 last_bound.per_set.resize(required_size);
918 }
919
920 // For any previously bound sets, need to set them to "invalid" if they were disturbed by this update
921 for (uint32_t set_idx = 0; set_idx < first_set; ++set_idx) {
922 if (last_bound.per_set[set_idx].compat_id_for_set != pipe_compat_ids[set_idx]) {
923 push_descriptor_cleanup(last_bound.per_set[set_idx].bound_descriptor_set);
924 last_bound.per_set[set_idx].bound_descriptor_set = nullptr;
925 last_bound.per_set[set_idx].dynamicOffsets.clear();
926 last_bound.per_set[set_idx].compat_id_for_set = pipe_compat_ids[set_idx];
927 }
928 }
929
930 // Now update the bound sets with the input sets
931 const uint32_t *input_dynamic_offsets = p_dynamic_offsets; // "read" pointer for dynamic offset data
932 for (uint32_t input_idx = 0; input_idx < set_count; input_idx++) {
933 auto set_idx = input_idx + first_set; // set_idx is index within layout, input_idx is index within input descriptor sets
934 cvdescriptorset::DescriptorSet *descriptor_set =
935 push_descriptor_set ? push_descriptor_set : dev_data->GetSetNode(pDescriptorSets[input_idx]);
936
937 // Record binding (or push)
938 if (descriptor_set != last_bound.push_descriptor_set.get()) {
939 // Only cleanup the push descriptors if they aren't the currently used set.
940 push_descriptor_cleanup(last_bound.per_set[set_idx].bound_descriptor_set);
941 }
942 last_bound.per_set[set_idx].bound_descriptor_set = descriptor_set;
943 last_bound.per_set[set_idx].compat_id_for_set = pipe_compat_ids[set_idx]; // compat ids are canonical *per* set index
944
945 if (descriptor_set) {
946 auto set_dynamic_descriptor_count = descriptor_set->GetDynamicDescriptorCount();
947 // TODO: Add logic for tracking push_descriptor offsets (here or in caller)
948 if (set_dynamic_descriptor_count && input_dynamic_offsets) {
949 const uint32_t *end_offset = input_dynamic_offsets + set_dynamic_descriptor_count;
950 last_bound.per_set[set_idx].dynamicOffsets = std::vector<uint32_t>(input_dynamic_offsets, end_offset);
951 input_dynamic_offsets = end_offset;
952 assert(input_dynamic_offsets <= (p_dynamic_offsets + dynamic_offset_count));
953 } else {
954 last_bound.per_set[set_idx].dynamicOffsets.clear();
955 }
956 if (!descriptor_set->IsPushDescriptor()) {
957 // Can't cache validation of push_descriptors
958 validated_descriptor_sets.insert(descriptor_set);
959 }
960 }
961 }
962}
963
964// Set image layout for given VkImageSubresourceRange struct
965void CMD_BUFFER_STATE::SetImageLayout(const IMAGE_STATE &image_state, const VkImageSubresourceRange &image_subresource_range,
966 VkImageLayout layout, VkImageLayout expected_layout) {
967 auto *subresource_map = GetImageSubresourceLayoutMap(image_state);
968 assert(subresource_map); // the non-const getter must return a valid pointer
969 if (subresource_map->SetSubresourceRangeLayout(*this, image_subresource_range, layout, expected_layout)) {
970 image_layout_change_count++; // Change the version of this data to force revalidation
971 }
972 for (const auto *alias_state : image_state.aliasing_images) {
973 assert(alias_state);
974 // The map state of the aliases should all be in sync, so no need to check the return value
975 subresource_map = GetImageSubresourceLayoutMap(*alias_state);
976 assert(subresource_map);
977 subresource_map->SetSubresourceRangeLayout(*this, image_subresource_range, layout, expected_layout);
978 }
979}
980
981// Set the initial image layout for all slices of an image view
982void CMD_BUFFER_STATE::SetImageViewInitialLayout(const IMAGE_VIEW_STATE &view_state, VkImageLayout layout) {
983 if (dev_data->disabled[image_layout_validation]) {
984 return;
985 }
986 IMAGE_STATE *image_state = view_state.image_state.get();
987 auto *subresource_map = GetImageSubresourceLayoutMap(*image_state);
988 subresource_map->SetSubresourceRangeInitialLayout(*this, layout, view_state);
989 for (const auto *alias_state : image_state->aliasing_images) {
990 assert(alias_state);
991 subresource_map = GetImageSubresourceLayoutMap(*alias_state);
992 subresource_map->SetSubresourceRangeInitialLayout(*this, layout, view_state);
993 }
994}
995
996// Set the initial image layout for a passed non-normalized subresource range
997void CMD_BUFFER_STATE::SetImageInitialLayout(const IMAGE_STATE &image_state, const VkImageSubresourceRange &range,
998 VkImageLayout layout) {
999 auto *subresource_map = GetImageSubresourceLayoutMap(image_state);
1000 assert(subresource_map);
1001 subresource_map->SetSubresourceRangeInitialLayout(*this, image_state.NormalizeSubresourceRange(range), layout);
1002 for (const auto *alias_state : image_state.aliasing_images) {
1003 assert(alias_state);
1004 subresource_map = GetImageSubresourceLayoutMap(*alias_state);
1005 assert(subresource_map);
1006 subresource_map->SetSubresourceRangeInitialLayout(*this, alias_state->NormalizeSubresourceRange(range), layout);
1007 }
1008}
1009
1010void CMD_BUFFER_STATE::SetImageInitialLayout(VkImage image, const VkImageSubresourceRange &range, VkImageLayout layout) {
1011 const IMAGE_STATE *image_state = dev_data->GetImageState(image);
1012 if (!image_state) return;
1013 SetImageInitialLayout(*image_state, range, layout);
1014}
1015
1016void CMD_BUFFER_STATE::SetImageInitialLayout(const IMAGE_STATE &image_state, const VkImageSubresourceLayers &layers,
1017 VkImageLayout layout) {
1018 SetImageInitialLayout(image_state, RangeFromLayers(layers), layout);
1019}
1020
1021// Set image layout for all slices of an image view
1022void CMD_BUFFER_STATE::SetImageViewLayout(const IMAGE_VIEW_STATE &view_state, VkImageLayout layout, VkImageLayout layoutStencil) {
1023 const IMAGE_STATE *image_state = view_state.image_state.get();
1024
1025 VkImageSubresourceRange sub_range = view_state.normalized_subresource_range;
1026
1027 if (sub_range.aspectMask == (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) && layoutStencil != kInvalidLayout) {
1028 sub_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1029 SetImageLayout(*image_state, sub_range, layout);
1030 sub_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
1031 SetImageLayout(*image_state, sub_range, layoutStencil);
1032 } else {
1033 SetImageLayout(*image_state, sub_range, layout);
1034 }
1035}
Jeremy Gebben10a0ed12021-08-17 09:54:29 -06001036
1037void CMD_BUFFER_STATE::RecordCmd(CMD_TYPE cmd_type) { commandCount++; }
1038
1039void CMD_BUFFER_STATE::RecordStateCmd(CMD_TYPE cmd_type, CBStatusFlags state_bits) {
1040 RecordCmd(cmd_type);
1041 status |= state_bits;
1042 static_status &= ~state_bits;
1043}
1044
1045void CMD_BUFFER_STATE::RecordTransferCmd(CMD_TYPE cmd_type, BINDABLE *buf1, BINDABLE *buf2) {
1046 RecordCmd(cmd_type);
1047 if (buf1) {
1048 AddChild(buf1);
1049 }
1050 if (buf2) {
1051 AddChild(buf2);
1052 }
1053}
Jeremy Gebben29110d22021-08-17 13:30:50 -06001054
1055static bool SetEventStageMask(VkEvent event, VkPipelineStageFlags2KHR stageMask, EventToStageMap *localEventToStageMap) {
1056 (*localEventToStageMap)[event] = stageMask;
1057 return false;
1058}
1059
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001060void CMD_BUFFER_STATE::RecordSetEvent(CMD_TYPE cmd_type, VkEvent event, VkPipelineStageFlags2KHR stageMask) {
1061 RecordCmd(cmd_type);
1062 if (!dev_data->disabled[command_buffer_state]) {
1063 auto event_state = dev_data->GetEventState(event);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001064 if (event_state) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001065 AddChild(event_state);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001066 }
1067 }
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001068 events.push_back(event);
1069 if (!waitedEvents.count(event)) {
1070 writeEventsBeforeWait.push_back(event);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001071 }
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001072 eventUpdates.emplace_back(
Jeremy Gebben29110d22021-08-17 13:30:50 -06001073 [event, stageMask](const ValidationStateTracker *device_data, bool do_validate, EventToStageMap *localEventToStageMap) {
1074 return SetEventStageMask(event, stageMask, localEventToStageMap);
1075 });
1076}
1077
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001078void CMD_BUFFER_STATE::RecordResetEvent(CMD_TYPE cmd_type, VkEvent event, VkPipelineStageFlags2KHR stageMask) {
1079 RecordCmd(cmd_type);
1080 if (!dev_data->disabled[command_buffer_state]) {
1081 auto event_state = dev_data->GetEventState(event);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001082 if (event_state) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001083 AddChild(event_state);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001084 }
1085 }
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001086 events.push_back(event);
1087 if (!waitedEvents.count(event)) {
1088 writeEventsBeforeWait.push_back(event);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001089 }
1090
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001091 eventUpdates.emplace_back([event](const ValidationStateTracker *, bool do_validate, EventToStageMap *localEventToStageMap) {
1092 return SetEventStageMask(event, VkPipelineStageFlags2KHR(0), localEventToStageMap);
1093 });
Jeremy Gebben29110d22021-08-17 13:30:50 -06001094}
1095
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001096void CMD_BUFFER_STATE::RecordWaitEvents(CMD_TYPE cmd_type, uint32_t eventCount, const VkEvent *pEvents) {
1097 RecordCmd(cmd_type);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001098 for (uint32_t i = 0; i < eventCount; ++i) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001099 if (!dev_data->disabled[command_buffer_state]) {
1100 auto event_state = dev_data->GetEventState(pEvents[i]);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001101 if (event_state) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001102 AddChild(event_state);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001103 }
1104 }
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001105 waitedEvents.insert(pEvents[i]);
1106 events.push_back(pEvents[i]);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001107 }
1108}
1109
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001110void CMD_BUFFER_STATE::RecordBarriers(uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
1111 uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
1112 uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) {
1113 if (dev_data->disabled[command_buffer_state]) return;
Jeremy Gebben29110d22021-08-17 13:30:50 -06001114
Jeremy Gebben29110d22021-08-17 13:30:50 -06001115 for (uint32_t i = 0; i < bufferMemoryBarrierCount; i++) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001116 auto buffer_state = dev_data->GetBufferState(pBufferMemoryBarriers[i].buffer);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001117 if (buffer_state) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001118 AddChild(buffer_state);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001119 }
1120 }
1121 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001122 auto image_state = dev_data->GetImageState(pImageMemoryBarriers[i].image);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001123 if (image_state) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001124 AddChild(image_state);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001125 }
1126 }
1127}
1128
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001129void CMD_BUFFER_STATE::RecordBarriers(const VkDependencyInfoKHR &dep_info) {
1130 if (dev_data->disabled[command_buffer_state]) return;
Jeremy Gebben29110d22021-08-17 13:30:50 -06001131
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001132 for (uint32_t i = 0; i < dep_info.bufferMemoryBarrierCount; i++) {
1133 auto buffer_state = dev_data->GetBufferState(dep_info.pBufferMemoryBarriers[i].buffer);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001134 if (buffer_state) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001135 AddChild(buffer_state);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001136 }
1137 }
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001138 for (uint32_t i = 0; i < dep_info.imageMemoryBarrierCount; i++) {
1139 auto image_state = dev_data->GetImageState(dep_info.pImageMemoryBarriers[i].image);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001140 if (image_state) {
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001141 AddChild(image_state);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001142 }
1143 }
1144}
1145
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001146void CMD_BUFFER_STATE::RecordWriteTimestamp(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR pipelineStage, VkQueryPool queryPool,
1147 uint32_t slot) {
1148 RecordCmd(cmd_type);
1149 if (dev_data->disabled[query_validation]) return;
1150
1151 if (!dev_data->disabled[command_buffer_state]) {
1152 auto pool_state = dev_data->GetQueryPoolState(queryPool);
1153 AddChild(pool_state);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001154 }
1155 QueryObject query = {queryPool, slot};
Jeremy Gebbencefa7fd2021-08-17 13:44:47 -06001156 EndQuery(query);
Jeremy Gebben29110d22021-08-17 13:30:50 -06001157}