blob: 9658c9f41da01aa09f7902a94f94564169a0465f [file] [log] [blame]
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -07001/* Copyright (c) 2015-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2020 Valve Corporation
3 * Copyright (c) 2015-2020 LunarG, Inc.
Camdeneaa86ea2019-07-26 11:00:09 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Camden Stocker <camden@lunarg.com>
18 */
19
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070020#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060021#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060022#include "best_practices_error_enums.h"
Camden5b184be2019-08-13 07:50:19 -060023
24#include <string>
25#include <iomanip>
Sam Walls8e77e4f2020-03-16 20:47:40 +000026#include <bitset>
Camden5b184be2019-08-13 07:50:19 -060027
28// get the API name is proper format
Jeff Bolz46c0ea02019-10-09 13:06:29 -050029std::string BestPractices::GetAPIVersionName(uint32_t version) const {
Camden5b184be2019-08-13 07:50:19 -060030 std::stringstream version_name;
31 uint32_t major = VK_VERSION_MAJOR(version);
32 uint32_t minor = VK_VERSION_MINOR(version);
33 uint32_t patch = VK_VERSION_PATCH(version);
34
35 version_name << major << "." << minor << "." << patch << " (0x" << std::setfill('0') << std::setw(8) << std::hex << version
36 << ")";
37
38 return version_name.str();
39}
40
Attilio Provenzano19d6a982020-02-27 12:41:41 +000041struct VendorSpecificInfo {
42 bool CHECK_ENABLED::*check;
43 std::string name;
44};
45
46const std::map<BPVendorFlagBits, VendorSpecificInfo> vendor_info = {
47 {kBPVendorArm, {&CHECK_ENABLED::vendor_specific_arm, "Arm"}},
48};
49
50bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
51 for (const auto& vendor : vendor_info) {
52 if (vendors & vendor.first && enabled.*(vendor.second.check)) {
53 return true;
54 }
55 }
56 return false;
57}
58
59const char* VendorSpecificTag(BPVendorFlags vendors) {
60 // Cache built vendor tags in a map
61 static std::unordered_map<BPVendorFlags, std::string> tag_map;
62
63 auto res = tag_map.find(vendors);
64 if (res == tag_map.end()) {
65 // Build the vendor tag string
66 std::stringstream vendor_tag;
67
68 vendor_tag << "[";
69 bool first_vendor = true;
70 for (const auto& vendor : vendor_info) {
71 if (vendors & vendor.first) {
72 if (!first_vendor) {
73 vendor_tag << ", ";
74 }
75 vendor_tag << vendor.second.name;
76 first_vendor = false;
77 }
78 }
79 vendor_tag << "]";
80
81 tag_map[vendors] = vendor_tag.str();
82 res = tag_map.find(vendors);
83 }
84
85 return res->second.c_str();
86}
87
Mark Lobodzinski6167e102020-02-24 17:03:55 -070088const char* DepReasonToString(ExtDeprecationReason reason) {
89 switch (reason) {
90 case kExtPromoted:
91 return "promoted to";
92 break;
93 case kExtObsoleted:
94 return "obsoleted by";
95 break;
96 case kExtDeprecated:
97 return "deprecated by";
98 break;
99 default:
100 return "";
101 break;
102 }
103}
104
105bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
106 const char* vuid) const {
107 bool skip = false;
108 auto dep_info_it = deprecated_extensions.find(extension_name);
109 if (dep_info_it != deprecated_extensions.end()) {
110 auto dep_info = dep_info_it->second;
111 if ((dep_info.target.compare("VK_VERSION_1_1") && (version >= VK_VERSION_1_1)) ||
112 (dep_info.target.compare("VK_VERSION_1_2") && (version >= VK_VERSION_1_2))) {
113 skip |=
114 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
115 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
116 } else if (!dep_info.target.find("VK_VERSION")) {
117 if (dep_info.target.length() == 0) {
118 skip |= LogWarning(instance, vuid,
119 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
120 "without replacement.",
121 api_name, extension_name);
122 } else {
123 skip |= LogWarning(instance, vuid,
124 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
125 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
126 }
127 }
128 }
129 return skip;
130}
131
Camden5b184be2019-08-13 07:50:19 -0600132bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500133 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600134 bool skip = false;
135
136 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
137 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800138 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700139 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
140 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600141 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700142 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
143 pCreateInfo->pApplicationInfo->apiVersion,
144 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600145 }
146
147 return skip;
148}
149
150void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
151 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700152 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100153
154 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr)
155 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
156 else
157 instance_api_version = 0;
Camden5b184be2019-08-13 07:50:19 -0600158}
159
160bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500161 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600162 bool skip = false;
163
164 // get API version of physical device passed when creating device.
165 VkPhysicalDeviceProperties physical_device_properties{};
166 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500167 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600168
169 // check api versions and warn if instance api Version is higher than version on device.
170 if (instance_api_version > device_api_version) {
171 std::string inst_api_name = GetAPIVersionName(instance_api_version);
172 std::string dev_api_name = GetAPIVersionName(device_api_version);
173
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700174 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
175 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
176 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600177 }
178
179 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
180 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800181 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700182 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
183 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600184 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700185 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
186 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600187 }
188
Camden83a9c372019-08-14 11:41:38 -0600189 auto pd_state = GetPhysicalDeviceState(physicalDevice);
Corta48da1d2019-09-20 18:59:07 +0200190 if ((pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700191 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
192 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600193 }
194
Camden5b184be2019-08-13 07:50:19 -0600195 return skip;
196}
197
198bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500199 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600200 bool skip = false;
201
202 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
203 std::stringstream bufferHex;
204 bufferHex << "0x" << std::hex << HandleToUint64(pBuffer);
205
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700206 skip |= LogWarning(
207 device, kVUID_BestPractices_SharingModeExclusive,
208 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
209 "(queueFamilyIndexCount of %" PRIu32 ").",
210 bufferHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600211 }
212
213 return skip;
214}
215
216bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500217 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600218 bool skip = false;
219
220 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
221 std::stringstream imageHex;
222 imageHex << "0x" << std::hex << HandleToUint64(pImage);
223
224 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700225 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
226 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
227 "(queueFamilyIndexCount of %" PRIu32 ").",
228 imageHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600229 }
230
Attilio Provenzano02859b22020-02-27 14:17:28 +0000231 if (VendorCheckEnabled(kBPVendorArm)) {
232 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
233 skip |= LogPerformanceWarning(
234 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
235 "%s vkCreateImage(): Trying to create an image with %u samples. "
236 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
237 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
238 }
239
240 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
241 skip |= LogPerformanceWarning(
242 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
243 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
244 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
245 "and do not need to be backed by physical storage. "
246 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
247 VendorSpecificTag(kBPVendorArm));
248 }
249 }
250
Camden5b184be2019-08-13 07:50:19 -0600251 return skip;
252}
253
254bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500255 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600256 bool skip = false;
257
Camden83a9c372019-08-14 11:41:38 -0600258 auto physical_device_state = GetPhysicalDeviceState();
259
260 if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700261 skip |= LogWarning(
262 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
Camden83a9c372019-08-14 11:41:38 -0600263 "vkCreateSwapchainKHR() called before getting surface capabilities from vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
264 }
265
266 if (physical_device_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700267 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
268 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
269 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
Camden83a9c372019-08-14 11:41:38 -0600270 }
271
272 if (physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700273 skip |= LogWarning(
274 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
275 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
Camden83a9c372019-08-14 11:41:38 -0600276 }
277
Camden5b184be2019-08-13 07:50:19 -0600278 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700279 skip |=
280 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600281 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700282 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
283 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600284 }
285
286 return skip;
287}
288
289bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
290 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500291 const VkAllocationCallbacks* pAllocator,
292 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600293 bool skip = false;
294
295 for (uint32_t i = 0; i < swapchainCount; i++) {
296 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700297 skip |= LogWarning(
298 device, kVUID_BestPractices_SharingModeExclusive,
299 "Warning: A shared swapchain (index %" PRIu32
300 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
301 "queues (queueFamilyIndexCount of %" PRIu32 ").",
302 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600303 }
304 }
305
306 return skip;
307}
308
309bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500310 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600311 bool skip = false;
312
313 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
314 VkFormat format = pCreateInfo->pAttachments[i].format;
315 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
316 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
317 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700318 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
319 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
320 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
321 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
322 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600323 }
324 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700325 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
326 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
327 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
328 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
329 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600330 }
331 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000332
333 const auto& attachment = pCreateInfo->pAttachments[i];
334 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
335 bool access_requires_memory =
336 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
337
338 if (FormatHasStencil(format)) {
339 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
340 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
341 }
342
343 if (access_requires_memory) {
344 skip |= LogPerformanceWarning(
345 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
346 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
347 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
348 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
349 i, static_cast<uint32_t>(attachment.samples));
350 }
351 }
Camden5b184be2019-08-13 07:50:19 -0600352 }
353
354 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
355 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
356 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
357 }
358
359 return skip;
360}
361
Tony-LunarG767180f2020-04-23 14:03:59 -0600362bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
363 const VkImageView* image_views) const {
364 bool skip = false;
365
366 // Check for non-transient attachments that should be transient and vice versa
367 for (uint32_t i = 0; i < attachmentCount; ++i) {
368 auto& attachment = rpci->pAttachments[i];
369 bool attachment_should_be_transient =
370 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
371
372 if (FormatHasStencil(attachment.format)) {
373 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
374 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
375 }
376
377 auto view_state = GetImageViewState(image_views[i]);
378 if (view_state) {
379 auto& ivci = view_state->create_info;
380 auto& ici = GetImageState(ivci.image)->createInfo;
381
382 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
383
384 // The check for an image that should not be transient applies to all GPUs
385 if (!attachment_should_be_transient && image_is_transient) {
386 skip |= LogPerformanceWarning(
387 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
388 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
389 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
390 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
391 i);
392 }
393
394 bool supports_lazy = false;
395 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
396 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
397 supports_lazy = true;
398 }
399 }
400
401 // The check for an image that should be transient only applies to GPUs supporting
402 // lazily allocated memory
403 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
404 skip |= LogPerformanceWarning(
405 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
406 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
407 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
408 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
409 i);
410 }
411 }
412 }
413 return skip;
414}
415
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000416bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
417 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
418 bool skip = false;
419
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000420 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Tony-LunarG767180f2020-04-23 14:03:59 -0600421 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
422 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000423 }
424
425 return skip;
426}
427
Sam Wallse746d522020-03-16 21:20:23 +0000428bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
429 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
430 bool skip = false;
431 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
432
433 if (!skip) {
434 const auto& pool_handle = pAllocateInfo->descriptorPool;
435 auto iter = descriptor_pool_freed_count.find(pool_handle);
436 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
437 // this warning is specific to Arm
438 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
439 skip |= LogPerformanceWarning(
440 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
441 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
442 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
443 VendorSpecificTag(kBPVendorArm));
444 }
445 }
446
447 return skip;
448}
449
450void BestPractices::PostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
451 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
452 ValidationStateTracker::PostCallRecordAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, result, ads_state);
453
454 if (result == VK_SUCCESS) {
455 // find the free count for the pool we allocated into
456 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
457 if (iter != descriptor_pool_freed_count.end()) {
458 // we record successful allocations by subtracting the allocation count from the last recorded free count
459 const auto alloc_count = pAllocateInfo->descriptorSetCount;
460 // clamp the unsigned subtraction to the range [0, last_free_count]
461 if (iter->second > alloc_count)
462 iter->second -= alloc_count;
463 else
464 iter->second = 0;
465 }
466 }
467}
468
469void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
470 const VkDescriptorSet* pDescriptorSets, VkResult result) {
471 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
472 if (result == VK_SUCCESS) {
473 // we want to track frees because we're interested in suggesting re-use
474 auto iter = descriptor_pool_freed_count.find(descriptorPool);
475 if (iter == descriptor_pool_freed_count.end()) {
476 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
477 } else {
478 iter->second += descriptorSetCount;
479 }
480 }
481}
482
Camden5b184be2019-08-13 07:50:19 -0600483bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500484 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600485 bool skip = false;
486
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500487 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700488 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
489 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600490 }
491
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000492 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
493 skip |= LogPerformanceWarning(
494 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
495 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
496 "threshold is %llu bytes). "
497 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
498 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
499 }
500
Camden83a9c372019-08-14 11:41:38 -0600501 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
502
503 return skip;
504}
505
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500506void BestPractices::PostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
507 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
508 VkResult result) {
Camden Stocker9738af92019-10-16 13:54:03 -0700509 ValidationStateTracker::PostCallRecordAllocateMemory(device, pAllocateInfo, pAllocator, pMemory, result);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700510 if (result != VK_SUCCESS) {
511 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
512 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
513 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
514 static std::vector<VkResult> success_codes = {};
515 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
516 return;
517 }
518 num_mem_objects++;
519}
Camden Stocker9738af92019-10-16 13:54:03 -0700520
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700521void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& success_codes,
522 const std::vector<VkResult>& error_codes) const {
523 auto error = std::find(error_codes.begin(), error_codes.end(), result);
524 if (error != error_codes.end()) {
525 LogWarning(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
526 return;
527 }
528 auto success = std::find(success_codes.begin(), success_codes.end(), result);
529 if (success != success_codes.end()) {
530 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned non-success return code %s.", api_name,
531 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500532 }
533}
534
Jeff Bolz5c801d12019-10-09 10:38:45 -0500535bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
536 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700537 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600538 bool skip = false;
539
Camden Stocker9738af92019-10-16 13:54:03 -0700540 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600541
542 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600543 LogObjectList objlist(device);
544 objlist.add(obj);
545 objlist.add(mem_info->mem);
546 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700547 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600548 }
549
Camden5b184be2019-08-13 07:50:19 -0600550 return skip;
551}
552
553void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700554 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600555 if (memory != VK_NULL_HANDLE) {
556 num_mem_objects--;
557 }
558}
559
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000560bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600561 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500562 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600563
sfricke-samsunge2441192019-11-06 14:07:57 -0800564 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700565 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
566 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
567 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600568 }
569
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000570 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
571
572 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
573 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
574 skip |= LogPerformanceWarning(
575 device, kVUID_BestPractices_SmallDedicatedAllocation,
576 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
577 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
578 "larger memory blocks. (Current threshold is %llu bytes.)",
579 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
580 }
581
Camden Stockerb603cc82019-09-03 10:09:02 -0600582 return skip;
583}
584
585bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500586 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600587 bool skip = false;
588 const char* api_name = "BindBufferMemory()";
589
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000590 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600591
592 return skip;
593}
594
595bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500596 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600597 char api_name[64];
598 bool skip = false;
599
600 for (uint32_t i = 0; i < bindInfoCount; i++) {
601 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000602 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600603 }
604
605 return skip;
606}
Camden Stockerb603cc82019-09-03 10:09:02 -0600607
608bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500609 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600610 char api_name[64];
611 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600612
Camden Stocker8b798ab2019-09-03 10:33:28 -0600613 for (uint32_t i = 0; i < bindInfoCount; i++) {
614 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000615 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600616 }
617
618 return skip;
619}
620
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000621bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600622 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500623 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600624
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700625 if ((image_state->createInfo.flags & VK_IMAGE_CREATE_DISJOINT_BIT) == 0) {
626 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
627 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
628 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
629 api_name, report_data->FormatHandle(image).c_str());
630 }
631 } else {
632 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
633 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600634 }
635
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000636 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
637
638 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
639 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
640 skip |= LogPerformanceWarning(
641 device, kVUID_BestPractices_SmallDedicatedAllocation,
642 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
643 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
644 "larger memory blocks. (Current threshold is %llu bytes.)",
645 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
646 }
647
648 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
649 // make sure this type is actually used.
650 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
651 // (i.e.most tile - based renderers)
652 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
653 bool supports_lazy = false;
654 uint32_t suggested_type = 0;
655
656 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
657 if ((1u << i) & image_state->requirements.memoryTypeBits) {
658 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
659 supports_lazy = true;
660 suggested_type = i;
661 break;
662 }
663 }
664 }
665
666 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
667
668 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
669 skip |= LogPerformanceWarning(
670 device, kVUID_BestPractices_NonLazyTransientImage,
671 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
672 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
673 "%llu bytes of physical memory.",
674 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
675 }
676 }
677
Camden Stocker8b798ab2019-09-03 10:33:28 -0600678 return skip;
679}
680
681bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500682 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600683 bool skip = false;
684 const char* api_name = "vkBindImageMemory()";
685
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000686 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600687
688 return skip;
689}
690
691bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500692 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600693 char api_name[64];
694 bool skip = false;
695
696 for (uint32_t i = 0; i < bindInfoCount; i++) {
697 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000698 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600699 }
700
701 return skip;
702}
703
704bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500705 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600706 char api_name[64];
707 bool skip = false;
708
709 for (uint32_t i = 0; i < bindInfoCount; i++) {
710 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000711 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600712 }
713
714 return skip;
715}
Camden83a9c372019-08-14 11:41:38 -0600716
Attilio Provenzano02859b22020-02-27 14:17:28 +0000717static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
718 switch (format) {
719 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
720 case VK_FORMAT_R16_SFLOAT:
721 case VK_FORMAT_R16G16_SFLOAT:
722 case VK_FORMAT_R16G16B16_SFLOAT:
723 case VK_FORMAT_R16G16B16A16_SFLOAT:
724 case VK_FORMAT_R32_SFLOAT:
725 case VK_FORMAT_R32G32_SFLOAT:
726 case VK_FORMAT_R32G32B32_SFLOAT:
727 case VK_FORMAT_R32G32B32A32_SFLOAT:
728 return false;
729
730 default:
731 return true;
732 }
733}
734
735bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
736 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
737 bool skip = false;
738
739 for (uint32_t i = 0; i < createInfoCount; i++) {
740 auto pCreateInfo = &pCreateInfos[i];
741
742 if (!pCreateInfo->pColorBlendState || !pCreateInfo->pMultisampleState ||
743 pCreateInfo->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
744 pCreateInfo->pMultisampleState->sampleShadingEnable) {
745 return skip;
746 }
747
748 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
749 auto& subpass = rp_state->createInfo.pSubpasses[pCreateInfo->subpass];
750
751 for (uint32_t j = 0; j < pCreateInfo->pColorBlendState->attachmentCount; j++) {
752 auto& blend_att = pCreateInfo->pColorBlendState->pAttachments[j];
753 uint32_t att = subpass.pColorAttachments[j].attachment;
754
755 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
756 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
757 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
758 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
759 "color attachment #%u makes use "
760 "of a format which cannot be blended at full throughput when using MSAA.",
761 VendorSpecificTag(kBPVendorArm), i, j);
762 }
763 }
764 }
765 }
766
767 return skip;
768}
769
Camden5b184be2019-08-13 07:50:19 -0600770bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
771 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600772 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500773 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600774 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
775 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600776 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600777
778 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700779 skip |= LogPerformanceWarning(
780 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
781 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
782 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600783 }
784
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000785 for (uint32_t i = 0; i < createInfoCount; i++) {
786 auto& createInfo = pCreateInfos[i];
787
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600788 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
789 auto& vertexInput = *createInfo.pVertexInputState;
790 uint32_t count = 0;
791 for (uint32_t j = 0; j < vertexInput.vertexBindingDescriptionCount; j++) {
792 if (vertexInput.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
793 count++;
794 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000795 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600796 if (count > kMaxInstancedVertexBuffers) {
797 skip |= LogPerformanceWarning(
798 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
799 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
800 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
801 count, kMaxInstancedVertexBuffers);
802 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000803 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000804
805 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000806 }
807
Camden5b184be2019-08-13 07:50:19 -0600808 return skip;
809}
810
811bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
812 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600813 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500814 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600815 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
816 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600817
818 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700819 skip |= LogPerformanceWarning(
820 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
821 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
822 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600823 }
824
825 return skip;
826}
827
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500828bool BestPractices::CheckPipelineStageFlags(std::string api_name, const VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -0600829 bool skip = false;
830
831 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700832 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
833 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600834 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700835 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
836 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600837 }
838
839 return skip;
840}
841
Mark Lobodzinski9b133c12020-03-10 10:42:56 -0600842void BestPractices::PostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
843 ValidationStateTracker::PostCallRecordQueuePresentKHR(queue, pPresentInfo, result);
844 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
845 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
846 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
847 LogPerformanceWarning(
848 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
849 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
850 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
851 "targets. Applications should query updated surface information and recreate their swapchain at the next "
852 "convenient opportunity.",
853 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
854 }
855 }
856}
857
Jeff Bolz5c801d12019-10-09 10:38:45 -0500858bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
859 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -0600860 bool skip = false;
861
862 for (uint32_t submit = 0; submit < submitCount; submit++) {
863 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
864 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
865 }
866 }
867
868 return skip;
869}
870
Attilio Provenzano746e43e2020-02-27 11:23:50 +0000871bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
872 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
873 bool skip = false;
874
875 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
876 skip |= LogPerformanceWarning(
877 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
878 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
879 "pool instead.");
880 }
881
882 return skip;
883}
884
885bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
886 const VkCommandBufferBeginInfo* pBeginInfo) const {
887 bool skip = false;
888
889 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
890 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
891 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
892 }
893
Attilio Provenzano02859b22020-02-27 14:17:28 +0000894 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
895 skip |= VendorCheckEnabled(kBPVendorArm) &&
896 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
897 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
898 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
899 VendorSpecificTag(kBPVendorArm));
900 }
901
Attilio Provenzano746e43e2020-02-27 11:23:50 +0000902 return skip;
903}
904
Jeff Bolz5c801d12019-10-09 10:38:45 -0500905bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -0600906 bool skip = false;
907
908 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
909
910 return skip;
911}
912
Jeff Bolz5c801d12019-10-09 10:38:45 -0500913bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
914 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -0600915 bool skip = false;
916
917 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
918
919 return skip;
920}
921
922bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
923 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
924 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
925 uint32_t bufferMemoryBarrierCount,
926 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
927 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500928 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -0600929 bool skip = false;
930
931 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
932 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
933
934 return skip;
935}
936
937bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
938 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
939 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
940 uint32_t bufferMemoryBarrierCount,
941 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
942 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500943 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -0600944 bool skip = false;
945
946 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
947 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
948
949 return skip;
950}
951
952bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500953 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -0600954 bool skip = false;
955
956 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
957
958 return skip;
959}
960
Attilio Provenzano02859b22020-02-27 14:17:28 +0000961static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
962 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
963 auto& subpassInfo = createInfo.pSubpasses[subpass];
964
965 // If an attachment is ever used as a color attachment,
966 // resolve attachment or depth stencil attachment,
967 // it needs to exist on tile at some point.
968
969 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
970 if (subpassInfo.pColorAttachments[i].attachment == attachment) return true;
971
972 if (subpassInfo.pResolveAttachments) {
973 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
974 if (subpassInfo.pResolveAttachments[i].attachment == attachment) return true;
975 }
976
977 if (subpassInfo.pDepthStencilAttachment && subpassInfo.pDepthStencilAttachment->attachment == attachment) return true;
978 }
979
980 return false;
981}
982
983bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
984 const VkRenderPassBeginInfo* pRenderPassBegin) const {
985 bool skip = false;
986
987 if (!pRenderPassBegin) {
988 return skip;
989 }
990
991 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
992 if (rp_state) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600993 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) {
994 const VkRenderPassAttachmentBeginInfo* rpabi =
995 lvl_find_in_chain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
996 if (rpabi) {
997 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
998 }
999 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001000 // Check if any attachments have LOAD operation on them
1001 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1002 auto& attachment = rp_state->createInfo.pAttachments[att];
1003
1004 bool attachmentHasReadback = false;
1005 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1006 attachmentHasReadback = true;
1007 }
1008
1009 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1010 attachmentHasReadback = true;
1011 }
1012
1013 bool attachmentNeedsReadback = false;
1014
1015 // Check if the attachment is actually used in any subpass on-tile
1016 if (attachmentHasReadback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1017 attachmentNeedsReadback = true;
1018 }
1019
1020 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
1021 if (attachmentNeedsReadback) {
1022 skip |= VendorCheckEnabled(kBPVendorArm) &&
1023 LogPerformanceWarning(
1024 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1025 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1026 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1027 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1028 VendorSpecificTag(kBPVendorArm), att,
1029 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1030 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1031 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1032 }
1033 }
1034 }
1035
1036 return skip;
1037}
1038
1039bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1040 VkSubpassContents contents) const {
1041 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1042 return skip;
1043}
1044
1045bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1046 const VkRenderPassBeginInfo* pRenderPassBegin,
1047 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
1048 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1049 return skip;
1050}
1051
1052bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1053 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
1054 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1055 return skip;
1056}
1057
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001058// Generic function to handle validation for all CmdDraw* type functions
1059bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1060 bool skip = false;
1061 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1062 if (cb_state) {
1063 const auto last_bound_it = cb_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1064 const PIPELINE_STATE* pipeline_state = nullptr;
1065 if (last_bound_it != cb_state->lastBound.cend()) {
1066 pipeline_state = last_bound_it->second.pipeline_state;
1067 }
1068 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
1069 // Verify vertex binding
1070 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1071 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001072 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1073 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1074 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1075 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001076 }
1077 }
1078 }
1079 return skip;
1080}
1081
Camden5b184be2019-08-13 07:50:19 -06001082bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001083 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001084 bool skip = false;
1085
1086 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001087 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1088 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001089 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001090 }
1091
1092 return skip;
1093}
1094
1095bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001096 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001097 bool skip = false;
1098
1099 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001100 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1101 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001102 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001103 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1104
Attilio Provenzano02859b22020-02-27 14:17:28 +00001105 // Check if we reached the limit for small indexed draw calls.
1106 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1107 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1108 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1109 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1110 skip |= VendorCheckEnabled(kBPVendorArm) &&
1111 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1112 "The command buffer contains many small indexed drawcalls "
1113 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1114 "You can try batching drawcalls or instancing when applicable.",
1115 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1116 }
1117
Sam Walls8e77e4f2020-03-16 20:47:40 +00001118 if (VendorCheckEnabled(kBPVendorArm)) {
1119 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1120 }
1121
1122 return skip;
1123}
1124
1125bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1126 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1127 bool skip = false;
1128
1129 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1130 const auto* cmd_state = GetCBState(commandBuffer);
1131 if (cmd_state == nullptr) return skip;
1132
1133 const auto* ib_state = GetBufferState(cmd_state->index_buffer_binding.buffer);
1134 if (ib_state == nullptr) return skip;
1135
1136 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1137 const auto& ib_mem_state = *ib_state->binding.mem_state;
1138 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1139 const void* ib_mem = ib_mem_state.p_driver_data;
1140 bool primitive_restart_enable = false;
1141
1142 const auto& pipeline_binding_iter = cmd_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1143
1144 if (pipeline_binding_iter != cmd_state->lastBound.end()) {
1145 const auto* pipeline_state = pipeline_binding_iter->second.pipeline_state;
1146 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1147 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
1148 }
1149
1150 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
1151 if (ib_mem && pipeline_binding_iter != cmd_state->lastBound.end()) {
1152 uint32_t scan_stride;
1153 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1154 scan_stride = sizeof(uint8_t);
1155 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1156 scan_stride = sizeof(uint16_t);
1157 } else {
1158 scan_stride = sizeof(uint32_t);
1159 }
1160
1161 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1162 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1163
1164 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1165 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1166 // irrespective of whether or not they're part of the draw call.
1167
1168 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1169 uint32_t min_index = ~0u;
1170 // start with maximum as 0 and adjust to indices in the buffer
1171 uint32_t max_index = 0u;
1172
1173 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1174 // for the given index buffer
1175 uint32_t vertex_shade_count = 0;
1176
1177 PostTransformLRUCacheModel post_transform_cache;
1178
1179 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1180 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1181 // target architecture.
1182 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1183 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1184 post_transform_cache.resize(32);
1185
1186 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1187 uint32_t scan_index;
1188 uint32_t primitive_restart_value;
1189 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1190 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1191 primitive_restart_value = 0xFF;
1192 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1193 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1194 primitive_restart_value = 0xFFFF;
1195 } else {
1196 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1197 primitive_restart_value = 0xFFFFFFFF;
1198 }
1199
1200 max_index = std::max(max_index, scan_index);
1201 min_index = std::min(min_index, scan_index);
1202
1203 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1204 bool in_cache = post_transform_cache.query_cache(scan_index);
1205 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1206 if (!in_cache) vertex_shade_count++;
1207 }
1208 }
1209
1210 // if the max and min values were not set, then we either have no indices, or all primitive restarts, exit...
1211 if (max_index < min_index) return skip;
1212
1213 if (max_index - min_index >= indexCount) {
1214 skip |= LogPerformanceWarning(
1215 device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1216 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1217 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1218 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1219 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1220 VendorSpecificTag(kBPVendorArm), (static_cast<float>(indexCount) / (max_index - min_index)) * 100.0f);
1221 return skip;
1222 }
1223
1224 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1225 // each bit of the n-th bucket contains the inclusion information for indices (n*n_buckets) to ((n+1)*n_buckets)
1226 const size_t n_buckets = 64;
1227 std::vector<std::bitset<n_buckets>> vertex_reference_buckets;
1228 vertex_reference_buckets.resize((max_index - min_index + 1) / n_buckets);
1229
1230 // To avoid using too much memory, we run over the indices again.
1231 // Knowing the size from the last scan allows us to record index usage with bitsets
1232 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1233 uint32_t scan_index;
1234 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1235 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1236 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1237 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1238 } else {
1239 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1240 }
1241 // keep track of the set of all indices used to reference vertices in the draw call
1242 size_t index_offset = scan_index - min_index;
1243 size_t bitset_bucket_index = index_offset / n_buckets;
1244 uint64_t used_indices = 1ull << ((index_offset % n_buckets) & 0xFFFFFFFFu);
1245 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1246 }
1247
1248 uint32_t vertex_reference_count = 0;
1249 for (const auto& bitset : vertex_reference_buckets) {
1250 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1251 }
1252
1253 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
1254 float utilization = static_cast<float>(vertex_reference_count) / (max_index - min_index + 1);
1255 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
1256 float cache_hit_rate = static_cast<float>(vertex_reference_count) / vertex_shade_count;
1257
1258 if (utilization < 0.5f) {
1259 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1260 "%s The indices which were specified for the draw call only utilise approximately "
1261 "%.02f%% of the bound vertex buffer.",
1262 VendorSpecificTag(kBPVendorArm), utilization);
1263 }
1264
1265 if (cache_hit_rate <= 0.5f) {
1266 skip |=
1267 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1268 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1269 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1270 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1271 "recently shaded vertices.",
1272 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1273 }
1274 }
1275
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001276 return skip;
1277}
1278
Attilio Provenzano02859b22020-02-27 14:17:28 +00001279void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1280 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1281 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1282 firstInstance);
1283
1284 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1285 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1286 cmd_state->small_indexed_draw_call_count++;
1287 }
1288}
1289
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001290bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1291 VkDeviceSize offset, VkBuffer countBuffer,
1292 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1293 uint32_t stride) const {
1294 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001295
1296 return skip;
1297}
1298
1299bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001300 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001301 bool skip = false;
1302
1303 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001304 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1305 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001306 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001307 }
1308
1309 return skip;
1310}
1311
1312bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001313 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001314 bool skip = false;
1315
1316 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001317 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1318 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001319 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001320 }
1321
1322 return skip;
1323}
1324
1325bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001326 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001327 bool skip = false;
1328
1329 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001330 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1331 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1332 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1333 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001334 }
1335
1336 return skip;
1337}
Camden83a9c372019-08-14 11:41:38 -06001338
Camden Stocker9c051442019-11-06 14:28:43 -08001339bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1340 const char* api_name) const {
1341 bool skip = false;
1342 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1343
1344 if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001345 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1346 "Potential problem with calling %s() without first retrieving properties from "
1347 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1348 api_name);
Camden Stocker9c051442019-11-06 14:28:43 -08001349 }
1350
1351 return skip;
1352}
1353
Camden83a9c372019-08-14 11:41:38 -06001354bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001355 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001356 bool skip = false;
1357
Camden Stocker9c051442019-11-06 14:28:43 -08001358 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001359
Camden Stocker9c051442019-11-06 14:28:43 -08001360 return skip;
1361}
1362
1363bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1364 uint32_t planeIndex,
1365 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1366 bool skip = false;
1367
1368 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1369
1370 return skip;
1371}
1372
1373bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1374 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1375 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1376 bool skip = false;
1377
1378 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001379
1380 return skip;
1381}
Camden05de2d42019-08-19 10:23:56 -06001382
1383bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001384 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001385 bool skip = false;
1386
1387 auto swapchain_state = GetSwapchainState(swapchain);
1388
1389 if (swapchain_state && pSwapchainImages) {
1390 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
1391 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001392 skip |=
1393 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1394 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1395 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001396 }
1397 }
1398
1399 return skip;
1400}
1401
1402// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001403bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1404 uint32_t requested_queue_family_property_count,
1405 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001406 bool skip = false;
1407 if (!qfp_null) {
1408 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
1409 if (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001410 skip |= LogWarning(
1411 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
Camden05de2d42019-08-19 10:23:56 -06001412 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is recommended "
1413 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1414 caller_name, caller_name);
1415 // Then verify that pCount that is passed in on second call matches what was returned
1416 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001417 skip |= LogWarning(
1418 pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
Camden05de2d42019-08-19 10:23:56 -06001419 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1420 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1421 ". It is recommended to instead receive all the properties by calling %s with pQueueFamilyPropertyCount that was "
1422 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1423 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name, caller_name);
1424 }
1425 }
1426
1427 return skip;
1428}
1429
Jeff Bolz5c801d12019-10-09 10:38:45 -05001430bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1431 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001432 bool skip = false;
1433
1434 for (uint32_t i = 0; i < bindInfoCount; i++) {
1435 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1436 if (!as_state->memory_requirements_checked) {
1437 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1438 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1439 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001440 skip |= LogWarning(
1441 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001442 "vkBindAccelerationStructureMemoryNV(): "
1443 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1444 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1445 }
1446 }
1447
1448 return skip;
1449}
1450
Camden05de2d42019-08-19 10:23:56 -06001451bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1452 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001453 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001454 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1455 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001456 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001457 (nullptr == pQueueFamilyProperties),
1458 "vkGetPhysicalDeviceQueueFamilyProperties()");
1459}
1460
Jeff Bolz5c801d12019-10-09 10:38:45 -05001461bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1462 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1463 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001464 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1465 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001466 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001467 (nullptr == pQueueFamilyProperties),
1468 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1469}
1470
Jeff Bolz5c801d12019-10-09 10:38:45 -05001471bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1472 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1473 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001474 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1475 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001476 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001477 (nullptr == pQueueFamilyProperties),
1478 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1479}
1480
1481bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1482 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001483 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001484 if (!pSurfaceFormats) return false;
1485 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1486 const auto& call_state = physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
1487 bool skip = false;
1488 if (call_state == UNCALLED) {
1489 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1490 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001491 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1492 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1493 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001494 } else {
1495 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001496 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001497 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1498 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1499 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1500 "when pSurfaceFormatCount was NULL.",
1501 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001502 }
1503 }
1504 return skip;
1505}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001506
1507bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001508 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001509 bool skip = false;
1510
1511 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1512 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1513 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001514 std::unordered_set<const IMAGE_STATE*> sparse_images;
1515 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1516 // in RecordQueueBindSparse.
1517 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001518 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1519 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1520 const auto& image_bind = bindInfo.pImageBinds[i];
1521 auto image_state = GetImageState(image_bind.image);
1522 if (!image_state)
1523 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1524 sparse_images.insert(image_state);
1525 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1526 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1527 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001528 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1529 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1530 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1531 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001532 }
1533 }
1534 if (!image_state->memory_requirements_checked) {
1535 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001536 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1537 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1538 "vkGetImageMemoryRequirements() to retrieve requirements.",
1539 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001540 }
1541 }
1542 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1543 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1544 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1545 if (!image_state)
1546 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1547 sparse_images.insert(image_state);
1548 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1549 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1550 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001551 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1552 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1553 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1554 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001555 }
1556 }
1557 if (!image_state->memory_requirements_checked) {
1558 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001559 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1560 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1561 "vkGetImageMemoryRequirements() to retrieve requirements.",
1562 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001563 }
1564 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1565 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001566 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001567 }
1568 }
1569 }
1570 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001571 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1572 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001573 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001574 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1575 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1576 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1577 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001578 }
1579 }
1580 }
1581
1582 return skip;
1583}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001584
1585void BestPractices::PostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1586 VkFence fence, VkResult result) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -07001587 ValidationStateTracker::PostCallRecordQueueBindSparse(queue, bindInfoCount, pBindInfo, fence, result);
1588
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001589 if (result != VK_SUCCESS) {
1590 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
1591 VK_ERROR_DEVICE_LOST};
1592 static std::vector<VkResult> success_codes = {};
1593 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
1594 return;
1595 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001596
1597 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1598 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1599 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1600 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1601 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1602 if (!image_state)
1603 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1604 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1605 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1606 image_state->sparse_metadata_bound = true;
1607 }
1608 }
1609 }
1610 }
1611}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001612
1613bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001614 const VkClearAttachment* pAttachments, uint32_t rectCount,
1615 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001616 bool skip = false;
1617 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1618 if (!cb_node) return skip;
1619
Camden Stockerf55721f2019-09-09 11:04:49 -06001620 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001621 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1622 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1623 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1624 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1625 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001626 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1627 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1628 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1629 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001630 }
1631
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001632 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1633 // as it can be more efficient to just use LOAD_OP_CLEAR
1634 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass;
1635 if (rp) {
1636 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1637
1638 for (uint32_t i = 0; i < attachmentCount; i++) {
1639 auto& attachment = pAttachments[i];
1640 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1641 uint32_t color_attachment = attachment.colorAttachment;
1642 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
1643
1644 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1645 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1646 skip |= LogPerformanceWarning(
1647 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1648 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
1649 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1650 "it is more efficient.",
1651 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
1652 }
1653 }
1654 }
1655
1656 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1657 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1658
1659 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1660 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1661 skip |= LogPerformanceWarning(
1662 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1663 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
1664 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1665 "it is more efficient.",
1666 report_data->FormatHandle(commandBuffer).c_str());
1667 }
1668 }
1669 }
1670
1671 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1672 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1673
1674 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1675 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1676 skip |= LogPerformanceWarning(
1677 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1678 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
1679 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1680 "it is more efficient.",
1681 report_data->FormatHandle(commandBuffer).c_str());
1682 }
1683 }
1684 }
1685 }
1686 }
1687
Camden Stockerf55721f2019-09-09 11:04:49 -06001688 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001689}
Attilio Provenzano02859b22020-02-27 14:17:28 +00001690
1691bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
1692 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
1693 const VkImageResolve* pRegions) const {
1694 bool skip = false;
1695
1696 skip |= VendorCheckEnabled(kBPVendorArm) &&
1697 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
1698 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
1699 "This is a very slow and extremely bandwidth intensive path. "
1700 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
1701 VendorSpecificTag(kBPVendorArm));
1702
1703 return skip;
1704}
1705
1706bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
1707 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
1708 bool skip = false;
1709
1710 if (VendorCheckEnabled(kBPVendorArm)) {
1711 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
1712 skip |= LogPerformanceWarning(
1713 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
1714 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
1715 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
1716 "image) are actually used. If you need different wrapping modes, disregard this warning.",
1717 VendorSpecificTag(kBPVendorArm));
1718 }
1719
1720 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
1721 skip |= LogPerformanceWarning(
1722 device, kVUID_BestPractices_CreateSampler_LodClamping,
1723 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
1724 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
1725 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
1726 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
1727 }
1728
1729 if (pCreateInfo->mipLodBias != 0.0f) {
1730 skip |=
1731 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
1732 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
1733 "descriptors being created and may cause reduced performance.",
1734 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
1735 }
1736
1737 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
1738 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
1739 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
1740 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
1741 skip |= LogPerformanceWarning(
1742 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
1743 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
1744 "This will lead to less efficient descriptors being created and may cause reduced performance. "
1745 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
1746 VendorSpecificTag(kBPVendorArm));
1747 }
1748
1749 if (pCreateInfo->unnormalizedCoordinates) {
1750 skip |= LogPerformanceWarning(
1751 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
1752 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
1753 "descriptors being created and may cause reduced performance.",
1754 VendorSpecificTag(kBPVendorArm));
1755 }
1756
1757 if (pCreateInfo->anisotropyEnable) {
1758 skip |= LogPerformanceWarning(
1759 device, kVUID_BestPractices_CreateSampler_Anisotropy,
1760 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
1761 "and may cause reduced performance.",
1762 VendorSpecificTag(kBPVendorArm));
1763 }
1764 }
1765
1766 return skip;
1767}
Sam Walls8e77e4f2020-03-16 20:47:40 +00001768
1769void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
1770
1771bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
1772 // look for a cache hit
1773 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
1774 if (hit != _entries.end()) {
1775 // mark the cache hit as being most recently used
1776 hit->age = iteration++;
1777 return true;
1778 }
1779
1780 // if there's no cache hit, we need to model the entry being inserted into the cache
1781 CacheEntry new_entry = {value, iteration};
1782 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
1783 // if there is still space left in the cache, use the next available slot
1784 *(_entries.begin() + iteration) = new_entry;
1785 } else {
1786 // otherwise replace the least recently used cache entry
1787 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
1788 *lru = new_entry;
1789 }
1790 iteration++;
1791 return false;
1792}