blob: 74b3a880fdb2521ffb6267e2c0ce742cf29c4cf4 [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
23#include "core_validation.h"
24#include "shader_validation.h"
Karl Schultz7b024b42018-08-30 16:18:18 -060025#include "spirv-tools/libspirv.h"
26#include "spirv-tools/optimizer.hpp"
27#include "spirv-tools/instrument.hpp"
28#include <SPIRV/spirv.hpp>
29#include <algorithm>
30#include <regex>
31
32// This is the number of bindings in the debug descriptor set.
33static const uint32_t kNumBindingsInSet = 1;
34
35// Implementation for Device Memory Manager class
36VkResult GpuDeviceMemoryManager::GetBlock(GpuDeviceMemoryBlock *block) {
37 assert(block->buffer == VK_NULL_HANDLE); // avoid possible overwrite/leak of an allocated block
38 VkResult result = VK_SUCCESS;
39 MemoryChunk *pChunk = nullptr;
40 // Look for a chunk with available offsets.
41 for (auto &chunk : chunk_list_) {
42 if (!chunk.available_offsets.empty()) {
43 pChunk = &chunk;
44 break;
45 }
46 }
47 // If no chunks with available offsets, allocate device memory and set up offsets.
48 if (pChunk == nullptr) {
49 MemoryChunk new_chunk;
50 result = AllocMemoryChunk(new_chunk);
51 if (result == VK_SUCCESS) {
52 new_chunk.available_offsets.resize(blocks_per_chunk_);
53 for (uint32_t offset = 0, i = 0; i < blocks_per_chunk_; offset += block_size_, ++i) {
54 new_chunk.available_offsets[i] = offset;
55 }
56 chunk_list_.push_front(std::move(new_chunk));
57 pChunk = &chunk_list_.front();
58 } else {
59 // Indicate failure
60 block->buffer = VK_NULL_HANDLE;
61 block->memory = VK_NULL_HANDLE;
62 return result;
63 }
64 }
65 // Give the requester an available offset
66 block->buffer = pChunk->buffer;
67 block->memory = pChunk->memory;
68 block->offset = pChunk->available_offsets.back();
69 pChunk->available_offsets.pop_back();
70 return result;
71}
72
73void GpuDeviceMemoryManager::PutBackBlock(VkBuffer buffer, VkDeviceMemory memory, uint32_t offset) {
74 GpuDeviceMemoryBlock block = {buffer, memory, offset};
75 PutBackBlock(block);
76}
77
78void GpuDeviceMemoryManager::PutBackBlock(GpuDeviceMemoryBlock &block) {
79 // Find the chunk belonging to the allocated offset and make the offset available again
80 auto chunk = std::find_if(std::begin(chunk_list_), std::end(chunk_list_),
81 [&block](const MemoryChunk &c) { return c.buffer == block.buffer; });
82 if (chunk_list_.end() == chunk) {
83 assert(false);
84 } else {
85 chunk->available_offsets.push_back(block.offset);
86 if (chunk->available_offsets.size() == blocks_per_chunk_) {
87 // All offsets have been returned
88 FreeMemoryChunk(*chunk);
89 chunk_list_.erase(chunk);
90 }
91 }
92}
93
94void ResetBlock(GpuDeviceMemoryBlock &block) {
95 block.buffer = VK_NULL_HANDLE;
96 block.memory = VK_NULL_HANDLE;
97 block.offset = 0;
98}
99
100bool BlockUsed(GpuDeviceMemoryBlock &block) { return (block.buffer != VK_NULL_HANDLE) && (block.memory != VK_NULL_HANDLE); }
101
102bool GpuDeviceMemoryManager::MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
103 // Search memtypes to find first index with those properties
104 const VkPhysicalDeviceMemoryProperties *props = GetPhysicalDeviceMemoryProperties(dev_data_);
105 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
106 if ((typeBits & 1) == 1) {
107 // Type is available, does it match user properties?
108 if ((props->memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
109 *typeIndex = i;
110 return true;
111 }
112 }
113 typeBits >>= 1;
114 }
115 // No memory types matched, return failure
116 return false;
117}
118
119VkResult GpuDeviceMemoryManager::AllocMemoryChunk(MemoryChunk &chunk) {
120 VkBuffer buffer;
121 VkDeviceMemory memory;
122 VkBufferCreateInfo buffer_create_info = {};
123 VkMemoryRequirements mem_reqs = {};
124 VkMemoryAllocateInfo mem_alloc = {};
125 VkResult result = VK_SUCCESS;
126 bool pass;
127 void *pData;
128 const auto *dispatch_table = GetDispatchTable(dev_data_);
129
130 buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
131 buffer_create_info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
132 buffer_create_info.size = chunk_size_;
133 result = dispatch_table->CreateBuffer(GetDevice(dev_data_), &buffer_create_info, NULL, &buffer);
134 if (result != VK_SUCCESS) {
135 return result;
136 }
137
138 dispatch_table->GetBufferMemoryRequirements(GetDevice(dev_data_), buffer, &mem_reqs);
139
140 mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
141 mem_alloc.pNext = NULL;
142 mem_alloc.allocationSize = mem_reqs.size;
143 pass = MemoryTypeFromProperties(mem_reqs.memoryTypeBits,
144 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
145 &mem_alloc.memoryTypeIndex);
146 if (!pass) {
147 dispatch_table->DestroyBuffer(GetDevice(dev_data_), buffer, NULL);
148 return result;
149 }
150 result = dispatch_table->AllocateMemory(GetDevice(dev_data_), &mem_alloc, NULL, &memory);
151 if (result != VK_SUCCESS) {
152 dispatch_table->DestroyBuffer(GetDevice(dev_data_), buffer, NULL);
153 return result;
154 }
155
156 result = dispatch_table->BindBufferMemory(GetDevice(dev_data_), buffer, memory, 0);
157 if (result != VK_SUCCESS) {
158 dispatch_table->DestroyBuffer(GetDevice(dev_data_), buffer, NULL);
159 dispatch_table->FreeMemory(GetDevice(dev_data_), memory, NULL);
160 return result;
161 }
162
163 result = dispatch_table->MapMemory(GetDevice(dev_data_), memory, 0, mem_alloc.allocationSize, 0, &pData);
164 if (result == VK_SUCCESS) {
165 memset(pData, 0, chunk_size_);
166 dispatch_table->UnmapMemory(GetDevice(dev_data_), memory);
167 } else {
168 dispatch_table->DestroyBuffer(GetDevice(dev_data_), buffer, NULL);
169 dispatch_table->FreeMemory(GetDevice(dev_data_), memory, NULL);
170 return result;
171 }
172 chunk.buffer = buffer;
173 chunk.memory = memory;
174 return result;
175}
176
177void GpuDeviceMemoryManager::FreeMemoryChunk(MemoryChunk &chunk) {
178 GetDispatchTable(dev_data_)->DestroyBuffer(GetDevice(dev_data_), chunk.buffer, NULL);
179 GetDispatchTable(dev_data_)->FreeMemory(GetDevice(dev_data_), chunk.memory, NULL);
180}
181
182// Implementation for Descriptor Set Manager class
183VkResult GpuDescriptorSetManager::GetDescriptorSets(uint32_t count, VkDescriptorPool *pool,
184 std::vector<VkDescriptorSet> *desc_sets) {
185 auto gpu_state = GetGpuValidationState(dev_data_);
186 const uint32_t default_pool_size = kItemsPerChunk;
187 VkResult result = VK_SUCCESS;
188 VkDescriptorPool pool_to_use = VK_NULL_HANDLE;
189
190 if (0 == count) {
191 return result;
192 }
193 desc_sets->clear();
194 desc_sets->resize(count);
195
196 for (auto &pool : desc_pool_map_) {
197 if (pool.second.used + count < pool.second.size) {
198 pool_to_use = pool.first;
199 break;
200 }
201 }
202 if (VK_NULL_HANDLE == pool_to_use) {
203 uint32_t pool_count = default_pool_size;
204 if (count > default_pool_size) {
205 pool_count = count;
206 }
207 const VkDescriptorPoolSize size_counts = {
208 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
209 pool_count * kNumBindingsInSet,
210 };
211 VkDescriptorPoolCreateInfo desc_pool_info = {};
212 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
213 desc_pool_info.pNext = NULL;
214 desc_pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
215 desc_pool_info.maxSets = pool_count;
216 desc_pool_info.poolSizeCount = 1;
217 desc_pool_info.pPoolSizes = &size_counts;
218 result = GetDispatchTable(dev_data_)->CreateDescriptorPool(GetDevice(dev_data_), &desc_pool_info, NULL, &pool_to_use);
219 assert(result == VK_SUCCESS);
220 if (result != VK_SUCCESS) {
221 return result;
222 }
223 desc_pool_map_[pool_to_use].size = desc_pool_info.maxSets;
224 desc_pool_map_[pool_to_use].used = 0;
225 }
226 std::vector<VkDescriptorSetLayout> desc_layouts(count, gpu_state->debug_desc_layout);
227
228 VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool_to_use, count,
229 desc_layouts.data()};
230
231 result = GetDispatchTable(dev_data_)->AllocateDescriptorSets(GetDevice(dev_data_), &alloc_info, desc_sets->data());
232 assert(result == VK_SUCCESS);
233 if (result != VK_SUCCESS) {
234 return result;
235 }
236 *pool = pool_to_use;
237 desc_pool_map_[pool_to_use].used += count;
238 return result;
239}
240
241void GpuDescriptorSetManager::PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set) {
242 auto iter = desc_pool_map_.find(desc_pool);
243 if (iter != desc_pool_map_.end()) {
244 VkResult result = GetDispatchTable(dev_data_)->FreeDescriptorSets(GetDevice(dev_data_), desc_pool, 1, &desc_set);
245 assert(result == VK_SUCCESS);
246 if (result != VK_SUCCESS) {
247 return;
248 }
249 desc_pool_map_[desc_pool].used--;
250 if (0 == desc_pool_map_[desc_pool].used) {
251 GetDispatchTable(dev_data_)->DestroyDescriptorPool(GetDevice(dev_data_), desc_pool, NULL);
252 desc_pool_map_.erase(desc_pool);
253 }
254 }
255 return;
256}
257
258// Convenience function for reporting problems with setting up GPU Validation.
259static void ReportSetupProblem(const layer_data *dev_data, VkDebugReportObjectTypeEXT object_type, uint64_t object_handle,
260 const char *const specific_message) {
261 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object_handle,
262 "UNASSIGNED-GPU-Assisted Validation Error. ", "Detail: (%s)", specific_message);
263}
264
265// Turn on necessary device features.
266std::unique_ptr<safe_VkDeviceCreateInfo> GpuPreCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *create_info,
267 VkPhysicalDeviceFeatures *supported_features) {
268 std::unique_ptr<safe_VkDeviceCreateInfo> new_info(new safe_VkDeviceCreateInfo(create_info));
269 if (supported_features->fragmentStoresAndAtomics || supported_features->vertexPipelineStoresAndAtomics) {
Tony-LunarG48b478a2019-01-15 16:35:22 -0700270 VkPhysicalDeviceFeatures new_features = {};
271 if (new_info->pEnabledFeatures) {
272 new_features = *new_info->pEnabledFeatures;
273 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600274 new_features.fragmentStoresAndAtomics = supported_features->fragmentStoresAndAtomics;
275 new_features.vertexPipelineStoresAndAtomics = supported_features->vertexPipelineStoresAndAtomics;
276 delete new_info->pEnabledFeatures;
277 new_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
278 }
279 return new_info;
280}
281
282// Perform initializations that can be done at Create Device time.
283void GpuPostCallRecordCreateDevice(layer_data *dev_data) {
284 auto gpu_state = GetGpuValidationState(dev_data);
285 const auto *dispatch_table = GetDispatchTable(dev_data);
286
Tony-LunarG65f9c492019-01-17 14:24:42 -0700287 gpu_state->aborted = false;
288 gpu_state->reserve_binding_slot = false;
289
Mark Lobodzinski1cf55ac2019-01-14 14:33:43 -0700290 if (GetPDProperties(dev_data)->apiVersion < VK_API_VERSION_1_1) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600291 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
292 "GPU-Assisted validation requires Vulkan 1.1 or later. GPU-Assisted Validation disabled.");
293 gpu_state->aborted = true;
294 return;
295 }
296 // Some devices have extremely high limits here, so set a reasonable max because we have to pad
297 // the pipeline layout with dummy descriptor set layouts.
Mark Lobodzinski1cf55ac2019-01-14 14:33:43 -0700298 gpu_state->adjusted_max_desc_sets = GetPDProperties(dev_data)->limits.maxBoundDescriptorSets;
Karl Schultz7b024b42018-08-30 16:18:18 -0600299 gpu_state->adjusted_max_desc_sets = std::min(33U, gpu_state->adjusted_max_desc_sets);
300
301 // We can't do anything if there is only one.
302 // Device probably not a legit Vulkan device, since there should be at least 4. Protect ourselves.
303 if (gpu_state->adjusted_max_desc_sets == 1) {
304 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
305 "Device can bind only a single descriptor set. GPU-Assisted Validation disabled.");
306 gpu_state->aborted = true;
307 return;
308 }
309 gpu_state->desc_set_bind_index = gpu_state->adjusted_max_desc_sets - 1;
310 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
311 HandleToUint64(GetDevice(dev_data)), "UNASSIGNED-GPU-Assisted Validation. ",
312 "Shaders using descriptor set at index %d. ", gpu_state->desc_set_bind_index);
313
314 std::unique_ptr<GpuDeviceMemoryManager> memory_manager(
315 new GpuDeviceMemoryManager(dev_data, sizeof(uint32_t) * (spvtools::kInstMaxOutCnt + 1)));
316 std::unique_ptr<GpuDescriptorSetManager> desc_set_manager(new GpuDescriptorSetManager(dev_data));
317
318 // The descriptor indexing checks require only the first "output" binding.
319 const VkDescriptorSetLayoutBinding debug_desc_layout_bindings[kNumBindingsInSet] = {
320 {
321 0, // output
322 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
323 1,
324 VK_SHADER_STAGE_ALL_GRAPHICS,
325 NULL,
326 },
327 };
328
329 const VkDescriptorSetLayoutCreateInfo debug_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0,
330 kNumBindingsInSet, debug_desc_layout_bindings};
331
332 const VkDescriptorSetLayoutCreateInfo dummy_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 0,
333 NULL};
334
335 VkResult result = dispatch_table->CreateDescriptorSetLayout(GetDevice(dev_data), &debug_desc_layout_info, NULL,
336 &gpu_state->debug_desc_layout);
337
338 // This is a layout used to "pad" a pipeline layout to fill in any gaps to the selected bind index.
339 VkResult result2 = dispatch_table->CreateDescriptorSetLayout(GetDevice(dev_data), &dummy_desc_layout_info, NULL,
340 &gpu_state->dummy_desc_layout);
341 assert((result == VK_SUCCESS) && (result2 == VK_SUCCESS));
342 if ((result != VK_SUCCESS) || (result2 != VK_SUCCESS)) {
343 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
344 "Unable to create descriptor set layout. GPU-Assisted Validation disabled.");
345 if (result == VK_SUCCESS) {
346 dispatch_table->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->debug_desc_layout, NULL);
347 }
348 if (result2 == VK_SUCCESS) {
349 dispatch_table->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->dummy_desc_layout, NULL);
350 }
351 gpu_state->debug_desc_layout = VK_NULL_HANDLE;
352 gpu_state->dummy_desc_layout = VK_NULL_HANDLE;
353 gpu_state->aborted = true;
354 return;
355 }
356 gpu_state->memory_manager = std::move(memory_manager);
357 gpu_state->desc_set_manager = std::move(desc_set_manager);
358}
359
360// Clean up device-related resources
361void GpuPreCallRecordDestroyDevice(layer_data *dev_data) {
362 auto gpu_state = GetGpuValidationState(dev_data);
363
Karl Schultz58674242019-01-22 15:35:02 -0700364 if (gpu_state->barrier_command_buffer) {
365 GetDispatchTable(dev_data)->FreeCommandBuffers(GetDevice(dev_data), gpu_state->barrier_command_pool, 1,
366 &gpu_state->barrier_command_buffer);
367 gpu_state->barrier_command_buffer = VK_NULL_HANDLE;
368 }
369 if (gpu_state->barrier_command_pool) {
370 GetDispatchTable(dev_data)->DestroyCommandPool(GetDevice(dev_data), gpu_state->barrier_command_pool, NULL);
371 gpu_state->barrier_command_pool = VK_NULL_HANDLE;
372 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600373 if (gpu_state->debug_desc_layout) {
374 GetDispatchTable(dev_data)->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->debug_desc_layout, NULL);
375 gpu_state->debug_desc_layout = VK_NULL_HANDLE;
376 }
377 if (gpu_state->dummy_desc_layout) {
378 GetDispatchTable(dev_data)->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->dummy_desc_layout, NULL);
379 gpu_state->dummy_desc_layout = VK_NULL_HANDLE;
380 }
381}
382
383// Bind our debug descriptor set immediately after binding a pipeline if the pipeline layout is not using our slot.
384void GpuPostCallDispatchCmdBindPipeline(layer_data *dev_data, VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
385 VkPipeline pipeline) {
386 auto gpu_state = GetGpuValidationState(dev_data);
387 if (gpu_state->aborted) {
388 return;
389 }
390 const GLOBAL_CB_NODE *cb_state = GetCBNode(dev_data, commandBuffer);
391 auto iter = cb_state->lastBound.find(pipelineBindPoint); // find() allows read-only access to cb_state
392 if (iter != cb_state->lastBound.end()) {
393 auto pipeline_state = iter->second.pipeline_state;
394 if (pipeline_state && (pipeline_state->pipeline_layout.set_layouts.size() <= gpu_state->desc_set_bind_index)) {
395 GetDispatchTable(dev_data)->CmdBindDescriptorSets(
396 commandBuffer, pipelineBindPoint, pipeline_state->pipeline_layout.layout, gpu_state->desc_set_bind_index, 1,
397 &cb_state->gpu_buffer_desc_set, 0, nullptr);
398 }
399 }
400}
401
402// Modify the pipeline layout to include our debug descriptor set and any needed padding with the dummy descriptor set.
403VkResult GpuOverrideDispatchCreatePipelineLayout(layer_data *dev_data, const VkPipelineLayoutCreateInfo *pCreateInfo,
404 const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout) {
405 auto gpu_state = GetGpuValidationState(dev_data);
406 if (gpu_state->aborted) {
407 return GetDispatchTable(dev_data)->CreatePipelineLayout(GetDevice(dev_data), pCreateInfo, pAllocator, pPipelineLayout);
408 }
409 VkPipelineLayoutCreateInfo new_create_info = *pCreateInfo;
410 std::vector<VkDescriptorSetLayout> new_layouts;
411 if (new_create_info.setLayoutCount >= gpu_state->adjusted_max_desc_sets) {
412 std::ostringstream strm;
413 strm << "Pipeline Layout conflict with validation's descriptor set at slot " << gpu_state->desc_set_bind_index << ". "
414 << "Application has too many descriptor sets in the pipeline layout to continue with gpu validation. "
415 << "Validation is not modifying the pipeline layout. "
416 << "Instrumented shaders are replaced with non-instrumented shaders.";
417 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
418 strm.str().c_str());
419 } else {
420 // Modify the pipeline layout by:
421 // 1. Copying the caller's descriptor set desc_layouts
422 // 2. Fill in dummy descriptor layouts up to the max binding
423 // 3. Fill in with the debug descriptor layout at the max binding slot
424 new_layouts.reserve(gpu_state->adjusted_max_desc_sets);
425 new_layouts.insert(new_layouts.end(), &pCreateInfo->pSetLayouts[0], &pCreateInfo->pSetLayouts[pCreateInfo->setLayoutCount]);
426 for (uint32_t i = pCreateInfo->setLayoutCount; i < gpu_state->adjusted_max_desc_sets - 1; ++i) {
427 new_layouts.push_back(gpu_state->dummy_desc_layout);
428 }
429 new_layouts.push_back(gpu_state->debug_desc_layout);
430 new_create_info.pSetLayouts = new_layouts.data();
431 new_create_info.setLayoutCount = gpu_state->adjusted_max_desc_sets;
432 }
433 VkResult result;
434 result = GetDispatchTable(dev_data)->CreatePipelineLayout(GetDevice(dev_data), &new_create_info, pAllocator, pPipelineLayout);
435 assert(result == VK_SUCCESS);
436 if (result != VK_SUCCESS) {
437 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
438 "Unable to create pipeline layout. Device could become unstable.");
439 gpu_state->aborted = true;
440 }
441 return result;
442}
443
444// Each command buffer gets a piece of device memory and a descriptor set for the debug buffer.
445void GpuPostCallRecordAllocateCommandBuffers(layer_data *dev_data, const VkCommandBufferAllocateInfo *pCreateInfo,
446 VkCommandBuffer *pCommandBuffer) {
447 VkResult result;
448
449 auto gpu_state = GetGpuValidationState(dev_data);
450 if (gpu_state->aborted) return;
451
452 std::vector<VkDescriptorSet> desc_sets;
453 VkDescriptorPool desc_pool = VK_NULL_HANDLE;
454 result = gpu_state->desc_set_manager->GetDescriptorSets(pCreateInfo->commandBufferCount, &desc_pool, &desc_sets);
455 assert(result == VK_SUCCESS);
456 if (result != VK_SUCCESS) {
457 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
458 "Unable to allocate descriptor sets. Device could become unstable.");
459 gpu_state->aborted = true;
460 return;
461 }
462
463 VkDescriptorBufferInfo desc_buffer_info = {};
464 desc_buffer_info.range = gpu_state->memory_manager->GetBlockSize();
465
466 VkWriteDescriptorSet desc_write = {};
467 desc_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
468 desc_write.descriptorCount = 1;
469 desc_write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
470 desc_write.pBufferInfo = &desc_buffer_info;
471
472 for (uint32_t i = 0; i < pCreateInfo->commandBufferCount; i++) {
473 auto cb_node = GetCBNode(dev_data, pCommandBuffer[i]);
474
475 GpuDeviceMemoryBlock block = {};
476 result = gpu_state->memory_manager->GetBlock(&block);
477 if (result != VK_SUCCESS) {
478 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
479 "Unable to allocate device memory. Device could become unstable.");
480 gpu_state->aborted = true;
481 return;
482 }
483
484 // Record buffer and memory info in CB state tracking
485 cb_node->gpu_output_memory_block = block;
486 cb_node->gpu_buffer_desc_set = desc_sets[i];
487 cb_node->gpu_buffer_desc_pool = desc_pool;
488
489 // Write the descriptor
490 desc_buffer_info.buffer = block.buffer;
491 desc_buffer_info.offset = block.offset;
492 desc_write.dstSet = cb_node->gpu_buffer_desc_set;
493 GetDispatchTable(dev_data)->UpdateDescriptorSets(GetDevice(dev_data), 1, &desc_write, 0, NULL);
494 }
495}
496
497// Free the device memory and descriptor set associated with a command buffer.
498void GpuPreCallRecordFreeCommandBuffers(layer_data *dev_data, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers) {
499 auto gpu_state = GetGpuValidationState(dev_data);
500 if (gpu_state->aborted) {
501 return;
502 }
503 for (uint32_t i = 0; i < commandBufferCount; ++i) {
504 auto cb_node = GetCBNode(dev_data, pCommandBuffers[i]);
505 if (BlockUsed(cb_node->gpu_output_memory_block)) {
506 gpu_state->memory_manager->PutBackBlock(cb_node->gpu_output_memory_block);
507 ResetBlock(cb_node->gpu_output_memory_block);
508 }
509 if (cb_node->gpu_buffer_desc_set != VK_NULL_HANDLE) {
510 gpu_state->desc_set_manager->PutBackDescriptorSet(cb_node->gpu_buffer_desc_pool, cb_node->gpu_buffer_desc_set);
511 cb_node->gpu_buffer_desc_set = VK_NULL_HANDLE;
512 }
513 }
514}
515
516// Just gives a warning about a possible deadlock.
517void GpuPreCallValidateCmdWaitEvents(layer_data *dev_data, VkPipelineStageFlags sourceStageMask) {
518 if (sourceStageMask & VK_PIPELINE_STAGE_HOST_BIT) {
519 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
520 "CmdWaitEvents recorded with VK_PIPELINE_STAGE_HOST_BIT set. "
521 "GPU_Assisted validation waits on queue completion. "
522 "This wait could block the host's signaling of this event, resulting in deadlock.");
523 }
524}
525
526// Examine the pipelines to see if they use the debug descriptor set binding index.
527// If any do, create new non-instrumented shader modules and use them to replace the instrumented
528// shaders in the pipeline. Return the (possibly) modified create infos to the caller.
529std::vector<safe_VkGraphicsPipelineCreateInfo> GpuPreCallRecordCreateGraphicsPipelines(
530 layer_data *dev_data, VkPipelineCache pipelineCache, uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
531 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) {
532 auto gpu_state = GetGpuValidationState(dev_data);
533
534 std::vector<safe_VkGraphicsPipelineCreateInfo> new_pipeline_create_infos;
535 std::vector<unsigned int> pipeline_uses_debug_index(count);
536
537 // Walk through all the pipelines, make a copy of each and flag each pipeline that contains a shader that uses the debug
538 // descriptor set index.
539 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
540 new_pipeline_create_infos.push_back(pipe_state[pipeline]->graphicsPipelineCI);
541 if (pipe_state[pipeline]->active_slots.find(gpu_state->desc_set_bind_index) != pipe_state[pipeline]->active_slots.end()) {
542 pipeline_uses_debug_index[pipeline] = 1;
543 }
544 }
545
546 // See if any pipeline has shaders using the debug descriptor set index
547 if (std::all_of(pipeline_uses_debug_index.begin(), pipeline_uses_debug_index.end(), [](unsigned int i) { return i == 0; })) {
548 // None of the shaders in all the pipelines use the debug descriptor set index, so use the pipelines
549 // as they stand with the instrumented shaders.
550 return new_pipeline_create_infos;
551 }
552
553 // At least one pipeline has a shader that uses the debug descriptor set index.
554 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
555 if (pipeline_uses_debug_index[pipeline]) {
556 for (uint32_t stage = 0; stage < pCreateInfos[pipeline].stageCount; ++stage) {
557 const shader_module *shader = GetShaderModuleState(dev_data, pCreateInfos[pipeline].pStages[stage].module);
558 VkShaderModuleCreateInfo create_info = {};
559 VkShaderModule shader_module;
560 create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
561 create_info.pCode = shader->words.data();
562 create_info.codeSize = shader->words.size() * sizeof(uint32_t);
563 VkResult result =
564 GetDispatchTable(dev_data)->CreateShaderModule(GetDevice(dev_data), &create_info, pAllocator, &shader_module);
565 if (result == VK_SUCCESS) {
566 new_pipeline_create_infos[pipeline].pStages[stage].module = shader_module;
567 } else {
568 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
569 HandleToUint64(pCreateInfos[pipeline].pStages[stage].module),
570 "Unable to replace instrumented shader with non-instrumented one. "
571 "Device could become unstable.");
572 }
573 }
574 }
575 }
576 return new_pipeline_create_infos;
577}
578
579// For every pipeline:
580// - For every shader in a pipeline:
581// - If the shader had to be replaced in PreCallRecord (because the pipeline is using the debug desc set index):
582// - Destroy it since it has been bound into the pipeline by now. This is our only chance to delete it.
583// - Track the shader in the shader_map
584// - Save the shader binary if it contains debug code
585void GpuPostCallRecordCreateGraphicsPipelines(layer_data *dev_data, const uint32_t count,
586 const VkGraphicsPipelineCreateInfo *pCreateInfos,
587 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) {
588 auto gpu_state = GetGpuValidationState(dev_data);
589 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
590 auto pipeline_state = GetPipelineState(dev_data, pPipelines[pipeline]);
591 if (nullptr == pipeline_state) continue;
592 for (uint32_t stage = 0; stage < pipeline_state->graphicsPipelineCI.stageCount; ++stage) {
593 if (pipeline_state->active_slots.find(gpu_state->desc_set_bind_index) != pipeline_state->active_slots.end()) {
594 GetDispatchTable(dev_data)->DestroyShaderModule(GetDevice(dev_data), pCreateInfos->pStages[stage].module,
595 pAllocator);
596 }
597 auto shader_state = GetShaderModuleState(dev_data, pipeline_state->graphicsPipelineCI.pStages[stage].module);
598 std::vector<unsigned int> code;
599 // Save the shader binary if debug info is present.
600 // The core_validation ShaderModule tracker saves the binary too, but discards it when the ShaderModule
601 // is destroyed. Applications may destroy ShaderModules after they are placed in a pipeline and before
602 // the pipeline is used, so we have to keep another copy.
603 if (shader_state && shader_state->has_valid_spirv) { // really checking for presense of SPIR-V code.
604 for (auto insn : *shader_state) {
605 if (insn.opcode() == spv::OpLine) {
606 code = shader_state->words;
607 break;
608 }
609 }
610 }
611 gpu_state->shader_map[shader_state->gpu_validation_shader_id].pipeline = pipeline_state->pipeline;
612 // Be careful to use the originally bound (instrumented) shader here, even if PreCallRecord had to back it
613 // out with a non-instrumented shader. The non-instrumented shader (found in pCreateInfo) was destroyed above.
614 gpu_state->shader_map[shader_state->gpu_validation_shader_id].shader_module =
615 pipeline_state->graphicsPipelineCI.pStages[stage].module;
616 gpu_state->shader_map[shader_state->gpu_validation_shader_id].pgm = std::move(code);
617 }
618 }
619}
620
621// Remove all the shader trackers associated with this destroyed pipeline.
622void GpuPreCallRecordDestroyPipeline(layer_data *dev_data, const VkPipeline pipeline) {
623 auto gpu_state = GetGpuValidationState(dev_data);
624 for (auto it = gpu_state->shader_map.begin(); it != gpu_state->shader_map.end();) {
625 if (it->second.pipeline == pipeline) {
626 it = gpu_state->shader_map.erase(it);
627 } else {
628 ++it;
629 }
630 }
631}
632
Karl Schultz24137052019-01-12 08:16:32 -0700633// This is a temporary workaround to fix a missing operation in the spirv-tools
634// instrumentation pass.
635// The instrumentation pass creates an array (of uint) variable to store the debug
636// data. But it doesn't set the ArrayStride decoration (to 4). Some drivers
637// move along and come up with a value of 4, but some don't and use a stride value of 0.
638// Add our own decoration to the SPIR-V type definition for the array.
639static void FixMissingStride(layer_data *dev_data, std::vector<unsigned int> &new_pgm) {
640 auto gpu_state = GetGpuValidationState(dev_data);
641 unsigned int insert_offset = 0;
642 shader_module shader;
643 shader.words = new_pgm;
644 if (shader.words.size() > 0) {
645 // Find the ID of the variable referenced by our debug descriptor set.
646 // If found, also save an offset for a good place to insert our additional decoration later.
647 unsigned int variable_id = 0;
648 for (auto insn : shader) {
649 if (insn.opcode() == spv::OpDecorate) {
650 if (insn.word(2) == spv::Decoration::DecorationDescriptorSet && insn.word(3) == gpu_state->desc_set_bind_index) {
651 variable_id = insn.word(1);
652 insn++;
653 insert_offset = insn.offset();
654 break;
655 }
656 }
657 }
658 if (variable_id == 0) return;
659
660 // Look up the variable and find its type ptr.
661 unsigned int variable_type_ptr_id = 0;
662 for (auto insn : shader) {
663 if (insn.opcode() == spv::OpVariable) {
664 if (insn.word(2) == variable_id) {
665 variable_type_ptr_id = insn.word(1);
666 break;
667 }
668 }
669 }
670 if (variable_type_ptr_id == 0) return;
671
672 // Look up the type ptr of the variable to find its type
673 unsigned int type_id = 0;
674 for (auto insn : shader) {
675 if (insn.opcode() == spv::OpTypePointer) {
676 if (insn.word(1) == variable_type_ptr_id) {
677 type_id = insn.word(3);
678 break;
679 }
680 }
681 }
682 if (type_id == 0) return;
683
684 // Look up the type that we want to annotate with the stride.
685 // We don't really know what the actual type is that is pointed to by the type ptr we just found.
686 // I suppose we could scan on the OpType* opcodes to look for an ID match.
687 // But we happen to know that there is a struct here, so look for just OpTypeStruct.
688 // We also know that the second struct member is the array of debug output words.
689 unsigned int array_type_id = 0;
690 for (auto insn : shader) {
691 if (insn.opcode() == spv::OpTypeStruct) {
692 if (insn.word(1) == type_id && insn.len() >= 4) { // has at least 2 members
693 array_type_id = insn.word(3); // second member type
694 break;
695 }
696 }
697 }
698 if (array_type_id == 0) return;
699
700 // See if the array stride decoration for the type of the debug data array is already there.
701 // Don't insert a new one if there is one already there.
702 bool stride_already_there = false;
703 for (auto insn : shader) {
704 if (insn.opcode() == spv::OpDecorate) {
705 if (insn.len() == 4 && insn.word(1) == array_type_id && insn.word(2) == spv::Decoration::DecorationArrayStride) {
706 stride_already_there = true;
707 break;
708 }
709 }
710 }
711 if (stride_already_there) return;
712
713 // Build an OpDecorate instruction to add the stride information and insert it in the program.
714 if (insert_offset != 0) {
715 std::vector<unsigned int> inst(4);
716 inst[0] = (4 << 16) | spv::OpDecorate;
717 inst[1] = array_type_id;
718 inst[2] = spv::Decoration::DecorationArrayStride;
719 inst[3] = 4;
720 auto it = new_pgm.begin();
721 new_pgm.insert(it + insert_offset, inst.begin(), inst.end());
722 }
723 }
724}
725
Karl Schultz7b024b42018-08-30 16:18:18 -0600726// Call the SPIR-V Optimizer to run the instrumentation pass on the shader.
727static bool GpuInstrumentShader(layer_data *dev_data, const VkShaderModuleCreateInfo *pCreateInfo,
728 std::vector<unsigned int> &new_pgm, uint32_t *unique_shader_id) {
729 auto gpu_state = GetGpuValidationState(dev_data);
730 if (gpu_state->aborted) return false;
731 if (pCreateInfo->pCode[0] != spv::MagicNumber) return false;
732
733 // Load original shader SPIR-V
734 uint32_t num_words = static_cast<uint32_t>(pCreateInfo->codeSize / 4);
735 new_pgm.clear();
736 new_pgm.reserve(num_words);
737 new_pgm.insert(new_pgm.end(), &pCreateInfo->pCode[0], &pCreateInfo->pCode[num_words]);
738
739 // Call the optimizer to instrument the shader.
740 // Use the unique_shader_module_id as a shader ID so we can look up its handle later in the shader_map.
741 using namespace spvtools;
742 spv_target_env target_env = SPV_ENV_VULKAN_1_1;
743 Optimizer optimizer(target_env);
744 optimizer.RegisterPass(CreateInstBindlessCheckPass(gpu_state->desc_set_bind_index, gpu_state->unique_shader_module_id));
745 optimizer.RegisterPass(CreateAggressiveDCEPass());
746 bool pass = optimizer.Run(new_pgm.data(), new_pgm.size(), &new_pgm);
747 if (!pass) {
748 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, VK_NULL_HANDLE,
749 "Failure to instrument shader. Proceeding with non-instrumented shader.");
750 }
Karl Schultz24137052019-01-12 08:16:32 -0700751 FixMissingStride(dev_data, new_pgm);
Karl Schultz7b024b42018-08-30 16:18:18 -0600752 *unique_shader_id = gpu_state->unique_shader_module_id++;
753 return pass;
754}
755
756// Override the CreateShaderModule command to provide the instrumented shader to the driver.
757VkResult GpuOverrideDispatchCreateShaderModule(layer_data *dev_data, const VkShaderModuleCreateInfo *pCreateInfo,
758 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
759 uint32_t *unique_shader_id) {
760 VkShaderModuleCreateInfo instrumented_create_info = *pCreateInfo;
761 std::vector<unsigned int> instrumented_pgm;
762 bool pass = GpuInstrumentShader(dev_data, pCreateInfo, instrumented_pgm, unique_shader_id);
763 if (pass) {
764 instrumented_create_info.pCode = instrumented_pgm.data();
765 instrumented_create_info.codeSize = instrumented_pgm.size() * sizeof(unsigned int);
766 }
767 // We trust the optimizer's instrumentation pass to not change the validity of the SPIR-V as determined by
768 // the prior call to PreCallValidate.
769 // But we do pass the instrumented shader to the driver.
770 VkResult result =
771 GetDispatchTable(dev_data)->CreateShaderModule(GetDevice(dev_data), &instrumented_create_info, pAllocator, pShaderModule);
772 return result;
773}
774
775// Generate the stage-specific part of the message.
776static void GenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
777 using namespace spvtools;
778 std::ostringstream strm;
779 switch (debug_record[kInstCommonOutStageIdx]) {
780 case 0: {
781 strm << "Stage = Vertex. Vertex ID = " << debug_record[kInstVertOutVertexId]
782 << " Instance ID = " << debug_record[kInstVertOutInstanceId] << ". ";
783 } break;
784 case 1: {
785 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
786 } break;
787 case 2: {
788 strm << "Stage = Tessellation Eval. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
789 } break;
790 case 3: {
791 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
792 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
793 } break;
794 case 4: {
795 strm << "Stage = Fragment. Fragment coord (x,y) = ("
796 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
797 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
798 } break;
799 case 5: {
800 strm << "Stage = Compute. Global invocation ID = " << debug_record[kInstCompOutGlobalInvocationId] << ". ";
801 } break;
802 default: {
803 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
804 assert(false);
805 } break;
806 }
807 msg = strm.str();
808}
809
810// Generate the part of the message describing the violation.
811static void GenerateValidationMessage(const uint32_t *debug_record, std::string &msg, std::string &vuid_msg) {
812 using namespace spvtools;
813 std::ostringstream strm;
814 switch (debug_record[kInstValidationOutError]) {
815 case 0: {
816 strm << "Index of " << debug_record[kInstBindlessOutDescIndex] << " used to index descriptor array of length "
817 << debug_record[kInstBindlessOutDescBound] << ". ";
818 vuid_msg = "UNASSIGNED-Image descriptor index out of bounds";
819 } break;
820 case 1: {
821 strm << "Index of " << debug_record[kInstBindlessOutDescIndex] << " used to index descriptor array of length "
822 << debug_record[kInstBindlessOutDescBound] << ". ";
823 vuid_msg = "UNASSIGNED-Sampler index out of bounds";
824 } break;
825 case 2: {
826 strm << "Descriptor index " << debug_record[kInstBindlessOutDescIndex] << " is uninitialized. ";
827 vuid_msg = "UNASSIGNED-Image descriptor uninitialized";
828 } break;
829 case 3: {
830 strm << "Descriptor index " << debug_record[kInstBindlessOutDescIndex] << " is uninitialized. ";
831 vuid_msg = "UNASSIGNED-Sampler descriptor uninitialized";
832 } break;
833 default: {
834 strm << "Internal Error (unexpected error type = " << debug_record[kInstValidationOutError] << "). ";
835 vuid_msg = "UNASSIGNED-Internal Error";
836 assert(false);
837 } break;
838 }
839 msg = strm.str();
840}
841
842static std::string LookupDebugUtilsName(const layer_data *dev_data, const uint64_t object) {
843 const debug_report_data *debug_data = GetReportData(dev_data);
844 auto utils_name_iter = debug_data->debugUtilsObjectNameMap->find(object);
845 if (utils_name_iter != debug_data->debugUtilsObjectNameMap->end()) {
846 return "(" + utils_name_iter->second + ")";
847 } else {
848 return "";
849 }
850}
851
852// Generate message from the common portion of the debug report record.
853static void GenerateCommonMessage(const layer_data *dev_data, const GLOBAL_CB_NODE *cb_node, const uint32_t *debug_record,
854 const VkShaderModule shader_module_handle, const VkPipeline pipeline_handle, std::string &msg) {
855 using namespace spvtools;
856 std::ostringstream strm;
857 if (shader_module_handle == VK_NULL_HANDLE) {
858 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
859 << LookupDebugUtilsName(dev_data, HandleToUint64(cb_node->commandBuffer)) << "("
860 << HandleToUint64(cb_node->commandBuffer) << "). ";
861 assert(true);
862 } else {
863 strm << std::hex << std::showbase << "Command buffer "
864 << LookupDebugUtilsName(dev_data, HandleToUint64(cb_node->commandBuffer)) << "("
865 << HandleToUint64(cb_node->commandBuffer) << "). "
866 << "Pipeline " << LookupDebugUtilsName(dev_data, HandleToUint64(pipeline_handle)) << "("
867 << HandleToUint64(pipeline_handle) << "). "
868 << "Shader Module " << LookupDebugUtilsName(dev_data, HandleToUint64(shader_module_handle)) << "("
869 << HandleToUint64(shader_module_handle) << "). ";
870 }
871 strm << std::dec << std::noshowbase;
872 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
873 msg = strm.str();
874}
875
876// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
877// Split the single string into a vector of strings, one for each line, for easier processing.
878static void ReadOpSource(const shader_module &shader, const uint32_t reported_file_id, std::vector<std::string> &opsource_lines) {
879 for (auto insn : shader) {
880 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
881 std::istringstream in_stream;
882 std::string cur_line;
883 in_stream.str((char *)&insn.word(4));
884 while (std::getline(in_stream, cur_line)) {
885 opsource_lines.push_back(cur_line);
886 }
887 while ((++insn).opcode() == spv::OpSourceContinued) {
888 in_stream.str((char *)&insn.word(1));
889 while (std::getline(in_stream, cur_line)) {
890 opsource_lines.push_back(cur_line);
891 }
892 }
893 break;
894 }
895 }
896}
897
898// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
899// Scan the source (from OpSource) to find the line of source at the reported line number and place it in another message string.
900static void GenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, std::string &filename_msg,
901 std::string &source_msg) {
902 using namespace spvtools;
903 std::ostringstream filename_stream;
904 std::ostringstream source_stream;
905 shader_module shader;
906 shader.words = pgm;
907 // Find the OpLine just before the failing instruction indicated by the debug info.
908 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
909 uint32_t instruction_index = 0;
910 uint32_t reported_file_id = 0;
911 uint32_t reported_line_number = 0;
912 uint32_t reported_column_number = 0;
913 if (shader.words.size() > 0) {
914 for (auto insn : shader) {
915 if (insn.opcode() == spv::OpLine) {
916 reported_file_id = insn.word(1);
917 reported_line_number = insn.word(2);
918 reported_column_number = insn.word(3);
919 }
920 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
921 break;
922 }
923 instruction_index++;
924 }
925 }
926 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
927 std::string reported_filename;
928 if (reported_file_id == 0) {
929 filename_stream
930 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
931 } else {
932 bool found_opstring = false;
933 for (auto insn : shader) {
934 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
935 found_opstring = true;
936 reported_filename = (char *)&insn.word(2);
937 if (reported_filename.empty()) {
938 filename_stream << "Shader validation error occurred at line " << reported_line_number;
939 } else {
940 filename_stream << "Shader validation error occurred in file: " << reported_filename << " at line "
941 << reported_line_number;
942 }
943 if (reported_column_number > 0) {
944 filename_stream << ", column " << reported_column_number;
945 }
946 filename_stream << ".";
947 break;
948 }
949 }
950 if (!found_opstring) {
951 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction.";
952 }
953 }
954 filename_msg = filename_stream.str();
955
956 // Create message to display source code line containing error.
957 if ((reported_file_id != 0)) {
958 // Read the source code and split it up into separate lines.
959 std::vector<std::string> opsource_lines;
960 ReadOpSource(shader, reported_file_id, opsource_lines);
961 // Find the line in the OpSource content that corresponds to the reported error file and line.
962 if (!opsource_lines.empty()) {
963 // The task here is to search the OpSource content to find the #line directive with the
964 // line number that is closest to, but still prior to the reported error line number and
965 // still within the reported filename.
966 // From this known position in the OpSource content we can add the difference between
967 // the #line line number and the reported error line number to determine the location
968 // in the OpSource content of the reported error line.
969 //
970 // Considerations:
971 // - Look only at #line directives that specify the reported_filename since
972 // the reported error line number refers to its location in the reported filename.
973 // - If a #line directive does not have a filename, the file is the reported filename, or
974 // the filename found in a prior #line directive. (This is C-preprocessor behavior)
975 // - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
976 // original order and the #line directives are used to keep the numbering correct. This
977 // is why we need to examine the entire contents of the source, instead of leaving early
978 // when finding a #line line number larger than the reported error line number.
979 //
980 std::regex line_regex( // matches #line directives
981 "^" // beginning of line
982 "\\s*" // optional whitespace
983 "#" // required text
984 "\\s*" // optional whitespace
985 "line" // required text
986 "\\s+" // required whitespace
987 "([0-9]+)" // required first capture - line number
988 "(\\s+)?" // optional second capture - whitespace
989 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
990 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
991 uint32_t saved_line_number = 0;
992 std::string current_filename = reported_filename; // current "preprocessor" filename state.
993 std::vector<std::string>::size_type saved_opsource_offset = 0;
994 bool found_best_line = false;
995 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
996 std::smatch captures;
997 bool found_line = std::regex_match(*it, captures, line_regex);
998 if (!found_line) continue;
999 // filename is optional and considered found only if the whitespace and the filename are captured
1000 bool found_filename = captures[2].matched && captures[3].matched;
1001 if (found_filename) {
1002 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
1003 current_filename = captures[3].str().substr(1, captures[3].str().size() - 2);
1004 }
1005 if ((!found_filename) || (current_filename == reported_filename)) {
1006 // captures[1] is valid whenever the regex matches, which it has at this point.
1007 uint32_t parsed_line_number = std::stoul(captures[1]);
1008 // Update the candidate best line directive, if the current one is prior and closer to the reported line
1009 if (reported_line_number >= parsed_line_number) {
1010 if (!found_best_line ||
1011 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
1012 saved_line_number = parsed_line_number;
1013 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
1014 found_best_line = true;
1015 }
1016 }
1017 }
1018 }
1019 if (found_best_line) {
1020 assert(reported_line_number >= saved_line_number);
1021 std::vector<std::string>::size_type opsource_index =
1022 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
1023 if (opsource_index < opsource_lines.size()) {
1024 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
1025 } else {
1026 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
1027 << opsource_lines.size() << " lines.";
1028 }
1029 } else {
1030 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
1031 }
1032 } else {
1033 source_stream << "Unable to find SPIR-V OpSource.";
1034 }
1035 }
1036 source_msg = source_stream.str();
1037}
1038
1039// Pull together all the information from the debug record to build the error message strings,
1040// and then assemble them into a single message string.
1041// Retrieve the shader program referenced by the unique shader ID provided in the debug record.
1042// We had to keep a copy of the shader program with the same lifecycle as the pipeline to make
1043// sure it is available when the pipeline is submitted. (The ShaderModule tracking object also
1044// keeps a copy, but it can be destroyed after the pipeline is created and before it is submitted.)
1045//
1046static void AnalyzeAndReportError(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node, VkQueue queue,
1047 uint32_t *const debug_output_buffer) {
1048 using namespace spvtools;
1049 const uint32_t total_words = debug_output_buffer[0];
1050 // A zero here means that the shader instrumentation didn't write anything.
1051 // If you have nothing to say, don't say it here.
1052 if (0 == total_words) {
1053 return;
1054 }
1055 // The first word in the debug output buffer is the number of words that would have
1056 // been written by the shader instrumentation, if there was enough room in the buffer we provided.
1057 // The number of words actually written by the shaders is determined by the size of the buffer
1058 // we provide via the descriptor. So, we process only the number of words that can fit in the
1059 // buffer.
1060 // Each "report" written by the shader instrumentation is considered a "record". This function
1061 // is hard-coded to process only one record because it expects the buffer to be large enough to
1062 // hold only one record. If there is a desire to process more than one record, this function needs
1063 // to be modified to loop over records and the buffer size increased.
1064 auto gpu_state = GetGpuValidationState(dev_data);
1065 std::string validation_message;
1066 std::string stage_message;
1067 std::string common_message;
1068 std::string filename_message;
1069 std::string source_message;
1070 std::string vuid_msg;
1071 VkShaderModule shader_module_handle = VK_NULL_HANDLE;
1072 VkPipeline pipeline_handle = VK_NULL_HANDLE;
1073 std::vector<unsigned int> pgm;
1074 // The first record starts at this offset after the total_words.
1075 const uint32_t *debug_record = &debug_output_buffer[kDebugOutputDataOffset];
1076 // Lookup the VkShaderModule handle and SPIR-V code used to create the shader, using the unique shader ID value returned
1077 // by the instrumented shader.
1078 auto it = gpu_state->shader_map.find(debug_record[kInstCommonOutShaderId]);
1079 if (it != gpu_state->shader_map.end()) {
1080 shader_module_handle = it->second.shader_module;
1081 pipeline_handle = it->second.pipeline;
1082 pgm = it->second.pgm;
1083 }
1084 GenerateValidationMessage(debug_record, validation_message, vuid_msg);
1085 GenerateStageMessage(debug_record, stage_message);
1086 GenerateCommonMessage(dev_data, cb_node, debug_record, shader_module_handle, pipeline_handle, common_message);
1087 GenerateSourceMessages(pgm, debug_record, filename_message, source_message);
1088 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, HandleToUint64(queue),
1089 vuid_msg.c_str(), "%s %s %s %s%s", validation_message.c_str(), common_message.c_str(), stage_message.c_str(),
1090 filename_message.c_str(), source_message.c_str());
1091 // The debug record at word kInstCommonOutSize is the number of words in the record
1092 // written by the shader. Clear the entire record plus the total_words word at the start.
1093 const uint32_t words_to_clear = 1 + std::min(debug_record[kInstCommonOutSize], (uint32_t)kInstMaxOutCnt);
1094 memset(debug_output_buffer, 0, sizeof(uint32_t) * words_to_clear);
1095}
1096
1097// For the given command buffer, map its debug data buffer and read its contents for analysis.
1098static void ProcessInstrumentationBuffer(const layer_data *dev_data, VkQueue queue, GLOBAL_CB_NODE *cb_node) {
1099 auto gpu_state = GetGpuValidationState(dev_data);
1100 if (cb_node && cb_node->hasDrawCmd && cb_node->gpu_output_memory_block.memory) {
1101 VkResult result;
1102 char *pData;
1103 uint32_t block_offset = cb_node->gpu_output_memory_block.offset;
1104 uint32_t block_size = gpu_state->memory_manager->GetBlockSize();
1105 uint32_t offset_to_data = 0;
Mark Lobodzinski1cf55ac2019-01-14 14:33:43 -07001106 const uint32_t map_align = std::max(1U, static_cast<uint32_t>(GetPDProperties(dev_data)->limits.minMemoryMapAlignment));
Karl Schultz7b024b42018-08-30 16:18:18 -06001107
1108 // Adjust the offset to the alignment required for mapping.
1109 block_offset = (block_offset / map_align) * map_align;
1110 offset_to_data = cb_node->gpu_output_memory_block.offset - block_offset;
1111 block_size += offset_to_data;
1112 result = GetDispatchTable(dev_data)->MapMemory(cb_node->device, cb_node->gpu_output_memory_block.memory, block_offset,
1113 block_size, 0, (void **)&pData);
1114 // Analyze debug output buffer
1115 if (result == VK_SUCCESS) {
1116 AnalyzeAndReportError(dev_data, cb_node, queue, (uint32_t *)(pData + offset_to_data));
1117 GetDispatchTable(dev_data)->UnmapMemory(cb_node->device, cb_node->gpu_output_memory_block.memory);
1118 }
1119 }
1120}
1121
Karl Schultz58674242019-01-22 15:35:02 -07001122// Submit a memory barrier on graphics queues.
1123// Lazy-create and record the needed command buffer.
1124static void SubmitBarrier(layer_data *dev_data, VkQueue queue) {
1125 auto gpu_state = GetGpuValidationState(dev_data);
1126 const auto *dispatch_table = GetDispatchTable(dev_data);
1127 uint32_t queue_family_index = 0;
1128
1129 auto it = dev_data->queueMap.find(queue);
1130 if (it != dev_data->queueMap.end()) {
1131 queue_family_index = it->second.queueFamilyIndex;
1132 }
1133
1134 // Pay attention only to queues that support graphics.
1135 // This ensures that the command buffer pool is created so that it can be used on a graphics queue.
1136 VkQueueFlags queue_flags = dev_data->phys_dev_properties.queue_family_properties[queue_family_index].queueFlags;
1137 if (!(queue_flags & VK_QUEUE_GRAPHICS_BIT)) {
1138 return;
1139 }
1140
1141 // Lazy-allocate and record the command buffer.
1142 if (gpu_state->barrier_command_buffer == VK_NULL_HANDLE) {
1143 VkResult result;
1144 VkCommandPoolCreateInfo pool_create_info = {};
1145 pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1146 pool_create_info.queueFamilyIndex = queue_family_index;
1147 result =
1148 dispatch_table->CreateCommandPool(GetDevice(dev_data), &pool_create_info, nullptr, &gpu_state->barrier_command_pool);
1149 if (result != VK_SUCCESS) {
1150 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
1151 "Unable to create command pool for barrier CB.");
1152 gpu_state->barrier_command_pool = VK_NULL_HANDLE;
1153 return;
1154 }
1155
1156 VkCommandBufferAllocateInfo command_buffer_alloc_info = {};
1157 command_buffer_alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1158 command_buffer_alloc_info.commandPool = gpu_state->barrier_command_pool;
1159 command_buffer_alloc_info.commandBufferCount = 1;
1160 command_buffer_alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1161 result = dispatch_table->AllocateCommandBuffers(GetDevice(dev_data), &command_buffer_alloc_info,
1162 &gpu_state->barrier_command_buffer);
1163 if (result != VK_SUCCESS) {
1164 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
1165 "Unable to create barrier command buffer.");
1166 dispatch_table->DestroyCommandPool(GetDevice(dev_data), gpu_state->barrier_command_pool, nullptr);
1167 gpu_state->barrier_command_pool = VK_NULL_HANDLE;
1168 gpu_state->barrier_command_buffer = VK_NULL_HANDLE;
1169 return;
1170 }
1171
1172 // Hook up command buffer dispatch
1173 *((const void **)gpu_state->barrier_command_buffer) = *(void **)(GetDevice(dev_data));
1174
1175 // Record a global memory barrier to force availability of device memory operations to the host domain.
1176 VkCommandBufferBeginInfo command_buffer_begin_info = {};
1177 command_buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1178 result = dispatch_table->BeginCommandBuffer(gpu_state->barrier_command_buffer, &command_buffer_begin_info);
1179
1180 if (result == VK_SUCCESS) {
1181 VkMemoryBarrier memory_barrier = {};
1182 memory_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
1183 memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
1184 memory_barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
1185
1186 dispatch_table->CmdPipelineBarrier(gpu_state->barrier_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
1187 VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &memory_barrier, 0, nullptr, 0, nullptr);
1188 dispatch_table->EndCommandBuffer(gpu_state->barrier_command_buffer);
1189 }
1190 }
1191
1192 if (gpu_state->barrier_command_buffer) {
1193 VkSubmitInfo submit_info = {};
1194 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1195 submit_info.commandBufferCount = 1;
1196 submit_info.pCommandBuffers = &gpu_state->barrier_command_buffer;
1197 dispatch_table->QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
1198 }
1199}
1200
1201// Issue a memory barrier to make GPU-written data available to host.
1202// Wait for the queue to complete execution.
1203// Check the debug buffers for all the command buffers that were submitted.
1204void GpuPostCallQueueSubmit(layer_data *dev_data, VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
Mark Lobodzinski42644592019-01-17 14:15:43 -07001205 VkFence fence) {
Karl Schultz7b024b42018-08-30 16:18:18 -06001206 auto gpu_state = GetGpuValidationState(dev_data);
1207 if (gpu_state->aborted) return;
Karl Schultz58674242019-01-22 15:35:02 -07001208
1209 SubmitBarrier(dev_data, queue);
1210
Mark Lobodzinski42644592019-01-17 14:15:43 -07001211 dev_data->dispatch_table.QueueWaitIdle(queue);
Karl Schultz58674242019-01-22 15:35:02 -07001212
Karl Schultz7b024b42018-08-30 16:18:18 -06001213 for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
1214 const VkSubmitInfo *submit = &pSubmits[submit_idx];
1215 for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
1216 auto cb_node = GetCBNode(dev_data, submit->pCommandBuffers[i]);
1217 ProcessInstrumentationBuffer(dev_data, queue, cb_node);
1218 for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
1219 ProcessInstrumentationBuffer(dev_data, queue, secondaryCmdBuffer);
1220 }
1221 }
1222 }
1223}