blob: d03f71fce573027905e0b1e6d1f2466571a04760 [file] [log] [blame]
Tony-LunarGf0634eb2021-01-05 15:11:12 -07001/* Copyright (c) 2020-2021 The Khronos Group Inc.
2 * Copyright (c) 2020-2021 Valve Corporation
3 * Copyright (c) 2020-2021 LunarG, Inc.
Tony-LunarG1dce2392019-10-23 16:49:29 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Tony Barbour <tony@lunarg.com>
18 */
19
20#include "chassis.h"
21#include "layer_chassis_dispatch.h"
22#include "state_tracker.h"
23#include "shader_validation.h"
24#include "spirv-tools/libspirv.h"
25#include "spirv-tools/optimizer.hpp"
26#include "spirv-tools/instrument.hpp"
Mark Lobodzinski102687e2020-04-28 11:03:28 -060027#include <spirv/unified1/spirv.hpp>
Tony-LunarG1dce2392019-10-23 16:49:29 -060028#include <algorithm>
29#include <regex>
30
31#define VMA_IMPLEMENTATION
32// This define indicates that we will supply Vulkan function pointers at initialization
33#define VMA_STATIC_VULKAN_FUNCTIONS 0
34#include "vk_mem_alloc.h"
35
Tony-LunarGb5fae462020-03-05 12:43:25 -070036class UtilDescriptorSetManager {
Tony-LunarG1dce2392019-10-23 16:49:29 -060037 public:
Tony-LunarGb5fae462020-03-05 12:43:25 -070038 UtilDescriptorSetManager(VkDevice device, uint32_t numBindingsInSet);
39 ~UtilDescriptorSetManager();
Tony-LunarG1dce2392019-10-23 16:49:29 -060040
41 VkResult GetDescriptorSet(VkDescriptorPool *desc_pool, VkDescriptorSetLayout ds_layout, VkDescriptorSet *desc_sets);
42 VkResult GetDescriptorSets(uint32_t count, VkDescriptorPool *pool, VkDescriptorSetLayout ds_layout,
43 std::vector<VkDescriptorSet> *desc_sets);
44 void PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set);
45
46 private:
47 static const uint32_t kItemsPerChunk = 512;
48 struct PoolTracker {
49 uint32_t size;
50 uint32_t used;
51 };
52 VkDevice device;
53 uint32_t numBindingsInSet;
Jeremy Gebbencbf22862021-03-03 12:01:22 -070054 layer_data::unordered_map<VkDescriptorPool, struct PoolTracker> desc_pool_map_;
Tony-LunarG1dce2392019-10-23 16:49:29 -060055};
56
57// Implementation for Descriptor Set Manager class
Tony-LunarGb5fae462020-03-05 12:43:25 -070058UtilDescriptorSetManager::UtilDescriptorSetManager(VkDevice device, uint32_t numBindingsInSet)
Tony-LunarG1dce2392019-10-23 16:49:29 -060059 : device(device), numBindingsInSet(numBindingsInSet) {}
60
Tony-LunarGb5fae462020-03-05 12:43:25 -070061UtilDescriptorSetManager::~UtilDescriptorSetManager() {
Tony-LunarG1dce2392019-10-23 16:49:29 -060062 for (auto &pool : desc_pool_map_) {
63 DispatchDestroyDescriptorPool(device, pool.first, NULL);
64 }
65 desc_pool_map_.clear();
66}
67
Tony-LunarGb5fae462020-03-05 12:43:25 -070068VkResult UtilDescriptorSetManager::GetDescriptorSet(VkDescriptorPool *desc_pool, VkDescriptorSetLayout ds_layout,
69 VkDescriptorSet *desc_set) {
Tony-LunarG1dce2392019-10-23 16:49:29 -060070 std::vector<VkDescriptorSet> desc_sets;
71 VkResult result = GetDescriptorSets(1, desc_pool, ds_layout, &desc_sets);
72 if (result == VK_SUCCESS) {
73 *desc_set = desc_sets[0];
74 }
75 return result;
76}
77
Tony-LunarGb5fae462020-03-05 12:43:25 -070078VkResult UtilDescriptorSetManager::GetDescriptorSets(uint32_t count, VkDescriptorPool *pool, VkDescriptorSetLayout ds_layout,
79 std::vector<VkDescriptorSet> *desc_sets) {
Tony-LunarG1dce2392019-10-23 16:49:29 -060080 const uint32_t default_pool_size = kItemsPerChunk;
81 VkResult result = VK_SUCCESS;
82 VkDescriptorPool pool_to_use = VK_NULL_HANDLE;
83
84 if (0 == count) {
85 return result;
86 }
87 desc_sets->clear();
88 desc_sets->resize(count);
89
90 for (auto &pool : desc_pool_map_) {
91 if (pool.second.used + count < pool.second.size) {
92 pool_to_use = pool.first;
93 break;
94 }
95 }
96 if (VK_NULL_HANDLE == pool_to_use) {
97 uint32_t pool_count = default_pool_size;
98 if (count > default_pool_size) {
99 pool_count = count;
100 }
101 const VkDescriptorPoolSize size_counts = {
102 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
103 pool_count * numBindingsInSet,
104 };
Nathaniel Cesariofc6291e2021-04-06 00:22:15 -0600105 auto desc_pool_info = LvlInitStruct<VkDescriptorPoolCreateInfo>();
Tony-LunarG1dce2392019-10-23 16:49:29 -0600106 desc_pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
107 desc_pool_info.maxSets = pool_count;
108 desc_pool_info.poolSizeCount = 1;
109 desc_pool_info.pPoolSizes = &size_counts;
110 result = DispatchCreateDescriptorPool(device, &desc_pool_info, NULL, &pool_to_use);
111 assert(result == VK_SUCCESS);
112 if (result != VK_SUCCESS) {
113 return result;
114 }
115 desc_pool_map_[pool_to_use].size = desc_pool_info.maxSets;
116 desc_pool_map_[pool_to_use].used = 0;
117 }
118 std::vector<VkDescriptorSetLayout> desc_layouts(count, ds_layout);
119
120 VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool_to_use, count,
121 desc_layouts.data()};
122
123 result = DispatchAllocateDescriptorSets(device, &alloc_info, desc_sets->data());
124 assert(result == VK_SUCCESS);
125 if (result != VK_SUCCESS) {
126 return result;
127 }
128 *pool = pool_to_use;
129 desc_pool_map_[pool_to_use].used += count;
130 return result;
131}
132
Tony-LunarGb5fae462020-03-05 12:43:25 -0700133void UtilDescriptorSetManager::PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600134 auto iter = desc_pool_map_.find(desc_pool);
135 if (iter != desc_pool_map_.end()) {
136 VkResult result = DispatchFreeDescriptorSets(device, desc_pool, 1, &desc_set);
137 assert(result == VK_SUCCESS);
138 if (result != VK_SUCCESS) {
139 return;
140 }
141 desc_pool_map_[desc_pool].used--;
142 if (0 == desc_pool_map_[desc_pool].used) {
143 DispatchDestroyDescriptorPool(device, desc_pool, NULL);
144 desc_pool_map_.erase(desc_pool);
145 }
146 }
147 return;
148}
149
150// Trampolines to make VMA call Dispatch for Vulkan calls
151static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
152 VkPhysicalDeviceProperties *pProperties) {
153 DispatchGetPhysicalDeviceProperties(physicalDevice, pProperties);
154}
155static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceMemoryProperties(VkPhysicalDevice physicalDevice,
156 VkPhysicalDeviceMemoryProperties *pMemoryProperties) {
157 DispatchGetPhysicalDeviceMemoryProperties(physicalDevice, pMemoryProperties);
158}
159static VKAPI_ATTR VkResult VKAPI_CALL gpuVkAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
160 const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) {
161 return DispatchAllocateMemory(device, pAllocateInfo, pAllocator, pMemory);
162}
163static VKAPI_ATTR void VKAPI_CALL gpuVkFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks *pAllocator) {
164 DispatchFreeMemory(device, memory, pAllocator);
165}
166static VKAPI_ATTR VkResult VKAPI_CALL gpuVkMapMemory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size,
167 VkMemoryMapFlags flags, void **ppData) {
168 return DispatchMapMemory(device, memory, offset, size, flags, ppData);
169}
170static VKAPI_ATTR void VKAPI_CALL gpuVkUnmapMemory(VkDevice device, VkDeviceMemory memory) { DispatchUnmapMemory(device, memory); }
171static VKAPI_ATTR VkResult VKAPI_CALL gpuVkFlushMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
172 const VkMappedMemoryRange *pMemoryRanges) {
173 return DispatchFlushMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
174}
175static VKAPI_ATTR VkResult VKAPI_CALL gpuVkInvalidateMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
176 const VkMappedMemoryRange *pMemoryRanges) {
177 return DispatchInvalidateMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
178}
179static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
180 VkDeviceSize memoryOffset) {
181 return DispatchBindBufferMemory(device, buffer, memory, memoryOffset);
182}
183static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
184 VkDeviceSize memoryOffset) {
185 return DispatchBindImageMemory(device, image, memory, memoryOffset);
186}
187static VKAPI_ATTR void VKAPI_CALL gpuVkGetBufferMemoryRequirements(VkDevice device, VkBuffer buffer,
188 VkMemoryRequirements *pMemoryRequirements) {
189 DispatchGetBufferMemoryRequirements(device, buffer, pMemoryRequirements);
190}
191static VKAPI_ATTR void VKAPI_CALL gpuVkGetImageMemoryRequirements(VkDevice device, VkImage image,
192 VkMemoryRequirements *pMemoryRequirements) {
193 DispatchGetImageMemoryRequirements(device, image, pMemoryRequirements);
194}
195static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
196 const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
197 return DispatchCreateBuffer(device, pCreateInfo, pAllocator, pBuffer);
198}
199static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
200 return DispatchDestroyBuffer(device, buffer, pAllocator);
201}
202static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
203 const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
204 return DispatchCreateImage(device, pCreateInfo, pAllocator, pImage);
205}
206static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
207 DispatchDestroyImage(device, image, pAllocator);
208}
209static VKAPI_ATTR void VKAPI_CALL gpuVkCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
210 uint32_t regionCount, const VkBufferCopy *pRegions) {
211 DispatchCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, regionCount, pRegions);
212}
213
Tony-LunarGb5fae462020-03-05 12:43:25 -0700214VkResult UtilInitializeVma(VkPhysicalDevice physical_device, VkDevice device, VmaAllocator *pAllocator) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600215 VmaVulkanFunctions functions;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700216 VmaAllocatorCreateInfo allocator_info = {};
217 allocator_info.device = device;
218 allocator_info.physicalDevice = physical_device;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600219
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700220 functions.vkGetPhysicalDeviceProperties = static_cast<PFN_vkGetPhysicalDeviceProperties>(gpuVkGetPhysicalDeviceProperties);
221 functions.vkGetPhysicalDeviceMemoryProperties =
222 static_cast<PFN_vkGetPhysicalDeviceMemoryProperties>(gpuVkGetPhysicalDeviceMemoryProperties);
223 functions.vkAllocateMemory = static_cast<PFN_vkAllocateMemory>(gpuVkAllocateMemory);
224 functions.vkFreeMemory = static_cast<PFN_vkFreeMemory>(gpuVkFreeMemory);
225 functions.vkMapMemory = static_cast<PFN_vkMapMemory>(gpuVkMapMemory);
226 functions.vkUnmapMemory = static_cast<PFN_vkUnmapMemory>(gpuVkUnmapMemory);
227 functions.vkFlushMappedMemoryRanges = static_cast<PFN_vkFlushMappedMemoryRanges>(gpuVkFlushMappedMemoryRanges);
228 functions.vkInvalidateMappedMemoryRanges = static_cast<PFN_vkInvalidateMappedMemoryRanges>(gpuVkInvalidateMappedMemoryRanges);
229 functions.vkBindBufferMemory = static_cast<PFN_vkBindBufferMemory>(gpuVkBindBufferMemory);
230 functions.vkBindImageMemory = static_cast<PFN_vkBindImageMemory>(gpuVkBindImageMemory);
231 functions.vkGetBufferMemoryRequirements = static_cast<PFN_vkGetBufferMemoryRequirements>(gpuVkGetBufferMemoryRequirements);
232 functions.vkGetImageMemoryRequirements = static_cast<PFN_vkGetImageMemoryRequirements>(gpuVkGetImageMemoryRequirements);
233 functions.vkCreateBuffer = static_cast<PFN_vkCreateBuffer>(gpuVkCreateBuffer);
234 functions.vkDestroyBuffer = static_cast<PFN_vkDestroyBuffer>(gpuVkDestroyBuffer);
235 functions.vkCreateImage = static_cast<PFN_vkCreateImage>(gpuVkCreateImage);
236 functions.vkDestroyImage = static_cast<PFN_vkDestroyImage>(gpuVkDestroyImage);
237 functions.vkCmdCopyBuffer = static_cast<PFN_vkCmdCopyBuffer>(gpuVkCmdCopyBuffer);
238 allocator_info.pVulkanFunctions = &functions;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600239
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700240 return vmaCreateAllocator(&allocator_info, pAllocator);
Tony-LunarG1dce2392019-10-23 16:49:29 -0600241}
242
Tony-LunarGb5fae462020-03-05 12:43:25 -0700243void UtilPreCallRecordCreateDevice(VkPhysicalDevice gpu, safe_VkDeviceCreateInfo *modified_create_info,
244 VkPhysicalDeviceFeatures supported_features, VkPhysicalDeviceFeatures desired_features) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600245 VkPhysicalDeviceFeatures *features = nullptr;
246 if (modified_create_info->pEnabledFeatures) {
247 // If pEnabledFeatures, VkPhysicalDeviceFeatures2 in pNext chain is not allowed
248 features = const_cast<VkPhysicalDeviceFeatures *>(modified_create_info->pEnabledFeatures);
249 } else {
250 VkPhysicalDeviceFeatures2 *features2 = nullptr;
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700251 features2 = const_cast<VkPhysicalDeviceFeatures2 *>(LvlFindInChain<VkPhysicalDeviceFeatures2>(modified_create_info->pNext));
Tony-LunarG1dce2392019-10-23 16:49:29 -0600252 if (features2) features = &features2->features;
253 }
Tony-LunarGf0634eb2021-01-05 15:11:12 -0700254 VkPhysicalDeviceFeatures new_features = {};
255 VkBool32 *desired = reinterpret_cast<VkBool32 *>(&desired_features);
256 VkBool32 *feature_ptr;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600257 if (features) {
Tony-LunarGf0634eb2021-01-05 15:11:12 -0700258 feature_ptr = reinterpret_cast<VkBool32 *>(features);
Tony-LunarG1dce2392019-10-23 16:49:29 -0600259 } else {
Tony-LunarGf0634eb2021-01-05 15:11:12 -0700260 feature_ptr = reinterpret_cast<VkBool32 *>(&new_features);
261 }
262 VkBool32 *supported = reinterpret_cast<VkBool32 *>(&supported_features);
263 for (size_t i = 0; i < sizeof(VkPhysicalDeviceFeatures); i += (sizeof(VkBool32))) {
264 if (*supported && *desired) {
265 *feature_ptr = true;
266 }
267 supported++;
268 desired++;
269 feature_ptr++;
270 }
271 if (!features) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600272 delete modified_create_info->pEnabledFeatures;
273 modified_create_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
274 }
275}
276
277// Generate the stage-specific part of the message.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700278void UtilGenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600279 using namespace spvtools;
280 std::ostringstream strm;
281 switch (debug_record[kInstCommonOutStageIdx]) {
282 case spv::ExecutionModelVertex: {
283 strm << "Stage = Vertex. Vertex Index = " << debug_record[kInstVertOutVertexIndex]
284 << " Instance Index = " << debug_record[kInstVertOutInstanceIndex] << ". ";
285 } break;
286 case spv::ExecutionModelTessellationControl: {
287 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessCtlOutInvocationId]
288 << ", Primitive ID = " << debug_record[kInstTessCtlOutPrimitiveId];
289 } break;
290 case spv::ExecutionModelTessellationEvaluation: {
291 strm << "Stage = Tessellation Eval. Primitive ID = " << debug_record[kInstTessEvalOutPrimitiveId]
292 << ", TessCoord (u, v) = (" << debug_record[kInstTessEvalOutTessCoordU] << ", "
293 << debug_record[kInstTessEvalOutTessCoordV] << "). ";
294 } break;
295 case spv::ExecutionModelGeometry: {
296 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
297 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
298 } break;
299 case spv::ExecutionModelFragment: {
300 strm << "Stage = Fragment. Fragment coord (x,y) = ("
301 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
302 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
303 } break;
304 case spv::ExecutionModelGLCompute: {
305 strm << "Stage = Compute. Global invocation ID (x, y, z) = (" << debug_record[kInstCompOutGlobalInvocationIdX] << ", "
306 << debug_record[kInstCompOutGlobalInvocationIdY] << ", " << debug_record[kInstCompOutGlobalInvocationIdZ] << " )";
307 } break;
308 case spv::ExecutionModelRayGenerationNV: {
309 strm << "Stage = Ray Generation. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
310 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
311 } break;
312 case spv::ExecutionModelIntersectionNV: {
313 strm << "Stage = Intersection. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
314 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
315 } break;
316 case spv::ExecutionModelAnyHitNV: {
317 strm << "Stage = Any Hit. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
318 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
319 } break;
320 case spv::ExecutionModelClosestHitNV: {
321 strm << "Stage = Closest Hit. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
322 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
323 } break;
324 case spv::ExecutionModelMissNV: {
325 strm << "Stage = Miss. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
326 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
327 } break;
328 case spv::ExecutionModelCallableNV: {
329 strm << "Stage = Callable. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
330 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
331 } break;
Tony-LunarGc7ed2082020-06-11 14:00:04 -0600332 case spv::ExecutionModelTaskNV: {
333 strm << "Stage = Task. Global invocation ID (x, y, z) = (" << debug_record[kInstTaskOutGlobalInvocationIdX] << ", "
334 << debug_record[kInstTaskOutGlobalInvocationIdY] << ", " << debug_record[kInstTaskOutGlobalInvocationIdZ] << " )";
335 } break;
336 case spv::ExecutionModelMeshNV: {
337 strm << "Stage = Mesh.Global invocation ID (x, y, z) = (" << debug_record[kInstMeshOutGlobalInvocationIdX] << ", "
338 << debug_record[kInstMeshOutGlobalInvocationIdY] << ", " << debug_record[kInstMeshOutGlobalInvocationIdZ] << " )";
339 } break;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600340 default: {
341 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
342 assert(false);
343 } break;
344 }
345 msg = strm.str();
346}
347
348std::string LookupDebugUtilsName(const debug_report_data *report_data, const uint64_t object) {
349 auto object_label = report_data->DebugReportGetUtilsObjectName(object);
350 if (object_label != "") {
351 object_label = "(" + object_label + ")";
352 }
353 return object_label;
354}
355
356// Generate message from the common portion of the debug report record.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700357void UtilGenerateCommonMessage(const debug_report_data *report_data, const VkCommandBuffer commandBuffer,
358 const uint32_t *debug_record, const VkShaderModule shader_module_handle,
359 const VkPipeline pipeline_handle, const VkPipelineBindPoint pipeline_bind_point,
360 const uint32_t operation_index, std::string &msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600361 using namespace spvtools;
362 std::ostringstream strm;
363 if (shader_module_handle == VK_NULL_HANDLE) {
364 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
365 << LookupDebugUtilsName(report_data, HandleToUint64(commandBuffer)) << "(" << HandleToUint64(commandBuffer) << "). ";
366 assert(true);
367 } else {
368 strm << std::hex << std::showbase << "Command buffer " << LookupDebugUtilsName(report_data, HandleToUint64(commandBuffer))
369 << "(" << HandleToUint64(commandBuffer) << "). ";
370 if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS) {
371 strm << "Draw ";
372 } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_COMPUTE) {
373 strm << "Compute ";
374 } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_RAY_TRACING_NV) {
375 strm << "Ray Trace ";
376 } else {
377 assert(false);
378 strm << "Unknown Pipeline Operation ";
379 }
380 strm << "Index " << operation_index << ". "
381 << "Pipeline " << LookupDebugUtilsName(report_data, HandleToUint64(pipeline_handle)) << "("
382 << HandleToUint64(pipeline_handle) << "). "
383 << "Shader Module " << LookupDebugUtilsName(report_data, HandleToUint64(shader_module_handle)) << "("
384 << HandleToUint64(shader_module_handle) << "). ";
385 }
386 strm << std::dec << std::noshowbase;
387 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
388 msg = strm.str();
389}
390
391// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
392// Split the single string into a vector of strings, one for each line, for easier processing.
393void ReadOpSource(const SHADER_MODULE_STATE &shader, const uint32_t reported_file_id, std::vector<std::string> &opsource_lines) {
394 for (auto insn : shader) {
395 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
396 std::istringstream in_stream;
397 std::string cur_line;
398 in_stream.str((char *)&insn.word(4));
399 while (std::getline(in_stream, cur_line)) {
400 opsource_lines.push_back(cur_line);
401 }
402 while ((++insn).opcode() == spv::OpSourceContinued) {
403 in_stream.str((char *)&insn.word(1));
404 while (std::getline(in_stream, cur_line)) {
405 opsource_lines.push_back(cur_line);
406 }
407 }
408 break;
409 }
410 }
411}
412
413// The task here is to search the OpSource content to find the #line directive with the
414// line number that is closest to, but still prior to the reported error line number and
415// still within the reported filename.
416// From this known position in the OpSource content we can add the difference between
417// the #line line number and the reported error line number to determine the location
418// in the OpSource content of the reported error line.
419//
420// Considerations:
421// - Look only at #line directives that specify the reported_filename since
422// the reported error line number refers to its location in the reported filename.
423// - If a #line directive does not have a filename, the file is the reported filename, or
424// the filename found in a prior #line directive. (This is C-preprocessor behavior)
425// - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
426// original order and the #line directives are used to keep the numbering correct. This
427// is why we need to examine the entire contents of the source, instead of leaving early
428// when finding a #line line number larger than the reported error line number.
429//
430
431// GCC 4.8 has a problem with std::regex that is fixed in GCC 4.9. Provide fallback code for 4.8
432#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
433
434#if defined(__GNUC__) && GCC_VERSION < 40900
435bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
436 // # line <linenumber> "<filename>" or
437 // #line <linenumber> "<filename>"
438 std::vector<std::string> tokens;
439 std::stringstream stream(string);
440 std::string temp;
441 uint32_t line_index = 0;
442
443 while (stream >> temp) tokens.push_back(temp);
444 auto size = tokens.size();
445 if (size > 1) {
446 if (tokens[0] == "#" && tokens[1] == "line") {
447 line_index = 2;
448 } else if (tokens[0] == "#line") {
449 line_index = 1;
450 }
451 }
452 if (0 == line_index) return false;
Mark Young0ec6b062020-11-19 15:32:17 -0700453 *linenumber = static_cast<uint32_t>(std::stoul(tokens[line_index]));
Tony-LunarG1dce2392019-10-23 16:49:29 -0600454 uint32_t filename_index = line_index + 1;
455 // Remove enclosing double quotes around filename
456 if (size > filename_index) filename = tokens[filename_index].substr(1, tokens[filename_index].size() - 2);
457 return true;
458}
459#else
460bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
461 static const std::regex line_regex( // matches #line directives
462 "^" // beginning of line
463 "\\s*" // optional whitespace
464 "#" // required text
465 "\\s*" // optional whitespace
466 "line" // required text
467 "\\s+" // required whitespace
468 "([0-9]+)" // required first capture - line number
469 "(\\s+)?" // optional second capture - whitespace
470 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
471 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
472
473 std::smatch captures;
474
475 bool found_line = std::regex_match(string, captures, line_regex);
476 if (!found_line) return false;
477
478 // filename is optional and considered found only if the whitespace and the filename are captured
479 if (captures[2].matched && captures[3].matched) {
480 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
481 filename = captures[3].str().substr(1, captures[3].str().size() - 2);
482 }
483 *linenumber = std::stoul(captures[1]);
484 return true;
485}
486#endif // GCC_VERSION
487
488// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
489// Scan the source (from OpSource) to find the line of source at the reported line number and place it in another message string.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700490void UtilGenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, bool from_printf,
491 std::string &filename_msg, std::string &source_msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600492 using namespace spvtools;
493 std::ostringstream filename_stream;
494 std::ostringstream source_stream;
495 SHADER_MODULE_STATE shader;
496 shader.words = pgm;
497 // Find the OpLine just before the failing instruction indicated by the debug info.
498 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
499 uint32_t instruction_index = 0;
500 uint32_t reported_file_id = 0;
501 uint32_t reported_line_number = 0;
502 uint32_t reported_column_number = 0;
503 if (shader.words.size() > 0) {
John Zulauf79f06582021-02-27 18:38:39 -0700504 for (const auto &insn : shader) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600505 if (insn.opcode() == spv::OpLine) {
506 reported_file_id = insn.word(1);
507 reported_line_number = insn.word(2);
508 reported_column_number = insn.word(3);
509 }
510 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
511 break;
512 }
513 instruction_index++;
514 }
515 }
516 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
517 std::string reported_filename;
518 if (reported_file_id == 0) {
519 filename_stream
520 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
521 } else {
522 bool found_opstring = false;
523 std::string prefix;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700524 if (from_printf) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600525 prefix = "Debug shader printf message generated ";
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700526 } else {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600527 prefix = "Shader validation error occurred ";
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700528 }
John Zulauf79f06582021-02-27 18:38:39 -0700529 for (const auto &insn : shader) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600530 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
531 found_opstring = true;
532 reported_filename = (char *)&insn.word(2);
533 if (reported_filename.empty()) {
534 filename_stream << prefix << "at line " << reported_line_number;
535 } else {
536 filename_stream << prefix << "in file " << reported_filename << " at line " << reported_line_number;
537 }
538 if (reported_column_number > 0) {
539 filename_stream << ", column " << reported_column_number;
540 }
541 filename_stream << ".";
542 break;
543 }
544 }
545 if (!found_opstring) {
Tony-LunarG6d195e12020-10-27 16:54:14 -0600546 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction."
547 << std::endl;
548 filename_stream << "File ID = " << reported_file_id << ", Line Number = " << reported_line_number
549 << ", Column = " << reported_column_number << std::endl;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600550 }
551 }
552 filename_msg = filename_stream.str();
553
554 // Create message to display source code line containing error.
555 if ((reported_file_id != 0)) {
556 // Read the source code and split it up into separate lines.
557 std::vector<std::string> opsource_lines;
558 ReadOpSource(shader, reported_file_id, opsource_lines);
559 // Find the line in the OpSource content that corresponds to the reported error file and line.
560 if (!opsource_lines.empty()) {
561 uint32_t saved_line_number = 0;
562 std::string current_filename = reported_filename; // current "preprocessor" filename state.
563 std::vector<std::string>::size_type saved_opsource_offset = 0;
564 bool found_best_line = false;
565 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
566 uint32_t parsed_line_number;
567 std::string parsed_filename;
568 bool found_line = GetLineAndFilename(*it, &parsed_line_number, parsed_filename);
569 if (!found_line) continue;
570
571 bool found_filename = parsed_filename.size() > 0;
572 if (found_filename) {
573 current_filename = parsed_filename;
574 }
575 if ((!found_filename) || (current_filename == reported_filename)) {
576 // Update the candidate best line directive, if the current one is prior and closer to the reported line
577 if (reported_line_number >= parsed_line_number) {
578 if (!found_best_line ||
579 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
580 saved_line_number = parsed_line_number;
581 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
582 found_best_line = true;
583 }
584 }
585 }
586 }
587 if (found_best_line) {
588 assert(reported_line_number >= saved_line_number);
589 std::vector<std::string>::size_type opsource_index =
590 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
591 if (opsource_index < opsource_lines.size()) {
592 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
593 } else {
594 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
595 << opsource_lines.size() << " lines.";
596 }
597 } else {
598 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
599 }
600 } else {
601 source_stream << "Unable to find SPIR-V OpSource.";
602 }
603 }
604 source_msg = source_stream.str();
605}