blob: 62f840549b3cd87b42a81e60d402ee09e7c4571d [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.
39static const uint32_t kNumBindingsInSet = 1;
40
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-LunarGd85808d2019-02-27 16:12:02 -0700125void GpuDescriptorSetManager::DestroyDescriptorPools() {
126 for (auto &pool : desc_pool_map_) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600127 DispatchDestroyDescriptorPool(dev_data_->device, pool.first, NULL);
Tony-LunarGd85808d2019-02-27 16:12:02 -0700128 }
129 desc_pool_map_.clear();
130}
131
Tony-LunarG0e564722019-03-19 16:09:14 -0600132// Trampolines to make VMA call Dispatch for Vulkan calls
133static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
134 VkPhysicalDeviceProperties *pProperties) {
135 DispatchGetPhysicalDeviceProperties(physicalDevice, pProperties);
136}
137static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceMemoryProperties(VkPhysicalDevice physicalDevice,
138 VkPhysicalDeviceMemoryProperties *pMemoryProperties) {
139 DispatchGetPhysicalDeviceMemoryProperties(physicalDevice, pMemoryProperties);
140}
141static VKAPI_ATTR VkResult VKAPI_CALL gpuVkAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
142 const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) {
143 return DispatchAllocateMemory(device, pAllocateInfo, pAllocator, pMemory);
144}
145static VKAPI_ATTR void VKAPI_CALL gpuVkFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks *pAllocator) {
146 DispatchFreeMemory(device, memory, pAllocator);
147}
148static VKAPI_ATTR VkResult VKAPI_CALL gpuVkMapMemory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size,
149 VkMemoryMapFlags flags, void **ppData) {
150 return DispatchMapMemory(device, memory, offset, size, flags, ppData);
151}
152static VKAPI_ATTR void VKAPI_CALL gpuVkUnmapMemory(VkDevice device, VkDeviceMemory memory) { DispatchUnmapMemory(device, memory); }
153static VKAPI_ATTR VkResult VKAPI_CALL gpuVkFlushMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
154 const VkMappedMemoryRange *pMemoryRanges) {
155 return DispatchFlushMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
156}
157static VKAPI_ATTR VkResult VKAPI_CALL gpuVkInvalidateMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
158 const VkMappedMemoryRange *pMemoryRanges) {
159 return DispatchInvalidateMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
160}
161static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
162 VkDeviceSize memoryOffset) {
163 return DispatchBindBufferMemory(device, buffer, memory, memoryOffset);
164}
165static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
166 VkDeviceSize memoryOffset) {
167 return DispatchBindImageMemory(device, image, memory, memoryOffset);
168}
169static VKAPI_ATTR void VKAPI_CALL gpuVkGetBufferMemoryRequirements(VkDevice device, VkBuffer buffer,
170 VkMemoryRequirements *pMemoryRequirements) {
171 DispatchGetBufferMemoryRequirements(device, buffer, pMemoryRequirements);
172}
173static VKAPI_ATTR void VKAPI_CALL gpuVkGetImageMemoryRequirements(VkDevice device, VkImage image,
174 VkMemoryRequirements *pMemoryRequirements) {
175 DispatchGetImageMemoryRequirements(device, image, pMemoryRequirements);
176}
177static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
178 const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
179 return DispatchCreateBuffer(device, pCreateInfo, pAllocator, pBuffer);
180}
181static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
182 return DispatchDestroyBuffer(device, buffer, pAllocator);
183}
184static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
185 const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
186 return DispatchCreateImage(device, pCreateInfo, pAllocator, pImage);
187}
188static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
189 DispatchDestroyImage(device, image, pAllocator);
190}
191static VKAPI_ATTR void VKAPI_CALL gpuVkCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
192 uint32_t regionCount, const VkBufferCopy *pRegions) {
193 DispatchCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, regionCount, pRegions);
194}
195
196VkResult CoreChecks::GpuInitializeVma() {
197 VmaVulkanFunctions functions;
198 VmaAllocatorCreateInfo allocatorInfo = {};
199 allocatorInfo.device = device;
200 ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(allocatorInfo.device), layer_data_map);
201 ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeCoreValidation);
202 CoreChecks *core_checks = static_cast<CoreChecks *>(validation_data);
203 allocatorInfo.physicalDevice = core_checks->physical_device;
204
205 functions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)gpuVkGetPhysicalDeviceProperties;
206 functions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)gpuVkGetPhysicalDeviceMemoryProperties;
207 functions.vkAllocateMemory = (PFN_vkAllocateMemory)gpuVkAllocateMemory;
208 functions.vkFreeMemory = (PFN_vkFreeMemory)gpuVkFreeMemory;
209 functions.vkMapMemory = (PFN_vkMapMemory)gpuVkMapMemory;
210 functions.vkUnmapMemory = (PFN_vkUnmapMemory)gpuVkUnmapMemory;
211 functions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)gpuVkFlushMappedMemoryRanges;
212 functions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)gpuVkInvalidateMappedMemoryRanges;
213 functions.vkBindBufferMemory = (PFN_vkBindBufferMemory)gpuVkBindBufferMemory;
214 functions.vkBindImageMemory = (PFN_vkBindImageMemory)gpuVkBindImageMemory;
215 functions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)gpuVkGetBufferMemoryRequirements;
216 functions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)gpuVkGetImageMemoryRequirements;
217 functions.vkCreateBuffer = (PFN_vkCreateBuffer)gpuVkCreateBuffer;
218 functions.vkDestroyBuffer = (PFN_vkDestroyBuffer)gpuVkDestroyBuffer;
219 functions.vkCreateImage = (PFN_vkCreateImage)gpuVkCreateImage;
220 functions.vkDestroyImage = (PFN_vkDestroyImage)gpuVkDestroyImage;
221 functions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)gpuVkCmdCopyBuffer;
222 allocatorInfo.pVulkanFunctions = &functions;
223
224 return vmaCreateAllocator(&allocatorInfo, &gpu_validation_state->vmaAllocator);
225}
226
Karl Schultz7b024b42018-08-30 16:18:18 -0600227// Convenience function for reporting problems with setting up GPU Validation.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700228void CoreChecks::ReportSetupProblem(VkDebugReportObjectTypeEXT object_type, uint64_t object_handle,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700229 const char *const specific_message) {
230 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object_handle, "UNASSIGNED-GPU-Assisted Validation Error. ",
231 "Detail: (%s)", specific_message);
Karl Schultz7b024b42018-08-30 16:18:18 -0600232}
233
234// Turn on necessary device features.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700235void CoreChecks::GpuPreCallRecordCreateDevice(VkPhysicalDevice gpu, std::unique_ptr<safe_VkDeviceCreateInfo> &create_info,
236 VkPhysicalDeviceFeatures *supported_features) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600237 if (supported_features->fragmentStoresAndAtomics || supported_features->vertexPipelineStoresAndAtomics) {
Tony-LunarG48b478a2019-01-15 16:35:22 -0700238 VkPhysicalDeviceFeatures new_features = {};
Mark Lobodzinski5eb3c262019-03-01 16:08:30 -0700239 if (create_info->pEnabledFeatures) {
240 new_features = *create_info->pEnabledFeatures;
Tony-LunarG48b478a2019-01-15 16:35:22 -0700241 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600242 new_features.fragmentStoresAndAtomics = supported_features->fragmentStoresAndAtomics;
243 new_features.vertexPipelineStoresAndAtomics = supported_features->vertexPipelineStoresAndAtomics;
Mark Lobodzinski5eb3c262019-03-01 16:08:30 -0700244 delete create_info->pEnabledFeatures;
245 create_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
Karl Schultz7b024b42018-08-30 16:18:18 -0600246 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600247}
248
249// Perform initializations that can be done at Create Device time.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600250void CoreChecks::GpuPostCallRecordCreateDevice(const CHECK_ENABLED *enables) {
251 gpu_validation_state = std::unique_ptr<GpuValidationState>(new GpuValidationState);
Karl Schultz7b024b42018-08-30 16:18:18 -0600252
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600253 gpu_validation_state->aborted = false;
254 gpu_validation_state->reserve_binding_slot = false;
255 gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
256 gpu_validation_state->barrier_command_buffer = VK_NULL_HANDLE;
257 gpu_validation_state->reserve_binding_slot = enables->gpu_validation_reserve_binding_slot;
Tony-LunarG65f9c492019-01-17 14:24:42 -0700258
Mark Lobodzinski5c048802019-03-07 10:47:31 -0700259 if (GetPDProperties()->apiVersion < VK_API_VERSION_1_1) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600260 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600261 "GPU-Assisted validation requires Vulkan 1.1 or later. GPU-Assisted Validation disabled.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600262 gpu_validation_state->aborted = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600263 return;
264 }
265 // Some devices have extremely high limits here, so set a reasonable max because we have to pad
266 // the pipeline layout with dummy descriptor set layouts.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600267 gpu_validation_state->adjusted_max_desc_sets = GetPDProperties()->limits.maxBoundDescriptorSets;
268 gpu_validation_state->adjusted_max_desc_sets = std::min(33U, gpu_validation_state->adjusted_max_desc_sets);
Karl Schultz7b024b42018-08-30 16:18:18 -0600269
270 // We can't do anything if there is only one.
271 // Device probably not a legit Vulkan device, since there should be at least 4. Protect ourselves.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600272 if (gpu_validation_state->adjusted_max_desc_sets == 1) {
273 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600274 "Device can bind only a single descriptor set. GPU-Assisted Validation disabled.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600275 gpu_validation_state->aborted = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600276 return;
277 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600278 gpu_validation_state->desc_set_bind_index = gpu_validation_state->adjusted_max_desc_sets - 1;
279 log_msg(report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
280 "UNASSIGNED-GPU-Assisted Validation. ", "Shaders using descriptor set at index %d. ",
281 gpu_validation_state->desc_set_bind_index);
Karl Schultz7b024b42018-08-30 16:18:18 -0600282
Tony-LunarG0e564722019-03-19 16:09:14 -0600283 gpu_validation_state->output_buffer_size = sizeof(uint32_t) * (spvtools::kInstMaxOutCnt + 1);
284 VkResult result = GpuInitializeVma();
285 assert(result == VK_SUCCESS);
Mark Lobodzinski3bf82a52019-03-11 11:49:34 -0600286 std::unique_ptr<GpuDescriptorSetManager> desc_set_manager(new GpuDescriptorSetManager(this));
Karl Schultz7b024b42018-08-30 16:18:18 -0600287
288 // The descriptor indexing checks require only the first "output" binding.
289 const VkDescriptorSetLayoutBinding debug_desc_layout_bindings[kNumBindingsInSet] = {
290 {
291 0, // output
292 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
293 1,
294 VK_SHADER_STAGE_ALL_GRAPHICS,
295 NULL,
296 },
297 };
298
299 const VkDescriptorSetLayoutCreateInfo debug_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0,
300 kNumBindingsInSet, debug_desc_layout_bindings};
301
302 const VkDescriptorSetLayoutCreateInfo dummy_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 0,
303 NULL};
304
Tony-LunarG0e564722019-03-19 16:09:14 -0600305 result = DispatchCreateDescriptorSetLayout(device, &debug_desc_layout_info, NULL, &gpu_validation_state->debug_desc_layout);
Karl Schultz7b024b42018-08-30 16:18:18 -0600306
307 // 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 -0700308 VkResult result2 =
Tony-LunarG152a88b2019-03-20 15:42:24 -0600309 DispatchCreateDescriptorSetLayout(device, &dummy_desc_layout_info, NULL, &gpu_validation_state->dummy_desc_layout);
Karl Schultz7b024b42018-08-30 16:18:18 -0600310 assert((result == VK_SUCCESS) && (result2 == VK_SUCCESS));
311 if ((result != VK_SUCCESS) || (result2 != VK_SUCCESS)) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600312 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600313 "Unable to create descriptor set layout. GPU-Assisted Validation disabled.");
314 if (result == VK_SUCCESS) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600315 DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->debug_desc_layout, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600316 }
317 if (result2 == VK_SUCCESS) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600318 DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->dummy_desc_layout, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600319 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600320 gpu_validation_state->debug_desc_layout = VK_NULL_HANDLE;
321 gpu_validation_state->dummy_desc_layout = VK_NULL_HANDLE;
322 gpu_validation_state->aborted = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600323 return;
324 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600325 gpu_validation_state->desc_set_manager = std::move(desc_set_manager);
Karl Schultz7b024b42018-08-30 16:18:18 -0600326}
327
328// Clean up device-related resources
Mark Lobodzinski70f00652019-03-07 15:22:47 -0700329void CoreChecks::GpuPreCallRecordDestroyDevice() {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600330 if (gpu_validation_state->barrier_command_buffer) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600331 DispatchFreeCommandBuffers(device, gpu_validation_state->barrier_command_pool, 1,
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600332 &gpu_validation_state->barrier_command_buffer);
333 gpu_validation_state->barrier_command_buffer = VK_NULL_HANDLE;
Karl Schultz58674242019-01-22 15:35:02 -0700334 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600335 if (gpu_validation_state->barrier_command_pool) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600336 DispatchDestroyCommandPool(device, gpu_validation_state->barrier_command_pool, NULL);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600337 gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
Karl Schultz58674242019-01-22 15:35:02 -0700338 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600339 if (gpu_validation_state->debug_desc_layout) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600340 DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->debug_desc_layout, NULL);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600341 gpu_validation_state->debug_desc_layout = VK_NULL_HANDLE;
Karl Schultz7b024b42018-08-30 16:18:18 -0600342 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600343 if (gpu_validation_state->dummy_desc_layout) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600344 DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->dummy_desc_layout, NULL);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600345 gpu_validation_state->dummy_desc_layout = VK_NULL_HANDLE;
Karl Schultz7b024b42018-08-30 16:18:18 -0600346 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600347 gpu_validation_state->desc_set_manager->DestroyDescriptorPools();
Tony-LunarG0e564722019-03-19 16:09:14 -0600348 vmaDestroyAllocator(gpu_validation_state->vmaAllocator);
Karl Schultz7b024b42018-08-30 16:18:18 -0600349}
350
Karl Schultz7b024b42018-08-30 16:18:18 -0600351// 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 -0700352bool CoreChecks::GpuPreCallCreatePipelineLayout(const VkPipelineLayoutCreateInfo *pCreateInfo,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700353 const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout,
354 std::vector<VkDescriptorSetLayout> *new_layouts,
355 VkPipelineLayoutCreateInfo *modified_create_info) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600356 if (gpu_validation_state->aborted) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700357 return false;
Karl Schultz7b024b42018-08-30 16:18:18 -0600358 }
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700359
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600360 if (modified_create_info->setLayoutCount >= gpu_validation_state->adjusted_max_desc_sets) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600361 std::ostringstream strm;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600362 strm << "Pipeline Layout conflict with validation's descriptor set at slot " << gpu_validation_state->desc_set_bind_index
363 << ". "
Karl Schultz7b024b42018-08-30 16:18:18 -0600364 << "Application has too many descriptor sets in the pipeline layout to continue with gpu validation. "
365 << "Validation is not modifying the pipeline layout. "
366 << "Instrumented shaders are replaced with non-instrumented shaders.";
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600367 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), strm.str().c_str());
Karl Schultz7b024b42018-08-30 16:18:18 -0600368 } else {
369 // Modify the pipeline layout by:
370 // 1. Copying the caller's descriptor set desc_layouts
371 // 2. Fill in dummy descriptor layouts up to the max binding
372 // 3. Fill in with the debug descriptor layout at the max binding slot
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600373 new_layouts->reserve(gpu_validation_state->adjusted_max_desc_sets);
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700374 new_layouts->insert(new_layouts->end(), &pCreateInfo->pSetLayouts[0],
375 &pCreateInfo->pSetLayouts[pCreateInfo->setLayoutCount]);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600376 for (uint32_t i = pCreateInfo->setLayoutCount; i < gpu_validation_state->adjusted_max_desc_sets - 1; ++i) {
377 new_layouts->push_back(gpu_validation_state->dummy_desc_layout);
Karl Schultz7b024b42018-08-30 16:18:18 -0600378 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600379 new_layouts->push_back(gpu_validation_state->debug_desc_layout);
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700380 modified_create_info->pSetLayouts = new_layouts->data();
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600381 modified_create_info->setLayoutCount = gpu_validation_state->adjusted_max_desc_sets;
Karl Schultz7b024b42018-08-30 16:18:18 -0600382 }
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700383 return true;
384}
385
386// Clean up GPU validation after the CreatePipelineLayout call is made
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700387void CoreChecks::GpuPostCallCreatePipelineLayout(VkResult result) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700388 // Clean up GPU validation
Karl Schultz7b024b42018-08-30 16:18:18 -0600389 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600390 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600391 "Unable to create pipeline layout. Device could become unstable.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600392 gpu_validation_state->aborted = true;
Karl Schultz7b024b42018-08-30 16:18:18 -0600393 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600394}
395
Karl Schultz7b024b42018-08-30 16:18:18 -0600396// Free the device memory and descriptor set associated with a command buffer.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700397void CoreChecks::GpuPreCallRecordFreeCommandBuffers(uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600398 if (gpu_validation_state->aborted) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600399 return;
400 }
401 for (uint32_t i = 0; i < commandBufferCount; ++i) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600402 auto gpu_buffer_list = gpu_validation_state->GetGpuBufferInfo(pCommandBuffers[i]);
403 for (auto buffer_info : gpu_buffer_list) {
Tony-LunarG0e564722019-03-19 16:09:14 -0600404 vmaDestroyBuffer(gpu_validation_state->vmaAllocator, buffer_info.mem_block.buffer, buffer_info.mem_block.allocation);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600405 if (buffer_info.desc_set != VK_NULL_HANDLE) {
406 gpu_validation_state->desc_set_manager->PutBackDescriptorSet(buffer_info.desc_pool, buffer_info.desc_set);
407 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600408 }
Tony-LunarG0e564722019-03-19 16:09:14 -0600409 gpu_validation_state->command_buffer_map.erase(pCommandBuffers[i]);
Karl Schultz7b024b42018-08-30 16:18:18 -0600410 }
411}
412
413// Just gives a warning about a possible deadlock.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700414void CoreChecks::GpuPreCallValidateCmdWaitEvents(VkPipelineStageFlags sourceStageMask) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600415 if (sourceStageMask & VK_PIPELINE_STAGE_HOST_BIT) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600416 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz7b024b42018-08-30 16:18:18 -0600417 "CmdWaitEvents recorded with VK_PIPELINE_STAGE_HOST_BIT set. "
418 "GPU_Assisted validation waits on queue completion. "
419 "This wait could block the host's signaling of this event, resulting in deadlock.");
420 }
421}
422
423// Examine the pipelines to see if they use the debug descriptor set binding index.
424// If any do, create new non-instrumented shader modules and use them to replace the instrumented
425// shaders in the pipeline. Return the (possibly) modified create infos to the caller.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700426std::vector<safe_VkGraphicsPipelineCreateInfo> CoreChecks::GpuPreCallRecordCreateGraphicsPipelines(
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700427 VkPipelineCache pipelineCache, uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
Karl Schultz7b024b42018-08-30 16:18:18 -0600428 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600429 std::vector<safe_VkGraphicsPipelineCreateInfo> new_pipeline_create_infos;
430 std::vector<unsigned int> pipeline_uses_debug_index(count);
431
432 // Walk through all the pipelines, make a copy of each and flag each pipeline that contains a shader that uses the debug
433 // descriptor set index.
434 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
435 new_pipeline_create_infos.push_back(pipe_state[pipeline]->graphicsPipelineCI);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600436 if (pipe_state[pipeline]->active_slots.find(gpu_validation_state->desc_set_bind_index) !=
437 pipe_state[pipeline]->active_slots.end()) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600438 pipeline_uses_debug_index[pipeline] = 1;
439 }
440 }
441
442 // See if any pipeline has shaders using the debug descriptor set index
443 if (std::all_of(pipeline_uses_debug_index.begin(), pipeline_uses_debug_index.end(), [](unsigned int i) { return i == 0; })) {
444 // None of the shaders in all the pipelines use the debug descriptor set index, so use the pipelines
445 // as they stand with the instrumented shaders.
446 return new_pipeline_create_infos;
447 }
448
449 // At least one pipeline has a shader that uses the debug descriptor set index.
450 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
451 if (pipeline_uses_debug_index[pipeline]) {
452 for (uint32_t stage = 0; stage < pCreateInfos[pipeline].stageCount; ++stage) {
Mark Lobodzinski9e9da292019-03-06 16:19:55 -0700453 const shader_module *shader = GetShaderModuleState(pCreateInfos[pipeline].pStages[stage].module);
Karl Schultz7b024b42018-08-30 16:18:18 -0600454 VkShaderModuleCreateInfo create_info = {};
455 VkShaderModule shader_module;
456 create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
457 create_info.pCode = shader->words.data();
458 create_info.codeSize = shader->words.size() * sizeof(uint32_t);
Tony-LunarG152a88b2019-03-20 15:42:24 -0600459 VkResult result = DispatchCreateShaderModule(device, &create_info, pAllocator, &shader_module);
Karl Schultz7b024b42018-08-30 16:18:18 -0600460 if (result == VK_SUCCESS) {
461 new_pipeline_create_infos[pipeline].pStages[stage].module = shader_module;
462 } else {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700463 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
Karl Schultz7b024b42018-08-30 16:18:18 -0600464 HandleToUint64(pCreateInfos[pipeline].pStages[stage].module),
465 "Unable to replace instrumented shader with non-instrumented one. "
466 "Device could become unstable.");
467 }
468 }
469 }
470 }
471 return new_pipeline_create_infos;
472}
473
474// For every pipeline:
475// - For every shader in a pipeline:
476// - If the shader had to be replaced in PreCallRecord (because the pipeline is using the debug desc set index):
477// - Destroy it since it has been bound into the pipeline by now. This is our only chance to delete it.
478// - Track the shader in the shader_map
479// - Save the shader binary if it contains debug code
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700480void CoreChecks::GpuPostCallRecordCreateGraphicsPipelines(const uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700481 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600482 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
Mark Lobodzinskifd917d22019-03-06 16:07:15 -0700483 auto pipeline_state = GetPipelineState(pPipelines[pipeline]);
Karl Schultz7b024b42018-08-30 16:18:18 -0600484 if (nullptr == pipeline_state) continue;
485 for (uint32_t stage = 0; stage < pipeline_state->graphicsPipelineCI.stageCount; ++stage) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600486 if (pipeline_state->active_slots.find(gpu_validation_state->desc_set_bind_index) !=
487 pipeline_state->active_slots.end()) {
Tony-LunarG152a88b2019-03-20 15:42:24 -0600488 DispatchDestroyShaderModule(device, pCreateInfos->pStages[stage].module, pAllocator);
Karl Schultz7b024b42018-08-30 16:18:18 -0600489 }
Mark Lobodzinski9e9da292019-03-06 16:19:55 -0700490 auto shader_state = GetShaderModuleState(pipeline_state->graphicsPipelineCI.pStages[stage].module);
Karl Schultz7b024b42018-08-30 16:18:18 -0600491 std::vector<unsigned int> code;
492 // Save the shader binary if debug info is present.
493 // The core_validation ShaderModule tracker saves the binary too, but discards it when the ShaderModule
494 // is destroyed. Applications may destroy ShaderModules after they are placed in a pipeline and before
495 // the pipeline is used, so we have to keep another copy.
496 if (shader_state && shader_state->has_valid_spirv) { // really checking for presense of SPIR-V code.
497 for (auto insn : *shader_state) {
498 if (insn.opcode() == spv::OpLine) {
499 code = shader_state->words;
500 break;
501 }
502 }
503 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600504 gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].pipeline = pipeline_state->pipeline;
Karl Schultz7b024b42018-08-30 16:18:18 -0600505 // Be careful to use the originally bound (instrumented) shader here, even if PreCallRecord had to back it
506 // out with a non-instrumented shader. The non-instrumented shader (found in pCreateInfo) was destroyed above.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600507 gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].shader_module =
Karl Schultz7b024b42018-08-30 16:18:18 -0600508 pipeline_state->graphicsPipelineCI.pStages[stage].module;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600509 gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].pgm = std::move(code);
Karl Schultz7b024b42018-08-30 16:18:18 -0600510 }
511 }
512}
513
514// Remove all the shader trackers associated with this destroyed pipeline.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700515void CoreChecks::GpuPreCallRecordDestroyPipeline(const VkPipeline pipeline) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600516 for (auto it = gpu_validation_state->shader_map.begin(); it != gpu_validation_state->shader_map.end();) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600517 if (it->second.pipeline == pipeline) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600518 it = gpu_validation_state->shader_map.erase(it);
Karl Schultz7b024b42018-08-30 16:18:18 -0600519 } else {
520 ++it;
521 }
522 }
523}
524
525// Call the SPIR-V Optimizer to run the instrumentation pass on the shader.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700526bool CoreChecks::GpuInstrumentShader(const VkShaderModuleCreateInfo *pCreateInfo, std::vector<unsigned int> &new_pgm,
527 uint32_t *unique_shader_id) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600528 if (gpu_validation_state->aborted) return false;
Karl Schultz7b024b42018-08-30 16:18:18 -0600529 if (pCreateInfo->pCode[0] != spv::MagicNumber) return false;
530
531 // Load original shader SPIR-V
532 uint32_t num_words = static_cast<uint32_t>(pCreateInfo->codeSize / 4);
533 new_pgm.clear();
534 new_pgm.reserve(num_words);
535 new_pgm.insert(new_pgm.end(), &pCreateInfo->pCode[0], &pCreateInfo->pCode[num_words]);
536
537 // Call the optimizer to instrument the shader.
538 // Use the unique_shader_module_id as a shader ID so we can look up its handle later in the shader_map.
539 using namespace spvtools;
540 spv_target_env target_env = SPV_ENV_VULKAN_1_1;
541 Optimizer optimizer(target_env);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600542 optimizer.RegisterPass(
543 CreateInstBindlessCheckPass(gpu_validation_state->desc_set_bind_index, gpu_validation_state->unique_shader_module_id));
Karl Schultz7b024b42018-08-30 16:18:18 -0600544 optimizer.RegisterPass(CreateAggressiveDCEPass());
545 bool pass = optimizer.Run(new_pgm.data(), new_pgm.size(), &new_pgm);
546 if (!pass) {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700547 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, VK_NULL_HANDLE,
Karl Schultz7b024b42018-08-30 16:18:18 -0600548 "Failure to instrument shader. Proceeding with non-instrumented shader.");
549 }
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600550 *unique_shader_id = gpu_validation_state->unique_shader_module_id++;
Karl Schultz7b024b42018-08-30 16:18:18 -0600551 return pass;
552}
553
Mark Lobodzinski01734072019-02-13 17:39:15 -0700554// Create the instrumented shader data to provide to the driver.
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700555bool CoreChecks::GpuPreCallCreateShaderModule(const VkShaderModuleCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator,
556 VkShaderModule *pShaderModule, uint32_t *unique_shader_id,
557 VkShaderModuleCreateInfo *instrumented_create_info,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700558 std::vector<unsigned int> *instrumented_pgm) {
Mark Lobodzinski586d10e2019-03-08 18:19:48 -0700559 bool pass = GpuInstrumentShader(pCreateInfo, *instrumented_pgm, unique_shader_id);
Karl Schultz7b024b42018-08-30 16:18:18 -0600560 if (pass) {
Mark Lobodzinski01734072019-02-13 17:39:15 -0700561 instrumented_create_info->pCode = instrumented_pgm->data();
562 instrumented_create_info->codeSize = instrumented_pgm->size() * sizeof(unsigned int);
Karl Schultz7b024b42018-08-30 16:18:18 -0600563 }
Mark Lobodzinski01734072019-02-13 17:39:15 -0700564 return pass;
Karl Schultz7b024b42018-08-30 16:18:18 -0600565}
566
567// Generate the stage-specific part of the message.
568static void GenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
569 using namespace spvtools;
570 std::ostringstream strm;
571 switch (debug_record[kInstCommonOutStageIdx]) {
572 case 0: {
Tony-LunarG6ff87582019-02-08 10:29:07 -0700573 strm << "Stage = Vertex. Vertex Index = " << debug_record[kInstVertOutVertexIndex]
574 << " Instance Index = " << debug_record[kInstVertOutInstanceIndex] << ". ";
Karl Schultz7b024b42018-08-30 16:18:18 -0600575 } break;
576 case 1: {
577 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
578 } break;
579 case 2: {
580 strm << "Stage = Tessellation Eval. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
581 } break;
582 case 3: {
583 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
584 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
585 } break;
586 case 4: {
587 strm << "Stage = Fragment. Fragment coord (x,y) = ("
588 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
589 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
590 } break;
591 case 5: {
592 strm << "Stage = Compute. Global invocation ID = " << debug_record[kInstCompOutGlobalInvocationId] << ". ";
593 } break;
594 default: {
595 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
596 assert(false);
597 } break;
598 }
599 msg = strm.str();
600}
601
602// Generate the part of the message describing the violation.
603static void GenerateValidationMessage(const uint32_t *debug_record, std::string &msg, std::string &vuid_msg) {
604 using namespace spvtools;
605 std::ostringstream strm;
606 switch (debug_record[kInstValidationOutError]) {
607 case 0: {
608 strm << "Index of " << debug_record[kInstBindlessOutDescIndex] << " used to index descriptor array of length "
609 << debug_record[kInstBindlessOutDescBound] << ". ";
Tony-LunarGc1d657d2019-02-22 14:55:19 -0700610 vuid_msg = "UNASSIGNED-Descriptor index out of bounds";
Karl Schultz7b024b42018-08-30 16:18:18 -0600611 } break;
612 case 1: {
Karl Schultz7b024b42018-08-30 16:18:18 -0600613 strm << "Descriptor index " << debug_record[kInstBindlessOutDescIndex] << " is uninitialized. ";
Tony-LunarGc1d657d2019-02-22 14:55:19 -0700614 vuid_msg = "UNASSIGNED-Descriptor uninitialized";
Karl Schultz7b024b42018-08-30 16:18:18 -0600615 } break;
616 default: {
617 strm << "Internal Error (unexpected error type = " << debug_record[kInstValidationOutError] << "). ";
618 vuid_msg = "UNASSIGNED-Internal Error";
619 assert(false);
620 } break;
621 }
622 msg = strm.str();
623}
624
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700625static std::string LookupDebugUtilsName(const debug_report_data *report_data, const uint64_t object) {
Mark Lobodzinski1d7313a2019-02-07 11:04:42 -0700626 auto object_label = report_data->DebugReportGetUtilsObjectName(object);
627 if (object_label != "") {
628 object_label = "(" + object_label + ")";
Karl Schultz7b024b42018-08-30 16:18:18 -0600629 }
Mark Lobodzinski1d7313a2019-02-07 11:04:42 -0700630 return object_label;
Karl Schultz7b024b42018-08-30 16:18:18 -0600631}
632
633// Generate message from the common portion of the debug report record.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700634static void GenerateCommonMessage(const debug_report_data *report_data, const GLOBAL_CB_NODE *cb_node, const uint32_t *debug_record,
Tony-LunarGd589c7c2019-01-31 11:23:44 -0700635 const VkShaderModule shader_module_handle, const VkPipeline pipeline_handle,
636 const uint32_t draw_index, std::string &msg) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600637 using namespace spvtools;
638 std::ostringstream strm;
639 if (shader_module_handle == VK_NULL_HANDLE) {
640 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700641 << LookupDebugUtilsName(report_data, HandleToUint64(cb_node->commandBuffer)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600642 << HandleToUint64(cb_node->commandBuffer) << "). ";
643 assert(true);
644 } else {
645 strm << std::hex << std::showbase << "Command buffer "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700646 << LookupDebugUtilsName(report_data, HandleToUint64(cb_node->commandBuffer)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600647 << HandleToUint64(cb_node->commandBuffer) << "). "
Tony-LunarGd589c7c2019-01-31 11:23:44 -0700648 << "Draw Index " << draw_index << ". "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700649 << "Pipeline " << LookupDebugUtilsName(report_data, HandleToUint64(pipeline_handle)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600650 << HandleToUint64(pipeline_handle) << "). "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700651 << "Shader Module " << LookupDebugUtilsName(report_data, HandleToUint64(shader_module_handle)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600652 << HandleToUint64(shader_module_handle) << "). ";
653 }
654 strm << std::dec << std::noshowbase;
655 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
656 msg = strm.str();
657}
658
659// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
660// Split the single string into a vector of strings, one for each line, for easier processing.
661static void ReadOpSource(const shader_module &shader, const uint32_t reported_file_id, std::vector<std::string> &opsource_lines) {
662 for (auto insn : shader) {
663 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
664 std::istringstream in_stream;
665 std::string cur_line;
666 in_stream.str((char *)&insn.word(4));
667 while (std::getline(in_stream, cur_line)) {
668 opsource_lines.push_back(cur_line);
669 }
670 while ((++insn).opcode() == spv::OpSourceContinued) {
671 in_stream.str((char *)&insn.word(1));
672 while (std::getline(in_stream, cur_line)) {
673 opsource_lines.push_back(cur_line);
674 }
675 }
676 break;
677 }
678 }
679}
Tony-LunarG03059b72019-02-19 13:57:41 -0700680
681// The task here is to search the OpSource content to find the #line directive with the
682// line number that is closest to, but still prior to the reported error line number and
683// still within the reported filename.
684// From this known position in the OpSource content we can add the difference between
685// the #line line number and the reported error line number to determine the location
686// in the OpSource content of the reported error line.
687//
688// Considerations:
689// - Look only at #line directives that specify the reported_filename since
690// the reported error line number refers to its location in the reported filename.
691// - If a #line directive does not have a filename, the file is the reported filename, or
692// the filename found in a prior #line directive. (This is C-preprocessor behavior)
693// - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
694// original order and the #line directives are used to keep the numbering correct. This
695// is why we need to examine the entire contents of the source, instead of leaving early
696// when finding a #line line number larger than the reported error line number.
697//
698
699// GCC 4.8 has a problem with std::regex that is fixed in GCC 4.9. Provide fallback code for 4.8
700#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
701
702#if defined(__GNUC__) && GCC_VERSION < 40900
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700703static bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
Tony-LunarG03059b72019-02-19 13:57:41 -0700704 // # line <linenumber> "<filename>" or
705 // #line <linenumber> "<filename>"
706 std::vector<std::string> tokens;
707 std::stringstream stream(string);
708 std::string temp;
709 uint32_t line_index = 0;
710
711 while (stream >> temp) tokens.push_back(temp);
712 auto size = tokens.size();
713 if (size > 1) {
714 if (tokens[0] == "#" && tokens[1] == "line") {
715 line_index = 2;
716 } else if (tokens[0] == "#line") {
717 line_index = 1;
718 }
719 }
720 if (0 == line_index) return false;
721 *linenumber = std::stoul(tokens[line_index]);
722 uint32_t filename_index = line_index + 1;
723 // Remove enclosing double quotes around filename
724 if (size > filename_index) filename = tokens[filename_index].substr(1, tokens[filename_index].size() - 2);
725 return true;
726}
727#else
728static bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700729 static const std::regex line_regex( // matches #line directives
730 "^" // beginning of line
731 "\\s*" // optional whitespace
732 "#" // required text
733 "\\s*" // optional whitespace
734 "line" // required text
735 "\\s+" // required whitespace
736 "([0-9]+)" // required first capture - line number
737 "(\\s+)?" // optional second capture - whitespace
738 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
739 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
Karl Schultz7b024b42018-08-30 16:18:18 -0600740
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700741 std::smatch captures;
742
743 bool found_line = std::regex_match(string, captures, line_regex);
744 if (!found_line) return false;
745
746 // filename is optional and considered found only if the whitespace and the filename are captured
747 if (captures[2].matched && captures[3].matched) {
748 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
749 filename = captures[3].str().substr(1, captures[3].str().size() - 2);
750 }
751 *linenumber = std::stoul(captures[1]);
752 return true;
753}
Tony-LunarG03059b72019-02-19 13:57:41 -0700754#endif // GCC_VERSION
755
Karl Schultz7b024b42018-08-30 16:18:18 -0600756// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
757// Scan the source (from OpSource) to find the line of source at the reported line number and place it in another message string.
758static void GenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, std::string &filename_msg,
759 std::string &source_msg) {
760 using namespace spvtools;
761 std::ostringstream filename_stream;
762 std::ostringstream source_stream;
763 shader_module shader;
764 shader.words = pgm;
765 // Find the OpLine just before the failing instruction indicated by the debug info.
766 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
767 uint32_t instruction_index = 0;
768 uint32_t reported_file_id = 0;
769 uint32_t reported_line_number = 0;
770 uint32_t reported_column_number = 0;
771 if (shader.words.size() > 0) {
772 for (auto insn : shader) {
773 if (insn.opcode() == spv::OpLine) {
774 reported_file_id = insn.word(1);
775 reported_line_number = insn.word(2);
776 reported_column_number = insn.word(3);
777 }
778 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
779 break;
780 }
781 instruction_index++;
782 }
783 }
784 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
785 std::string reported_filename;
786 if (reported_file_id == 0) {
787 filename_stream
788 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
789 } else {
790 bool found_opstring = false;
791 for (auto insn : shader) {
792 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
793 found_opstring = true;
794 reported_filename = (char *)&insn.word(2);
795 if (reported_filename.empty()) {
796 filename_stream << "Shader validation error occurred at line " << reported_line_number;
797 } else {
798 filename_stream << "Shader validation error occurred in file: " << reported_filename << " at line "
799 << reported_line_number;
800 }
801 if (reported_column_number > 0) {
802 filename_stream << ", column " << reported_column_number;
803 }
804 filename_stream << ".";
805 break;
806 }
807 }
808 if (!found_opstring) {
809 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction.";
810 }
811 }
812 filename_msg = filename_stream.str();
813
814 // Create message to display source code line containing error.
815 if ((reported_file_id != 0)) {
816 // Read the source code and split it up into separate lines.
817 std::vector<std::string> opsource_lines;
818 ReadOpSource(shader, reported_file_id, opsource_lines);
819 // Find the line in the OpSource content that corresponds to the reported error file and line.
820 if (!opsource_lines.empty()) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600821 uint32_t saved_line_number = 0;
822 std::string current_filename = reported_filename; // current "preprocessor" filename state.
823 std::vector<std::string>::size_type saved_opsource_offset = 0;
824 bool found_best_line = false;
825 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700826 uint32_t parsed_line_number;
827 std::string parsed_filename;
828 bool found_line = GetLineAndFilename(*it, &parsed_line_number, parsed_filename);
Karl Schultz7b024b42018-08-30 16:18:18 -0600829 if (!found_line) continue;
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700830
831 bool found_filename = parsed_filename.size() > 0;
Karl Schultz7b024b42018-08-30 16:18:18 -0600832 if (found_filename) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700833 current_filename = parsed_filename;
Karl Schultz7b024b42018-08-30 16:18:18 -0600834 }
835 if ((!found_filename) || (current_filename == reported_filename)) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600836 // Update the candidate best line directive, if the current one is prior and closer to the reported line
837 if (reported_line_number >= parsed_line_number) {
838 if (!found_best_line ||
839 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
840 saved_line_number = parsed_line_number;
841 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
842 found_best_line = true;
843 }
844 }
845 }
846 }
847 if (found_best_line) {
848 assert(reported_line_number >= saved_line_number);
849 std::vector<std::string>::size_type opsource_index =
850 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
851 if (opsource_index < opsource_lines.size()) {
852 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
853 } else {
854 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
855 << opsource_lines.size() << " lines.";
856 }
857 } else {
858 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
859 }
860 } else {
861 source_stream << "Unable to find SPIR-V OpSource.";
862 }
863 }
864 source_msg = source_stream.str();
865}
866
867// Pull together all the information from the debug record to build the error message strings,
868// and then assemble them into a single message string.
869// Retrieve the shader program referenced by the unique shader ID provided in the debug record.
870// We had to keep a copy of the shader program with the same lifecycle as the pipeline to make
871// sure it is available when the pipeline is submitted. (The ShaderModule tracking object also
872// keeps a copy, but it can be destroyed after the pipeline is created and before it is submitted.)
873//
Mark Lobodzinskie377ac32019-03-07 16:12:46 -0700874void CoreChecks::AnalyzeAndReportError(GLOBAL_CB_NODE *cb_node, VkQueue queue, uint32_t draw_index,
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700875 uint32_t *const debug_output_buffer) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600876 using namespace spvtools;
877 const uint32_t total_words = debug_output_buffer[0];
878 // A zero here means that the shader instrumentation didn't write anything.
879 // If you have nothing to say, don't say it here.
880 if (0 == total_words) {
881 return;
882 }
883 // The first word in the debug output buffer is the number of words that would have
884 // been written by the shader instrumentation, if there was enough room in the buffer we provided.
885 // The number of words actually written by the shaders is determined by the size of the buffer
886 // we provide via the descriptor. So, we process only the number of words that can fit in the
887 // buffer.
888 // Each "report" written by the shader instrumentation is considered a "record". This function
889 // is hard-coded to process only one record because it expects the buffer to be large enough to
890 // hold only one record. If there is a desire to process more than one record, this function needs
891 // to be modified to loop over records and the buffer size increased.
Karl Schultz7b024b42018-08-30 16:18:18 -0600892 std::string validation_message;
893 std::string stage_message;
894 std::string common_message;
895 std::string filename_message;
896 std::string source_message;
897 std::string vuid_msg;
898 VkShaderModule shader_module_handle = VK_NULL_HANDLE;
899 VkPipeline pipeline_handle = VK_NULL_HANDLE;
900 std::vector<unsigned int> pgm;
901 // The first record starts at this offset after the total_words.
902 const uint32_t *debug_record = &debug_output_buffer[kDebugOutputDataOffset];
903 // Lookup the VkShaderModule handle and SPIR-V code used to create the shader, using the unique shader ID value returned
904 // by the instrumented shader.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600905 auto it = gpu_validation_state->shader_map.find(debug_record[kInstCommonOutShaderId]);
906 if (it != gpu_validation_state->shader_map.end()) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600907 shader_module_handle = it->second.shader_module;
908 pipeline_handle = it->second.pipeline;
909 pgm = it->second.pgm;
910 }
911 GenerateValidationMessage(debug_record, validation_message, vuid_msg);
912 GenerateStageMessage(debug_record, stage_message);
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700913 GenerateCommonMessage(report_data, cb_node, debug_record, shader_module_handle, pipeline_handle, draw_index, common_message);
Karl Schultz7b024b42018-08-30 16:18:18 -0600914 GenerateSourceMessages(pgm, debug_record, filename_message, source_message);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600915 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 -0600916 vuid_msg.c_str(), "%s %s %s %s%s", validation_message.c_str(), common_message.c_str(), stage_message.c_str(),
917 filename_message.c_str(), source_message.c_str());
918 // The debug record at word kInstCommonOutSize is the number of words in the record
919 // written by the shader. Clear the entire record plus the total_words word at the start.
920 const uint32_t words_to_clear = 1 + std::min(debug_record[kInstCommonOutSize], (uint32_t)kInstMaxOutCnt);
921 memset(debug_output_buffer, 0, sizeof(uint32_t) * words_to_clear);
922}
923
Tony-LunarG5ad17272019-03-05 12:48:24 -0700924// For the given command buffer, map its debug data buffers and read their contents for analysis.
Mark Lobodzinskie377ac32019-03-07 16:12:46 -0700925void CoreChecks::ProcessInstrumentationBuffer(VkQueue queue, GLOBAL_CB_NODE *cb_node) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600926 auto gpu_buffer_list = gpu_validation_state->GetGpuBufferInfo(cb_node->commandBuffer);
927 if (cb_node && cb_node->hasDrawCmd && gpu_buffer_list.size() > 0) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600928 VkResult result;
929 char *pData;
Tony-LunarG5ad17272019-03-05 12:48:24 -0700930 uint32_t draw_index = 0;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600931 for (auto &buffer_info : gpu_buffer_list) {
Tony-LunarG0e564722019-03-19 16:09:14 -0600932 result = vmaMapMemory(gpu_validation_state->vmaAllocator, buffer_info.mem_block.allocation, (void **)&pData);
Tony-LunarGb2501d22019-01-28 09:59:13 -0700933 // Analyze debug output buffer
934 if (result == VK_SUCCESS) {
Tony-LunarG0e564722019-03-19 16:09:14 -0600935 AnalyzeAndReportError(cb_node, queue, draw_index, (uint32_t *)pData);
936 vmaUnmapMemory(gpu_validation_state->vmaAllocator, buffer_info.mem_block.allocation);
Tony-LunarGb2501d22019-01-28 09:59:13 -0700937 }
Tony-LunarGd589c7c2019-01-31 11:23:44 -0700938 draw_index++;
Karl Schultz7b024b42018-08-30 16:18:18 -0600939 }
940 }
941}
942
Karl Schultz58674242019-01-22 15:35:02 -0700943// Submit a memory barrier on graphics queues.
944// Lazy-create and record the needed command buffer.
Mark Lobodzinskie377ac32019-03-07 16:12:46 -0700945void CoreChecks::SubmitBarrier(VkQueue queue) {
Karl Schultz58674242019-01-22 15:35:02 -0700946 uint32_t queue_family_index = 0;
947
Mark Lobodzinskie377ac32019-03-07 16:12:46 -0700948 auto it = queueMap.find(queue);
949 if (it != queueMap.end()) {
Karl Schultz58674242019-01-22 15:35:02 -0700950 queue_family_index = it->second.queueFamilyIndex;
951 }
952
953 // Pay attention only to queues that support graphics.
954 // 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 -0700955 VkQueueFlags queue_flags = GetPhysicalDeviceState()->queue_family_properties[queue_family_index].queueFlags;
Karl Schultz58674242019-01-22 15:35:02 -0700956 if (!(queue_flags & VK_QUEUE_GRAPHICS_BIT)) {
957 return;
958 }
959
960 // Lazy-allocate and record the command buffer.
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600961 if (gpu_validation_state->barrier_command_buffer == VK_NULL_HANDLE) {
Karl Schultz58674242019-01-22 15:35:02 -0700962 VkResult result;
963 VkCommandPoolCreateInfo pool_create_info = {};
964 pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
965 pool_create_info.queueFamilyIndex = queue_family_index;
Tony-LunarG152a88b2019-03-20 15:42:24 -0600966 result = DispatchCreateCommandPool(device, &pool_create_info, nullptr, &gpu_validation_state->barrier_command_pool);
Karl Schultz58674242019-01-22 15:35:02 -0700967 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600968 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz58674242019-01-22 15:35:02 -0700969 "Unable to create command pool for barrier CB.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600970 gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
Karl Schultz58674242019-01-22 15:35:02 -0700971 return;
972 }
973
974 VkCommandBufferAllocateInfo command_buffer_alloc_info = {};
975 command_buffer_alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600976 command_buffer_alloc_info.commandPool = gpu_validation_state->barrier_command_pool;
Karl Schultz58674242019-01-22 15:35:02 -0700977 command_buffer_alloc_info.commandBufferCount = 1;
978 command_buffer_alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
Tony-LunarG152a88b2019-03-20 15:42:24 -0600979 result = DispatchAllocateCommandBuffers(device, &command_buffer_alloc_info, &gpu_validation_state->barrier_command_buffer);
Karl Schultz58674242019-01-22 15:35:02 -0700980 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600981 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Karl Schultz58674242019-01-22 15:35:02 -0700982 "Unable to create barrier command buffer.");
Tony-LunarG152a88b2019-03-20 15:42:24 -0600983 DispatchDestroyCommandPool(device, gpu_validation_state->barrier_command_pool, nullptr);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600984 gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
985 gpu_validation_state->barrier_command_buffer = VK_NULL_HANDLE;
Karl Schultz58674242019-01-22 15:35:02 -0700986 return;
987 }
988
989 // Hook up command buffer dispatch
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -0600990 *((const void **)gpu_validation_state->barrier_command_buffer) = *(void **)(device);
Karl Schultz58674242019-01-22 15:35:02 -0700991
992 // Record a global memory barrier to force availability of device memory operations to the host domain.
993 VkCommandBufferBeginInfo command_buffer_begin_info = {};
994 command_buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
Tony-LunarG152a88b2019-03-20 15:42:24 -0600995 result = DispatchBeginCommandBuffer(gpu_validation_state->barrier_command_buffer, &command_buffer_begin_info);
Karl Schultz58674242019-01-22 15:35:02 -0700996
997 if (result == VK_SUCCESS) {
998 VkMemoryBarrier memory_barrier = {};
999 memory_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
1000 memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
1001 memory_barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
1002
Tony-LunarG152a88b2019-03-20 15:42:24 -06001003 DispatchCmdPipelineBarrier(gpu_validation_state->barrier_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
Mark Lobodzinskie514d1a2019-03-12 08:47:45 -06001004 VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &memory_barrier, 0, nullptr, 0, nullptr);
Tony-LunarG152a88b2019-03-20 15:42:24 -06001005 DispatchEndCommandBuffer(gpu_validation_state->barrier_command_buffer);
Karl Schultz58674242019-01-22 15:35:02 -07001006 }
1007 }
1008
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001009 if (gpu_validation_state->barrier_command_buffer) {
Karl Schultz58674242019-01-22 15:35:02 -07001010 VkSubmitInfo submit_info = {};
1011 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1012 submit_info.commandBufferCount = 1;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001013 submit_info.pCommandBuffers = &gpu_validation_state->barrier_command_buffer;
Tony-LunarG152a88b2019-03-20 15:42:24 -06001014 DispatchQueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
Karl Schultz58674242019-01-22 15:35:02 -07001015 }
1016}
1017
1018// Issue a memory barrier to make GPU-written data available to host.
1019// Wait for the queue to complete execution.
1020// Check the debug buffers for all the command buffers that were submitted.
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001021void CoreChecks::GpuPostCallQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001022 if (gpu_validation_state->aborted) return;
Karl Schultz58674242019-01-22 15:35:02 -07001023
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001024 SubmitBarrier(queue);
Karl Schultz58674242019-01-22 15:35:02 -07001025
Tony-LunarG152a88b2019-03-20 15:42:24 -06001026 DispatchQueueWaitIdle(queue);
Karl Schultz58674242019-01-22 15:35:02 -07001027
Karl Schultz7b024b42018-08-30 16:18:18 -06001028 for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
1029 const VkSubmitInfo *submit = &pSubmits[submit_idx];
1030 for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
Mark Lobodzinski1b3a9712019-03-06 15:51:47 -07001031 auto cb_node = GetCBNode(submit->pCommandBuffers[i]);
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001032 ProcessInstrumentationBuffer(queue, cb_node);
Karl Schultz7b024b42018-08-30 16:18:18 -06001033 for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
Mark Lobodzinskie377ac32019-03-07 16:12:46 -07001034 ProcessInstrumentationBuffer(queue, secondaryCmdBuffer);
Karl Schultz7b024b42018-08-30 16:18:18 -06001035 }
1036 }
1037 }
1038}
Tony-LunarGb2501d22019-01-28 09:59:13 -07001039
Mark Lobodzinski586d10e2019-03-08 18:19:48 -07001040void CoreChecks::GpuAllocateValidationResources(const VkCommandBuffer cmd_buffer, const VkPipelineBindPoint bind_point) {
Tony-LunarGb2501d22019-01-28 09:59:13 -07001041 VkResult result;
1042
Mark Lobodzinski44da62c2019-03-07 10:50:59 -07001043 if (!(GetEnables()->gpu_validation)) return;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001044
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001045 if (gpu_validation_state->aborted) return;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001046
1047 std::vector<VkDescriptorSet> desc_sets;
1048 VkDescriptorPool desc_pool = VK_NULL_HANDLE;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001049 result = gpu_validation_state->desc_set_manager->GetDescriptorSets(1, &desc_pool, &desc_sets);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001050 assert(result == VK_SUCCESS);
1051 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001052 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Tony-LunarGb2501d22019-01-28 09:59:13 -07001053 "Unable to allocate descriptor sets. Device could become unstable.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001054 gpu_validation_state->aborted = true;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001055 return;
1056 }
1057
1058 VkDescriptorBufferInfo desc_buffer_info = {};
Tony-LunarG0e564722019-03-19 16:09:14 -06001059 desc_buffer_info.range = gpu_validation_state->output_buffer_size;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001060
Mark Lobodzinski1b3a9712019-03-06 15:51:47 -07001061 auto cb_node = GetCBNode(cmd_buffer);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001062 if (!cb_node) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001063 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "Unrecognized command buffer");
1064 gpu_validation_state->aborted = true;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001065 return;
1066 }
1067
1068 GpuDeviceMemoryBlock block = {};
Tony-LunarG0e564722019-03-19 16:09:14 -06001069 VkBufferCreateInfo bufferInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
1070 bufferInfo.size = gpu_validation_state->output_buffer_size;
1071 bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
1072 VmaAllocationCreateInfo allocInfo = {};
1073 allocInfo.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
1074 result =
1075 vmaCreateBuffer(gpu_validation_state->vmaAllocator, &bufferInfo, &allocInfo, &block.buffer, &block.allocation, nullptr);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001076 if (result != VK_SUCCESS) {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001077 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
Tony-LunarGb2501d22019-01-28 09:59:13 -07001078 "Unable to allocate device memory. Device could become unstable.");
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001079 gpu_validation_state->aborted = true;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001080 return;
1081 }
Tony-LunarG0e564722019-03-19 16:09:14 -06001082 void *pData;
1083 result = vmaMapMemory(gpu_validation_state->vmaAllocator, block.allocation, (void **)&pData);
1084 if (result == VK_SUCCESS) {
1085 memset(pData, 0, gpu_validation_state->output_buffer_size);
1086 vmaUnmapMemory(gpu_validation_state->vmaAllocator, block.allocation);
1087 }
Tony-LunarGb2501d22019-01-28 09:59:13 -07001088
1089 // Write the descriptor
1090 desc_buffer_info.buffer = block.buffer;
Tony-LunarG0e564722019-03-19 16:09:14 -06001091 desc_buffer_info.offset = 0;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001092
1093 VkWriteDescriptorSet desc_write = {};
1094 desc_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1095 desc_write.descriptorCount = 1;
1096 desc_write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
1097 desc_write.pBufferInfo = &desc_buffer_info;
1098 desc_write.dstSet = desc_sets[0];
Tony-LunarG152a88b2019-03-20 15:42:24 -06001099 DispatchUpdateDescriptorSets(device, 1, &desc_write, 0, NULL);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001100
andreyg25ce2622019-04-05 23:07:59 +03001101 auto iter = cb_node->lastBound.find(bind_point); // find() allows read-only access to cb_state
Tony-LunarGb2501d22019-01-28 09:59:13 -07001102 if (iter != cb_node->lastBound.end()) {
1103 auto pipeline_state = iter->second.pipeline_state;
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001104 if (pipeline_state && (pipeline_state->pipeline_layout.set_layouts.size() <= gpu_validation_state->desc_set_bind_index)) {
Tony-LunarG152a88b2019-03-20 15:42:24 -06001105 DispatchCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_state->pipeline_layout.layout,
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001106 gpu_validation_state->desc_set_bind_index, 1, desc_sets.data(), 0, nullptr);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001107 }
Tony-LunarG0e564722019-03-19 16:09:14 -06001108 // Record buffer and memory info in CB state tracking
1109 gpu_validation_state->GetGpuBufferInfo(cmd_buffer).emplace_back(block, desc_sets[0], desc_pool);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001110 } else {
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001111 ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "Unable to find pipeline state");
Tony-LunarG0e564722019-03-19 16:09:14 -06001112 vmaDestroyBuffer(gpu_validation_state->vmaAllocator, block.buffer, block.allocation);
Mark Lobodzinski2a3ee4a2019-03-13 13:11:39 -06001113 gpu_validation_state->aborted = true;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001114 return;
1115 }
1116}