blob: 8c753da101d1323d9aa6524bf67058c10f1a03da [file] [log] [blame]
Karl Schultz7b024b42018-08-30 16:18:18 -06001/* Copyright (c) 2018-2019 The Khronos Group Inc.
2 * Copyright (c) 2018-2019 Valve Corporation
3 * Copyright (c) 2018-2019 LunarG, Inc.
4 * Copyright (C) 2018-2019 Google Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 */
19
20// Allow use of STL min and max functions in Windows
21#define NOMINMAX
22
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070023#include "chassis.h"
Karl Schultz7b024b42018-08-30 16:18:18 -060024#include "core_validation.h"
Tony-LunarG0e564722019-03-19 16:09:14 -060025// This define indicates to build the VMA routines themselves
26#define VMA_IMPLEMENTATION
27// This define indicates that we will supply Vulkan function pointers at initialization
28#define VMA_STATIC_VULKAN_FUNCTIONS 0
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070029#include "gpu_validation.h"
Karl Schultz7b024b42018-08-30 16:18:18 -060030#include "shader_validation.h"
Karl Schultz7b024b42018-08-30 16:18:18 -060031#include "spirv-tools/libspirv.h"
32#include "spirv-tools/optimizer.hpp"
33#include "spirv-tools/instrument.hpp"
34#include <SPIRV/spirv.hpp>
35#include <algorithm>
36#include <regex>
37
38// This is the number of bindings in the debug descriptor set.
Tony-LunarG1b2e0c32019-02-07 17:13:27 -070039static const uint32_t kNumBindingsInSet = 2;
Karl Schultz7b024b42018-08-30 16:18:18 -060040
Karl Schultz7b024b42018-08-30 16:18:18 -060041// Implementation for Descriptor Set Manager class
Mark Lobodzinski586d10e2019-03-08 18:19:48 -070042GpuDescriptorSetManager::GpuDescriptorSetManager(CoreChecks *dev_data) { dev_data_ = dev_data; }
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070043
44GpuDescriptorSetManager::~GpuDescriptorSetManager() {
45 for (auto &pool : desc_pool_map_) {
Tony-LunarG152a88b2019-03-20 15:42:24 -060046 DispatchDestroyDescriptorPool(dev_data_->device, pool.first, NULL);
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070047 }
48 desc_pool_map_.clear();
49}
50
Karl Schultz7b024b42018-08-30 16:18:18 -060051VkResult GpuDescriptorSetManager::GetDescriptorSets(uint32_t count, VkDescriptorPool *pool,
52 std::vector<VkDescriptorSet> *desc_sets) {
Karl Schultz7b024b42018-08-30 16:18:18 -060053 const uint32_t default_pool_size = kItemsPerChunk;
54 VkResult result = VK_SUCCESS;
55 VkDescriptorPool pool_to_use = VK_NULL_HANDLE;
56
57 if (0 == count) {
58 return result;
59 }
60 desc_sets->clear();
61 desc_sets->resize(count);
62
63 for (auto &pool : desc_pool_map_) {
64 if (pool.second.used + count < pool.second.size) {
65 pool_to_use = pool.first;
66 break;
67 }
68 }
69 if (VK_NULL_HANDLE == pool_to_use) {
70 uint32_t pool_count = default_pool_size;
71 if (count > default_pool_size) {
72 pool_count = count;
73 }
74 const VkDescriptorPoolSize size_counts = {
75 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
76 pool_count * kNumBindingsInSet,
77 };
78 VkDescriptorPoolCreateInfo desc_pool_info = {};
79 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
80 desc_pool_info.pNext = NULL;
81 desc_pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
82 desc_pool_info.maxSets = pool_count;
83 desc_pool_info.poolSizeCount = 1;
84 desc_pool_info.pPoolSizes = &size_counts;
Tony-LunarG152a88b2019-03-20 15:42:24 -060085 result = DispatchCreateDescriptorPool(dev_data_->device, &desc_pool_info, NULL, &pool_to_use);
Karl Schultz7b024b42018-08-30 16:18:18 -060086 assert(result == VK_SUCCESS);
87 if (result != VK_SUCCESS) {
88 return result;
89 }
90 desc_pool_map_[pool_to_use].size = desc_pool_info.maxSets;
91 desc_pool_map_[pool_to_use].used = 0;
92 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -060093 std::vector<VkDescriptorSetLayout> desc_layouts(count, dev_data_->gpu_validation_state->debug_desc_layout);
Karl Schultz7b024b42018-08-30 16:18:18 -060094
95 VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool_to_use, count,
96 desc_layouts.data()};
97
Tony-LunarG152a88b2019-03-20 15:42:24 -060098 result = DispatchAllocateDescriptorSets(dev_data_->device, &alloc_info, desc_sets->data());
Karl Schultz7b024b42018-08-30 16:18:18 -060099 assert(result == VK_SUCCESS);
100 if (result != VK_SUCCESS) {
101 return result;
102 }
103 *pool = pool_to_use;
104 desc_pool_map_[pool_to_use].used += count;
105 return result;
106}
107
108void GpuDescriptorSetManager::PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set) {
109 auto iter = desc_pool_map_.find(desc_pool);
110 if (iter != desc_pool_map_.end()) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600111 VkResult result = DispatchFreeDescriptorSets(dev_data_->device, desc_pool, 1, &desc_set);
Karl Schultz7b024b42018-08-30 16:18:18 -0600112 assert(result == VK_SUCCESS);
113 if (result != VK_SUCCESS) {
114 return;
115 }
116 desc_pool_map_[desc_pool].used--;
117 if (0 == desc_pool_map_[desc_pool].used) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600118 DispatchDestroyDescriptorPool(dev_data_->device, desc_pool, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600119 desc_pool_map_.erase(desc_pool);
120 }
121 }
122 return;
123}
124
Tony-LunarG0e564722019-03-19 16:09:14 -0600125// Trampolines to make VMA call Dispatch for Vulkan calls
126static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
127 VkPhysicalDeviceProperties *pProperties) {
128 DispatchGetPhysicalDeviceProperties(physicalDevice, pProperties);
129}
130static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceMemoryProperties(VkPhysicalDevice physicalDevice,
131 VkPhysicalDeviceMemoryProperties *pMemoryProperties) {
132 DispatchGetPhysicalDeviceMemoryProperties(physicalDevice, pMemoryProperties);
133}
134static VKAPI_ATTR VkResult VKAPI_CALL gpuVkAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
135 const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) {
136 return DispatchAllocateMemory(device, pAllocateInfo, pAllocator, pMemory);
137}
138static VKAPI_ATTR void VKAPI_CALL gpuVkFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks *pAllocator) {
139 DispatchFreeMemory(device, memory, pAllocator);
140}
141static VKAPI_ATTR VkResult VKAPI_CALL gpuVkMapMemory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size,
142 VkMemoryMapFlags flags, void **ppData) {
143 return DispatchMapMemory(device, memory, offset, size, flags, ppData);
144}
145static VKAPI_ATTR void VKAPI_CALL gpuVkUnmapMemory(VkDevice device, VkDeviceMemory memory) { DispatchUnmapMemory(device, memory); }
146static VKAPI_ATTR VkResult VKAPI_CALL gpuVkFlushMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
147 const VkMappedMemoryRange *pMemoryRanges) {
148 return DispatchFlushMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
149}
150static VKAPI_ATTR VkResult VKAPI_CALL gpuVkInvalidateMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
151 const VkMappedMemoryRange *pMemoryRanges) {
152 return DispatchInvalidateMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
153}
154static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
155 VkDeviceSize memoryOffset) {
156 return DispatchBindBufferMemory(device, buffer, memory, memoryOffset);
157}
158static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
159 VkDeviceSize memoryOffset) {
160 return DispatchBindImageMemory(device, image, memory, memoryOffset);
161}
162static VKAPI_ATTR void VKAPI_CALL gpuVkGetBufferMemoryRequirements(VkDevice device, VkBuffer buffer,
163 VkMemoryRequirements *pMemoryRequirements) {
164 DispatchGetBufferMemoryRequirements(device, buffer, pMemoryRequirements);
165}
166static VKAPI_ATTR void VKAPI_CALL gpuVkGetImageMemoryRequirements(VkDevice device, VkImage image,
167 VkMemoryRequirements *pMemoryRequirements) {
168 DispatchGetImageMemoryRequirements(device, image, pMemoryRequirements);
169}
170static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
171 const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
172 return DispatchCreateBuffer(device, pCreateInfo, pAllocator, pBuffer);
173}
174static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
175 return DispatchDestroyBuffer(device, buffer, pAllocator);
176}
177static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
178 const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
179 return DispatchCreateImage(device, pCreateInfo, pAllocator, pImage);
180}
181static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
182 DispatchDestroyImage(device, image, pAllocator);
183}
184static VKAPI_ATTR void VKAPI_CALL gpuVkCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
185 uint32_t regionCount, const VkBufferCopy *pRegions) {
186 DispatchCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, regionCount, pRegions);
187}
188
189VkResult CoreChecks::GpuInitializeVma() {
190 VmaVulkanFunctions functions;
191 VmaAllocatorCreateInfo allocatorInfo = {};
192 allocatorInfo.device = device;
193 ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(allocatorInfo.device), layer_data_map);
194 ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeCoreValidation);
195 CoreChecks *core_checks = static_cast<CoreChecks *>(validation_data);
196 allocatorInfo.physicalDevice = core_checks->physical_device;
197
198 functions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)gpuVkGetPhysicalDeviceProperties;
199 functions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)gpuVkGetPhysicalDeviceMemoryProperties;
200 functions.vkAllocateMemory = (PFN_vkAllocateMemory)gpuVkAllocateMemory;
201 functions.vkFreeMemory = (PFN_vkFreeMemory)gpuVkFreeMemory;
202 functions.vkMapMemory = (PFN_vkMapMemory)gpuVkMapMemory;
203 functions.vkUnmapMemory = (PFN_vkUnmapMemory)gpuVkUnmapMemory;
204 functions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)gpuVkFlushMappedMemoryRanges;
205 functions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)gpuVkInvalidateMappedMemoryRanges;
206 functions.vkBindBufferMemory = (PFN_vkBindBufferMemory)gpuVkBindBufferMemory;
207 functions.vkBindImageMemory = (PFN_vkBindImageMemory)gpuVkBindImageMemory;
208 functions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)gpuVkGetBufferMemoryRequirements;
209 functions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)gpuVkGetImageMemoryRequirements;
210 functions.vkCreateBuffer = (PFN_vkCreateBuffer)gpuVkCreateBuffer;
211 functions.vkDestroyBuffer = (PFN_vkDestroyBuffer)gpuVkDestroyBuffer;
212 functions.vkCreateImage = (PFN_vkCreateImage)gpuVkCreateImage;
213 functions.vkDestroyImage = (PFN_vkDestroyImage)gpuVkDestroyImage;
214 functions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)gpuVkCmdCopyBuffer;
215 allocatorInfo.pVulkanFunctions = &functions;
216
217 return vmaCreateAllocator(&allocatorInfo, &gpu_validation_state->vmaAllocator);
218}
219
Karl Schultz7b024b42018-08-30 16:18:18 -0600220// Convenience function for reporting problems with setting up GPU Validation.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700221void CoreChecks::ReportSetupProblem(VkDebugReportObjectTypeEXT object_type, uint64_t object_handle,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700222 const char *const specific_message) {
223 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object_handle, "UNASSIGNED-GPU-Assisted Validation Error. ",
224 "Detail: (%s)", specific_message);
Karl Schultz7b024b42018-08-30 16:18:18 -0600225}
226
227// Turn on necessary device features.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700228void CoreChecks::GpuPreCallRecordCreateDevice(VkPhysicalDevice gpu, std::unique_ptr<safe_VkDeviceCreateInfo> &create_info,
229 VkPhysicalDeviceFeatures *supported_features) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600230 if (supported_features->fragmentStoresAndAtomics || supported_features->vertexPipelineStoresAndAtomics) {
Tony-LunarG48b478a2019-01-15 16:35:22 -0700231 VkPhysicalDeviceFeatures new_features = {};
Mark Lobodzinski5eb3c262019-03-01 16:08:30 -0700232 if (create_info->pEnabledFeatures) {
233 new_features = *create_info->pEnabledFeatures;
Tony-LunarG48b478a2019-01-15 16:35:22 -0700234 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600235 new_features.fragmentStoresAndAtomics = supported_features->fragmentStoresAndAtomics;
236 new_features.vertexPipelineStoresAndAtomics = supported_features->vertexPipelineStoresAndAtomics;
Mark Lobodzinski5eb3c262019-03-01 16:08:30 -0700237 delete create_info->pEnabledFeatures;
238 create_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
Karl Schultz7b024b42018-08-30 16:18:18 -0600239 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600240}
241
242// Perform initializations that can be done at Create Device time.
Tony-LunarG2ab9ede2019-05-10 14:34:31 -0600243void CoreChecks::GpuPostCallRecordCreateDevice(const CHECK_ENABLED *enables, const VkDeviceCreateInfo *pCreateInfo) {
Mark Lobodzinski5dc3dcd2019-04-23 14:26:28 -0600244 // Set instance-level enables in device-enable data structure if using legacy settings
245 enabled.gpu_validation = enables->gpu_validation;
246 enabled.gpu_validation_reserve_binding_slot = enables->gpu_validation_reserve_binding_slot;
247
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600248 gpu_validation_state = std::unique_ptr<GpuValidationState>(new GpuValidationState);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600249 gpu_validation_state->reserve_binding_slot = enables->gpu_validation_reserve_binding_slot;
Tony-LunarG65f9c492019-01-17 14:24:42 -0700250
Mark Lobodzinski79b5d5b2019-04-19 12:27:10 -0600251 if (phys_dev_props.apiVersion < VK_API_VERSION_1_1) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600252 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600253 "GPU-Assisted validation requires Vulkan 1.1 or later. GPU-Assisted Validation disabled.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600254 gpu_validation_state->aborted = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600255 return;
256 }
Tony-LunarG2ab9ede2019-05-10 14:34:31 -0600257
258 // If api version 1.1 or later, SetDeviceLoaderData will be in the loader
259 auto chain_info = get_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK);
260 assert(chain_info->u.pfnSetDeviceLoaderData);
261 gpu_validation_state->vkSetDeviceLoaderData = chain_info->u.pfnSetDeviceLoaderData;
262
Karl Schultz7b024b42018-08-30 16:18:18 -0600263 // Some devices have extremely high limits here, so set a reasonable max because we have to pad
264 // the pipeline layout with dummy descriptor set layouts.
Mark Lobodzinski79b5d5b2019-04-19 12:27:10 -0600265 gpu_validation_state->adjusted_max_desc_sets = phys_dev_props.limits.maxBoundDescriptorSets;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600266 gpu_validation_state->adjusted_max_desc_sets = std::min(33U, gpu_validation_state->adjusted_max_desc_sets);
Karl Schultz7b024b42018-08-30 16:18:18 -0600267
268 // We can't do anything if there is only one.
269 // Device probably not a legit Vulkan device, since there should be at least 4. Protect ourselves.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600270 if (gpu_validation_state->adjusted_max_desc_sets == 1) {
271 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600272 "Device can bind only a single descriptor set. GPU-Assisted Validation disabled.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600273 gpu_validation_state->aborted = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600274 return;
275 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600276 gpu_validation_state->desc_set_bind_index = gpu_validation_state->adjusted_max_desc_sets - 1;
277 log_msg(report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
278 "UNASSIGNED-GPU-Assisted Validation. ", "Shaders using descriptor set at index %d. ",
279 gpu_validation_state->desc_set_bind_index);
Karl Schultz7b024b42018-08-30 16:18:18 -0600280
Tony-LunarG0e564722019-03-19 16:09:14 -0600281 gpu_validation_state->output_buffer_size = sizeof(uint32_t) * (spvtools::kInstMaxOutCnt + 1);
282 VkResult result = GpuInitializeVma();
283 assert(result == VK_SUCCESS);
Mark Lobodzinski3bf82a52019-03-11 11:49:34 -0600284 std::unique_ptr<GpuDescriptorSetManager> desc_set_manager(new GpuDescriptorSetManager(this));
Karl Schultz7b024b42018-08-30 16:18:18 -0600285
286 // The descriptor indexing checks require only the first "output" binding.
287 const VkDescriptorSetLayoutBinding debug_desc_layout_bindings[kNumBindingsInSet] = {
288 {
289 0, // output
290 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
291 1,
292 VK_SHADER_STAGE_ALL_GRAPHICS,
293 NULL,
294 },
Tony-LunarG1b2e0c32019-02-07 17:13:27 -0700295 {
296 1, // input
297 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
298 1,
299 VK_SHADER_STAGE_ALL_GRAPHICS,
300 NULL,
301 },
Karl Schultz7b024b42018-08-30 16:18:18 -0600302 };
303
304 const VkDescriptorSetLayoutCreateInfo debug_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0,
305 kNumBindingsInSet, debug_desc_layout_bindings};
306
307 const VkDescriptorSetLayoutCreateInfo dummy_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 0,
308 NULL};
309
Tony-LunarG0e564722019-03-19 16:09:14 -0600310 result = DispatchCreateDescriptorSetLayout(device, &debug_desc_layout_info, NULL, &gpu_validation_state->debug_desc_layout);
Karl Schultz7b024b42018-08-30 16:18:18 -0600311
312 // This is a layout used to "pad" a pipeline layout to fill in any gaps to the selected bind index.
Mark Lobodzinski155d7632019-03-07 11:20:42 -0700313 VkResult result2 =
Tony-LunarG152a88b2019-03-20 15:42:24 -0600314 DispatchCreateDescriptorSetLayout(device, &dummy_desc_layout_info, NULL, &gpu_validation_state->dummy_desc_layout);
Karl Schultz7b024b42018-08-30 16:18:18 -0600315 assert((result == VK_SUCCESS) && (result2 == VK_SUCCESS));
316 if ((result != VK_SUCCESS) || (result2 != VK_SUCCESS)) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600317 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600318 "Unable to create descriptor set layout. GPU-Assisted Validation disabled.");
319 if (result == VK_SUCCESS) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600320 DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->debug_desc_layout, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600321 }
322 if (result2 == VK_SUCCESS) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600323 DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->dummy_desc_layout, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600324 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600325 gpu_validation_state->debug_desc_layout = VK_NULL_HANDLE;
326 gpu_validation_state->dummy_desc_layout = VK_NULL_HANDLE;
327 gpu_validation_state->aborted = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600328 return;
329 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600330 gpu_validation_state->desc_set_manager = std::move(desc_set_manager);
Karl Schultz7b024b42018-08-30 16:18:18 -0600331}
332
333// Clean up device-related resources
Mark Lobodzinski70f00652019-03-07 15:22:47 -0700334void CoreChecks::GpuPreCallRecordDestroyDevice() {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600335 if (gpu_validation_state->barrier_command_buffer) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600336 DispatchFreeCommandBuffers(device, gpu_validation_state->barrier_command_pool, 1,
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600337 &gpu_validation_state->barrier_command_buffer);
338 gpu_validation_state->barrier_command_buffer = VK_NULL_HANDLE;
Karl Schultz58674242019-01-22 15:35:02 -0700339 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600340 if (gpu_validation_state->barrier_command_pool) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600341 DispatchDestroyCommandPool(device, gpu_validation_state->barrier_command_pool, NULL);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600342 gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
Karl Schultz58674242019-01-22 15:35:02 -0700343 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600344 if (gpu_validation_state->debug_desc_layout) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600345 DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->debug_desc_layout, NULL);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600346 gpu_validation_state->debug_desc_layout = VK_NULL_HANDLE;
Karl Schultz7b024b42018-08-30 16:18:18 -0600347 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600348 if (gpu_validation_state->dummy_desc_layout) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600349 DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->dummy_desc_layout, NULL);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600350 gpu_validation_state->dummy_desc_layout = VK_NULL_HANDLE;
Karl Schultz7b024b42018-08-30 16:18:18 -0600351 }
Tony-LunarG29f48a72019-04-16 11:53:37 -0600352 gpu_validation_state->desc_set_manager.reset();
353 if (gpu_validation_state->vmaAllocator) {
354 vmaDestroyAllocator(gpu_validation_state->vmaAllocator);
355 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600356}
357
Karl Schultz7b024b42018-08-30 16:18:18 -0600358// Modify the pipeline layout to include our debug descriptor set and any needed padding with the dummy descriptor set.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700359bool CoreChecks::GpuPreCallCreatePipelineLayout(const VkPipelineLayoutCreateInfo *pCreateInfo,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700360 const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout,
361 std::vector<VkDescriptorSetLayout> *new_layouts,
362 VkPipelineLayoutCreateInfo *modified_create_info) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600363 if (gpu_validation_state->aborted) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700364 return false;
Karl Schultz7b024b42018-08-30 16:18:18 -0600365 }
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700366
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600367 if (modified_create_info->setLayoutCount >= gpu_validation_state->adjusted_max_desc_sets) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600368 std::ostringstream strm;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600369 strm << "Pipeline Layout conflict with validation's descriptor set at slot " << gpu_validation_state->desc_set_bind_index
370 << ". "
Karl Schultz7b024b42018-08-30 16:18:18 -0600371 << "Application has too many descriptor sets in the pipeline layout to continue with gpu validation. "
372 << "Validation is not modifying the pipeline layout. "
373 << "Instrumented shaders are replaced with non-instrumented shaders.";
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600374 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), strm.str().c_str());
Karl Schultz7b024b42018-08-30 16:18:18 -0600375 } else {
376 // Modify the pipeline layout by:
377 // 1. Copying the caller's descriptor set desc_layouts
378 // 2. Fill in dummy descriptor layouts up to the max binding
379 // 3. Fill in with the debug descriptor layout at the max binding slot
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600380 new_layouts->reserve(gpu_validation_state->adjusted_max_desc_sets);
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700381 new_layouts->insert(new_layouts->end(), &pCreateInfo->pSetLayouts[0],
382 &pCreateInfo->pSetLayouts[pCreateInfo->setLayoutCount]);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600383 for (uint32_t i = pCreateInfo->setLayoutCount; i < gpu_validation_state->adjusted_max_desc_sets - 1; ++i) {
384 new_layouts->push_back(gpu_validation_state->dummy_desc_layout);
Karl Schultz7b024b42018-08-30 16:18:18 -0600385 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600386 new_layouts->push_back(gpu_validation_state->debug_desc_layout);
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700387 modified_create_info->pSetLayouts = new_layouts->data();
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600388 modified_create_info->setLayoutCount = gpu_validation_state->adjusted_max_desc_sets;
Karl Schultz7b024b42018-08-30 16:18:18 -0600389 }
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700390 return true;
391}
392
393// Clean up GPU validation after the CreatePipelineLayout call is made
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700394void CoreChecks::GpuPostCallCreatePipelineLayout(VkResult result) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700395 // Clean up GPU validation
Karl Schultz7b024b42018-08-30 16:18:18 -0600396 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600397 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600398 "Unable to create pipeline layout. Device could become unstable.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600399 gpu_validation_state->aborted = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600400 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600401}
402
Karl Schultz7b024b42018-08-30 16:18:18 -0600403// Free the device memory and descriptor set associated with a command buffer.
Tony-LunarGdcbc2c32019-05-06 10:17:44 -0600404void CoreChecks::GpuResetCommandBuffer(const VkCommandBuffer commandBuffer) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600405 if (gpu_validation_state->aborted) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600406 return;
407 }
Tony-LunarGdcbc2c32019-05-06 10:17:44 -0600408 auto gpu_buffer_list = gpu_validation_state->GetGpuBufferInfo(commandBuffer);
409 for (auto buffer_info : gpu_buffer_list) {
410 vmaDestroyBuffer(gpu_validation_state->vmaAllocator, buffer_info.output_mem_block.buffer,
411 buffer_info.output_mem_block.allocation);
412 if (buffer_info.input_mem_block.buffer) {
413 vmaDestroyBuffer(gpu_validation_state->vmaAllocator, buffer_info.input_mem_block.buffer,
414 buffer_info.input_mem_block.allocation);
Karl Schultz7b024b42018-08-30 16:18:18 -0600415 }
Tony-LunarGdcbc2c32019-05-06 10:17:44 -0600416 if (buffer_info.desc_set != VK_NULL_HANDLE) {
417 gpu_validation_state->desc_set_manager->PutBackDescriptorSet(buffer_info.desc_pool, buffer_info.desc_set);
418 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600419 }
Tony-LunarGdcbc2c32019-05-06 10:17:44 -0600420 gpu_validation_state->command_buffer_map.erase(commandBuffer);
Karl Schultz7b024b42018-08-30 16:18:18 -0600421}
422
423// Just gives a warning about a possible deadlock.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700424void CoreChecks::GpuPreCallValidateCmdWaitEvents(VkPipelineStageFlags sourceStageMask) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600425 if (sourceStageMask & VK_PIPELINE_STAGE_HOST_BIT) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600426 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600427 "CmdWaitEvents recorded with VK_PIPELINE_STAGE_HOST_BIT set. "
428 "GPU_Assisted validation waits on queue completion. "
429 "This wait could block the host's signaling of this event, resulting in deadlock.");
430 }
431}
432
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700433std::vector<safe_VkGraphicsPipelineCreateInfo> CoreChecks::GpuPreCallRecordCreateGraphicsPipelines(
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700434 VkPipelineCache pipelineCache, uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
Karl Schultz7b024b42018-08-30 16:18:18 -0600435 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600436 std::vector<safe_VkGraphicsPipelineCreateInfo> new_pipeline_create_infos;
Karl Schultz7b024b42018-08-30 16:18:18 -0600437
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600438 GpuPreCallRecordPipelineCreations(count, pCreateInfos, nullptr, pAllocator, pPipelines, pipe_state, &new_pipeline_create_infos,
439 nullptr, VK_PIPELINE_BIND_POINT_GRAPHICS);
440 return new_pipeline_create_infos;
441}
442std::vector<safe_VkComputePipelineCreateInfo> CoreChecks::GpuPreCallRecordCreateComputePipelines(
443 VkPipelineCache pipelineCache, uint32_t count, const VkComputePipelineCreateInfo *pCreateInfos,
444 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) {
445 std::vector<safe_VkComputePipelineCreateInfo> new_pipeline_create_infos;
446 GpuPreCallRecordPipelineCreations(count, nullptr, pCreateInfos, pAllocator, pPipelines, pipe_state, nullptr,
447 &new_pipeline_create_infos, VK_PIPELINE_BIND_POINT_COMPUTE);
448 return new_pipeline_create_infos;
449}
450
451// Examine the pipelines to see if they use the debug descriptor set binding index.
452// If any do, create new non-instrumented shader modules and use them to replace the instrumented
453// shaders in the pipeline. Return the (possibly) modified create infos to the caller.
454void CoreChecks::GpuPreCallRecordPipelineCreations(
455 uint32_t count, const VkGraphicsPipelineCreateInfo *pGraphicsCreateInfos,
456 const VkComputePipelineCreateInfo *pComputeCreateInfos, const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
457 std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state,
458 std::vector<safe_VkGraphicsPipelineCreateInfo> *new_graphics_pipeline_create_infos,
459 std::vector<safe_VkComputePipelineCreateInfo> *new_compute_pipeline_create_infos, const VkPipelineBindPoint bind_point) {
460 if (bind_point != VK_PIPELINE_BIND_POINT_GRAPHICS && bind_point != VK_PIPELINE_BIND_POINT_COMPUTE) {
461 return;
462 }
463 bool graphics_pipeline = (bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS);
464
Karl Schultz7b024b42018-08-30 16:18:18 -0600465 // Walk through all the pipelines, make a copy of each and flag each pipeline that contains a shader that uses the debug
466 // descriptor set index.
467 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600468 auto stageCount = graphics_pipeline ? pGraphicsCreateInfos[pipeline].stageCount : 1;
Tony-LunarGd4da33b2019-04-16 16:28:22 -0600469 bool replace_shaders = false;
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600470 if (graphics_pipeline)
471 new_graphics_pipeline_create_infos->push_back(pipe_state[pipeline]->graphicsPipelineCI);
472 else
473 new_compute_pipeline_create_infos->push_back(pipe_state[pipeline]->computePipelineCI);
474
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600475 if (pipe_state[pipeline]->active_slots.find(gpu_validation_state->desc_set_bind_index) !=
476 pipe_state[pipeline]->active_slots.end()) {
Tony-LunarGd4da33b2019-04-16 16:28:22 -0600477 replace_shaders = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600478 }
Tony-LunarGd4da33b2019-04-16 16:28:22 -0600479 // If the app requests all available sets, the pipeline layout was not modified at pipeline layout creation and the already
480 // instrumented shaders need to be replaced with uninstrumented shaders
481 if (pipe_state[pipeline]->pipeline_layout.set_layouts.size() >= gpu_validation_state->adjusted_max_desc_sets) {
482 replace_shaders = true;
483 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600484
Tony-LunarGd4da33b2019-04-16 16:28:22 -0600485 if (replace_shaders) {
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600486 for (uint32_t stage = 0; stage < stageCount; ++stage) {
487 const SHADER_MODULE_STATE *shader;
488 if (graphics_pipeline)
489 shader = GetShaderModuleState(pGraphicsCreateInfos[pipeline].pStages[stage].module);
490 else
491 shader = GetShaderModuleState(pComputeCreateInfos[pipeline].stage.module);
Karl Schultz7b024b42018-08-30 16:18:18 -0600492 VkShaderModuleCreateInfo create_info = {};
493 VkShaderModule shader_module;
494 create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
495 create_info.pCode = shader->words.data();
496 create_info.codeSize = shader->words.size() * sizeof(uint32_t);
Tony-LunarG152a88b2019-03-20 15:42:24 -0600497 VkResult result = DispatchCreateShaderModule(device, &create_info, pAllocator, &shader_module);
Karl Schultz7b024b42018-08-30 16:18:18 -0600498 if (result == VK_SUCCESS) {
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600499 if (graphics_pipeline)
500 new_graphics_pipeline_create_infos[pipeline].data()->pStages[stage].module = shader_module;
501 else
502 new_compute_pipeline_create_infos[pipeline].data()->stage.module = shader_module;
Karl Schultz7b024b42018-08-30 16:18:18 -0600503 } else {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700504 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600505 (graphics_pipeline) ? HandleToUint64(pGraphicsCreateInfos[pipeline].pStages[stage].module)
506 : HandleToUint64(pComputeCreateInfos[pipeline].stage.module),
Karl Schultz7b024b42018-08-30 16:18:18 -0600507 "Unable to replace instrumented shader with non-instrumented one. "
508 "Device could become unstable.");
509 }
510 }
511 }
512 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600513}
514
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600515void CoreChecks::GpuPostCallRecordCreateGraphicsPipelines(const uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
516 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) {
517 GpuPostCallRecordPipelineCreations(count, pCreateInfos, nullptr, pAllocator, pPipelines, VK_PIPELINE_BIND_POINT_GRAPHICS);
518}
519void CoreChecks::GpuPostCallRecordCreateComputePipelines(const uint32_t count, const VkComputePipelineCreateInfo *pCreateInfos,
520 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) {
521 GpuPostCallRecordPipelineCreations(count, nullptr, pCreateInfos, pAllocator, pPipelines, VK_PIPELINE_BIND_POINT_GRAPHICS);
522}
Karl Schultz7b024b42018-08-30 16:18:18 -0600523// For every pipeline:
524// - For every shader in a pipeline:
525// - If the shader had to be replaced in PreCallRecord (because the pipeline is using the debug desc set index):
526// - Destroy it since it has been bound into the pipeline by now. This is our only chance to delete it.
527// - Track the shader in the shader_map
528// - Save the shader binary if it contains debug code
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600529void CoreChecks::GpuPostCallRecordPipelineCreations(const uint32_t count, const VkGraphicsPipelineCreateInfo *pGraphicsCreateInfos,
530 const VkComputePipelineCreateInfo *pComputeCreateInfos,
531 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
532 const VkPipelineBindPoint bind_point) {
533 if (bind_point != VK_PIPELINE_BIND_POINT_GRAPHICS && bind_point != VK_PIPELINE_BIND_POINT_COMPUTE) {
534 return;
535 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600536 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
Mark Lobodzinskifd917d22019-03-06 16:07:15 -0700537 auto pipeline_state = GetPipelineState(pPipelines[pipeline]);
Karl Schultz7b024b42018-08-30 16:18:18 -0600538 if (nullptr == pipeline_state) continue;
539 for (uint32_t stage = 0; stage < pipeline_state->graphicsPipelineCI.stageCount; ++stage) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600540 if (pipeline_state->active_slots.find(gpu_validation_state->desc_set_bind_index) !=
541 pipeline_state->active_slots.end()) {
Tony-LunarGeb25bf52019-04-26 10:46:41 -0600542 if (bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS)
543 DispatchDestroyShaderModule(device, pGraphicsCreateInfos->pStages[stage].module, pAllocator);
544 else
545 DispatchDestroyShaderModule(device, pComputeCreateInfos->stage.module, pAllocator);
Karl Schultz7b024b42018-08-30 16:18:18 -0600546 }
Mark Lobodzinski9e9da292019-03-06 16:19:55 -0700547 auto shader_state = GetShaderModuleState(pipeline_state->graphicsPipelineCI.pStages[stage].module);
Karl Schultz7b024b42018-08-30 16:18:18 -0600548 std::vector<unsigned int> code;
549 // Save the shader binary if debug info is present.
550 // The core_validation ShaderModule tracker saves the binary too, but discards it when the ShaderModule
551 // is destroyed. Applications may destroy ShaderModules after they are placed in a pipeline and before
552 // the pipeline is used, so we have to keep another copy.
553 if (shader_state && shader_state->has_valid_spirv) { // really checking for presense of SPIR-V code.
554 for (auto insn : *shader_state) {
555 if (insn.opcode() == spv::OpLine) {
556 code = shader_state->words;
557 break;
558 }
559 }
560 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600561 gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].pipeline = pipeline_state->pipeline;
Karl Schultz7b024b42018-08-30 16:18:18 -0600562 // Be careful to use the originally bound (instrumented) shader here, even if PreCallRecord had to back it
563 // out with a non-instrumented shader. The non-instrumented shader (found in pCreateInfo) was destroyed above.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600564 gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].shader_module =
Karl Schultz7b024b42018-08-30 16:18:18 -0600565 pipeline_state->graphicsPipelineCI.pStages[stage].module;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600566 gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].pgm = std::move(code);
Karl Schultz7b024b42018-08-30 16:18:18 -0600567 }
568 }
569}
570
571// Remove all the shader trackers associated with this destroyed pipeline.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700572void CoreChecks::GpuPreCallRecordDestroyPipeline(const VkPipeline pipeline) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600573 for (auto it = gpu_validation_state->shader_map.begin(); it != gpu_validation_state->shader_map.end();) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600574 if (it->second.pipeline == pipeline) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600575 it = gpu_validation_state->shader_map.erase(it);
Karl Schultz7b024b42018-08-30 16:18:18 -0600576 } else {
577 ++it;
578 }
579 }
580}
581
582// Call the SPIR-V Optimizer to run the instrumentation pass on the shader.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700583bool CoreChecks::GpuInstrumentShader(const VkShaderModuleCreateInfo *pCreateInfo, std::vector<unsigned int> &new_pgm,
584 uint32_t *unique_shader_id) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600585 if (gpu_validation_state->aborted) return false;
Karl Schultz7b024b42018-08-30 16:18:18 -0600586 if (pCreateInfo->pCode[0] != spv::MagicNumber) return false;
587
588 // Load original shader SPIR-V
589 uint32_t num_words = static_cast<uint32_t>(pCreateInfo->codeSize / 4);
590 new_pgm.clear();
591 new_pgm.reserve(num_words);
592 new_pgm.insert(new_pgm.end(), &pCreateInfo->pCode[0], &pCreateInfo->pCode[num_words]);
593
594 // Call the optimizer to instrument the shader.
595 // Use the unique_shader_module_id as a shader ID so we can look up its handle later in the shader_map.
Tony-LunarGa77cade2019-03-06 10:49:22 -0700596 // If descriptor indexing is enabled, enable length checks and updated descriptor checks
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -0600597 const bool descriptor_indexing = device_extensions.vk_ext_descriptor_indexing;
Karl Schultz7b024b42018-08-30 16:18:18 -0600598 using namespace spvtools;
599 spv_target_env target_env = SPV_ENV_VULKAN_1_1;
600 Optimizer optimizer(target_env);
Tony-LunarG1b2e0c32019-02-07 17:13:27 -0700601 optimizer.RegisterPass(CreateInstBindlessCheckPass(gpu_validation_state->desc_set_bind_index,
Tony-LunarGa77cade2019-03-06 10:49:22 -0700602 gpu_validation_state->unique_shader_module_id, descriptor_indexing,
603 descriptor_indexing));
Karl Schultz7b024b42018-08-30 16:18:18 -0600604 optimizer.RegisterPass(CreateAggressiveDCEPass());
605 bool pass = optimizer.Run(new_pgm.data(), new_pgm.size(), &new_pgm);
606 if (!pass) {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700607 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, VK_NULL_HANDLE,
Karl Schultz7b024b42018-08-30 16:18:18 -0600608 "Failure to instrument shader. Proceeding with non-instrumented shader.");
609 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600610 *unique_shader_id = gpu_validation_state->unique_shader_module_id++;
Karl Schultz7b024b42018-08-30 16:18:18 -0600611 return pass;
612}
613
Mark Lobodzinski01734072019-02-13 17:39:15 -0700614// Create the instrumented shader data to provide to the driver.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700615bool CoreChecks::GpuPreCallCreateShaderModule(const VkShaderModuleCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator,
616 VkShaderModule *pShaderModule, uint32_t *unique_shader_id,
617 VkShaderModuleCreateInfo *instrumented_create_info,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700618 std::vector<unsigned int> *instrumented_pgm) {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700619 bool pass = GpuInstrumentShader(pCreateInfo, *instrumented_pgm, unique_shader_id);
Karl Schultz7b024b42018-08-30 16:18:18 -0600620 if (pass) {
Mark Lobodzinski01734072019-02-13 17:39:15 -0700621 instrumented_create_info->pCode = instrumented_pgm->data();
622 instrumented_create_info->codeSize = instrumented_pgm->size() * sizeof(unsigned int);
Karl Schultz7b024b42018-08-30 16:18:18 -0600623 }
Mark Lobodzinski01734072019-02-13 17:39:15 -0700624 return pass;
Karl Schultz7b024b42018-08-30 16:18:18 -0600625}
626
627// Generate the stage-specific part of the message.
628static void GenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
629 using namespace spvtools;
630 std::ostringstream strm;
631 switch (debug_record[kInstCommonOutStageIdx]) {
632 case 0: {
Tony-LunarG6ff87582019-02-08 10:29:07 -0700633 strm << "Stage = Vertex. Vertex Index = " << debug_record[kInstVertOutVertexIndex]
634 << " Instance Index = " << debug_record[kInstVertOutInstanceIndex] << ". ";
Karl Schultz7b024b42018-08-30 16:18:18 -0600635 } break;
636 case 1: {
637 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
638 } break;
639 case 2: {
640 strm << "Stage = Tessellation Eval. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
641 } break;
642 case 3: {
643 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
644 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
645 } break;
646 case 4: {
647 strm << "Stage = Fragment. Fragment coord (x,y) = ("
648 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
649 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
650 } break;
651 case 5: {
652 strm << "Stage = Compute. Global invocation ID = " << debug_record[kInstCompOutGlobalInvocationId] << ". ";
653 } break;
654 default: {
655 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
656 assert(false);
657 } break;
658 }
659 msg = strm.str();
660}
661
662// Generate the part of the message describing the violation.
663static void GenerateValidationMessage(const uint32_t *debug_record, std::string &msg, std::string &vuid_msg) {
664 using namespace spvtools;
665 std::ostringstream strm;
666 switch (debug_record[kInstValidationOutError]) {
667 case 0: {
668 strm << "Index of " << debug_record[kInstBindlessOutDescIndex] << " used to index descriptor array of length "
669 << debug_record[kInstBindlessOutDescBound] << ". ";
Tony-LunarGc1d657d2019-02-22 14:55:19 -0700670 vuid_msg = "UNASSIGNED-Descriptor index out of bounds";
Karl Schultz7b024b42018-08-30 16:18:18 -0600671 } break;
672 case 1: {
Karl Schultz7b024b42018-08-30 16:18:18 -0600673 strm << "Descriptor index " << debug_record[kInstBindlessOutDescIndex] << " is uninitialized. ";
Tony-LunarGc1d657d2019-02-22 14:55:19 -0700674 vuid_msg = "UNASSIGNED-Descriptor uninitialized";
Karl Schultz7b024b42018-08-30 16:18:18 -0600675 } break;
676 default: {
677 strm << "Internal Error (unexpected error type = " << debug_record[kInstValidationOutError] << "). ";
678 vuid_msg = "UNASSIGNED-Internal Error";
679 assert(false);
680 } break;
681 }
682 msg = strm.str();
683}
684
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700685static std::string LookupDebugUtilsName(const debug_report_data *report_data, const uint64_t object) {
Mark Lobodzinski1d7313a2019-02-07 11:04:42 -0700686 auto object_label = report_data->DebugReportGetUtilsObjectName(object);
687 if (object_label != "") {
688 object_label = "(" + object_label + ")";
Karl Schultz7b024b42018-08-30 16:18:18 -0600689 }
Mark Lobodzinski1d7313a2019-02-07 11:04:42 -0700690 return object_label;
Karl Schultz7b024b42018-08-30 16:18:18 -0600691}
692
693// Generate message from the common portion of the debug report record.
Mark Lobodzinski33a34b82019-04-25 11:38:36 -0600694static void GenerateCommonMessage(const debug_report_data *report_data, const CMD_BUFFER_STATE *cb_node,
695 const uint32_t *debug_record, const VkShaderModule shader_module_handle,
696 const VkPipeline pipeline_handle, const uint32_t draw_index, std::string &msg) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600697 using namespace spvtools;
698 std::ostringstream strm;
699 if (shader_module_handle == VK_NULL_HANDLE) {
700 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700701 << LookupDebugUtilsName(report_data, HandleToUint64(cb_node->commandBuffer)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600702 << HandleToUint64(cb_node->commandBuffer) << "). ";
703 assert(true);
704 } else {
705 strm << std::hex << std::showbase << "Command buffer "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700706 << LookupDebugUtilsName(report_data, HandleToUint64(cb_node->commandBuffer)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600707 << HandleToUint64(cb_node->commandBuffer) << "). "
Tony-LunarGd589c7c2019-01-31 11:23:44 -0700708 << "Draw Index " << draw_index << ". "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700709 << "Pipeline " << LookupDebugUtilsName(report_data, HandleToUint64(pipeline_handle)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600710 << HandleToUint64(pipeline_handle) << "). "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700711 << "Shader Module " << LookupDebugUtilsName(report_data, HandleToUint64(shader_module_handle)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600712 << HandleToUint64(shader_module_handle) << "). ";
713 }
714 strm << std::dec << std::noshowbase;
715 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
716 msg = strm.str();
717}
718
719// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
720// Split the single string into a vector of strings, one for each line, for easier processing.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600721static void ReadOpSource(const SHADER_MODULE_STATE &shader, const uint32_t reported_file_id,
722 std::vector<std::string> &opsource_lines) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600723 for (auto insn : shader) {
724 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
725 std::istringstream in_stream;
726 std::string cur_line;
727 in_stream.str((char *)&insn.word(4));
728 while (std::getline(in_stream, cur_line)) {
729 opsource_lines.push_back(cur_line);
730 }
731 while ((++insn).opcode() == spv::OpSourceContinued) {
732 in_stream.str((char *)&insn.word(1));
733 while (std::getline(in_stream, cur_line)) {
734 opsource_lines.push_back(cur_line);
735 }
736 }
737 break;
738 }
739 }
740}
Tony-LunarG03059b72019-02-19 13:57:41 -0700741
742// The task here is to search the OpSource content to find the #line directive with the
743// line number that is closest to, but still prior to the reported error line number and
744// still within the reported filename.
745// From this known position in the OpSource content we can add the difference between
746// the #line line number and the reported error line number to determine the location
747// in the OpSource content of the reported error line.
748//
749// Considerations:
750// - Look only at #line directives that specify the reported_filename since
751// the reported error line number refers to its location in the reported filename.
752// - If a #line directive does not have a filename, the file is the reported filename, or
753// the filename found in a prior #line directive. (This is C-preprocessor behavior)
754// - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
755// original order and the #line directives are used to keep the numbering correct. This
756// is why we need to examine the entire contents of the source, instead of leaving early
757// when finding a #line line number larger than the reported error line number.
758//
759
760// GCC 4.8 has a problem with std::regex that is fixed in GCC 4.9. Provide fallback code for 4.8
761#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
762
763#if defined(__GNUC__) && GCC_VERSION < 40900
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700764static bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
Tony-LunarG03059b72019-02-19 13:57:41 -0700765 // # line <linenumber> "<filename>" or
766 // #line <linenumber> "<filename>"
767 std::vector<std::string> tokens;
768 std::stringstream stream(string);
769 std::string temp;
770 uint32_t line_index = 0;
771
772 while (stream >> temp) tokens.push_back(temp);
773 auto size = tokens.size();
774 if (size > 1) {
775 if (tokens[0] == "#" && tokens[1] == "line") {
776 line_index = 2;
777 } else if (tokens[0] == "#line") {
778 line_index = 1;
779 }
780 }
781 if (0 == line_index) return false;
782 *linenumber = std::stoul(tokens[line_index]);
783 uint32_t filename_index = line_index + 1;
784 // Remove enclosing double quotes around filename
785 if (size > filename_index) filename = tokens[filename_index].substr(1, tokens[filename_index].size() - 2);
786 return true;
787}
788#else
789static bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700790 static const std::regex line_regex( // matches #line directives
791 "^" // beginning of line
792 "\\s*" // optional whitespace
793 "#" // required text
794 "\\s*" // optional whitespace
795 "line" // required text
796 "\\s+" // required whitespace
797 "([0-9]+)" // required first capture - line number
798 "(\\s+)?" // optional second capture - whitespace
799 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
800 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
Karl Schultz7b024b42018-08-30 16:18:18 -0600801
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700802 std::smatch captures;
803
804 bool found_line = std::regex_match(string, captures, line_regex);
805 if (!found_line) return false;
806
807 // filename is optional and considered found only if the whitespace and the filename are captured
808 if (captures[2].matched && captures[3].matched) {
809 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
810 filename = captures[3].str().substr(1, captures[3].str().size() - 2);
811 }
812 *linenumber = std::stoul(captures[1]);
813 return true;
814}
Tony-LunarG03059b72019-02-19 13:57:41 -0700815#endif // GCC_VERSION
816
Karl Schultz7b024b42018-08-30 16:18:18 -0600817// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
818// Scan the source (from OpSource) to find the line of source at the reported line number and place it in another message string.
819static void GenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, std::string &filename_msg,
820 std::string &source_msg) {
821 using namespace spvtools;
822 std::ostringstream filename_stream;
823 std::ostringstream source_stream;
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600824 SHADER_MODULE_STATE shader;
Karl Schultz7b024b42018-08-30 16:18:18 -0600825 shader.words = pgm;
826 // Find the OpLine just before the failing instruction indicated by the debug info.
827 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
828 uint32_t instruction_index = 0;
829 uint32_t reported_file_id = 0;
830 uint32_t reported_line_number = 0;
831 uint32_t reported_column_number = 0;
832 if (shader.words.size() > 0) {
833 for (auto insn : shader) {
834 if (insn.opcode() == spv::OpLine) {
835 reported_file_id = insn.word(1);
836 reported_line_number = insn.word(2);
837 reported_column_number = insn.word(3);
838 }
839 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
840 break;
841 }
842 instruction_index++;
843 }
844 }
845 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
846 std::string reported_filename;
847 if (reported_file_id == 0) {
848 filename_stream
849 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
850 } else {
851 bool found_opstring = false;
852 for (auto insn : shader) {
853 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
854 found_opstring = true;
855 reported_filename = (char *)&insn.word(2);
856 if (reported_filename.empty()) {
857 filename_stream << "Shader validation error occurred at line " << reported_line_number;
858 } else {
859 filename_stream << "Shader validation error occurred in file: " << reported_filename << " at line "
860 << reported_line_number;
861 }
862 if (reported_column_number > 0) {
863 filename_stream << ", column " << reported_column_number;
864 }
865 filename_stream << ".";
866 break;
867 }
868 }
869 if (!found_opstring) {
870 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction.";
871 }
872 }
873 filename_msg = filename_stream.str();
874
875 // Create message to display source code line containing error.
876 if ((reported_file_id != 0)) {
877 // Read the source code and split it up into separate lines.
878 std::vector<std::string> opsource_lines;
879 ReadOpSource(shader, reported_file_id, opsource_lines);
880 // Find the line in the OpSource content that corresponds to the reported error file and line.
881 if (!opsource_lines.empty()) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600882 uint32_t saved_line_number = 0;
883 std::string current_filename = reported_filename; // current "preprocessor" filename state.
884 std::vector<std::string>::size_type saved_opsource_offset = 0;
885 bool found_best_line = false;
886 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700887 uint32_t parsed_line_number;
888 std::string parsed_filename;
889 bool found_line = GetLineAndFilename(*it, &parsed_line_number, parsed_filename);
Karl Schultz7b024b42018-08-30 16:18:18 -0600890 if (!found_line) continue;
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700891
892 bool found_filename = parsed_filename.size() > 0;
Karl Schultz7b024b42018-08-30 16:18:18 -0600893 if (found_filename) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700894 current_filename = parsed_filename;
Karl Schultz7b024b42018-08-30 16:18:18 -0600895 }
896 if ((!found_filename) || (current_filename == reported_filename)) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600897 // Update the candidate best line directive, if the current one is prior and closer to the reported line
898 if (reported_line_number >= parsed_line_number) {
899 if (!found_best_line ||
900 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
901 saved_line_number = parsed_line_number;
902 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
903 found_best_line = true;
904 }
905 }
906 }
907 }
908 if (found_best_line) {
909 assert(reported_line_number >= saved_line_number);
910 std::vector<std::string>::size_type opsource_index =
911 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
912 if (opsource_index < opsource_lines.size()) {
913 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
914 } else {
915 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
916 << opsource_lines.size() << " lines.";
917 }
918 } else {
919 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
920 }
921 } else {
922 source_stream << "Unable to find SPIR-V OpSource.";
923 }
924 }
925 source_msg = source_stream.str();
926}
927
928// Pull together all the information from the debug record to build the error message strings,
929// and then assemble them into a single message string.
930// Retrieve the shader program referenced by the unique shader ID provided in the debug record.
931// We had to keep a copy of the shader program with the same lifecycle as the pipeline to make
932// sure it is available when the pipeline is submitted. (The ShaderModule tracking object also
933// keeps a copy, but it can be destroyed after the pipeline is created and before it is submitted.)
934//
Mark Lobodzinski33a34b82019-04-25 11:38:36 -0600935void CoreChecks::AnalyzeAndReportError(CMD_BUFFER_STATE *cb_node, VkQueue queue, uint32_t draw_index,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700936 uint32_t *const debug_output_buffer) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600937 using namespace spvtools;
938 const uint32_t total_words = debug_output_buffer[0];
939 // A zero here means that the shader instrumentation didn't write anything.
940 // If you have nothing to say, don't say it here.
941 if (0 == total_words) {
942 return;
943 }
944 // The first word in the debug output buffer is the number of words that would have
945 // been written by the shader instrumentation, if there was enough room in the buffer we provided.
946 // The number of words actually written by the shaders is determined by the size of the buffer
947 // we provide via the descriptor. So, we process only the number of words that can fit in the
948 // buffer.
949 // Each "report" written by the shader instrumentation is considered a "record". This function
950 // is hard-coded to process only one record because it expects the buffer to be large enough to
951 // hold only one record. If there is a desire to process more than one record, this function needs
952 // to be modified to loop over records and the buffer size increased.
Karl Schultz7b024b42018-08-30 16:18:18 -0600953 std::string validation_message;
954 std::string stage_message;
955 std::string common_message;
956 std::string filename_message;
957 std::string source_message;
958 std::string vuid_msg;
959 VkShaderModule shader_module_handle = VK_NULL_HANDLE;
960 VkPipeline pipeline_handle = VK_NULL_HANDLE;
961 std::vector<unsigned int> pgm;
962 // The first record starts at this offset after the total_words.
963 const uint32_t *debug_record = &debug_output_buffer[kDebugOutputDataOffset];
964 // Lookup the VkShaderModule handle and SPIR-V code used to create the shader, using the unique shader ID value returned
965 // by the instrumented shader.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600966 auto it = gpu_validation_state->shader_map.find(debug_record[kInstCommonOutShaderId]);
967 if (it != gpu_validation_state->shader_map.end()) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600968 shader_module_handle = it->second.shader_module;
969 pipeline_handle = it->second.pipeline;
970 pgm = it->second.pgm;
971 }
972 GenerateValidationMessage(debug_record, validation_message, vuid_msg);
973 GenerateStageMessage(debug_record, stage_message);
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700974 GenerateCommonMessage(report_data, cb_node, debug_record, shader_module_handle, pipeline_handle, draw_index, common_message);
Karl Schultz7b024b42018-08-30 16:18:18 -0600975 GenerateSourceMessages(pgm, debug_record, filename_message, source_message);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600976 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, HandleToUint64(queue),
Karl Schultz7b024b42018-08-30 16:18:18 -0600977 vuid_msg.c_str(), "%s %s %s %s%s", validation_message.c_str(), common_message.c_str(), stage_message.c_str(),
978 filename_message.c_str(), source_message.c_str());
979 // The debug record at word kInstCommonOutSize is the number of words in the record
980 // written by the shader. Clear the entire record plus the total_words word at the start.
981 const uint32_t words_to_clear = 1 + std::min(debug_record[kInstCommonOutSize], (uint32_t)kInstMaxOutCnt);
982 memset(debug_output_buffer, 0, sizeof(uint32_t) * words_to_clear);
983}
984
Tony-LunarG5ad17272019-03-05 12:48:24 -0700985// For the given command buffer, map its debug data buffers and read their contents for analysis.
Mark Lobodzinski33a34b82019-04-25 11:38:36 -0600986void CoreChecks::ProcessInstrumentationBuffer(VkQueue queue, CMD_BUFFER_STATE *cb_node) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600987 auto gpu_buffer_list = gpu_validation_state->GetGpuBufferInfo(cb_node->commandBuffer);
988 if (cb_node && cb_node->hasDrawCmd && gpu_buffer_list.size() > 0) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600989 VkResult result;
990 char *pData;
Tony-LunarG5ad17272019-03-05 12:48:24 -0700991 uint32_t draw_index = 0;
Tony-LunarG1b2e0c32019-02-07 17:13:27 -0700992
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600993 for (auto &buffer_info : gpu_buffer_list) {
Tony-LunarG1b2e0c32019-02-07 17:13:27 -0700994 result = vmaMapMemory(gpu_validation_state->vmaAllocator, buffer_info.output_mem_block.allocation, (void **)&pData);
Tony-LunarGb2501d22019-01-28 09:59:13 -0700995 // Analyze debug output buffer
996 if (result == VK_SUCCESS) {
Tony-LunarG0e564722019-03-19 16:09:14 -0600997 AnalyzeAndReportError(cb_node, queue, draw_index, (uint32_t *)pData);
Tony-LunarG1b2e0c32019-02-07 17:13:27 -0700998 vmaUnmapMemory(gpu_validation_state->vmaAllocator, buffer_info.output_mem_block.allocation);
Tony-LunarGb2501d22019-01-28 09:59:13 -0700999 }
Tony-LunarGd589c7c2019-01-31 11:23:44 -07001000 draw_index++;
Karl Schultz7b024b42018-08-30 16:18:18 -06001001 }
1002 }
1003}
1004
Tony-LunarG81efe392019-03-07 15:43:27 -07001005// For the given command buffer, map its debug data buffers and update the status of any update after bind descriptors
Mark Lobodzinski33a34b82019-04-25 11:38:36 -06001006void CoreChecks::UpdateInstrumentationBuffer(CMD_BUFFER_STATE *cb_node) {
Tony-LunarG81efe392019-03-07 15:43:27 -07001007 auto gpu_buffer_list = gpu_validation_state->GetGpuBufferInfo(cb_node->commandBuffer);
1008 uint32_t *pData;
1009 for (auto &buffer_info : gpu_buffer_list) {
1010 if (buffer_info.input_mem_block.update_at_submit.size() > 0) {
1011 VkResult result =
1012 vmaMapMemory(gpu_validation_state->vmaAllocator, buffer_info.input_mem_block.allocation, (void **)&pData);
1013 if (result == VK_SUCCESS) {
1014 for (auto update : buffer_info.input_mem_block.update_at_submit) {
1015 if (update.second->updated) pData[update.first] = 1;
1016 }
1017 vmaUnmapMemory(gpu_validation_state->vmaAllocator, buffer_info.input_mem_block.allocation);
1018 }
1019 }
1020 }
1021}
1022
Karl Schultz58674242019-01-22 15:35:02 -07001023// Submit a memory barrier on graphics queues.
1024// Lazy-create and record the needed command buffer.
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001025void CoreChecks::SubmitBarrier(VkQueue queue) {
Karl Schultz58674242019-01-22 15:35:02 -07001026 uint32_t queue_family_index = 0;
1027
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001028 auto it = queueMap.find(queue);
1029 if (it != queueMap.end()) {
Mark Lobodzinski547b5342019-05-03 14:37:44 -06001030 queue_family_index = it->second.queueFamilyIndex;
Karl Schultz58674242019-01-22 15:35:02 -07001031 }
1032
1033 // Pay attention only to queues that support graphics.
1034 // This ensures that the command buffer pool is created so that it can be used on a graphics queue.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07001035 VkQueueFlags queue_flags = GetPhysicalDeviceState()->queue_family_properties[queue_family_index].queueFlags;
Karl Schultz58674242019-01-22 15:35:02 -07001036 if (!(queue_flags & VK_QUEUE_GRAPHICS_BIT)) {
1037 return;
1038 }
1039
1040 // Lazy-allocate and record the command buffer.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001041 if (gpu_validation_state->barrier_command_buffer == VK_NULL_HANDLE) {
Karl Schultz58674242019-01-22 15:35:02 -07001042 VkResult result;
1043 VkCommandPoolCreateInfo pool_create_info = {};
1044 pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1045 pool_create_info.queueFamilyIndex = queue_family_index;
Tony-LunarG152a88b2019-03-20 15:42:24 -06001046 result = DispatchCreateCommandPool(device, &pool_create_info, nullptr, &gpu_validation_state->barrier_command_pool);
Karl Schultz58674242019-01-22 15:35:02 -07001047 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001048 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz58674242019-01-22 15:35:02 -07001049 "Unable to create command pool for barrier CB.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001050 gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
Karl Schultz58674242019-01-22 15:35:02 -07001051 return;
1052 }
1053
1054 VkCommandBufferAllocateInfo command_buffer_alloc_info = {};
1055 command_buffer_alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001056 command_buffer_alloc_info.commandPool = gpu_validation_state->barrier_command_pool;
Karl Schultz58674242019-01-22 15:35:02 -07001057 command_buffer_alloc_info.commandBufferCount = 1;
1058 command_buffer_alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
Tony-LunarG152a88b2019-03-20 15:42:24 -06001059 result = DispatchAllocateCommandBuffers(device, &command_buffer_alloc_info, &gpu_validation_state->barrier_command_buffer);
Karl Schultz58674242019-01-22 15:35:02 -07001060 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001061 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz58674242019-01-22 15:35:02 -07001062 "Unable to create barrier command buffer.");
Tony-LunarG152a88b2019-03-20 15:42:24 -06001063 DispatchDestroyCommandPool(device, gpu_validation_state->barrier_command_pool, nullptr);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001064 gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
1065 gpu_validation_state->barrier_command_buffer = VK_NULL_HANDLE;
Karl Schultz58674242019-01-22 15:35:02 -07001066 return;
1067 }
1068
1069 // Hook up command buffer dispatch
Tony-LunarG2ab9ede2019-05-10 14:34:31 -06001070 gpu_validation_state->vkSetDeviceLoaderData(device, gpu_validation_state->barrier_command_buffer);
Karl Schultz58674242019-01-22 15:35:02 -07001071
1072 // Record a global memory barrier to force availability of device memory operations to the host domain.
1073 VkCommandBufferBeginInfo command_buffer_begin_info = {};
1074 command_buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
Tony-LunarG152a88b2019-03-20 15:42:24 -06001075 result = DispatchBeginCommandBuffer(gpu_validation_state->barrier_command_buffer, &command_buffer_begin_info);
Karl Schultz58674242019-01-22 15:35:02 -07001076
1077 if (result == VK_SUCCESS) {
1078 VkMemoryBarrier memory_barrier = {};
1079 memory_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
1080 memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
1081 memory_barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
1082
Tony-LunarG152a88b2019-03-20 15:42:24 -06001083 DispatchCmdPipelineBarrier(gpu_validation_state->barrier_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
Mark Lobodzinskie514d1a2019-03-12 08:47:45 -06001084 VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &memory_barrier, 0, nullptr, 0, nullptr);
Tony-LunarG152a88b2019-03-20 15:42:24 -06001085 DispatchEndCommandBuffer(gpu_validation_state->barrier_command_buffer);
Karl Schultz58674242019-01-22 15:35:02 -07001086 }
1087 }
1088
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001089 if (gpu_validation_state->barrier_command_buffer) {
Karl Schultz58674242019-01-22 15:35:02 -07001090 VkSubmitInfo submit_info = {};
1091 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1092 submit_info.commandBufferCount = 1;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001093 submit_info.pCommandBuffers = &gpu_validation_state->barrier_command_buffer;
Tony-LunarG152a88b2019-03-20 15:42:24 -06001094 DispatchQueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
Karl Schultz58674242019-01-22 15:35:02 -07001095 }
1096}
1097
Tony-LunarG81efe392019-03-07 15:43:27 -07001098void CoreChecks::GpuPreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) {
1099 for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
1100 const VkSubmitInfo *submit = &pSubmits[submit_idx];
1101 for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
Mark Lobodzinskicefe42f2019-04-25 12:16:27 -06001102 auto cb_node = GetCBState(submit->pCommandBuffers[i]);
Tony-LunarG81efe392019-03-07 15:43:27 -07001103 UpdateInstrumentationBuffer(cb_node);
1104 for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
1105 UpdateInstrumentationBuffer(secondaryCmdBuffer);
1106 }
1107 }
1108 }
1109}
1110
Karl Schultz58674242019-01-22 15:35:02 -07001111// Issue a memory barrier to make GPU-written data available to host.
1112// Wait for the queue to complete execution.
1113// Check the debug buffers for all the command buffers that were submitted.
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001114void CoreChecks::GpuPostCallQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001115 if (gpu_validation_state->aborted) return;
Karl Schultz58674242019-01-22 15:35:02 -07001116
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001117 SubmitBarrier(queue);
Karl Schultz58674242019-01-22 15:35:02 -07001118
Tony-LunarG152a88b2019-03-20 15:42:24 -06001119 DispatchQueueWaitIdle(queue);
Karl Schultz58674242019-01-22 15:35:02 -07001120
Karl Schultz7b024b42018-08-30 16:18:18 -06001121 for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
1122 const VkSubmitInfo *submit = &pSubmits[submit_idx];
1123 for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
Mark Lobodzinskicefe42f2019-04-25 12:16:27 -06001124 auto cb_node = GetCBState(submit->pCommandBuffers[i]);
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001125 ProcessInstrumentationBuffer(queue, cb_node);
Karl Schultz7b024b42018-08-30 16:18:18 -06001126 for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001127 ProcessInstrumentationBuffer(queue, secondaryCmdBuffer);
Karl Schultz7b024b42018-08-30 16:18:18 -06001128 }
1129 }
1130 }
1131}
Tony-LunarGb2501d22019-01-28 09:59:13 -07001132
Mark Lobodzinski586d10e2019-03-08 18:19:48 -07001133void CoreChecks::GpuAllocateValidationResources(const VkCommandBuffer cmd_buffer, const VkPipelineBindPoint bind_point) {
andreygca287f22019-04-10 00:15:33 +03001134 // Does GPUAV support VK_PIPELINE_BIND_POINT_RAY_TRACING_NV?
1135 if (bind_point != VK_PIPELINE_BIND_POINT_GRAPHICS && bind_point != VK_PIPELINE_BIND_POINT_COMPUTE) {
1136 return;
1137 }
Tony-LunarGb2501d22019-01-28 09:59:13 -07001138 VkResult result;
1139
Mark Lobodzinskib02a4852019-04-19 12:35:30 -06001140 if (!(enabled.gpu_validation)) return;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001141
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001142 if (gpu_validation_state->aborted) return;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001143
1144 std::vector<VkDescriptorSet> desc_sets;
1145 VkDescriptorPool desc_pool = VK_NULL_HANDLE;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001146 result = gpu_validation_state->desc_set_manager->GetDescriptorSets(1, &desc_pool, &desc_sets);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001147 assert(result == VK_SUCCESS);
1148 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001149 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Tony-LunarGb2501d22019-01-28 09:59:13 -07001150 "Unable to allocate descriptor sets. Device could become unstable.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001151 gpu_validation_state->aborted = true;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001152 return;
1153 }
1154
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001155 VkDescriptorBufferInfo output_desc_buffer_info = {};
1156 output_desc_buffer_info.range = gpu_validation_state->output_buffer_size;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001157
Mark Lobodzinskicefe42f2019-04-25 12:16:27 -06001158 auto cb_node = GetCBState(cmd_buffer);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001159 if (!cb_node) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001160 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "Unrecognized command buffer");
1161 gpu_validation_state->aborted = true;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001162 return;
1163 }
1164
Tony-LunarG81efe392019-03-07 15:43:27 -07001165 // Allocate memory for the output block that the gpu will use to return any error information
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001166 GpuDeviceMemoryBlock output_block = {};
Tony-LunarG0e564722019-03-19 16:09:14 -06001167 VkBufferCreateInfo bufferInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
1168 bufferInfo.size = gpu_validation_state->output_buffer_size;
1169 bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
1170 VmaAllocationCreateInfo allocInfo = {};
1171 allocInfo.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001172 result = vmaCreateBuffer(gpu_validation_state->vmaAllocator, &bufferInfo, &allocInfo, &output_block.buffer,
1173 &output_block.allocation, nullptr);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001174 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001175 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Tony-LunarGb2501d22019-01-28 09:59:13 -07001176 "Unable to allocate device memory. Device could become unstable.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001177 gpu_validation_state->aborted = true;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001178 return;
1179 }
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001180
Tony-LunarG81efe392019-03-07 15:43:27 -07001181 // Clear the output block to zeros so that only error information from the gpu will be present
Tony-LunarGa77cade2019-03-06 10:49:22 -07001182 uint32_t *pData;
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001183 result = vmaMapMemory(gpu_validation_state->vmaAllocator, output_block.allocation, (void **)&pData);
Tony-LunarG0e564722019-03-19 16:09:14 -06001184 if (result == VK_SUCCESS) {
1185 memset(pData, 0, gpu_validation_state->output_buffer_size);
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001186 vmaUnmapMemory(gpu_validation_state->vmaAllocator, output_block.allocation);
1187 }
Tony-LunarG81efe392019-03-07 15:43:27 -07001188
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001189 GpuDeviceMemoryBlock input_block = {};
1190 VkWriteDescriptorSet desc_writes[2] = {};
1191 uint32_t desc_count = 1;
1192 auto const &state = cb_node->lastBound[bind_point];
1193 uint32_t number_of_sets = (uint32_t)state.boundDescriptorSets.size();
1194
Tony-LunarG81efe392019-03-07 15:43:27 -07001195 // Figure out how much memory we need for the input block based on how many sets and bindings there are
1196 // and how big each of the bindings is
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06001197 if (number_of_sets > 0 && device_extensions.vk_ext_descriptor_indexing) {
Tony-LunarG81efe392019-03-07 15:43:27 -07001198 uint32_t descriptor_count = 0; // Number of descriptors, including all array elements
1199 uint32_t binding_count = 0; // Number of bindings based on the max binding number used
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001200 for (auto desc : state.boundDescriptorSets) {
Tony-LunarGa77cade2019-03-06 10:49:22 -07001201 auto bindings = desc->GetLayout()->GetSortedBindingSet();
1202 if (bindings.size() > 0) {
1203 binding_count += desc->GetLayout()->GetMaxBinding() + 1;
1204 for (auto binding : bindings) {
1205 if (binding == desc->GetLayout()->GetMaxBinding() && desc->IsVariableDescriptorCount(binding)) {
1206 descriptor_count += desc->GetVariableDescriptorCount();
1207 } else {
1208 descriptor_count += desc->GetDescriptorCountFromBinding(binding);
1209 }
1210 }
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001211 }
1212 }
1213
Tony-LunarGa77cade2019-03-06 10:49:22 -07001214 // Note that the size of the input buffer is dependent on the maximum binding number, which
1215 // can be very large. This is because for (set = s, binding = b, index = i), the validation
1216 // code is going to dereference Input[ i + Input[ b + Input[ s + Input[ Input[0] ] ] ] ] to
1217 // see if descriptors have been written. In gpu_validation.md, we note this and advise
1218 // using densely packed bindings as a best practice when using gpu-av with descriptor indexing
1219 uint32_t words_needed = 1 + (number_of_sets * 2) + (binding_count * 2) + descriptor_count;
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001220 allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
1221 bufferInfo.size = words_needed * 4;
1222 result = vmaCreateBuffer(gpu_validation_state->vmaAllocator, &bufferInfo, &allocInfo, &input_block.buffer,
1223 &input_block.allocation, nullptr);
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001224 if (result != VK_SUCCESS) {
1225 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
1226 "Unable to allocate device memory. Device could become unstable.");
1227 gpu_validation_state->aborted = true;
1228 return;
1229 }
1230
Tony-LunarGa77cade2019-03-06 10:49:22 -07001231 // Populate input buffer first with the sizes of every descriptor in every set, then with whether
1232 // each element of each descriptor has been written or not. See gpu_validation.md for a more thourough
1233 // outline of the input buffer format
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001234 result = vmaMapMemory(gpu_validation_state->vmaAllocator, input_block.allocation, (void **)&pData);
Tony-LunarG76cdcac2019-05-22 16:13:12 -06001235 memset(pData, 0, static_cast<size_t>(bufferInfo.size));
Tony-LunarGa77cade2019-03-06 10:49:22 -07001236 // Pointer to a sets array that points into the sizes array
1237 uint32_t *sets_to_sizes = pData + 1;
1238 // Pointer to the sizes array that contains the array size of the descriptor at each binding
1239 uint32_t *sizes = sets_to_sizes + number_of_sets;
1240 // Pointer to another sets array that points into the bindings array that points into the written array
1241 uint32_t *sets_to_bindings = sizes + binding_count;
1242 // Pointer to the bindings array that points at the start of the writes in the writes array for each binding
1243 uint32_t *bindings_to_written = sets_to_bindings + number_of_sets;
1244 // Index of the next entry in the written array to be updated
1245 uint32_t written_index = 1 + (number_of_sets * 2) + (binding_count * 2);
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001246 uint32_t bindCounter = number_of_sets + 1;
Tony-LunarGa77cade2019-03-06 10:49:22 -07001247 // Index of the start of the sets_to_bindings array
1248 pData[0] = number_of_sets + binding_count + 1;
1249
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001250 for (auto desc : state.boundDescriptorSets) {
1251 auto layout = desc->GetLayout();
Tony-LunarG81efe392019-03-07 15:43:27 -07001252 auto bindings = layout->GetSortedBindingSet();
1253 if (bindings.size() > 0) {
1254 // For each set, fill in index of its bindings sizes in the sizes array
Tony-LunarGa77cade2019-03-06 10:49:22 -07001255 *sets_to_sizes++ = bindCounter;
Tony-LunarG81efe392019-03-07 15:43:27 -07001256 // For each set, fill in the index of its bindings in the bindings_to_written array
Tony-LunarGa77cade2019-03-06 10:49:22 -07001257 *sets_to_bindings++ = bindCounter + number_of_sets + binding_count;
Tony-LunarG81efe392019-03-07 15:43:27 -07001258 for (auto binding : bindings) {
Tony-LunarGa77cade2019-03-06 10:49:22 -07001259 // For each binding, fill in its size in the sizes array
1260 if (binding == layout->GetMaxBinding() && desc->IsVariableDescriptorCount(binding)) {
1261 sizes[binding] = desc->GetVariableDescriptorCount();
1262 } else {
1263 sizes[binding] = desc->GetDescriptorCountFromBinding(binding);
1264 }
1265 // Fill in the starting index for this binding in the written array in the bindings_to_written array
1266 bindings_to_written[binding] = written_index;
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001267
Tony-LunarGa77cade2019-03-06 10:49:22 -07001268 auto index_range = desc->GetGlobalIndexRangeFromBinding(binding, true);
1269 // For each array element in the binding, update the written array with whether it has been written
1270 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
1271 auto *descriptor = desc->GetDescriptorFromGlobalIndex(i);
Tony-LunarG81efe392019-03-07 15:43:27 -07001272 if (descriptor->updated) {
1273 pData[written_index] = 1;
1274 } else if (desc->IsUpdateAfterBind(binding)) {
1275 // If it hasn't been written now and it's update after bind, put it in a list to check at QueueSubmit
1276 input_block.update_at_submit[written_index] = descriptor;
1277 }
Tony-LunarGa77cade2019-03-06 10:49:22 -07001278 written_index++;
1279 }
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001280 }
Tony-LunarG81efe392019-03-07 15:43:27 -07001281 auto last = desc->GetLayout()->GetMaxBinding();
1282 bindings_to_written += last + 1;
1283 bindCounter += last + 1;
1284 sizes += last + 1;
Tony-LunarGa77cade2019-03-06 10:49:22 -07001285 } else {
1286 *sets_to_sizes++ = 0;
1287 *sets_to_bindings++ = 0;
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001288 }
1289 }
1290 vmaUnmapMemory(gpu_validation_state->vmaAllocator, input_block.allocation);
1291
1292 VkDescriptorBufferInfo input_desc_buffer_info = {};
1293 input_desc_buffer_info.range = (words_needed * 4);
1294 input_desc_buffer_info.buffer = input_block.buffer;
1295 input_desc_buffer_info.offset = 0;
1296
1297 desc_writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1298 desc_writes[1].dstBinding = 1;
1299 desc_writes[1].descriptorCount = 1;
1300 desc_writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
1301 desc_writes[1].pBufferInfo = &input_desc_buffer_info;
1302 desc_writes[1].dstSet = desc_sets[0];
1303
1304 desc_count = 2;
Tony-LunarG0e564722019-03-19 16:09:14 -06001305 }
Tony-LunarGb2501d22019-01-28 09:59:13 -07001306
1307 // Write the descriptor
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001308 output_desc_buffer_info.buffer = output_block.buffer;
1309 output_desc_buffer_info.offset = 0;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001310
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001311 desc_writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1312 desc_writes[0].descriptorCount = 1;
1313 desc_writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
1314 desc_writes[0].pBufferInfo = &output_desc_buffer_info;
1315 desc_writes[0].dstSet = desc_sets[0];
1316 DispatchUpdateDescriptorSets(device, desc_count, desc_writes, 0, NULL);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001317
andreyg25ce2622019-04-05 23:07:59 +03001318 auto iter = cb_node->lastBound.find(bind_point); // find() allows read-only access to cb_state
Tony-LunarGb2501d22019-01-28 09:59:13 -07001319 if (iter != cb_node->lastBound.end()) {
1320 auto pipeline_state = iter->second.pipeline_state;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001321 if (pipeline_state && (pipeline_state->pipeline_layout.set_layouts.size() <= gpu_validation_state->desc_set_bind_index)) {
Tony-LunarG152a88b2019-03-20 15:42:24 -06001322 DispatchCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_state->pipeline_layout.layout,
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001323 gpu_validation_state->desc_set_bind_index, 1, desc_sets.data(), 0, nullptr);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001324 }
Tony-LunarG0e564722019-03-19 16:09:14 -06001325 // Record buffer and memory info in CB state tracking
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001326 gpu_validation_state->GetGpuBufferInfo(cmd_buffer).emplace_back(output_block, input_block, desc_sets[0], desc_pool);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001327 } else {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001328 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "Unable to find pipeline state");
Tony-LunarG1b2e0c32019-02-07 17:13:27 -07001329 vmaDestroyBuffer(gpu_validation_state->vmaAllocator, input_block.buffer, input_block.allocation);
1330 vmaDestroyBuffer(gpu_validation_state->vmaAllocator, output_block.buffer, output_block.allocation);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001331 gpu_validation_state->aborted = true;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001332 return;
1333 }
1334}