blob: a7065b2b981ad8f96722730b43a7234fc9c1bbb6 [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"
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070025#include "gpu_validation.h"
Karl Schultz7b024b42018-08-30 16:18:18 -060026#include "shader_validation.h"
Karl Schultz7b024b42018-08-30 16:18:18 -060027#include "spirv-tools/libspirv.h"
28#include "spirv-tools/optimizer.hpp"
29#include "spirv-tools/instrument.hpp"
30#include <SPIRV/spirv.hpp>
31#include <algorithm>
32#include <regex>
33
34// This is the number of bindings in the debug descriptor set.
35static const uint32_t kNumBindingsInSet = 1;
36
37// Implementation for Device Memory Manager class
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -070038GpuDeviceMemoryManager::GpuDeviceMemoryManager(layer_data *dev_data, uint32_t data_size) {
39 uint32_t align = static_cast<uint32_t>(dev_data->GetPDProperties(dev_data)->limits.minStorageBufferOffsetAlignment);
40 if (0 == align) {
41 align = 1;
42 }
43 record_size_ = data_size;
44 // Round the requested size up to the next multiple of the storage buffer offset alignment
45 // so that we can address each block in the storage buffer using the offset.
46 block_size_ = ((record_size_ + align - 1) / align) * align;
47 blocks_per_chunk_ = kItemsPerChunk;
48 chunk_size_ = blocks_per_chunk_ * block_size_;
49 dev_data_ = dev_data;
50}
51
52GpuDeviceMemoryManager::~GpuDeviceMemoryManager() {
53 for (auto &chunk : chunk_list_) {
54 FreeMemoryChunk(chunk);
55 }
56 chunk_list_.clear();
57}
58
Karl Schultz7b024b42018-08-30 16:18:18 -060059VkResult GpuDeviceMemoryManager::GetBlock(GpuDeviceMemoryBlock *block) {
60 assert(block->buffer == VK_NULL_HANDLE); // avoid possible overwrite/leak of an allocated block
61 VkResult result = VK_SUCCESS;
62 MemoryChunk *pChunk = nullptr;
63 // Look for a chunk with available offsets.
64 for (auto &chunk : chunk_list_) {
65 if (!chunk.available_offsets.empty()) {
66 pChunk = &chunk;
67 break;
68 }
69 }
70 // If no chunks with available offsets, allocate device memory and set up offsets.
71 if (pChunk == nullptr) {
72 MemoryChunk new_chunk;
73 result = AllocMemoryChunk(new_chunk);
74 if (result == VK_SUCCESS) {
75 new_chunk.available_offsets.resize(blocks_per_chunk_);
76 for (uint32_t offset = 0, i = 0; i < blocks_per_chunk_; offset += block_size_, ++i) {
77 new_chunk.available_offsets[i] = offset;
78 }
79 chunk_list_.push_front(std::move(new_chunk));
80 pChunk = &chunk_list_.front();
81 } else {
82 // Indicate failure
83 block->buffer = VK_NULL_HANDLE;
84 block->memory = VK_NULL_HANDLE;
85 return result;
86 }
87 }
88 // Give the requester an available offset
89 block->buffer = pChunk->buffer;
90 block->memory = pChunk->memory;
91 block->offset = pChunk->available_offsets.back();
92 pChunk->available_offsets.pop_back();
93 return result;
94}
95
96void GpuDeviceMemoryManager::PutBackBlock(VkBuffer buffer, VkDeviceMemory memory, uint32_t offset) {
97 GpuDeviceMemoryBlock block = {buffer, memory, offset};
98 PutBackBlock(block);
99}
100
101void GpuDeviceMemoryManager::PutBackBlock(GpuDeviceMemoryBlock &block) {
102 // Find the chunk belonging to the allocated offset and make the offset available again
103 auto chunk = std::find_if(std::begin(chunk_list_), std::end(chunk_list_),
104 [&block](const MemoryChunk &c) { return c.buffer == block.buffer; });
105 if (chunk_list_.end() == chunk) {
106 assert(false);
107 } else {
108 chunk->available_offsets.push_back(block.offset);
109 if (chunk->available_offsets.size() == blocks_per_chunk_) {
110 // All offsets have been returned
111 FreeMemoryChunk(*chunk);
112 chunk_list_.erase(chunk);
113 }
114 }
115}
116
117void ResetBlock(GpuDeviceMemoryBlock &block) {
118 block.buffer = VK_NULL_HANDLE;
119 block.memory = VK_NULL_HANDLE;
120 block.offset = 0;
121}
122
123bool BlockUsed(GpuDeviceMemoryBlock &block) { return (block.buffer != VK_NULL_HANDLE) && (block.memory != VK_NULL_HANDLE); }
124
125bool GpuDeviceMemoryManager::MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
126 // Search memtypes to find first index with those properties
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700127 const VkPhysicalDeviceMemoryProperties *props = dev_data_->GetPhysicalDeviceMemoryProperties(dev_data_);
Karl Schultz7b024b42018-08-30 16:18:18 -0600128 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
129 if ((typeBits & 1) == 1) {
130 // Type is available, does it match user properties?
131 if ((props->memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
132 *typeIndex = i;
133 return true;
134 }
135 }
136 typeBits >>= 1;
137 }
138 // No memory types matched, return failure
139 return false;
140}
141
142VkResult GpuDeviceMemoryManager::AllocMemoryChunk(MemoryChunk &chunk) {
143 VkBuffer buffer;
144 VkDeviceMemory memory;
145 VkBufferCreateInfo buffer_create_info = {};
146 VkMemoryRequirements mem_reqs = {};
147 VkMemoryAllocateInfo mem_alloc = {};
148 VkResult result = VK_SUCCESS;
149 bool pass;
150 void *pData;
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700151 const auto *dispatch_table = dev_data_->GetDispatchTable(dev_data_);
Karl Schultz7b024b42018-08-30 16:18:18 -0600152
153 buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
154 buffer_create_info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
155 buffer_create_info.size = chunk_size_;
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700156 result = dispatch_table->CreateBuffer(dev_data_->GetDevice(dev_data_), &buffer_create_info, NULL, &buffer);
Karl Schultz7b024b42018-08-30 16:18:18 -0600157 if (result != VK_SUCCESS) {
158 return result;
159 }
160
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700161 dispatch_table->GetBufferMemoryRequirements(dev_data_->GetDevice(dev_data_), buffer, &mem_reqs);
Karl Schultz7b024b42018-08-30 16:18:18 -0600162
163 mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
164 mem_alloc.pNext = NULL;
165 mem_alloc.allocationSize = mem_reqs.size;
166 pass = MemoryTypeFromProperties(mem_reqs.memoryTypeBits,
167 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
168 &mem_alloc.memoryTypeIndex);
169 if (!pass) {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700170 dispatch_table->DestroyBuffer(dev_data_->GetDevice(dev_data_), buffer, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600171 return result;
172 }
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700173 result = dispatch_table->AllocateMemory(dev_data_->GetDevice(dev_data_), &mem_alloc, NULL, &memory);
Karl Schultz7b024b42018-08-30 16:18:18 -0600174 if (result != VK_SUCCESS) {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700175 dispatch_table->DestroyBuffer(dev_data_->GetDevice(dev_data_), buffer, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600176 return result;
177 }
178
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700179 result = dispatch_table->BindBufferMemory(dev_data_->GetDevice(dev_data_), buffer, memory, 0);
Karl Schultz7b024b42018-08-30 16:18:18 -0600180 if (result != VK_SUCCESS) {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700181 dispatch_table->DestroyBuffer(dev_data_->GetDevice(dev_data_), buffer, NULL);
182 dispatch_table->FreeMemory(dev_data_->GetDevice(dev_data_), memory, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600183 return result;
184 }
185
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700186 result = dispatch_table->MapMemory(dev_data_->GetDevice(dev_data_), memory, 0, mem_alloc.allocationSize, 0, &pData);
Karl Schultz7b024b42018-08-30 16:18:18 -0600187 if (result == VK_SUCCESS) {
188 memset(pData, 0, chunk_size_);
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700189 dispatch_table->UnmapMemory(dev_data_->GetDevice(dev_data_), memory);
Karl Schultz7b024b42018-08-30 16:18:18 -0600190 } else {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700191 dispatch_table->DestroyBuffer(dev_data_->GetDevice(dev_data_), buffer, NULL);
192 dispatch_table->FreeMemory(dev_data_->GetDevice(dev_data_), memory, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600193 return result;
194 }
195 chunk.buffer = buffer;
196 chunk.memory = memory;
197 return result;
198}
199
200void GpuDeviceMemoryManager::FreeMemoryChunk(MemoryChunk &chunk) {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700201 dev_data_->GetDispatchTable(dev_data_)->DestroyBuffer(dev_data_->GetDevice(dev_data_), chunk.buffer, NULL);
202 dev_data_->GetDispatchTable(dev_data_)->FreeMemory(dev_data_->GetDevice(dev_data_), chunk.memory, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600203}
204
Tony-LunarGd85808d2019-02-27 16:12:02 -0700205void GpuDeviceMemoryManager::FreeAllBlocks() {
206 for (auto &chunk : chunk_list_) {
207 FreeMemoryChunk(chunk);
208 }
209 chunk_list_.clear();
210}
211
Karl Schultz7b024b42018-08-30 16:18:18 -0600212// Implementation for Descriptor Set Manager class
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700213GpuDescriptorSetManager::GpuDescriptorSetManager(layer_data *dev_data) { dev_data_ = dev_data; }
214
215GpuDescriptorSetManager::~GpuDescriptorSetManager() {
216 for (auto &pool : desc_pool_map_) {
217 dev_data_->GetDispatchTable(dev_data_)->DestroyDescriptorPool(dev_data_->GetDevice(dev_data_), pool.first, NULL);
218 }
219 desc_pool_map_.clear();
220}
221
Karl Schultz7b024b42018-08-30 16:18:18 -0600222VkResult GpuDescriptorSetManager::GetDescriptorSets(uint32_t count, VkDescriptorPool *pool,
223 std::vector<VkDescriptorSet> *desc_sets) {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700224 auto gpu_state = dev_data_->GetGpuValidationState(dev_data_);
Karl Schultz7b024b42018-08-30 16:18:18 -0600225 const uint32_t default_pool_size = kItemsPerChunk;
226 VkResult result = VK_SUCCESS;
227 VkDescriptorPool pool_to_use = VK_NULL_HANDLE;
228
229 if (0 == count) {
230 return result;
231 }
232 desc_sets->clear();
233 desc_sets->resize(count);
234
235 for (auto &pool : desc_pool_map_) {
236 if (pool.second.used + count < pool.second.size) {
237 pool_to_use = pool.first;
238 break;
239 }
240 }
241 if (VK_NULL_HANDLE == pool_to_use) {
242 uint32_t pool_count = default_pool_size;
243 if (count > default_pool_size) {
244 pool_count = count;
245 }
246 const VkDescriptorPoolSize size_counts = {
247 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
248 pool_count * kNumBindingsInSet,
249 };
250 VkDescriptorPoolCreateInfo desc_pool_info = {};
251 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
252 desc_pool_info.pNext = NULL;
253 desc_pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
254 desc_pool_info.maxSets = pool_count;
255 desc_pool_info.poolSizeCount = 1;
256 desc_pool_info.pPoolSizes = &size_counts;
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700257 result = dev_data_->GetDispatchTable(dev_data_)->CreateDescriptorPool(dev_data_->GetDevice(dev_data_), &desc_pool_info,
258 NULL, &pool_to_use);
Karl Schultz7b024b42018-08-30 16:18:18 -0600259 assert(result == VK_SUCCESS);
260 if (result != VK_SUCCESS) {
261 return result;
262 }
263 desc_pool_map_[pool_to_use].size = desc_pool_info.maxSets;
264 desc_pool_map_[pool_to_use].used = 0;
265 }
266 std::vector<VkDescriptorSetLayout> desc_layouts(count, gpu_state->debug_desc_layout);
267
268 VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool_to_use, count,
269 desc_layouts.data()};
270
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700271 result = dev_data_->GetDispatchTable(dev_data_)->AllocateDescriptorSets(dev_data_->GetDevice(dev_data_), &alloc_info,
272 desc_sets->data());
Karl Schultz7b024b42018-08-30 16:18:18 -0600273 assert(result == VK_SUCCESS);
274 if (result != VK_SUCCESS) {
275 return result;
276 }
277 *pool = pool_to_use;
278 desc_pool_map_[pool_to_use].used += count;
279 return result;
280}
281
282void GpuDescriptorSetManager::PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set) {
283 auto iter = desc_pool_map_.find(desc_pool);
284 if (iter != desc_pool_map_.end()) {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700285 VkResult result =
286 dev_data_->GetDispatchTable(dev_data_)->FreeDescriptorSets(dev_data_->GetDevice(dev_data_), desc_pool, 1, &desc_set);
Karl Schultz7b024b42018-08-30 16:18:18 -0600287 assert(result == VK_SUCCESS);
288 if (result != VK_SUCCESS) {
289 return;
290 }
291 desc_pool_map_[desc_pool].used--;
292 if (0 == desc_pool_map_[desc_pool].used) {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700293 dev_data_->GetDispatchTable(dev_data_)->DestroyDescriptorPool(dev_data_->GetDevice(dev_data_), desc_pool, NULL);
Karl Schultz7b024b42018-08-30 16:18:18 -0600294 desc_pool_map_.erase(desc_pool);
295 }
296 }
297 return;
298}
299
Tony-LunarGd85808d2019-02-27 16:12:02 -0700300void GpuDescriptorSetManager::DestroyDescriptorPools() {
301 for (auto &pool : desc_pool_map_) {
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700302 dev_data_->GetDispatchTable(dev_data_)->DestroyDescriptorPool(dev_data_->GetDevice(dev_data_), pool.first, NULL);
Tony-LunarGd85808d2019-02-27 16:12:02 -0700303 }
304 desc_pool_map_.clear();
305}
306
Karl Schultz7b024b42018-08-30 16:18:18 -0600307// Convenience function for reporting problems with setting up GPU Validation.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700308void CoreChecks::ReportSetupProblem(const layer_data *dev_data, VkDebugReportObjectTypeEXT object_type, uint64_t object_handle,
309 const char *const specific_message) {
310 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object_handle, "UNASSIGNED-GPU-Assisted Validation Error. ",
311 "Detail: (%s)", specific_message);
Karl Schultz7b024b42018-08-30 16:18:18 -0600312}
313
314// Turn on necessary device features.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700315void CoreChecks::GpuPreCallRecordCreateDevice(VkPhysicalDevice gpu, std::unique_ptr<safe_VkDeviceCreateInfo> &create_info,
316 VkPhysicalDeviceFeatures *supported_features) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600317 if (supported_features->fragmentStoresAndAtomics || supported_features->vertexPipelineStoresAndAtomics) {
Tony-LunarG48b478a2019-01-15 16:35:22 -0700318 VkPhysicalDeviceFeatures new_features = {};
Mark Lobodzinski5eb3c262019-03-01 16:08:30 -0700319 if (create_info->pEnabledFeatures) {
320 new_features = *create_info->pEnabledFeatures;
Tony-LunarG48b478a2019-01-15 16:35:22 -0700321 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600322 new_features.fragmentStoresAndAtomics = supported_features->fragmentStoresAndAtomics;
323 new_features.vertexPipelineStoresAndAtomics = supported_features->vertexPipelineStoresAndAtomics;
Mark Lobodzinski5eb3c262019-03-01 16:08:30 -0700324 delete create_info->pEnabledFeatures;
325 create_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
Karl Schultz7b024b42018-08-30 16:18:18 -0600326 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600327}
328
329// Perform initializations that can be done at Create Device time.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700330void CoreChecks::GpuPostCallRecordCreateDevice(layer_data *dev_data) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600331 auto gpu_state = GetGpuValidationState(dev_data);
332 const auto *dispatch_table = GetDispatchTable(dev_data);
333
Tony-LunarG65f9c492019-01-17 14:24:42 -0700334 gpu_state->aborted = false;
335 gpu_state->reserve_binding_slot = false;
Tony-LunarG03270752019-01-24 13:18:13 -0700336 gpu_state->barrier_command_pool = VK_NULL_HANDLE;
337 gpu_state->barrier_command_buffer = VK_NULL_HANDLE;
Tony-LunarG65f9c492019-01-17 14:24:42 -0700338
Mark Lobodzinski1cf55ac2019-01-14 14:33:43 -0700339 if (GetPDProperties(dev_data)->apiVersion < VK_API_VERSION_1_1) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600340 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
341 "GPU-Assisted validation requires Vulkan 1.1 or later. GPU-Assisted Validation disabled.");
342 gpu_state->aborted = true;
343 return;
344 }
345 // Some devices have extremely high limits here, so set a reasonable max because we have to pad
346 // the pipeline layout with dummy descriptor set layouts.
Mark Lobodzinski1cf55ac2019-01-14 14:33:43 -0700347 gpu_state->adjusted_max_desc_sets = GetPDProperties(dev_data)->limits.maxBoundDescriptorSets;
Karl Schultz7b024b42018-08-30 16:18:18 -0600348 gpu_state->adjusted_max_desc_sets = std::min(33U, gpu_state->adjusted_max_desc_sets);
349
350 // We can't do anything if there is only one.
351 // Device probably not a legit Vulkan device, since there should be at least 4. Protect ourselves.
352 if (gpu_state->adjusted_max_desc_sets == 1) {
353 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
354 "Device can bind only a single descriptor set. GPU-Assisted Validation disabled.");
355 gpu_state->aborted = true;
356 return;
357 }
358 gpu_state->desc_set_bind_index = gpu_state->adjusted_max_desc_sets - 1;
359 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
360 HandleToUint64(GetDevice(dev_data)), "UNASSIGNED-GPU-Assisted Validation. ",
361 "Shaders using descriptor set at index %d. ", gpu_state->desc_set_bind_index);
362
363 std::unique_ptr<GpuDeviceMemoryManager> memory_manager(
364 new GpuDeviceMemoryManager(dev_data, sizeof(uint32_t) * (spvtools::kInstMaxOutCnt + 1)));
365 std::unique_ptr<GpuDescriptorSetManager> desc_set_manager(new GpuDescriptorSetManager(dev_data));
366
367 // The descriptor indexing checks require only the first "output" binding.
368 const VkDescriptorSetLayoutBinding debug_desc_layout_bindings[kNumBindingsInSet] = {
369 {
370 0, // output
371 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
372 1,
373 VK_SHADER_STAGE_ALL_GRAPHICS,
374 NULL,
375 },
376 };
377
378 const VkDescriptorSetLayoutCreateInfo debug_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0,
379 kNumBindingsInSet, debug_desc_layout_bindings};
380
381 const VkDescriptorSetLayoutCreateInfo dummy_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 0,
382 NULL};
383
384 VkResult result = dispatch_table->CreateDescriptorSetLayout(GetDevice(dev_data), &debug_desc_layout_info, NULL,
385 &gpu_state->debug_desc_layout);
386
387 // This is a layout used to "pad" a pipeline layout to fill in any gaps to the selected bind index.
388 VkResult result2 = dispatch_table->CreateDescriptorSetLayout(GetDevice(dev_data), &dummy_desc_layout_info, NULL,
389 &gpu_state->dummy_desc_layout);
390 assert((result == VK_SUCCESS) && (result2 == VK_SUCCESS));
391 if ((result != VK_SUCCESS) || (result2 != VK_SUCCESS)) {
392 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
393 "Unable to create descriptor set layout. GPU-Assisted Validation disabled.");
394 if (result == VK_SUCCESS) {
395 dispatch_table->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->debug_desc_layout, NULL);
396 }
397 if (result2 == VK_SUCCESS) {
398 dispatch_table->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->dummy_desc_layout, NULL);
399 }
400 gpu_state->debug_desc_layout = VK_NULL_HANDLE;
401 gpu_state->dummy_desc_layout = VK_NULL_HANDLE;
402 gpu_state->aborted = true;
403 return;
404 }
405 gpu_state->memory_manager = std::move(memory_manager);
406 gpu_state->desc_set_manager = std::move(desc_set_manager);
407}
408
409// Clean up device-related resources
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700410void CoreChecks::GpuPreCallRecordDestroyDevice(layer_data *dev_data) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600411 auto gpu_state = GetGpuValidationState(dev_data);
412
Karl Schultz58674242019-01-22 15:35:02 -0700413 if (gpu_state->barrier_command_buffer) {
414 GetDispatchTable(dev_data)->FreeCommandBuffers(GetDevice(dev_data), gpu_state->barrier_command_pool, 1,
415 &gpu_state->barrier_command_buffer);
416 gpu_state->barrier_command_buffer = VK_NULL_HANDLE;
417 }
418 if (gpu_state->barrier_command_pool) {
419 GetDispatchTable(dev_data)->DestroyCommandPool(GetDevice(dev_data), gpu_state->barrier_command_pool, NULL);
420 gpu_state->barrier_command_pool = VK_NULL_HANDLE;
421 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600422 if (gpu_state->debug_desc_layout) {
423 GetDispatchTable(dev_data)->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->debug_desc_layout, NULL);
424 gpu_state->debug_desc_layout = VK_NULL_HANDLE;
425 }
426 if (gpu_state->dummy_desc_layout) {
427 GetDispatchTable(dev_data)->DestroyDescriptorSetLayout(GetDevice(dev_data), gpu_state->dummy_desc_layout, NULL);
428 gpu_state->dummy_desc_layout = VK_NULL_HANDLE;
429 }
Tony-LunarGd85808d2019-02-27 16:12:02 -0700430 gpu_state->memory_manager->FreeAllBlocks();
431 gpu_state->desc_set_manager->DestroyDescriptorPools();
Karl Schultz7b024b42018-08-30 16:18:18 -0600432}
433
Karl Schultz7b024b42018-08-30 16:18:18 -0600434// Modify the pipeline layout to include our debug descriptor set and any needed padding with the dummy descriptor set.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700435bool CoreChecks::GpuPreCallCreatePipelineLayout(layer_data *device_data, const VkPipelineLayoutCreateInfo *pCreateInfo,
436 const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout,
437 std::vector<VkDescriptorSetLayout> *new_layouts,
438 VkPipelineLayoutCreateInfo *modified_create_info) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700439 auto gpu_state = GetGpuValidationState(device_data);
Karl Schultz7b024b42018-08-30 16:18:18 -0600440 if (gpu_state->aborted) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700441 return false;
Karl Schultz7b024b42018-08-30 16:18:18 -0600442 }
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700443
444 if (modified_create_info->setLayoutCount >= gpu_state->adjusted_max_desc_sets) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600445 std::ostringstream strm;
446 strm << "Pipeline Layout conflict with validation's descriptor set at slot " << gpu_state->desc_set_bind_index << ". "
447 << "Application has too many descriptor sets in the pipeline layout to continue with gpu validation. "
448 << "Validation is not modifying the pipeline layout. "
449 << "Instrumented shaders are replaced with non-instrumented shaders.";
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700450 ReportSetupProblem(device_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(device_data)),
Karl Schultz7b024b42018-08-30 16:18:18 -0600451 strm.str().c_str());
452 } else {
453 // Modify the pipeline layout by:
454 // 1. Copying the caller's descriptor set desc_layouts
455 // 2. Fill in dummy descriptor layouts up to the max binding
456 // 3. Fill in with the debug descriptor layout at the max binding slot
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700457 new_layouts->reserve(gpu_state->adjusted_max_desc_sets);
458 new_layouts->insert(new_layouts->end(), &pCreateInfo->pSetLayouts[0],
459 &pCreateInfo->pSetLayouts[pCreateInfo->setLayoutCount]);
Karl Schultz7b024b42018-08-30 16:18:18 -0600460 for (uint32_t i = pCreateInfo->setLayoutCount; i < gpu_state->adjusted_max_desc_sets - 1; ++i) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700461 new_layouts->push_back(gpu_state->dummy_desc_layout);
Karl Schultz7b024b42018-08-30 16:18:18 -0600462 }
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700463 new_layouts->push_back(gpu_state->debug_desc_layout);
464 modified_create_info->pSetLayouts = new_layouts->data();
465 modified_create_info->setLayoutCount = gpu_state->adjusted_max_desc_sets;
Karl Schultz7b024b42018-08-30 16:18:18 -0600466 }
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700467 return true;
468}
469
470// Clean up GPU validation after the CreatePipelineLayout call is made
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700471void CoreChecks::GpuPostCallCreatePipelineLayout(layer_data *device_data, VkResult result) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700472 auto gpu_state = GetGpuValidationState(device_data);
473 // Clean up GPU validation
Karl Schultz7b024b42018-08-30 16:18:18 -0600474 if (result != VK_SUCCESS) {
Mark Lobodzinskiff7d8002019-02-13 13:01:26 -0700475 ReportSetupProblem(device_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(device_data)),
Karl Schultz7b024b42018-08-30 16:18:18 -0600476 "Unable to create pipeline layout. Device could become unstable.");
477 gpu_state->aborted = true;
478 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600479}
480
Karl Schultz7b024b42018-08-30 16:18:18 -0600481// Free the device memory and descriptor set associated with a command buffer.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700482void CoreChecks::GpuPreCallRecordFreeCommandBuffers(layer_data *dev_data, uint32_t commandBufferCount,
483 const VkCommandBuffer *pCommandBuffers) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600484 auto gpu_state = GetGpuValidationState(dev_data);
485 if (gpu_state->aborted) {
486 return;
487 }
488 for (uint32_t i = 0; i < commandBufferCount; ++i) {
489 auto cb_node = GetCBNode(dev_data, pCommandBuffers[i]);
Tony-LunarGb2501d22019-01-28 09:59:13 -0700490 if (cb_node) {
491 for (auto &buffer_info : cb_node->gpu_buffer_list) {
492 if (BlockUsed(buffer_info.mem_block)) {
493 gpu_state->memory_manager->PutBackBlock(buffer_info.mem_block);
494 ResetBlock(buffer_info.mem_block);
495 }
496 if (buffer_info.desc_set != VK_NULL_HANDLE) {
497 gpu_state->desc_set_manager->PutBackDescriptorSet(buffer_info.desc_pool, buffer_info.desc_set);
498 }
499 }
500 cb_node->gpu_buffer_list.clear();
Karl Schultz7b024b42018-08-30 16:18:18 -0600501 }
502 }
503}
504
505// Just gives a warning about a possible deadlock.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700506void CoreChecks::GpuPreCallValidateCmdWaitEvents(layer_data *dev_data, VkPipelineStageFlags sourceStageMask) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600507 if (sourceStageMask & VK_PIPELINE_STAGE_HOST_BIT) {
508 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
509 "CmdWaitEvents recorded with VK_PIPELINE_STAGE_HOST_BIT set. "
510 "GPU_Assisted validation waits on queue completion. "
511 "This wait could block the host's signaling of this event, resulting in deadlock.");
512 }
513}
514
515// Examine the pipelines to see if they use the debug descriptor set binding index.
516// If any do, create new non-instrumented shader modules and use them to replace the instrumented
517// shaders in the pipeline. Return the (possibly) modified create infos to the caller.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700518std::vector<safe_VkGraphicsPipelineCreateInfo> CoreChecks::GpuPreCallRecordCreateGraphicsPipelines(
Karl Schultz7b024b42018-08-30 16:18:18 -0600519 layer_data *dev_data, VkPipelineCache pipelineCache, uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
520 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) {
521 auto gpu_state = GetGpuValidationState(dev_data);
522
523 std::vector<safe_VkGraphicsPipelineCreateInfo> new_pipeline_create_infos;
524 std::vector<unsigned int> pipeline_uses_debug_index(count);
525
526 // Walk through all the pipelines, make a copy of each and flag each pipeline that contains a shader that uses the debug
527 // descriptor set index.
528 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
529 new_pipeline_create_infos.push_back(pipe_state[pipeline]->graphicsPipelineCI);
530 if (pipe_state[pipeline]->active_slots.find(gpu_state->desc_set_bind_index) != pipe_state[pipeline]->active_slots.end()) {
531 pipeline_uses_debug_index[pipeline] = 1;
532 }
533 }
534
535 // See if any pipeline has shaders using the debug descriptor set index
536 if (std::all_of(pipeline_uses_debug_index.begin(), pipeline_uses_debug_index.end(), [](unsigned int i) { return i == 0; })) {
537 // None of the shaders in all the pipelines use the debug descriptor set index, so use the pipelines
538 // as they stand with the instrumented shaders.
539 return new_pipeline_create_infos;
540 }
541
542 // At least one pipeline has a shader that uses the debug descriptor set index.
543 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
544 if (pipeline_uses_debug_index[pipeline]) {
545 for (uint32_t stage = 0; stage < pCreateInfos[pipeline].stageCount; ++stage) {
546 const shader_module *shader = GetShaderModuleState(dev_data, pCreateInfos[pipeline].pStages[stage].module);
547 VkShaderModuleCreateInfo create_info = {};
548 VkShaderModule shader_module;
549 create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
550 create_info.pCode = shader->words.data();
551 create_info.codeSize = shader->words.size() * sizeof(uint32_t);
552 VkResult result =
553 GetDispatchTable(dev_data)->CreateShaderModule(GetDevice(dev_data), &create_info, pAllocator, &shader_module);
554 if (result == VK_SUCCESS) {
555 new_pipeline_create_infos[pipeline].pStages[stage].module = shader_module;
556 } else {
557 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
558 HandleToUint64(pCreateInfos[pipeline].pStages[stage].module),
559 "Unable to replace instrumented shader with non-instrumented one. "
560 "Device could become unstable.");
561 }
562 }
563 }
564 }
565 return new_pipeline_create_infos;
566}
567
568// For every pipeline:
569// - For every shader in a pipeline:
570// - If the shader had to be replaced in PreCallRecord (because the pipeline is using the debug desc set index):
571// - Destroy it since it has been bound into the pipeline by now. This is our only chance to delete it.
572// - Track the shader in the shader_map
573// - Save the shader binary if it contains debug code
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700574void CoreChecks::GpuPostCallRecordCreateGraphicsPipelines(layer_data *dev_data, const uint32_t count,
575 const VkGraphicsPipelineCreateInfo *pCreateInfos,
576 const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600577 auto gpu_state = GetGpuValidationState(dev_data);
578 for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
579 auto pipeline_state = GetPipelineState(dev_data, pPipelines[pipeline]);
580 if (nullptr == pipeline_state) continue;
581 for (uint32_t stage = 0; stage < pipeline_state->graphicsPipelineCI.stageCount; ++stage) {
582 if (pipeline_state->active_slots.find(gpu_state->desc_set_bind_index) != pipeline_state->active_slots.end()) {
583 GetDispatchTable(dev_data)->DestroyShaderModule(GetDevice(dev_data), pCreateInfos->pStages[stage].module,
584 pAllocator);
585 }
586 auto shader_state = GetShaderModuleState(dev_data, pipeline_state->graphicsPipelineCI.pStages[stage].module);
587 std::vector<unsigned int> code;
588 // Save the shader binary if debug info is present.
589 // The core_validation ShaderModule tracker saves the binary too, but discards it when the ShaderModule
590 // is destroyed. Applications may destroy ShaderModules after they are placed in a pipeline and before
591 // the pipeline is used, so we have to keep another copy.
592 if (shader_state && shader_state->has_valid_spirv) { // really checking for presense of SPIR-V code.
593 for (auto insn : *shader_state) {
594 if (insn.opcode() == spv::OpLine) {
595 code = shader_state->words;
596 break;
597 }
598 }
599 }
600 gpu_state->shader_map[shader_state->gpu_validation_shader_id].pipeline = pipeline_state->pipeline;
601 // Be careful to use the originally bound (instrumented) shader here, even if PreCallRecord had to back it
602 // out with a non-instrumented shader. The non-instrumented shader (found in pCreateInfo) was destroyed above.
603 gpu_state->shader_map[shader_state->gpu_validation_shader_id].shader_module =
604 pipeline_state->graphicsPipelineCI.pStages[stage].module;
605 gpu_state->shader_map[shader_state->gpu_validation_shader_id].pgm = std::move(code);
606 }
607 }
608}
609
610// Remove all the shader trackers associated with this destroyed pipeline.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700611void CoreChecks::GpuPreCallRecordDestroyPipeline(layer_data *dev_data, const VkPipeline pipeline) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600612 auto gpu_state = GetGpuValidationState(dev_data);
613 for (auto it = gpu_state->shader_map.begin(); it != gpu_state->shader_map.end();) {
614 if (it->second.pipeline == pipeline) {
615 it = gpu_state->shader_map.erase(it);
616 } else {
617 ++it;
618 }
619 }
620}
621
622// Call the SPIR-V Optimizer to run the instrumentation pass on the shader.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700623bool CoreChecks::GpuInstrumentShader(layer_data *dev_data, const VkShaderModuleCreateInfo *pCreateInfo,
624 std::vector<unsigned int> &new_pgm, uint32_t *unique_shader_id) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600625 auto gpu_state = GetGpuValidationState(dev_data);
626 if (gpu_state->aborted) return false;
627 if (pCreateInfo->pCode[0] != spv::MagicNumber) return false;
628
629 // Load original shader SPIR-V
630 uint32_t num_words = static_cast<uint32_t>(pCreateInfo->codeSize / 4);
631 new_pgm.clear();
632 new_pgm.reserve(num_words);
633 new_pgm.insert(new_pgm.end(), &pCreateInfo->pCode[0], &pCreateInfo->pCode[num_words]);
634
635 // Call the optimizer to instrument the shader.
636 // Use the unique_shader_module_id as a shader ID so we can look up its handle later in the shader_map.
637 using namespace spvtools;
638 spv_target_env target_env = SPV_ENV_VULKAN_1_1;
639 Optimizer optimizer(target_env);
640 optimizer.RegisterPass(CreateInstBindlessCheckPass(gpu_state->desc_set_bind_index, gpu_state->unique_shader_module_id));
641 optimizer.RegisterPass(CreateAggressiveDCEPass());
642 bool pass = optimizer.Run(new_pgm.data(), new_pgm.size(), &new_pgm);
643 if (!pass) {
644 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, VK_NULL_HANDLE,
645 "Failure to instrument shader. Proceeding with non-instrumented shader.");
646 }
Karl Schultz7b024b42018-08-30 16:18:18 -0600647 *unique_shader_id = gpu_state->unique_shader_module_id++;
648 return pass;
649}
650
Mark Lobodzinski01734072019-02-13 17:39:15 -0700651// Create the instrumented shader data to provide to the driver.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700652bool CoreChecks::GpuPreCallCreateShaderModule(layer_data *dev_data, const VkShaderModuleCreateInfo *pCreateInfo,
653 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
654 uint32_t *unique_shader_id, VkShaderModuleCreateInfo *instrumented_create_info,
655 std::vector<unsigned int> *instrumented_pgm) {
Mark Lobodzinski01734072019-02-13 17:39:15 -0700656 bool pass = GpuInstrumentShader(dev_data, pCreateInfo, *instrumented_pgm, unique_shader_id);
Karl Schultz7b024b42018-08-30 16:18:18 -0600657 if (pass) {
Mark Lobodzinski01734072019-02-13 17:39:15 -0700658 instrumented_create_info->pCode = instrumented_pgm->data();
659 instrumented_create_info->codeSize = instrumented_pgm->size() * sizeof(unsigned int);
Karl Schultz7b024b42018-08-30 16:18:18 -0600660 }
Mark Lobodzinski01734072019-02-13 17:39:15 -0700661 return pass;
Karl Schultz7b024b42018-08-30 16:18:18 -0600662}
663
664// Generate the stage-specific part of the message.
665static void GenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
666 using namespace spvtools;
667 std::ostringstream strm;
668 switch (debug_record[kInstCommonOutStageIdx]) {
669 case 0: {
Tony-LunarG6ff87582019-02-08 10:29:07 -0700670 strm << "Stage = Vertex. Vertex Index = " << debug_record[kInstVertOutVertexIndex]
671 << " Instance Index = " << debug_record[kInstVertOutInstanceIndex] << ". ";
Karl Schultz7b024b42018-08-30 16:18:18 -0600672 } break;
673 case 1: {
674 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
675 } break;
676 case 2: {
677 strm << "Stage = Tessellation Eval. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
678 } break;
679 case 3: {
680 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
681 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
682 } break;
683 case 4: {
684 strm << "Stage = Fragment. Fragment coord (x,y) = ("
685 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
686 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
687 } break;
688 case 5: {
689 strm << "Stage = Compute. Global invocation ID = " << debug_record[kInstCompOutGlobalInvocationId] << ". ";
690 } break;
691 default: {
692 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
693 assert(false);
694 } break;
695 }
696 msg = strm.str();
697}
698
699// Generate the part of the message describing the violation.
700static void GenerateValidationMessage(const uint32_t *debug_record, std::string &msg, std::string &vuid_msg) {
701 using namespace spvtools;
702 std::ostringstream strm;
703 switch (debug_record[kInstValidationOutError]) {
704 case 0: {
705 strm << "Index of " << debug_record[kInstBindlessOutDescIndex] << " used to index descriptor array of length "
706 << debug_record[kInstBindlessOutDescBound] << ". ";
Tony-LunarGc1d657d2019-02-22 14:55:19 -0700707 vuid_msg = "UNASSIGNED-Descriptor index out of bounds";
Karl Schultz7b024b42018-08-30 16:18:18 -0600708 } break;
709 case 1: {
Karl Schultz7b024b42018-08-30 16:18:18 -0600710 strm << "Descriptor index " << debug_record[kInstBindlessOutDescIndex] << " is uninitialized. ";
Tony-LunarGc1d657d2019-02-22 14:55:19 -0700711 vuid_msg = "UNASSIGNED-Descriptor uninitialized";
Karl Schultz7b024b42018-08-30 16:18:18 -0600712 } break;
713 default: {
714 strm << "Internal Error (unexpected error type = " << debug_record[kInstValidationOutError] << "). ";
715 vuid_msg = "UNASSIGNED-Internal Error";
716 assert(false);
717 } break;
718 }
719 msg = strm.str();
720}
721
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700722static std::string LookupDebugUtilsName(const debug_report_data *report_data, const uint64_t object) {
Mark Lobodzinski1d7313a2019-02-07 11:04:42 -0700723 auto object_label = report_data->DebugReportGetUtilsObjectName(object);
724 if (object_label != "") {
725 object_label = "(" + object_label + ")";
Karl Schultz7b024b42018-08-30 16:18:18 -0600726 }
Mark Lobodzinski1d7313a2019-02-07 11:04:42 -0700727 return object_label;
Karl Schultz7b024b42018-08-30 16:18:18 -0600728}
729
730// Generate message from the common portion of the debug report record.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700731static 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 -0700732 const VkShaderModule shader_module_handle, const VkPipeline pipeline_handle,
733 const uint32_t draw_index, std::string &msg) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600734 using namespace spvtools;
735 std::ostringstream strm;
736 if (shader_module_handle == VK_NULL_HANDLE) {
737 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700738 << LookupDebugUtilsName(report_data, HandleToUint64(cb_node->commandBuffer)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600739 << HandleToUint64(cb_node->commandBuffer) << "). ";
740 assert(true);
741 } else {
742 strm << std::hex << std::showbase << "Command buffer "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700743 << LookupDebugUtilsName(report_data, HandleToUint64(cb_node->commandBuffer)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600744 << HandleToUint64(cb_node->commandBuffer) << "). "
Tony-LunarGd589c7c2019-01-31 11:23:44 -0700745 << "Draw Index " << draw_index << ". "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700746 << "Pipeline " << LookupDebugUtilsName(report_data, HandleToUint64(pipeline_handle)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600747 << HandleToUint64(pipeline_handle) << "). "
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700748 << "Shader Module " << LookupDebugUtilsName(report_data, HandleToUint64(shader_module_handle)) << "("
Karl Schultz7b024b42018-08-30 16:18:18 -0600749 << HandleToUint64(shader_module_handle) << "). ";
750 }
751 strm << std::dec << std::noshowbase;
752 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
753 msg = strm.str();
754}
755
756// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
757// Split the single string into a vector of strings, one for each line, for easier processing.
758static void ReadOpSource(const shader_module &shader, const uint32_t reported_file_id, std::vector<std::string> &opsource_lines) {
759 for (auto insn : shader) {
760 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
761 std::istringstream in_stream;
762 std::string cur_line;
763 in_stream.str((char *)&insn.word(4));
764 while (std::getline(in_stream, cur_line)) {
765 opsource_lines.push_back(cur_line);
766 }
767 while ((++insn).opcode() == spv::OpSourceContinued) {
768 in_stream.str((char *)&insn.word(1));
769 while (std::getline(in_stream, cur_line)) {
770 opsource_lines.push_back(cur_line);
771 }
772 }
773 break;
774 }
775 }
776}
Tony-LunarG03059b72019-02-19 13:57:41 -0700777
778// The task here is to search the OpSource content to find the #line directive with the
779// line number that is closest to, but still prior to the reported error line number and
780// still within the reported filename.
781// From this known position in the OpSource content we can add the difference between
782// the #line line number and the reported error line number to determine the location
783// in the OpSource content of the reported error line.
784//
785// Considerations:
786// - Look only at #line directives that specify the reported_filename since
787// the reported error line number refers to its location in the reported filename.
788// - If a #line directive does not have a filename, the file is the reported filename, or
789// the filename found in a prior #line directive. (This is C-preprocessor behavior)
790// - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
791// original order and the #line directives are used to keep the numbering correct. This
792// is why we need to examine the entire contents of the source, instead of leaving early
793// when finding a #line line number larger than the reported error line number.
794//
795
796// GCC 4.8 has a problem with std::regex that is fixed in GCC 4.9. Provide fallback code for 4.8
797#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
798
799#if defined(__GNUC__) && GCC_VERSION < 40900
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700800static bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
Tony-LunarG03059b72019-02-19 13:57:41 -0700801 // # line <linenumber> "<filename>" or
802 // #line <linenumber> "<filename>"
803 std::vector<std::string> tokens;
804 std::stringstream stream(string);
805 std::string temp;
806 uint32_t line_index = 0;
807
808 while (stream >> temp) tokens.push_back(temp);
809 auto size = tokens.size();
810 if (size > 1) {
811 if (tokens[0] == "#" && tokens[1] == "line") {
812 line_index = 2;
813 } else if (tokens[0] == "#line") {
814 line_index = 1;
815 }
816 }
817 if (0 == line_index) return false;
818 *linenumber = std::stoul(tokens[line_index]);
819 uint32_t filename_index = line_index + 1;
820 // Remove enclosing double quotes around filename
821 if (size > filename_index) filename = tokens[filename_index].substr(1, tokens[filename_index].size() - 2);
822 return true;
823}
824#else
825static bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700826 static const std::regex line_regex( // matches #line directives
827 "^" // beginning of line
828 "\\s*" // optional whitespace
829 "#" // required text
830 "\\s*" // optional whitespace
831 "line" // required text
832 "\\s+" // required whitespace
833 "([0-9]+)" // required first capture - line number
834 "(\\s+)?" // optional second capture - whitespace
835 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
836 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
Karl Schultz7b024b42018-08-30 16:18:18 -0600837
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700838 std::smatch captures;
839
840 bool found_line = std::regex_match(string, captures, line_regex);
841 if (!found_line) return false;
842
843 // filename is optional and considered found only if the whitespace and the filename are captured
844 if (captures[2].matched && captures[3].matched) {
845 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
846 filename = captures[3].str().substr(1, captures[3].str().size() - 2);
847 }
848 *linenumber = std::stoul(captures[1]);
849 return true;
850}
Tony-LunarG03059b72019-02-19 13:57:41 -0700851#endif // GCC_VERSION
852
Karl Schultz7b024b42018-08-30 16:18:18 -0600853// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
854// Scan the source (from OpSource) to find the line of source at the reported line number and place it in another message string.
855static void GenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, std::string &filename_msg,
856 std::string &source_msg) {
857 using namespace spvtools;
858 std::ostringstream filename_stream;
859 std::ostringstream source_stream;
860 shader_module shader;
861 shader.words = pgm;
862 // Find the OpLine just before the failing instruction indicated by the debug info.
863 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
864 uint32_t instruction_index = 0;
865 uint32_t reported_file_id = 0;
866 uint32_t reported_line_number = 0;
867 uint32_t reported_column_number = 0;
868 if (shader.words.size() > 0) {
869 for (auto insn : shader) {
870 if (insn.opcode() == spv::OpLine) {
871 reported_file_id = insn.word(1);
872 reported_line_number = insn.word(2);
873 reported_column_number = insn.word(3);
874 }
875 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
876 break;
877 }
878 instruction_index++;
879 }
880 }
881 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
882 std::string reported_filename;
883 if (reported_file_id == 0) {
884 filename_stream
885 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
886 } else {
887 bool found_opstring = false;
888 for (auto insn : shader) {
889 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
890 found_opstring = true;
891 reported_filename = (char *)&insn.word(2);
892 if (reported_filename.empty()) {
893 filename_stream << "Shader validation error occurred at line " << reported_line_number;
894 } else {
895 filename_stream << "Shader validation error occurred in file: " << reported_filename << " at line "
896 << reported_line_number;
897 }
898 if (reported_column_number > 0) {
899 filename_stream << ", column " << reported_column_number;
900 }
901 filename_stream << ".";
902 break;
903 }
904 }
905 if (!found_opstring) {
906 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction.";
907 }
908 }
909 filename_msg = filename_stream.str();
910
911 // Create message to display source code line containing error.
912 if ((reported_file_id != 0)) {
913 // Read the source code and split it up into separate lines.
914 std::vector<std::string> opsource_lines;
915 ReadOpSource(shader, reported_file_id, opsource_lines);
916 // Find the line in the OpSource content that corresponds to the reported error file and line.
917 if (!opsource_lines.empty()) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600918 uint32_t saved_line_number = 0;
919 std::string current_filename = reported_filename; // current "preprocessor" filename state.
920 std::vector<std::string>::size_type saved_opsource_offset = 0;
921 bool found_best_line = false;
922 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700923 uint32_t parsed_line_number;
924 std::string parsed_filename;
925 bool found_line = GetLineAndFilename(*it, &parsed_line_number, parsed_filename);
Karl Schultz7b024b42018-08-30 16:18:18 -0600926 if (!found_line) continue;
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700927
928 bool found_filename = parsed_filename.size() > 0;
Karl Schultz7b024b42018-08-30 16:18:18 -0600929 if (found_filename) {
Tony-LunarG16f9b7e2019-02-19 13:02:03 -0700930 current_filename = parsed_filename;
Karl Schultz7b024b42018-08-30 16:18:18 -0600931 }
932 if ((!found_filename) || (current_filename == reported_filename)) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600933 // Update the candidate best line directive, if the current one is prior and closer to the reported line
934 if (reported_line_number >= parsed_line_number) {
935 if (!found_best_line ||
936 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
937 saved_line_number = parsed_line_number;
938 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
939 found_best_line = true;
940 }
941 }
942 }
943 }
944 if (found_best_line) {
945 assert(reported_line_number >= saved_line_number);
946 std::vector<std::string>::size_type opsource_index =
947 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
948 if (opsource_index < opsource_lines.size()) {
949 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
950 } else {
951 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
952 << opsource_lines.size() << " lines.";
953 }
954 } else {
955 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
956 }
957 } else {
958 source_stream << "Unable to find SPIR-V OpSource.";
959 }
960 }
961 source_msg = source_stream.str();
962}
963
964// Pull together all the information from the debug record to build the error message strings,
965// and then assemble them into a single message string.
966// Retrieve the shader program referenced by the unique shader ID provided in the debug record.
967// We had to keep a copy of the shader program with the same lifecycle as the pipeline to make
968// sure it is available when the pipeline is submitted. (The ShaderModule tracking object also
969// keeps a copy, but it can be destroyed after the pipeline is created and before it is submitted.)
970//
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -0700971void CoreChecks::AnalyzeAndReportError(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node, VkQueue queue, uint32_t draw_index,
972 uint32_t *const debug_output_buffer) {
Karl Schultz7b024b42018-08-30 16:18:18 -0600973 using namespace spvtools;
974 const uint32_t total_words = debug_output_buffer[0];
975 // A zero here means that the shader instrumentation didn't write anything.
976 // If you have nothing to say, don't say it here.
977 if (0 == total_words) {
978 return;
979 }
980 // The first word in the debug output buffer is the number of words that would have
981 // been written by the shader instrumentation, if there was enough room in the buffer we provided.
982 // The number of words actually written by the shaders is determined by the size of the buffer
983 // we provide via the descriptor. So, we process only the number of words that can fit in the
984 // buffer.
985 // Each "report" written by the shader instrumentation is considered a "record". This function
986 // is hard-coded to process only one record because it expects the buffer to be large enough to
987 // hold only one record. If there is a desire to process more than one record, this function needs
988 // to be modified to loop over records and the buffer size increased.
989 auto gpu_state = GetGpuValidationState(dev_data);
990 std::string validation_message;
991 std::string stage_message;
992 std::string common_message;
993 std::string filename_message;
994 std::string source_message;
995 std::string vuid_msg;
996 VkShaderModule shader_module_handle = VK_NULL_HANDLE;
997 VkPipeline pipeline_handle = VK_NULL_HANDLE;
998 std::vector<unsigned int> pgm;
999 // The first record starts at this offset after the total_words.
1000 const uint32_t *debug_record = &debug_output_buffer[kDebugOutputDataOffset];
1001 // Lookup the VkShaderModule handle and SPIR-V code used to create the shader, using the unique shader ID value returned
1002 // by the instrumented shader.
1003 auto it = gpu_state->shader_map.find(debug_record[kInstCommonOutShaderId]);
1004 if (it != gpu_state->shader_map.end()) {
1005 shader_module_handle = it->second.shader_module;
1006 pipeline_handle = it->second.pipeline;
1007 pgm = it->second.pgm;
1008 }
1009 GenerateValidationMessage(debug_record, validation_message, vuid_msg);
1010 GenerateStageMessage(debug_record, stage_message);
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07001011 GenerateCommonMessage(report_data, cb_node, debug_record, shader_module_handle, pipeline_handle, draw_index, common_message);
Karl Schultz7b024b42018-08-30 16:18:18 -06001012 GenerateSourceMessages(pgm, debug_record, filename_message, source_message);
1013 log_msg(GetReportData(dev_data), VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, HandleToUint64(queue),
1014 vuid_msg.c_str(), "%s %s %s %s%s", validation_message.c_str(), common_message.c_str(), stage_message.c_str(),
1015 filename_message.c_str(), source_message.c_str());
1016 // The debug record at word kInstCommonOutSize is the number of words in the record
1017 // written by the shader. Clear the entire record plus the total_words word at the start.
1018 const uint32_t words_to_clear = 1 + std::min(debug_record[kInstCommonOutSize], (uint32_t)kInstMaxOutCnt);
1019 memset(debug_output_buffer, 0, sizeof(uint32_t) * words_to_clear);
1020}
1021
Tony-LunarG5ad17272019-03-05 12:48:24 -07001022// For the given command buffer, map its debug data buffers and read their contents for analysis.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07001023void CoreChecks::ProcessInstrumentationBuffer(const layer_data *dev_data, VkQueue queue, GLOBAL_CB_NODE *cb_node) {
Karl Schultz7b024b42018-08-30 16:18:18 -06001024 auto gpu_state = GetGpuValidationState(dev_data);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001025 if (cb_node && cb_node->hasDrawCmd && cb_node->gpu_buffer_list.size() > 0) {
Karl Schultz7b024b42018-08-30 16:18:18 -06001026 VkResult result;
1027 char *pData;
Tony-LunarG5ad17272019-03-05 12:48:24 -07001028 uint32_t draw_index = 0;
Tony-LunarGb2501d22019-01-28 09:59:13 -07001029 for (auto &buffer_info : cb_node->gpu_buffer_list) {
1030 uint32_t block_offset = buffer_info.mem_block.offset;
1031 uint32_t block_size = gpu_state->memory_manager->GetBlockSize();
1032 uint32_t offset_to_data = 0;
1033 const uint32_t map_align = std::max(1U, static_cast<uint32_t>(GetPDProperties(dev_data)->limits.minMemoryMapAlignment));
Karl Schultz7b024b42018-08-30 16:18:18 -06001034
Tony-LunarGb2501d22019-01-28 09:59:13 -07001035 // Adjust the offset to the alignment required for mapping.
1036 block_offset = (block_offset / map_align) * map_align;
1037 offset_to_data = buffer_info.mem_block.offset - block_offset;
1038 block_size += offset_to_data;
1039 result = GetDispatchTable(dev_data)->MapMemory(cb_node->device, buffer_info.mem_block.memory, block_offset, block_size,
1040 0, (void **)&pData);
1041 // Analyze debug output buffer
1042 if (result == VK_SUCCESS) {
Tony-LunarGd589c7c2019-01-31 11:23:44 -07001043 AnalyzeAndReportError(dev_data, cb_node, queue, draw_index, (uint32_t *)(pData + offset_to_data));
Tony-LunarGb2501d22019-01-28 09:59:13 -07001044 GetDispatchTable(dev_data)->UnmapMemory(cb_node->device, buffer_info.mem_block.memory);
1045 }
Tony-LunarGd589c7c2019-01-31 11:23:44 -07001046 draw_index++;
Karl Schultz7b024b42018-08-30 16:18:18 -06001047 }
1048 }
1049}
1050
Karl Schultz58674242019-01-22 15:35:02 -07001051// Submit a memory barrier on graphics queues.
1052// Lazy-create and record the needed command buffer.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07001053void CoreChecks::SubmitBarrier(layer_data *dev_data, VkQueue queue) {
Karl Schultz58674242019-01-22 15:35:02 -07001054 auto gpu_state = GetGpuValidationState(dev_data);
1055 const auto *dispatch_table = GetDispatchTable(dev_data);
1056 uint32_t queue_family_index = 0;
1057
1058 auto it = dev_data->queueMap.find(queue);
1059 if (it != dev_data->queueMap.end()) {
1060 queue_family_index = it->second.queueFamilyIndex;
1061 }
1062
1063 // Pay attention only to queues that support graphics.
1064 // 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 -07001065 VkQueueFlags queue_flags = GetPhysicalDeviceState()->queue_family_properties[queue_family_index].queueFlags;
Karl Schultz58674242019-01-22 15:35:02 -07001066 if (!(queue_flags & VK_QUEUE_GRAPHICS_BIT)) {
1067 return;
1068 }
1069
1070 // Lazy-allocate and record the command buffer.
1071 if (gpu_state->barrier_command_buffer == VK_NULL_HANDLE) {
1072 VkResult result;
1073 VkCommandPoolCreateInfo pool_create_info = {};
1074 pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1075 pool_create_info.queueFamilyIndex = queue_family_index;
1076 result =
1077 dispatch_table->CreateCommandPool(GetDevice(dev_data), &pool_create_info, nullptr, &gpu_state->barrier_command_pool);
1078 if (result != VK_SUCCESS) {
1079 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
1080 "Unable to create command pool for barrier CB.");
1081 gpu_state->barrier_command_pool = VK_NULL_HANDLE;
1082 return;
1083 }
1084
1085 VkCommandBufferAllocateInfo command_buffer_alloc_info = {};
1086 command_buffer_alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1087 command_buffer_alloc_info.commandPool = gpu_state->barrier_command_pool;
1088 command_buffer_alloc_info.commandBufferCount = 1;
1089 command_buffer_alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1090 result = dispatch_table->AllocateCommandBuffers(GetDevice(dev_data), &command_buffer_alloc_info,
1091 &gpu_state->barrier_command_buffer);
1092 if (result != VK_SUCCESS) {
1093 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
1094 "Unable to create barrier command buffer.");
1095 dispatch_table->DestroyCommandPool(GetDevice(dev_data), gpu_state->barrier_command_pool, nullptr);
1096 gpu_state->barrier_command_pool = VK_NULL_HANDLE;
1097 gpu_state->barrier_command_buffer = VK_NULL_HANDLE;
1098 return;
1099 }
1100
1101 // Hook up command buffer dispatch
1102 *((const void **)gpu_state->barrier_command_buffer) = *(void **)(GetDevice(dev_data));
1103
1104 // Record a global memory barrier to force availability of device memory operations to the host domain.
1105 VkCommandBufferBeginInfo command_buffer_begin_info = {};
1106 command_buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1107 result = dispatch_table->BeginCommandBuffer(gpu_state->barrier_command_buffer, &command_buffer_begin_info);
1108
1109 if (result == VK_SUCCESS) {
1110 VkMemoryBarrier memory_barrier = {};
1111 memory_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
1112 memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
1113 memory_barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
1114
1115 dispatch_table->CmdPipelineBarrier(gpu_state->barrier_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
1116 VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &memory_barrier, 0, nullptr, 0, nullptr);
1117 dispatch_table->EndCommandBuffer(gpu_state->barrier_command_buffer);
1118 }
1119 }
1120
1121 if (gpu_state->barrier_command_buffer) {
1122 VkSubmitInfo submit_info = {};
1123 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1124 submit_info.commandBufferCount = 1;
1125 submit_info.pCommandBuffers = &gpu_state->barrier_command_buffer;
1126 dispatch_table->QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
1127 }
1128}
1129
1130// Issue a memory barrier to make GPU-written data available to host.
1131// Wait for the queue to complete execution.
1132// Check the debug buffers for all the command buffers that were submitted.
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07001133void CoreChecks::GpuPostCallQueueSubmit(layer_data *dev_data, VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
1134 VkFence fence) {
Karl Schultz7b024b42018-08-30 16:18:18 -06001135 auto gpu_state = GetGpuValidationState(dev_data);
1136 if (gpu_state->aborted) return;
Karl Schultz58674242019-01-22 15:35:02 -07001137
1138 SubmitBarrier(dev_data, queue);
1139
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07001140 dev_data->device_dispatch_table.QueueWaitIdle(queue);
Karl Schultz58674242019-01-22 15:35:02 -07001141
Karl Schultz7b024b42018-08-30 16:18:18 -06001142 for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
1143 const VkSubmitInfo *submit = &pSubmits[submit_idx];
1144 for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
1145 auto cb_node = GetCBNode(dev_data, submit->pCommandBuffers[i]);
1146 ProcessInstrumentationBuffer(dev_data, queue, cb_node);
1147 for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
1148 ProcessInstrumentationBuffer(dev_data, queue, secondaryCmdBuffer);
1149 }
1150 }
1151 }
1152}
Tony-LunarGb2501d22019-01-28 09:59:13 -07001153
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07001154void CoreChecks::GpuAllocateValidationResources(layer_data *dev_data, const VkCommandBuffer cmd_buffer,
1155 const VkPipelineBindPoint bind_point) {
Tony-LunarGb2501d22019-01-28 09:59:13 -07001156 VkResult result;
1157
1158 if (!(GetEnables(dev_data)->gpu_validation)) return;
1159
1160 auto gpu_state = GetGpuValidationState(dev_data);
1161 if (gpu_state->aborted) return;
1162
1163 std::vector<VkDescriptorSet> desc_sets;
1164 VkDescriptorPool desc_pool = VK_NULL_HANDLE;
1165 result = gpu_state->desc_set_manager->GetDescriptorSets(1, &desc_pool, &desc_sets);
1166 assert(result == VK_SUCCESS);
1167 if (result != VK_SUCCESS) {
1168 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
1169 "Unable to allocate descriptor sets. Device could become unstable.");
1170 gpu_state->aborted = true;
1171 return;
1172 }
1173
1174 VkDescriptorBufferInfo desc_buffer_info = {};
1175 desc_buffer_info.range = gpu_state->memory_manager->GetBlockSize();
1176
1177 auto cb_node = GetCBNode(dev_data, cmd_buffer);
1178 if (!cb_node) {
1179 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
1180 "Unrecognized command buffer");
1181 gpu_state->aborted = true;
1182 return;
1183 }
1184
1185 GpuDeviceMemoryBlock block = {};
1186 result = gpu_state->memory_manager->GetBlock(&block);
1187 if (result != VK_SUCCESS) {
1188 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
1189 "Unable to allocate device memory. Device could become unstable.");
1190 gpu_state->aborted = true;
1191 return;
1192 }
1193
1194 // Record buffer and memory info in CB state tracking
1195 cb_node->gpu_buffer_list.emplace_back(block, desc_sets[0], desc_pool);
1196
1197 // Write the descriptor
1198 desc_buffer_info.buffer = block.buffer;
1199 desc_buffer_info.offset = block.offset;
1200
1201 VkWriteDescriptorSet desc_write = {};
1202 desc_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1203 desc_write.descriptorCount = 1;
1204 desc_write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
1205 desc_write.pBufferInfo = &desc_buffer_info;
1206 desc_write.dstSet = desc_sets[0];
1207 GetDispatchTable(dev_data)->UpdateDescriptorSets(GetDevice(dev_data), 1, &desc_write, 0, NULL);
1208
1209 auto iter = cb_node->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS); // find() allows read-only access to cb_state
1210 if (iter != cb_node->lastBound.end()) {
1211 auto pipeline_state = iter->second.pipeline_state;
1212 if (pipeline_state && (pipeline_state->pipeline_layout.set_layouts.size() <= gpu_state->desc_set_bind_index)) {
Tony-LunarG5ad17272019-03-05 12:48:24 -07001213 GetDispatchTable(dev_data)->CmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
1214 pipeline_state->pipeline_layout.layout,
1215 gpu_state->desc_set_bind_index, 1, desc_sets.data(), 0, nullptr);
Tony-LunarGb2501d22019-01-28 09:59:13 -07001216 }
1217 } else {
1218 ReportSetupProblem(dev_data, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(GetDevice(dev_data)),
1219 "Unable to find pipeline state");
1220 gpu_state->aborted = true;
1221 return;
1222 }
1223}