blob: 93ce241237c1a052a82440d75b9fa8a166141e14 [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 {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060042 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000043 std::string name;
44};
45
46const std::map<BPVendorFlagBits, VendorSpecificInfo> vendor_info = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060047 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000048};
49
50bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
51 for (const auto& vendor : vendor_info) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060052 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000053 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;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600111 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
112 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700113 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());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600116 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700117 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 Lobodzinski17d8dc62020-06-03 08:48:58 -0600142 uint32_t specified_version =
143 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
144 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700145 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600146 }
147
148 return skip;
149}
150
151void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
152 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700153 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100154
155 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr)
156 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
157 else
158 instance_api_version = 0;
Camden5b184be2019-08-13 07:50:19 -0600159}
160
161bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500162 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600163 bool skip = false;
164
165 // get API version of physical device passed when creating device.
166 VkPhysicalDeviceProperties physical_device_properties{};
167 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500168 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600169
170 // check api versions and warn if instance api Version is higher than version on device.
171 if (instance_api_version > device_api_version) {
172 std::string inst_api_name = GetAPIVersionName(instance_api_version);
173 std::string dev_api_name = GetAPIVersionName(device_api_version);
174
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700175 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
176 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
177 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600178 }
179
180 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
181 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800182 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700183 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
184 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600185 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700186 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
187 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Camden5b184be2019-08-13 07:50:19 -0600188 }
189
Camden83a9c372019-08-14 11:41:38 -0600190 auto pd_state = GetPhysicalDeviceState(physicalDevice);
Corta48da1d2019-09-20 18:59:07 +0200191 if ((pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700192 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
193 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600194 }
195
Camden5b184be2019-08-13 07:50:19 -0600196 return skip;
197}
198
199bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500200 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600201 bool skip = false;
202
203 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
204 std::stringstream bufferHex;
205 bufferHex << "0x" << std::hex << HandleToUint64(pBuffer);
206
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700207 skip |= LogWarning(
208 device, kVUID_BestPractices_SharingModeExclusive,
209 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
210 "(queueFamilyIndexCount of %" PRIu32 ").",
211 bufferHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600212 }
213
214 return skip;
215}
216
217bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500218 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600219 bool skip = false;
220
221 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
222 std::stringstream imageHex;
223 imageHex << "0x" << std::hex << HandleToUint64(pImage);
224
225 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700226 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
227 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
228 "(queueFamilyIndexCount of %" PRIu32 ").",
229 imageHex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600230 }
231
Attilio Provenzano02859b22020-02-27 14:17:28 +0000232 if (VendorCheckEnabled(kBPVendorArm)) {
233 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
234 skip |= LogPerformanceWarning(
235 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
236 "%s vkCreateImage(): Trying to create an image with %u samples. "
237 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
238 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
239 }
240
241 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
242 skip |= LogPerformanceWarning(
243 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
244 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
245 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
246 "and do not need to be backed by physical storage. "
247 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
248 VendorSpecificTag(kBPVendorArm));
249 }
250 }
251
Camden5b184be2019-08-13 07:50:19 -0600252 return skip;
253}
254
255bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500256 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600257 bool skip = false;
258
Camden83a9c372019-08-14 11:41:38 -0600259 auto physical_device_state = GetPhysicalDeviceState();
260
261 if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700262 skip |= LogWarning(
263 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
Camden83a9c372019-08-14 11:41:38 -0600264 "vkCreateSwapchainKHR() called before getting surface capabilities from vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
265 }
266
267 if (physical_device_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700268 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
269 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
270 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
Camden83a9c372019-08-14 11:41:38 -0600271 }
272
273 if (physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700274 skip |= LogWarning(
275 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
276 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
Camden83a9c372019-08-14 11:41:38 -0600277 }
278
Camden5b184be2019-08-13 07:50:19 -0600279 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700280 skip |=
281 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600282 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700283 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
284 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600285 }
286
287 return skip;
288}
289
290bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
291 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500292 const VkAllocationCallbacks* pAllocator,
293 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600294 bool skip = false;
295
296 for (uint32_t i = 0; i < swapchainCount; i++) {
297 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700298 skip |= LogWarning(
299 device, kVUID_BestPractices_SharingModeExclusive,
300 "Warning: A shared swapchain (index %" PRIu32
301 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
302 "queues (queueFamilyIndexCount of %" PRIu32 ").",
303 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600304 }
305 }
306
307 return skip;
308}
309
310bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500311 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600312 bool skip = false;
313
314 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
315 VkFormat format = pCreateInfo->pAttachments[i].format;
316 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
317 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
318 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700319 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
320 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
321 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
322 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
323 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600324 }
325 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700326 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
327 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
328 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
329 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
330 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600331 }
332 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000333
334 const auto& attachment = pCreateInfo->pAttachments[i];
335 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
336 bool access_requires_memory =
337 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
338
339 if (FormatHasStencil(format)) {
340 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
341 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
342 }
343
344 if (access_requires_memory) {
345 skip |= LogPerformanceWarning(
346 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
347 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
348 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
349 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
350 i, static_cast<uint32_t>(attachment.samples));
351 }
352 }
Camden5b184be2019-08-13 07:50:19 -0600353 }
354
355 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
356 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
357 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
358 }
359
360 return skip;
361}
362
Tony-LunarG767180f2020-04-23 14:03:59 -0600363bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
364 const VkImageView* image_views) const {
365 bool skip = false;
366
367 // Check for non-transient attachments that should be transient and vice versa
368 for (uint32_t i = 0; i < attachmentCount; ++i) {
369 auto& attachment = rpci->pAttachments[i];
370 bool attachment_should_be_transient =
371 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
372
373 if (FormatHasStencil(attachment.format)) {
374 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
375 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
376 }
377
378 auto view_state = GetImageViewState(image_views[i]);
379 if (view_state) {
380 auto& ivci = view_state->create_info;
381 auto& ici = GetImageState(ivci.image)->createInfo;
382
383 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
384
385 // The check for an image that should not be transient applies to all GPUs
386 if (!attachment_should_be_transient && image_is_transient) {
387 skip |= LogPerformanceWarning(
388 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
389 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
390 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
391 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
392 i);
393 }
394
395 bool supports_lazy = false;
396 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
397 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
398 supports_lazy = true;
399 }
400 }
401
402 // The check for an image that should be transient only applies to GPUs supporting
403 // lazily allocated memory
404 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
405 skip |= LogPerformanceWarning(
406 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
407 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
408 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
409 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
410 i);
411 }
412 }
413 }
414 return skip;
415}
416
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000417bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
418 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
419 bool skip = false;
420
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000421 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Tony-LunarG767180f2020-04-23 14:03:59 -0600422 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
423 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000424 }
425
426 return skip;
427}
428
Sam Wallse746d522020-03-16 21:20:23 +0000429bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
430 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
431 bool skip = false;
432 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
433
434 if (!skip) {
435 const auto& pool_handle = pAllocateInfo->descriptorPool;
436 auto iter = descriptor_pool_freed_count.find(pool_handle);
437 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
438 // this warning is specific to Arm
439 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
440 skip |= LogPerformanceWarning(
441 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
442 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
443 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
444 VendorSpecificTag(kBPVendorArm));
445 }
446 }
447
448 return skip;
449}
450
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600451void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
452 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000453 if (result == VK_SUCCESS) {
454 // find the free count for the pool we allocated into
455 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
456 if (iter != descriptor_pool_freed_count.end()) {
457 // we record successful allocations by subtracting the allocation count from the last recorded free count
458 const auto alloc_count = pAllocateInfo->descriptorSetCount;
459 // clamp the unsigned subtraction to the range [0, last_free_count]
460 if (iter->second > alloc_count)
461 iter->second -= alloc_count;
462 else
463 iter->second = 0;
464 }
465 }
466}
467
468void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
469 const VkDescriptorSet* pDescriptorSets, VkResult result) {
470 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
471 if (result == VK_SUCCESS) {
472 // we want to track frees because we're interested in suggesting re-use
473 auto iter = descriptor_pool_freed_count.find(descriptorPool);
474 if (iter == descriptor_pool_freed_count.end()) {
475 descriptor_pool_freed_count.insert(std::make_pair(descriptorPool, descriptorSetCount));
476 } else {
477 iter->second += descriptorSetCount;
478 }
479 }
480}
481
Camden5b184be2019-08-13 07:50:19 -0600482bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500483 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600484 bool skip = false;
485
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500486 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700487 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
488 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600489 }
490
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000491 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
492 skip |= LogPerformanceWarning(
493 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
494 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %llu. This is a very small allocation (current "
495 "threshold is %llu bytes). "
496 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
497 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
498 }
499
Camden83a9c372019-08-14 11:41:38 -0600500 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
501
502 return skip;
503}
504
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600505void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
506 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
507 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700508 if (result != VK_SUCCESS) {
509 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
510 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
511 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR};
512 static std::vector<VkResult> success_codes = {};
513 ValidateReturnCodes("vkReleaseFullScreenExclusiveModeEXT", result, error_codes, success_codes);
514 return;
515 }
516 num_mem_objects++;
517}
Camden Stocker9738af92019-10-16 13:54:03 -0700518
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600519void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
520 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700521 auto error = std::find(error_codes.begin(), error_codes.end(), result);
522 if (error != error_codes.end()) {
Mark Lobodzinski629defa2020-04-29 12:00:23 -0600523 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700524 return;
525 }
526 auto success = std::find(success_codes.begin(), success_codes.end(), result);
527 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600528 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
529 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500530 }
531}
532
Jeff Bolz5c801d12019-10-09 10:38:45 -0500533bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
534 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700535 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600536 bool skip = false;
537
Camden Stocker9738af92019-10-16 13:54:03 -0700538 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600539
540 for (auto& obj : mem_info->obj_bindings) {
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600541 LogObjectList objlist(device);
542 objlist.add(obj);
543 objlist.add(mem_info->mem);
544 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 -0700545 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem).c_str());
Camden83a9c372019-08-14 11:41:38 -0600546 }
547
Camden5b184be2019-08-13 07:50:19 -0600548 return skip;
549}
550
551void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700552 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600553 if (memory != VK_NULL_HANDLE) {
554 num_mem_objects--;
555 }
556}
557
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000558bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600559 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500560 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600561
sfricke-samsunge2441192019-11-06 14:07:57 -0800562 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700563 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
564 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
565 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600566 }
567
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000568 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
569
570 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
571 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
572 skip |= LogPerformanceWarning(
573 device, kVUID_BestPractices_SmallDedicatedAllocation,
574 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
575 "The required size of the allocation is %llu, but smaller buffers like this should be sub-allocated from "
576 "larger memory blocks. (Current threshold is %llu bytes.)",
577 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
578 }
579
Camden Stockerb603cc82019-09-03 10:09:02 -0600580 return skip;
581}
582
583bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500584 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600585 bool skip = false;
586 const char* api_name = "BindBufferMemory()";
587
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000588 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600589
590 return skip;
591}
592
593bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500594 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600595 char api_name[64];
596 bool skip = false;
597
598 for (uint32_t i = 0; i < bindInfoCount; i++) {
599 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000600 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600601 }
602
603 return skip;
604}
Camden Stockerb603cc82019-09-03 10:09:02 -0600605
606bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500607 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600608 char api_name[64];
609 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600610
Camden Stocker8b798ab2019-09-03 10:33:28 -0600611 for (uint32_t i = 0; i < bindInfoCount; i++) {
612 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000613 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600614 }
615
616 return skip;
617}
618
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000619bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600620 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500621 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600622
sfricke-samsung71bc6572020-04-29 15:49:43 -0700623 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700624 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
625 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
626 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
627 api_name, report_data->FormatHandle(image).c_str());
628 }
629 } else {
630 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
631 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600632 }
633
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000634 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
635
636 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
637 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
638 skip |= LogPerformanceWarning(
639 device, kVUID_BestPractices_SmallDedicatedAllocation,
640 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
641 "The required size of the allocation is %llu, but smaller images like this should be sub-allocated from "
642 "larger memory blocks. (Current threshold is %llu bytes.)",
643 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
644 }
645
646 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
647 // make sure this type is actually used.
648 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
649 // (i.e.most tile - based renderers)
650 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
651 bool supports_lazy = false;
652 uint32_t suggested_type = 0;
653
654 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
655 if ((1u << i) & image_state->requirements.memoryTypeBits) {
656 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
657 supports_lazy = true;
658 suggested_type = i;
659 break;
660 }
661 }
662 }
663
664 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
665
666 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
667 skip |= LogPerformanceWarning(
668 device, kVUID_BestPractices_NonLazyTransientImage,
669 "%s: Attempting to bind memory type % u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
670 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
671 "%llu bytes of physical memory.",
672 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
673 }
674 }
675
Camden Stocker8b798ab2019-09-03 10:33:28 -0600676 return skip;
677}
678
679bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500680 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600681 bool skip = false;
682 const char* api_name = "vkBindImageMemory()";
683
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000684 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600685
686 return skip;
687}
688
689bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500690 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600691 char api_name[64];
692 bool skip = false;
693
694 for (uint32_t i = 0; i < bindInfoCount; i++) {
695 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Tony-LunarG5e60b852020-04-27 11:27:54 -0600696 if (!lvl_find_in_chain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
697 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
698 }
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 Lobodzinski84101d72020-04-24 09:43:48 -0600842void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -0600843 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
844 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
845 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
846 LogPerformanceWarning(
847 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
848 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
849 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
850 "targets. Applications should query updated surface information and recreate their swapchain at the next "
851 "convenient opportunity.",
852 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
853 }
854 }
855}
856
Jeff Bolz5c801d12019-10-09 10:38:45 -0500857bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
858 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -0600859 bool skip = false;
860
861 for (uint32_t submit = 0; submit < submitCount; submit++) {
862 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
863 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
864 }
865 }
866
867 return skip;
868}
869
Attilio Provenzano746e43e2020-02-27 11:23:50 +0000870bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
871 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
872 bool skip = false;
873
874 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
875 skip |= LogPerformanceWarning(
876 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
877 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
878 "pool instead.");
879 }
880
881 return skip;
882}
883
884bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
885 const VkCommandBufferBeginInfo* pBeginInfo) const {
886 bool skip = false;
887
888 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
889 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
890 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
891 }
892
Attilio Provenzano02859b22020-02-27 14:17:28 +0000893 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
894 skip |= VendorCheckEnabled(kBPVendorArm) &&
895 LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
896 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
897 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
898 VendorSpecificTag(kBPVendorArm));
899 }
900
Attilio Provenzano746e43e2020-02-27 11:23:50 +0000901 return skip;
902}
903
Jeff Bolz5c801d12019-10-09 10:38:45 -0500904bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -0600905 bool skip = false;
906
907 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
908
909 return skip;
910}
911
Jeff Bolz5c801d12019-10-09 10:38:45 -0500912bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
913 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -0600914 bool skip = false;
915
916 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
917
918 return skip;
919}
920
921bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
922 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
923 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
924 uint32_t bufferMemoryBarrierCount,
925 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
926 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500927 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -0600928 bool skip = false;
929
930 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
931 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
932
933 return skip;
934}
935
936bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
937 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
938 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
939 uint32_t bufferMemoryBarrierCount,
940 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
941 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500942 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -0600943 bool skip = false;
944
945 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
946 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
947
948 return skip;
949}
950
951bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500952 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -0600953 bool skip = false;
954
955 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", pipelineStage);
956
957 return skip;
958}
959
Attilio Provenzano02859b22020-02-27 14:17:28 +0000960static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
961 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
962 auto& subpassInfo = createInfo.pSubpasses[subpass];
963
964 // If an attachment is ever used as a color attachment,
965 // resolve attachment or depth stencil attachment,
966 // it needs to exist on tile at some point.
967
968 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
969 if (subpassInfo.pColorAttachments[i].attachment == attachment) return true;
970
971 if (subpassInfo.pResolveAttachments) {
972 for (uint32_t i = 0; i < subpassInfo.colorAttachmentCount; i++)
973 if (subpassInfo.pResolveAttachments[i].attachment == attachment) return true;
974 }
975
976 if (subpassInfo.pDepthStencilAttachment && subpassInfo.pDepthStencilAttachment->attachment == attachment) return true;
977 }
978
979 return false;
980}
981
982bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
983 const VkRenderPassBeginInfo* pRenderPassBegin) const {
984 bool skip = false;
985
986 if (!pRenderPassBegin) {
987 return skip;
988 }
989
990 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
991 if (rp_state) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600992 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR) {
993 const VkRenderPassAttachmentBeginInfo* rpabi =
994 lvl_find_in_chain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
995 if (rpabi) {
996 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
997 }
998 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000999 // Check if any attachments have LOAD operation on them
1000 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1001 auto& attachment = rp_state->createInfo.pAttachments[att];
1002
1003 bool attachmentHasReadback = false;
1004 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1005 attachmentHasReadback = true;
1006 }
1007
1008 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1009 attachmentHasReadback = true;
1010 }
1011
1012 bool attachmentNeedsReadback = false;
1013
1014 // Check if the attachment is actually used in any subpass on-tile
1015 if (attachmentHasReadback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1016 attachmentNeedsReadback = true;
1017 }
1018
1019 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
1020 if (attachmentNeedsReadback) {
1021 skip |= VendorCheckEnabled(kBPVendorArm) &&
1022 LogPerformanceWarning(
1023 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1024 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1025 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1026 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1027 VendorSpecificTag(kBPVendorArm), att,
1028 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1029 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1030 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
1031 }
1032 }
1033 }
1034
1035 return skip;
1036}
1037
1038bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1039 VkSubpassContents contents) const {
1040 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1041 return skip;
1042}
1043
1044bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1045 const VkRenderPassBeginInfo* pRenderPassBegin,
1046 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
1047 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1048 return skip;
1049}
1050
1051bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1052 const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const {
1053 bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1054 return skip;
1055}
1056
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001057// Generic function to handle validation for all CmdDraw* type functions
1058bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1059 bool skip = false;
1060 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1061 if (cb_state) {
1062 const auto last_bound_it = cb_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1063 const PIPELINE_STATE* pipeline_state = nullptr;
1064 if (last_bound_it != cb_state->lastBound.cend()) {
1065 pipeline_state = last_bound_it->second.pipeline_state;
1066 }
1067 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
1068 // Verify vertex binding
1069 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1070 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001071 skip |= LogPerformanceWarning(cb_state->commandBuffer, kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
1072 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
1073 report_data->FormatHandle(cb_state->commandBuffer).c_str(),
1074 report_data->FormatHandle(pipeline_state->pipeline).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001075 }
1076 }
1077 }
1078 return skip;
1079}
1080
Camden5b184be2019-08-13 07:50:19 -06001081bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001082 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001083 bool skip = false;
1084
1085 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001086 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1087 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001088 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001089 }
1090
1091 return skip;
1092}
1093
1094bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001095 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001096 bool skip = false;
1097
1098 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001099 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1100 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001101 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001102 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1103
Attilio Provenzano02859b22020-02-27 14:17:28 +00001104 // Check if we reached the limit for small indexed draw calls.
1105 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1106 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1107 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
1108 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1)) {
1109 skip |= VendorCheckEnabled(kBPVendorArm) &&
1110 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
1111 "The command buffer contains many small indexed drawcalls "
1112 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1113 "You can try batching drawcalls or instancing when applicable.",
1114 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1115 }
1116
Sam Walls8e77e4f2020-03-16 20:47:40 +00001117 if (VendorCheckEnabled(kBPVendorArm)) {
1118 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1119 }
1120
1121 return skip;
1122}
1123
1124bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1125 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1126 bool skip = false;
1127
1128 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1129 const auto* cmd_state = GetCBState(commandBuffer);
1130 if (cmd_state == nullptr) return skip;
1131
1132 const auto* ib_state = GetBufferState(cmd_state->index_buffer_binding.buffer);
1133 if (ib_state == nullptr) return skip;
1134
1135 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1136 const auto& ib_mem_state = *ib_state->binding.mem_state;
1137 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1138 const void* ib_mem = ib_mem_state.p_driver_data;
1139 bool primitive_restart_enable = false;
1140
1141 const auto& pipeline_binding_iter = cmd_state->lastBound.find(VK_PIPELINE_BIND_POINT_GRAPHICS);
1142
1143 if (pipeline_binding_iter != cmd_state->lastBound.end()) {
1144 const auto* pipeline_state = pipeline_binding_iter->second.pipeline_state;
1145 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr)
1146 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
1147 }
1148
1149 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
1150 if (ib_mem && pipeline_binding_iter != cmd_state->lastBound.end()) {
1151 uint32_t scan_stride;
1152 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1153 scan_stride = sizeof(uint8_t);
1154 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1155 scan_stride = sizeof(uint16_t);
1156 } else {
1157 scan_stride = sizeof(uint32_t);
1158 }
1159
1160 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1161 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1162
1163 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1164 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1165 // irrespective of whether or not they're part of the draw call.
1166
1167 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1168 uint32_t min_index = ~0u;
1169 // start with maximum as 0 and adjust to indices in the buffer
1170 uint32_t max_index = 0u;
1171
1172 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1173 // for the given index buffer
1174 uint32_t vertex_shade_count = 0;
1175
1176 PostTransformLRUCacheModel post_transform_cache;
1177
1178 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1179 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1180 // target architecture.
1181 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1182 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1183 post_transform_cache.resize(32);
1184
1185 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1186 uint32_t scan_index;
1187 uint32_t primitive_restart_value;
1188 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1189 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1190 primitive_restart_value = 0xFF;
1191 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1192 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1193 primitive_restart_value = 0xFFFF;
1194 } else {
1195 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1196 primitive_restart_value = 0xFFFFFFFF;
1197 }
1198
1199 max_index = std::max(max_index, scan_index);
1200 min_index = std::min(min_index, scan_index);
1201
1202 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1203 bool in_cache = post_transform_cache.query_cache(scan_index);
1204 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1205 if (!in_cache) vertex_shade_count++;
1206 }
1207 }
1208
1209 // if the max and min values were not set, then we either have no indices, or all primitive restarts, exit...
1210 if (max_index < min_index) return skip;
1211
1212 if (max_index - min_index >= indexCount) {
1213 skip |= LogPerformanceWarning(
1214 device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1215 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1216 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1217 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1218 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1219 VendorSpecificTag(kBPVendorArm), (static_cast<float>(indexCount) / (max_index - min_index)) * 100.0f);
1220 return skip;
1221 }
1222
1223 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1224 // each bit of the n-th bucket contains the inclusion information for indices (n*n_buckets) to ((n+1)*n_buckets)
1225 const size_t n_buckets = 64;
1226 std::vector<std::bitset<n_buckets>> vertex_reference_buckets;
1227 vertex_reference_buckets.resize((max_index - min_index + 1) / n_buckets);
1228
1229 // To avoid using too much memory, we run over the indices again.
1230 // Knowing the size from the last scan allows us to record index usage with bitsets
1231 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1232 uint32_t scan_index;
1233 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1234 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1235 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1236 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1237 } else {
1238 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1239 }
1240 // keep track of the set of all indices used to reference vertices in the draw call
1241 size_t index_offset = scan_index - min_index;
1242 size_t bitset_bucket_index = index_offset / n_buckets;
1243 uint64_t used_indices = 1ull << ((index_offset % n_buckets) & 0xFFFFFFFFu);
1244 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1245 }
1246
1247 uint32_t vertex_reference_count = 0;
1248 for (const auto& bitset : vertex_reference_buckets) {
1249 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1250 }
1251
1252 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
1253 float utilization = static_cast<float>(vertex_reference_count) / (max_index - min_index + 1);
1254 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
1255 float cache_hit_rate = static_cast<float>(vertex_reference_count) / vertex_shade_count;
1256
1257 if (utilization < 0.5f) {
1258 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1259 "%s The indices which were specified for the draw call only utilise approximately "
1260 "%.02f%% of the bound vertex buffer.",
1261 VendorSpecificTag(kBPVendorArm), utilization);
1262 }
1263
1264 if (cache_hit_rate <= 0.5f) {
1265 skip |=
1266 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1267 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1268 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1269 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1270 "recently shaded vertices.",
1271 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1272 }
1273 }
1274
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001275 return skip;
1276}
1277
Attilio Provenzano02859b22020-02-27 14:17:28 +00001278void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1279 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1280 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1281 firstInstance);
1282
1283 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1284 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1285 cmd_state->small_indexed_draw_call_count++;
1286 }
1287}
1288
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001289bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1290 VkDeviceSize offset, VkBuffer countBuffer,
1291 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1292 uint32_t stride) const {
1293 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001294
1295 return skip;
1296}
1297
1298bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001299 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001300 bool skip = false;
1301
1302 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001303 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1304 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001305 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001306 }
1307
1308 return skip;
1309}
1310
1311bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001312 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06001313 bool skip = false;
1314
1315 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001316 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
1317 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001318 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06001319 }
1320
1321 return skip;
1322}
1323
1324bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001325 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06001326 bool skip = false;
1327
1328 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001329 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
1330 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
1331 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
1332 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06001333 }
1334
1335 return skip;
1336}
Camden83a9c372019-08-14 11:41:38 -06001337
Camden Stocker9c051442019-11-06 14:28:43 -08001338bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
1339 const char* api_name) const {
1340 bool skip = false;
1341 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1342
1343 if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001344 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
1345 "Potential problem with calling %s() without first retrieving properties from "
1346 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
1347 api_name);
Camden Stocker9c051442019-11-06 14:28:43 -08001348 }
1349
1350 return skip;
1351}
1352
Camden83a9c372019-08-14 11:41:38 -06001353bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001354 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06001355 bool skip = false;
1356
Camden Stocker9c051442019-11-06 14:28:43 -08001357 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06001358
Camden Stocker9c051442019-11-06 14:28:43 -08001359 return skip;
1360}
1361
1362bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
1363 uint32_t planeIndex,
1364 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
1365 bool skip = false;
1366
1367 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
1368
1369 return skip;
1370}
1371
1372bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
1373 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
1374 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
1375 bool skip = false;
1376
1377 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06001378
1379 return skip;
1380}
Camden05de2d42019-08-19 10:23:56 -06001381
1382bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001383 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06001384 bool skip = false;
1385
1386 auto swapchain_state = GetSwapchainState(swapchain);
1387
1388 if (swapchain_state && pSwapchainImages) {
1389 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
1390 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001391 skip |=
1392 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
1393 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
1394 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06001395 }
1396 }
1397
1398 return skip;
1399}
1400
1401// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001402bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
1403 uint32_t requested_queue_family_property_count,
1404 bool qfp_null, const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06001405 bool skip = false;
1406 if (!qfp_null) {
1407 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
1408 if (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001409 skip |= LogWarning(
1410 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
Camden05de2d42019-08-19 10:23:56 -06001411 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is recommended "
1412 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
1413 caller_name, caller_name);
1414 // Then verify that pCount that is passed in on second call matches what was returned
1415 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001416 skip |= LogWarning(
1417 pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
Camden05de2d42019-08-19 10:23:56 -06001418 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
1419 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
1420 ". It is recommended to instead receive all the properties by calling %s with pQueueFamilyPropertyCount that was "
1421 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
1422 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name, caller_name);
1423 }
1424 }
1425
1426 return skip;
1427}
1428
Jeff Bolz5c801d12019-10-09 10:38:45 -05001429bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
1430 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06001431 bool skip = false;
1432
1433 for (uint32_t i = 0; i < bindInfoCount; i++) {
1434 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureState(pBindInfos[i].accelerationStructure);
1435 if (!as_state->memory_requirements_checked) {
1436 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
1437 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
1438 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001439 skip |= LogWarning(
1440 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06001441 "vkBindAccelerationStructureMemoryNV(): "
1442 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
1443 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
1444 }
1445 }
1446
1447 return skip;
1448}
1449
Camden05de2d42019-08-19 10:23:56 -06001450bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
1451 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001452 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001453 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1454 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001455 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001456 (nullptr == pQueueFamilyProperties),
1457 "vkGetPhysicalDeviceQueueFamilyProperties()");
1458}
1459
Jeff Bolz5c801d12019-10-09 10:38:45 -05001460bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(
1461 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1462 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001463 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1464 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001465 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001466 (nullptr == pQueueFamilyProperties),
1467 "vkGetPhysicalDeviceQueueFamilyProperties2()");
1468}
1469
Jeff Bolz5c801d12019-10-09 10:38:45 -05001470bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
1471 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount,
1472 VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06001473 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1474 assert(physical_device_state);
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001475 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
Camden05de2d42019-08-19 10:23:56 -06001476 (nullptr == pQueueFamilyProperties),
1477 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
1478}
1479
1480bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
1481 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001482 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06001483 if (!pSurfaceFormats) return false;
1484 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
1485 const auto& call_state = physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
1486 bool skip = false;
1487 if (call_state == UNCALLED) {
1488 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
1489 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001490 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
1491 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
1492 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06001493 } else {
1494 auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size();
Peter Chene191bd72019-09-16 13:04:37 -04001495 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001496 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
1497 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
1498 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
1499 "when pSurfaceFormatCount was NULL.",
1500 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06001501 }
1502 }
1503 return skip;
1504}
Camden Stocker23cc47d2019-09-03 14:53:57 -06001505
1506bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001507 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001508 bool skip = false;
1509
1510 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1511 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1512 // 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 -05001513 std::unordered_set<const IMAGE_STATE*> sparse_images;
1514 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
1515 // in RecordQueueBindSparse.
1516 std::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06001517 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
1518 for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) {
1519 const auto& image_bind = bindInfo.pImageBinds[i];
1520 auto image_state = GetImageState(image_bind.image);
1521 if (!image_state)
1522 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1523 sparse_images.insert(image_state);
1524 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1525 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1526 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001527 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1528 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1529 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1530 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001531 }
1532 }
1533 if (!image_state->memory_requirements_checked) {
1534 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001535 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1536 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
1537 "vkGetImageMemoryRequirements() to retrieve requirements.",
1538 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001539 }
1540 }
1541 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1542 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1543 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1544 if (!image_state)
1545 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1546 sparse_images.insert(image_state);
1547 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
1548 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
1549 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001550 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1551 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1552 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
1553 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001554 }
1555 }
1556 if (!image_state->memory_requirements_checked) {
1557 // For now just warning if sparse image binding occurs without calling to get reqs first
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001558 skip |= LogWarning(image_state->image, kVUID_Core_MemTrack_InvalidState,
1559 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
1560 "vkGetImageMemoryRequirements() to retrieve requirements.",
1561 report_data->FormatHandle(image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001562 }
1563 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1564 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001565 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06001566 }
1567 }
1568 }
1569 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001570 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
1571 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06001572 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001573 skip |= LogWarning(sparse_image_state->image, kVUID_Core_MemTrack_InvalidState,
1574 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
1575 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
1576 report_data->FormatHandle(sparse_image_state->image).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06001577 }
1578 }
1579 }
1580
1581 return skip;
1582}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001583
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001584void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
1585 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001586 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07001587 return;
1588 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05001589
1590 for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; bindIdx++) {
1591 const VkBindSparseInfo& bindInfo = pBindInfo[bindIdx];
1592 for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) {
1593 const auto& image_opaque_bind = bindInfo.pImageOpaqueBinds[i];
1594 auto image_state = GetImageState(bindInfo.pImageOpaqueBinds[i].image);
1595 if (!image_state)
1596 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
1597 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
1598 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
1599 image_state->sparse_metadata_bound = true;
1600 }
1601 }
1602 }
1603 }
1604}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001605
1606bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06001607 const VkClearAttachment* pAttachments, uint32_t rectCount,
1608 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001609 bool skip = false;
1610 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
1611 if (!cb_node) return skip;
1612
Camden Stockerf55721f2019-09-09 11:04:49 -06001613 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001614 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
1615 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
1616 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
1617 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
1618 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001619 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
1620 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
1621 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
1622 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001623 }
1624
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001625 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
1626 // as it can be more efficient to just use LOAD_OP_CLEAR
1627 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass;
1628 if (rp) {
1629 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
1630
1631 for (uint32_t i = 0; i < attachmentCount; i++) {
1632 auto& attachment = pAttachments[i];
1633 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
1634 uint32_t color_attachment = attachment.colorAttachment;
1635 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
1636
1637 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1638 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1639 skip |= LogPerformanceWarning(
1640 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1641 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
1642 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1643 "it is more efficient.",
1644 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
1645 }
1646 }
1647 }
1648
1649 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1650 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1651
1652 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1653 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1654 skip |= LogPerformanceWarning(
1655 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1656 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
1657 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1658 "it is more efficient.",
1659 report_data->FormatHandle(commandBuffer).c_str());
1660 }
1661 }
1662 }
1663
1664 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1665 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
1666
1667 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
1668 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
1669 skip |= LogPerformanceWarning(
1670 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
1671 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
1672 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
1673 "it is more efficient.",
1674 report_data->FormatHandle(commandBuffer).c_str());
1675 }
1676 }
1677 }
1678 }
1679 }
1680
Camden Stockerf55721f2019-09-09 11:04:49 -06001681 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07001682}
Attilio Provenzano02859b22020-02-27 14:17:28 +00001683
1684bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
1685 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
1686 const VkImageResolve* pRegions) const {
1687 bool skip = false;
1688
1689 skip |= VendorCheckEnabled(kBPVendorArm) &&
1690 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
1691 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
1692 "This is a very slow and extremely bandwidth intensive path. "
1693 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
1694 VendorSpecificTag(kBPVendorArm));
1695
1696 return skip;
1697}
1698
1699bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
1700 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
1701 bool skip = false;
1702
1703 if (VendorCheckEnabled(kBPVendorArm)) {
1704 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
1705 skip |= LogPerformanceWarning(
1706 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
1707 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
1708 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
1709 "image) are actually used. If you need different wrapping modes, disregard this warning.",
1710 VendorSpecificTag(kBPVendorArm));
1711 }
1712
1713 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
1714 skip |= LogPerformanceWarning(
1715 device, kVUID_BestPractices_CreateSampler_LodClamping,
1716 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
1717 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
1718 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
1719 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
1720 }
1721
1722 if (pCreateInfo->mipLodBias != 0.0f) {
1723 skip |=
1724 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
1725 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
1726 "descriptors being created and may cause reduced performance.",
1727 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
1728 }
1729
1730 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
1731 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
1732 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
1733 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
1734 skip |= LogPerformanceWarning(
1735 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
1736 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
1737 "This will lead to less efficient descriptors being created and may cause reduced performance. "
1738 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
1739 VendorSpecificTag(kBPVendorArm));
1740 }
1741
1742 if (pCreateInfo->unnormalizedCoordinates) {
1743 skip |= LogPerformanceWarning(
1744 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
1745 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
1746 "descriptors being created and may cause reduced performance.",
1747 VendorSpecificTag(kBPVendorArm));
1748 }
1749
1750 if (pCreateInfo->anisotropyEnable) {
1751 skip |= LogPerformanceWarning(
1752 device, kVUID_BestPractices_CreateSampler_Anisotropy,
1753 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
1754 "and may cause reduced performance.",
1755 VendorSpecificTag(kBPVendorArm));
1756 }
1757 }
1758
1759 return skip;
1760}
Sam Walls8e77e4f2020-03-16 20:47:40 +00001761
1762void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
1763
1764bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
1765 // look for a cache hit
1766 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
1767 if (hit != _entries.end()) {
1768 // mark the cache hit as being most recently used
1769 hit->age = iteration++;
1770 return true;
1771 }
1772
1773 // if there's no cache hit, we need to model the entry being inserted into the cache
1774 CacheEntry new_entry = {value, iteration};
1775 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
1776 // if there is still space left in the cache, use the next available slot
1777 *(_entries.begin() + iteration) = new_entry;
1778 } else {
1779 // otherwise replace the least recently used cache entry
1780 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
1781 *lru = new_entry;
1782 }
1783 iteration++;
1784 return false;
1785}