blob: 911c736a239640056245f3b63f27319274764941 [file] [log] [blame]
Jeremy Gebben610d3a62022-01-01 12:53:17 -07001/* Copyright (c) 2015-2022 The Khronos Group Inc.
2 * Copyright (c) 2015-2022 Valve Corporation
3 * Copyright (c) 2015-2022 LunarG, Inc.
Nadav Geva41c12a22021-05-21 13:14:05 -04004 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
Camdeneaa86ea2019-07-26 11:00:09 -06005 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Camden Stocker <camden@lunarg.com>
Nadav Geva41c12a22021-05-21 13:14:05 -040019 * Author: Nadav Geva <nadav.geva@amd.com>
Camdeneaa86ea2019-07-26 11:00:09 -060020 */
21
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070022#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060023#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060024#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010025#include "shader_validation.h"
Jeremy Gebbena3705f42021-01-19 16:47:43 -070026#include "sync_utils.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060027#include "cmd_buffer_state.h"
28#include "device_state.h"
29#include "render_pass_state.h"
Camden5b184be2019-08-13 07:50:19 -060030
31#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000032#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010033#include <memory>
Camden5b184be2019-08-13 07:50:19 -060034
Attilio Provenzano19d6a982020-02-27 12:41:41 +000035struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060036 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000037 std::string name;
38};
39
LawG475463092022-02-22 10:45:54 +000040const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {{kBPVendorArm, {vendor_specific_arm, "Arm"}},
41 {kBPVendorAMD, {vendor_specific_amd, "AMD"}},
Rodrigo Locattic779cb32022-02-25 19:26:31 -030042 {kBPVendorIMG, {vendor_specific_img, "IMG"}},
43 {kBPVendorNVIDIA, {vendor_specific_nvidia, "NVIDIA"}}};
Attilio Provenzano19d6a982020-02-27 12:41:41 +000044
Hannes Harnisch607d1d92021-07-10 18:44:56 +020045const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
48 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
49 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
50 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
51};
52
53const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
56 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
57 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
58 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
59};
60
Rodrigo Locattie4c08a02022-04-04 18:12:18 -030061static constexpr std::array<VkFormat, 12> kCustomClearColorCompressedFormatsNVIDIA = {
62 VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_A8B8G8R8_UNORM_PACK32,
63 VK_FORMAT_A2R10G10B10_UNORM_PACK32, VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_R16G16B16A16_UNORM,
64 VK_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_UINT, VK_FORMAT_R16G16B16A16_SINT,
65 VK_FORMAT_R16G16B16A16_SFLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32,
66};
67
Jeremy Gebben20da7a12022-02-25 14:07:46 -070068ReadLockGuard BestPractices::ReadLock() {
69 if (fine_grained_locking) {
70 return ReadLockGuard(validation_object_mutex, std::defer_lock);
71 } else {
72 return ReadLockGuard(validation_object_mutex);
73 }
74}
75
76WriteLockGuard BestPractices::WriteLock() {
77 if (fine_grained_locking) {
78 return WriteLockGuard(validation_object_mutex, std::defer_lock);
79 } else {
80 return WriteLockGuard(validation_object_mutex);
81 }
82}
83
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060084std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
85 const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060086 const COMMAND_POOL_STATE* pool) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -070087 return std::static_pointer_cast<CMD_BUFFER_STATE>(std::make_shared<bp_state::CommandBuffer>(this, cb, pCreateInfo, pool));
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060088}
89
Jeremy Gebben20da7a12022-02-25 14:07:46 -070090bp_state::CommandBuffer::CommandBuffer(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
91 const COMMAND_POOL_STATE* pool)
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060092 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
93
Attilio Provenzano19d6a982020-02-27 12:41:41 +000094bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070095 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060096 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000097 return true;
98 }
99 }
100 return false;
101}
102
103const char* VendorSpecificTag(BPVendorFlags vendors) {
104 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700105 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +0000106
107 auto res = tag_map.find(vendors);
108 if (res == tag_map.end()) {
109 // Build the vendor tag string
110 std::stringstream vendor_tag;
111
112 vendor_tag << "[";
113 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700114 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +0000115 if (vendors & vendor.first) {
116 if (!first_vendor) {
117 vendor_tag << ", ";
118 }
119 vendor_tag << vendor.second.name;
120 first_vendor = false;
121 }
122 }
123 vendor_tag << "]";
124
125 tag_map[vendors] = vendor_tag.str();
126 res = tag_map.find(vendors);
127 }
128
129 return res->second.c_str();
130}
131
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700132const char* DepReasonToString(ExtDeprecationReason reason) {
133 switch (reason) {
134 case kExtPromoted:
135 return "promoted to";
136 break;
137 case kExtObsoleted:
138 return "obsoleted by";
139 break;
140 case kExtDeprecated:
141 return "deprecated by";
142 break;
143 default:
144 return "";
145 break;
146 }
147}
148
149bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
150 const char* vuid) const {
151 bool skip = false;
152 auto dep_info_it = deprecated_extensions.find(extension_name);
153 if (dep_info_it != deprecated_extensions.end()) {
154 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600155 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
Tony-LunarGc30b59f2022-02-15 11:02:36 -0700156 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2)) ||
157 ((dep_info.target.compare("VK_VERSION_1_3") == 0) && (version >= VK_API_VERSION_1_3))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700158 skip |=
159 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
160 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600161 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700162 if (dep_info.target.length() == 0) {
163 skip |= LogWarning(instance, vuid,
164 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
165 "without replacement.",
166 api_name, extension_name);
167 } else {
168 skip |= LogWarning(instance, vuid,
169 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
170 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
171 }
172 }
173 }
174 return skip;
175}
176
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200177bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
178{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700179 bool skip = false;
180 auto dep_info_it = special_use_extensions.find(extension_name);
181
182 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200183 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
184 "and it is strongly recommended that it be otherwise avoided.";
185 auto& special_uses = dep_info_it->second;
sfricke-samsungef15e482022-01-26 11:32:49 -0800186
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700187 if (special_uses.find("cadsupport") != std::string::npos) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800188 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
189 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700190 }
191 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200192 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
193 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700194 }
195 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200196 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
197 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700198 }
199 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200200 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
201 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700202 }
203 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200204 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700205 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200206 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700207 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700208 }
209 return skip;
210}
211
Camden5b184be2019-08-13 07:50:19 -0600212bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500213 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600214 bool skip = false;
215
216 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
217 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800218 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700219 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
220 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600221 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600222 uint32_t specified_version =
223 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
224 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700225 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200226 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600227 }
228
229 return skip;
230}
231
Camden5b184be2019-08-13 07:50:19 -0600232bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500233 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600234 bool skip = false;
235
236 // get API version of physical device passed when creating device.
237 VkPhysicalDeviceProperties physical_device_properties{};
238 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500239 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600240
241 // check api versions and warn if instance api Version is higher than version on device.
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600242 if (api_version > device_api_version) {
243 std::string inst_api_name = StringAPIVersion(api_version);
Mark Lobodzinski60880782020-08-11 08:02:07 -0600244 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600245
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700246 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
247 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
248 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600249 }
250
Rodrigo Locattic2d5cf42022-03-01 18:05:26 -0300251 std::vector<std::string> extensions;
252 {
253 uint32_t property_count = 0;
254 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, nullptr) == VK_SUCCESS) {
255 std::vector<VkExtensionProperties> property_list(property_count);
256 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, property_list.data()) == VK_SUCCESS) {
257 extensions.reserve(property_list.size());
258 for (const VkExtensionProperties& properties : property_list) {
259 extensions.push_back(properties.extensionName);
260 }
261 }
262 }
263 }
264
Camden5b184be2019-08-13 07:50:19 -0600265 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300266 const char *extension_name = pCreateInfo->ppEnabledExtensionNames[i];
267
268 if (white_list(extension_name, kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800269 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700270 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300271 extension_name);
Camden5b184be2019-08-13 07:50:19 -0600272 }
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300273
274 skip |= ValidateDeprecatedExtensions("CreateDevice", extension_name, api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700275 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300276 skip |= ValidateSpecialUseExtensions("CreateDevice", extension_name, kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600277 }
278
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700279 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600280 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700281 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
282 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600283 }
284
LawG43f848c72022-02-23 09:35:21 +0000285 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorIMG)) &&
286 (pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
Szilard Papp7d2c7952020-06-22 14:38:13 +0100287 skip |= LogPerformanceWarning(
288 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
LawG4015be1c2022-03-01 10:37:52 +0000289 "%s %s %s: vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100290 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
291 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
292 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
LawG43f848c72022-02-23 09:35:21 +0000293 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorIMG));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100294 }
295
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300296 const bool enabled_pageable_device_local_memory = IsExtEnabled(device_extensions.vk_ext_pageable_device_local_memory);
297 if (VendorCheckEnabled(kBPVendorNVIDIA) && !enabled_pageable_device_local_memory &&
298 std::find(extensions.begin(), extensions.end(), VK_EXT_PAGEABLE_DEVICE_LOCAL_MEMORY_EXTENSION_NAME) != extensions.end()) {
299 skip |= LogPerformanceWarning(
300 device, kVUID_BestPractices_CreateDevice_PageableDeviceLocalMemory,
301 "%s vkCreateDevice() called without pageable device local memory. "
302 "Use pageableDeviceLocalMemory from VK_EXT_pageable_device_local_memory when it is available.",
303 VendorSpecificTag(kBPVendorNVIDIA));
304 }
305
Camden5b184be2019-08-13 07:50:19 -0600306 return skip;
307}
308
309bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500310 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600311 bool skip = false;
312
313 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700314 std::stringstream buffer_hex;
315 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600316
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700317 skip |= LogWarning(
318 device, kVUID_BestPractices_SharingModeExclusive,
319 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
320 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700321 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600322 }
323
324 return skip;
325}
326
327bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500328 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600329 bool skip = false;
330
331 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700332 std::stringstream image_hex;
333 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600334
335 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700336 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
337 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
338 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700339 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600340 }
341
ziga-lunarg6df3d102022-03-18 17:02:14 +0100342 if ((pCreateInfo->flags & VK_IMAGE_CREATE_EXTENDED_USAGE_BIT) && !(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
343 skip |= LogWarning(device, kVUID_BestPractices_ImageCreateFlags,
344 "vkCreateImage(): pCreateInfo->flags has VK_IMAGE_CREATE_EXTENDED_USAGE_BIT set, but not "
345 "VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, therefore image views created from this image will have to use the "
346 "same format and VK_IMAGE_CREATE_EXTENDED_USAGE_BIT will not have any effect.");
347 }
348
LawG4655f59c2022-02-23 13:55:55 +0000349 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000350 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
351 skip |= LogPerformanceWarning(
352 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
LawG4655f59c2022-02-23 13:55:55 +0000353 "%s %s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
Attilio Provenzano02859b22020-02-27 14:17:28 +0000354 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
355 "and do not need to be backed by physical storage. "
356 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
LawG4655f59c2022-02-23 13:55:55 +0000357 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Attilio Provenzano02859b22020-02-27 14:17:28 +0000358 }
359 }
360
LawG4ba113892022-02-23 14:39:02 +0000361 if (VendorCheckEnabled(kBPVendorArm) && pCreateInfo->samples > kMaxEfficientSamplesArm) {
362 skip |= LogPerformanceWarning(
363 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
364 "%s vkCreateImage(): Trying to create an image with %u samples. "
365 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
366 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
367 }
368
369 if (VendorCheckEnabled(kBPVendorIMG) && pCreateInfo->samples > kMaxEfficientSamplesImg) {
370 skip |= LogPerformanceWarning(
371 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
372 "%s vkCreateImage(): Trying to create an image with %u samples. "
373 "The device may not have full support for true multisampling for images with more than %u samples. "
374 "XT devices support up to 8 samples, XE up to 4 samples.",
375 VendorSpecificTag(kBPVendorIMG), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesImg);
376 }
377
LawG4db16f802022-03-21 17:33:39 +0000378 if (VendorCheckEnabled(kBPVendorIMG) && (pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ||
379 pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ||
380 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ||
381 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ||
382 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG ||
383 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG ||
384 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG ||
385 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG)) {
386 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Texture_Format_PVRTC_Outdated,
387 "%s vkCreateImage(): Trying to create an image with a PVRTC format. Both PVRTC1 and PVRTC2 "
388 "are slower than standard image formats on PowerVR GPUs, prefer ETC, BC, ASTC, etc.",
389 VendorSpecificTag(kBPVendorIMG));
390 }
391
Nadav Gevaf0808442021-05-21 13:51:25 -0400392 if (VendorCheckEnabled(kBPVendorAMD)) {
393 std::stringstream image_hex;
394 image_hex << "0x" << std::hex << HandleToUint64(pImage);
395
396 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
397 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
398 skip |= LogPerformanceWarning(device,
399 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
400 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
401 "Using a SHARING_MODE_CONCURRENT "
402 "is not recommended with color and depth targets",
403 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
404 }
405
406 if ((pCreateInfo->usage &
407 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
408 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
409 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
410 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
411 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
412 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
413 }
414
415 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
416 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
417 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
418 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
419 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
420 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
421 }
422 }
423
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300424 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
425 std::stringstream image_hex;
426 image_hex << "0x" << std::hex << HandleToUint64(pImage);
427
428 if (pCreateInfo->tiling == VK_IMAGE_TILING_LINEAR) {
429 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateImage_TilingLinear,
430 "%s Performance warning: image (%s) is created with tiling VK_IMAGE_TILING_LINEAR. "
431 "Use VK_IMAGE_TILING_OPTIMAL instead.",
432 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
433 }
Rodrigo Locatti3290c2b2022-03-09 18:25:56 -0300434
435 if (pCreateInfo->format == VK_FORMAT_D32_SFLOAT || pCreateInfo->format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
436 skip |= LogPerformanceWarning(
437 device, kVUID_BestPractices_CreateImage_Depth32Format,
438 "%s Performance warning: image (%s) is created with a 32-bit depth format. Use VK_FORMAT_D24_UNORM_S8_UINT or "
439 "VK_FORMAT_D16_UNORM instead, unless the extra precision is needed.",
440 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
441 }
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300442 }
443
Camden5b184be2019-08-13 07:50:19 -0600444 return skip;
445}
446
447bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500448 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600449 bool skip = false;
450
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600451 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600452 if (bp_pd_state) {
453 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
454 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
455 "vkCreateSwapchainKHR() called before getting surface capabilities from "
456 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
457 }
Camden83a9c372019-08-14 11:41:38 -0600458
Shannon McPherson73e58c82021-03-05 17:14:26 -0700459 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
460 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600461 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
462 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
463 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
464 }
Camden83a9c372019-08-14 11:41:38 -0600465
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600466 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
467 skip |= LogWarning(
468 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
469 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
470 }
Camden83a9c372019-08-14 11:41:38 -0600471 }
472
Camden5b184be2019-08-13 07:50:19 -0600473 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700474 skip |=
475 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600476 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700477 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
478 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600479 }
480
ziga-lunarg79beba62022-03-30 01:17:30 +0200481 const auto present_mode = pCreateInfo->presentMode;
482 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
483 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100484 skip |= LogPerformanceWarning(
485 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
486 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
487 ", which means double buffering is going "
488 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
489 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
490 "3 to use triple buffering to maximize performance in such cases.",
491 pCreateInfo->minImageCount);
492 }
493
Szilard Pappd5f0f812020-06-22 09:01:29 +0100494 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
495 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
496 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
497 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
498 "Presentation modes which are not FIFO will present the latest available frame and discard other "
499 "frame(s) if any.",
500 VendorSpecificTag(kBPVendorArm));
501 }
502
Camden5b184be2019-08-13 07:50:19 -0600503 return skip;
504}
505
506bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
507 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500508 const VkAllocationCallbacks* pAllocator,
509 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600510 bool skip = false;
511
512 for (uint32_t i = 0; i < swapchainCount; i++) {
513 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700514 skip |= LogWarning(
515 device, kVUID_BestPractices_SharingModeExclusive,
516 "Warning: A shared swapchain (index %" PRIu32
517 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
518 "queues (queueFamilyIndexCount of %" PRIu32 ").",
519 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600520 }
521 }
522
523 return skip;
524}
525
526bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500527 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600528 bool skip = false;
529
530 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
531 VkFormat format = pCreateInfo->pAttachments[i].format;
532 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
533 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
534 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700535 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
536 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
537 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
538 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
539 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600540 }
541 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700542 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
543 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
544 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
545 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
546 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600547 }
548 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000549
550 const auto& attachment = pCreateInfo->pAttachments[i];
551 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
552 bool access_requires_memory =
553 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
554
555 if (FormatHasStencil(format)) {
556 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
557 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
558 }
559
560 if (access_requires_memory) {
561 skip |= LogPerformanceWarning(
562 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
563 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
564 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
565 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
566 i, static_cast<uint32_t>(attachment.samples));
567 }
568 }
Camden5b184be2019-08-13 07:50:19 -0600569 }
570
571 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
572 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
573 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
574 }
575
576 return skip;
577}
578
Tony-LunarG767180f2020-04-23 14:03:59 -0600579bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
580 const VkImageView* image_views) const {
581 bool skip = false;
582
583 // Check for non-transient attachments that should be transient and vice versa
584 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200585 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600586 bool attachment_should_be_transient =
587 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
588
589 if (FormatHasStencil(attachment.format)) {
590 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
591 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
592 }
593
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600594 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600595 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600596 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600597
598 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
599
600 // The check for an image that should not be transient applies to all GPUs
601 if (!attachment_should_be_transient && image_is_transient) {
602 skip |= LogPerformanceWarning(
603 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
604 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
605 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
606 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
607 i);
608 }
609
610 bool supports_lazy = false;
611 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
612 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
613 supports_lazy = true;
614 }
615 }
616
617 // The check for an image that should be transient only applies to GPUs supporting
618 // lazily allocated memory
619 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
620 skip |= LogPerformanceWarning(
621 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
622 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
623 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
624 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
625 i);
626 }
627 }
628 }
629 return skip;
630}
631
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000632bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
633 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
634 bool skip = false;
635
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600636 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800637 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600638 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000639 }
640
641 return skip;
642}
643
Sam Wallse746d522020-03-16 21:20:23 +0000644bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
645 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
646 bool skip = false;
647 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
648
649 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700650 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000651 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
652 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700653 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000654 skip |= LogPerformanceWarning(
655 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
656 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
657 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
658 VendorSpecificTag(kBPVendorArm));
659 }
ziga-lunarg5a76c442022-04-17 18:04:08 +0200660
661 if (IsExtEnabled(device_extensions.vk_khr_maintenance1)) {
662 // Track number of descriptorSets allowable in this pool
663 if (pool_state->GetAvailableSets() < pAllocateInfo->descriptorSetCount) {
664 skip |= LogWarning(pool_state->Handle(), kVUID_BestPractices_EmptyDescriptorPool,
665 "vkAllocateDescriptorSets(): Unable to allocate %" PRIu32 " descriptorSets from %s"
666 ". This pool only has %" PRIu32 " descriptorSets remaining.",
667 pAllocateInfo->descriptorSetCount, report_data->FormatHandle(pool_state->Handle()).c_str(),
668 pool_state->GetAvailableSets());
669 }
670 }
Sam Wallse746d522020-03-16 21:20:23 +0000671 }
672
673 return skip;
674}
675
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600676void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
677 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000678 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700679 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
680 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000681 // we record successful allocations by subtracting the allocation count from the last recorded free count
682 const auto alloc_count = pAllocateInfo->descriptorSetCount;
683 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700684 if (pool_state->freed_count > alloc_count) {
685 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700686 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700687 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700688 }
Sam Wallse746d522020-03-16 21:20:23 +0000689 }
690 }
691}
692
693void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
694 const VkDescriptorSet* pDescriptorSets, VkResult result) {
695 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
696 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700697 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000698 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700699 if (pool_state) {
700 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000701 }
702 }
703}
704
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300705void BestPractices::PreCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
706 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) {
707 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
708 WriteLockGuard guard{memory_free_events_lock_};
709
710 // Release old allocations to avoid overpopulating the container
711 const auto now = std::chrono::high_resolution_clock::now();
712 const auto last_old = std::find_if(memory_free_events_.rbegin(), memory_free_events_.rend(), [now](const MemoryFreeEvent& event) {
713 return now - event.time > kAllocateMemoryReuseTimeThresholdNVIDIA;
714 });
715 memory_free_events_.erase(memory_free_events_.begin(), last_old.base());
716 }
717}
718
Camden5b184be2019-08-13 07:50:19 -0600719bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500720 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600721 bool skip = false;
722
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700723 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700724 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
725 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600726 }
727
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000728 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
729 skip |= LogPerformanceWarning(
730 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600731 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
732 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000733 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
734 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
735 }
736
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300737 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
738 if (!device_extensions.vk_ext_pageable_device_local_memory &&
739 !LvlFindInChain<VkMemoryPriorityAllocateInfoEXT>(pAllocateInfo->pNext)) {
740 skip |= LogPerformanceWarning(
741 device, kVUID_BestPractices_AllocateMemory_SetPriority,
742 "%s Use VkMemoryPriorityAllocateInfoEXT to provide the operating system information on the allocations that "
743 "should stay in video memory and which should be demoted first when video memory is limited. "
744 "The highest priority should be given to GPU-written resources like color attachments, depth attachments, "
745 "storage images, and buffers written from the GPU.",
746 VendorSpecificTag(kBPVendorNVIDIA));
747 }
748
749 {
750 // Size in bytes for an allocation to be considered "compatible"
751 static constexpr VkDeviceSize size_threshold = VkDeviceSize{1} << 20;
752
753 ReadLockGuard guard{memory_free_events_lock_};
754
755 const auto now = std::chrono::high_resolution_clock::now();
756 const VkDeviceSize alloc_size = pAllocateInfo->allocationSize;
757 const uint32_t memory_type_index = pAllocateInfo->memoryTypeIndex;
758 const auto latest_event = std::find_if(memory_free_events_.rbegin(), memory_free_events_.rend(), [&](const MemoryFreeEvent& event) {
759 return (memory_type_index == event.memory_type_index) && (alloc_size <= event.allocation_size) &&
760 (alloc_size - event.allocation_size <= size_threshold) && (now - event.time < kAllocateMemoryReuseTimeThresholdNVIDIA);
761 });
762
763 if (latest_event != memory_free_events_.rend()) {
764 const auto time_delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - latest_event->time);
765 if (time_delta < std::chrono::milliseconds{5}) {
766 skip |=
767 LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_ReuseAllocations,
768 "%s Reuse memory allocations instead of releasing and reallocating. A memory allocation "
769 "has just been released, and it could have been reused in place of this allocation.",
770 VendorSpecificTag(kBPVendorNVIDIA));
771 } else {
772 const uint32_t seconds = static_cast<uint32_t>(time_delta.count() / 1000);
773 const uint32_t milliseconds = static_cast<uint32_t>(time_delta.count() % 1000);
774
775 skip |= LogPerformanceWarning(
776 device, kVUID_BestPractices_AllocateMemory_ReuseAllocations,
777 "%s Reuse memory allocations instead of releasing and reallocating. A memory allocation has been released "
778 "%" PRIu32 ".%03" PRIu32 " seconds ago, and it could have been reused in place of this allocation.",
779 VendorSpecificTag(kBPVendorNVIDIA), seconds, milliseconds);
780 }
781 }
782 }
Rodrigo Locattie4f8d522022-03-15 16:30:49 -0300783 }
784
Camden83a9c372019-08-14 11:41:38 -0600785 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
786
787 return skip;
788}
789
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600790void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
791 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
792 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700793 if (result != VK_SUCCESS) {
794 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
795 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800796 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700797 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600798 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700799 return;
800 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700801}
Camden Stocker9738af92019-10-16 13:54:03 -0700802
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600803void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
804 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700805 auto error = std::find(error_codes.begin(), error_codes.end(), result);
806 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000807 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
808 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
809
810 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
811 if (common_failure != common_failure_codes.end()) {
812 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
813 } else {
814 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
815 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700816 return;
817 }
818 auto success = std::find(success_codes.begin(), success_codes.end(), result);
819 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600820 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
821 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500822 }
823}
824
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300825void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
826 if (memory != VK_NULL_HANDLE && VendorCheckEnabled(kBPVendorNVIDIA)) {
827 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
828
829 // Exclude memory free events on dedicated allocations, or imported/exported allocations.
830 if (!mem_info->IsDedicatedBuffer() && !mem_info->IsDedicatedImage() && !mem_info->IsExport() && !mem_info->IsImport()) {
831 MemoryFreeEvent event;
832 event.time = std::chrono::high_resolution_clock::now();
833 event.memory_type_index = mem_info->alloc_info.memoryTypeIndex;
834 event.allocation_size = mem_info->alloc_info.allocationSize;
835
836 WriteLockGuard guard{memory_free_events_lock_};
837 memory_free_events_.push_back(event);
838 }
839 }
840
841 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
842}
843
Jeff Bolz5c801d12019-10-09 10:38:45 -0500844bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
845 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700846 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600847 bool skip = false;
848
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700849 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600850
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700851 for (const auto& item : mem_info->ObjectBindings()) {
852 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600853 LogObjectList objlist(device);
854 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600855 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600856 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600857 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600858 }
859
Camden5b184be2019-08-13 07:50:19 -0600860 return skip;
861}
862
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000863bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600864 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700865 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600866
sfricke-samsunge2441192019-11-06 14:07:57 -0800867 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700868 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
869 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
870 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600871 }
872
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700873 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000874
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300875 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000876 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
877 skip |= LogPerformanceWarning(
878 device, kVUID_BestPractices_SmallDedicatedAllocation,
879 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600880 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
881 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000882 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
883 }
884
Rodrigo Locatti66b23352022-03-15 17:28:32 -0300885 skip |= ValidateBindMemory(device, memory);
886
Camden Stockerb603cc82019-09-03 10:09:02 -0600887 return skip;
888}
889
890bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500891 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600892 bool skip = false;
893 const char* api_name = "BindBufferMemory()";
894
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000895 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600896
897 return skip;
898}
899
900bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500901 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600902 char api_name[64];
903 bool skip = false;
904
905 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200906 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000907 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600908 }
909
910 return skip;
911}
Camden Stockerb603cc82019-09-03 10:09:02 -0600912
913bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500914 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600915 char api_name[64];
916 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600917
Camden Stocker8b798ab2019-09-03 10:33:28 -0600918 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200919 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000920 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600921 }
922
923 return skip;
924}
925
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000926bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600927 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700928 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600929
sfricke-samsung71bc6572020-04-29 15:49:43 -0700930 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600931 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700932 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
933 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
934 api_name, report_data->FormatHandle(image).c_str());
935 }
936 } else {
937 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
938 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600939 }
940
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700941 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000942
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600943 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000944 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
945 skip |= LogPerformanceWarning(
946 device, kVUID_BestPractices_SmallDedicatedAllocation,
947 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600948 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
949 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000950 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
951 }
952
953 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
954 // make sure this type is actually used.
955 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
956 // (i.e.most tile - based renderers)
957 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
958 bool supports_lazy = false;
959 uint32_t suggested_type = 0;
960
961 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600962 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000963 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
964 supports_lazy = true;
965 suggested_type = i;
966 break;
967 }
968 }
969 }
970
971 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
972
973 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
974 skip |= LogPerformanceWarning(
975 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600976 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000977 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600978 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600979 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000980 }
981 }
982
Rodrigo Locatti66b23352022-03-15 17:28:32 -0300983 skip |= ValidateBindMemory(device, memory);
984
Camden Stocker8b798ab2019-09-03 10:33:28 -0600985 return skip;
986}
987
988bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500989 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600990 bool skip = false;
991 const char* api_name = "vkBindImageMemory()";
992
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000993 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600994
995 return skip;
996}
997
998bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500999 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -06001000 char api_name[64];
1001 bool skip = false;
1002
1003 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +02001004 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001005 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -06001006 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
1007 }
Camden Stocker8b798ab2019-09-03 10:33:28 -06001008 }
1009
1010 return skip;
1011}
1012
1013bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001014 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -06001015 char api_name[64];
1016 bool skip = false;
1017
1018 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +02001019 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +00001020 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -06001021 }
1022
1023 return skip;
1024}
Camden83a9c372019-08-14 11:41:38 -06001025
Rodrigo Locatti66b23352022-03-15 17:28:32 -03001026void BestPractices::PreCallRecordSetDeviceMemoryPriorityEXT(VkDevice device, VkDeviceMemory memory, float priority) {
1027 auto mem_info = std::static_pointer_cast<bp_state::DeviceMemory>(Get<DEVICE_MEMORY_STATE>(memory));
1028 mem_info->dynamic_priority.emplace(priority);
1029}
1030
Attilio Provenzano02859b22020-02-27 14:17:28 +00001031static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
1032 switch (format) {
1033 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
1034 case VK_FORMAT_R16_SFLOAT:
1035 case VK_FORMAT_R16G16_SFLOAT:
1036 case VK_FORMAT_R16G16B16_SFLOAT:
1037 case VK_FORMAT_R16G16B16A16_SFLOAT:
1038 case VK_FORMAT_R32_SFLOAT:
1039 case VK_FORMAT_R32G32_SFLOAT:
1040 case VK_FORMAT_R32G32B32_SFLOAT:
1041 case VK_FORMAT_R32G32B32A32_SFLOAT:
1042 return false;
1043
1044 default:
1045 return true;
1046 }
1047}
1048
1049bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
1050 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
1051 bool skip = false;
1052
1053 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001054 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001055
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001056 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
1057 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
1058 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001059 return skip;
1060 }
1061
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001062 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001063 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001064
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +02001065 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1066 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
1067
1068 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001069 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001070 uint32_t att = subpass.pColorAttachments[j].attachment;
1071
1072 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
1073 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
1074 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
1075 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
1076 "color attachment #%u makes use "
1077 "of a format which cannot be blended at full throughput when using MSAA.",
1078 VendorSpecificTag(kBPVendorArm), i, j);
1079 }
1080 }
1081 }
1082 }
1083
1084 return skip;
1085}
1086
Nadav Gevaf0808442021-05-21 13:51:25 -04001087void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1088 const VkComputePipelineCreateInfo* pCreateInfos,
1089 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1090 VkResult result, void* pipe_state) {
1091 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001092 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -04001093}
1094
Camden5b184be2019-08-13 07:50:19 -06001095bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1096 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001097 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001098 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001099 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1100 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +01001101 if (skip) {
1102 return skip;
1103 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001104 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001105
1106 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001107 skip |= LogPerformanceWarning(
1108 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1109 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
1110 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001111 }
1112
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001113 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001114 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001115
Tony-LunarGb6a2daf2022-07-29 11:30:55 -06001116 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV) && create_info.pVertexInputState) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001117 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001118 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001119 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
1120 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001121 count++;
1122 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001123 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001124 if (count > kMaxInstancedVertexBuffers) {
1125 skip |= LogPerformanceWarning(
1126 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
1127 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
1128 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
1129 count, kMaxInstancedVertexBuffers);
1130 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001131 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001132
Szilard Pappaaf2da32020-06-22 10:37:35 +01001133 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
1134 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001135 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1136 VendorCheckEnabled(kBPVendorArm)) {
1137 skip |= LogPerformanceWarning(
1138 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1139 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1140 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1141 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1142 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1143 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001144 }
1145
Attilio Provenzano02859b22020-02-27 14:17:28 +00001146 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001147 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001148 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001149 auto prev_pipeline = pipeline_cache_.load();
1150 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001151 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001152 "%s %s Performance Warning: A second pipeline cache is in use. "
1153 "Consider using only one pipeline cache to improve cache hit rate.",
1154 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04001155 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001156 }
1157 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001158 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001159 skip |=
1160 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1161 "%s Performance warning: Too many pipelines created, consider consolidation",
1162 VendorSpecificTag(kBPVendorAMD));
1163 }
1164
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001165 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001166 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1167 "%s Performance warning: Use of primitive restart is not recommended",
1168 VendorSpecificTag(kBPVendorAMD));
1169 }
1170
1171 // TODO: this might be too aggressive of a check
1172 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1173 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1174 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1175 VendorSpecificTag(kBPVendorAMD));
1176 }
1177 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001178
Camden5b184be2019-08-13 07:50:19 -06001179 return skip;
1180}
1181
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001182static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1183 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1184 std::vector<bp_state::AttachmentInfo> result;
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06001185 if (!rp || rp->UsesDynamicRendering()) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001186 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001187 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001188
1189 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1190
1191 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1192 // are only non-null if they are enabled.
1193 if (create_info.pColorBlendState) {
1194 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1195 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1196 for (uint32_t j = 0; j < num_color_attachments; j++) {
1197 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1198 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1199 if (attachment != VK_ATTACHMENT_UNUSED) {
1200 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1201 }
1202 }
1203 }
1204 }
1205
1206 if (create_info.pDepthStencilState &&
1207 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1208 create_info.pDepthStencilState->stencilTestEnable)) {
1209 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1210 if (attachment != VK_ATTACHMENT_UNUSED) {
1211 VkImageAspectFlags aspects = 0;
1212 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1213 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1214 }
1215 if (create_info.pDepthStencilState->stencilTestEnable) {
1216 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1217 }
1218 result.push_back({attachment, aspects});
1219 }
1220 }
1221 return result;
1222}
1223
1224bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1225 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1226 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1227 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1228 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1229
1230std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1231 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1232 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1233 return std::static_pointer_cast<PIPELINE_STATE>(
1234 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001235}
1236
Sam Walls0961ec02020-03-31 16:39:15 +01001237void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1238 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1239 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1240 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001241 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001242 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001243}
1244
Camden5b184be2019-08-13 07:50:19 -06001245bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1246 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001247 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001248 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001249 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1250 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001251
1252 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001253 skip |= LogPerformanceWarning(
1254 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1255 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1256 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001257 }
1258
Nadav Gevaf0808442021-05-21 13:51:25 -04001259 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001260 auto prev_pipeline = pipeline_cache_.load();
1261 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1262 skip |= LogPerformanceWarning(
1263 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1264 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001265 "improve cache hit rate",
1266 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001267 }
1268 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001269
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001270 for (uint32_t i = 0; i < createInfoCount; i++) {
1271 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1272 if (VendorCheckEnabled(kBPVendorArm)) {
1273 skip |= ValidateCreateComputePipelineArm(createInfo);
1274 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001275
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001276 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1277 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1278 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1279 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1280 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1281 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1282 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1283 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1284 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001285 }
1286 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001287 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001288 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001289
1290 return skip;
1291}
1292
1293bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1294 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001295 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001296 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001297 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1298 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001299
1300 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001301 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001302
1303 uint32_t thread_count = x * y * z;
1304
1305 // Generate a priori warnings about work group sizes.
1306 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1307 skip |= LogPerformanceWarning(
1308 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1309 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1310 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1311 "groups with less than %u threads, especially when using barrier() or shared memory.",
1312 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1313 }
1314
1315 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1316 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1317 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1318 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1319 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1320 "%u, %u) is not aligned to %u "
1321 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1322 "leave threads idle on the shader "
1323 "core.",
1324 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1325 kThreadGroupDispatchCountAlignmentArm);
1326 }
1327
sfricke-samsungef15e482022-01-26 11:32:49 -08001328 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1329 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001330
1331 unsigned dimensions = 0;
1332 if (x > 1) dimensions++;
1333 if (y > 1) dimensions++;
1334 if (z > 1) dimensions++;
1335 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1336 dimensions = std::max(dimensions, 1u);
1337
1338 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1339 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1340 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1341 bool accesses_2d = false;
1342 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001343 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001344 if (dim < 0) continue;
1345 auto spvdim = spv::Dim(dim);
1346 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1347 }
1348
1349 if (accesses_2d && dimensions < 2) {
1350 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1351 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1352 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1353 "exhibiting poor spatial locality with respect to one or more shader resources.",
1354 VendorSpecificTag(kBPVendorArm), x, y, z);
1355 }
1356
Camden5b184be2019-08-13 07:50:19 -06001357 return skip;
1358}
1359
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001360bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001361 bool skip = false;
1362
1363 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001364 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1365 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001366 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001367 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1368 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001369 }
1370
1371 return skip;
1372}
1373
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001374bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1375 bool skip = false;
1376
1377 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1378 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1379 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1380 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1381 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1382 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1383 }
1384
1385 return skip;
1386}
1387
1388bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1389 bool skip = false;
1390 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1391
1392 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1393 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1394
1395 return skip;
1396}
1397
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001398void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001399 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1400 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1401 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1402 LogPerformanceWarning(
1403 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1404 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1405 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1406 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1407 "convenient opportunity.",
1408 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1409 }
1410 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001411
1412 // AMD best practice
1413 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001414 num_queue_submissions_ = 0;
1415 num_barriers_objects_ = 0;
1416 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001417}
1418
Jeff Bolz5c801d12019-10-09 10:38:45 -05001419bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1420 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001421 bool skip = false;
1422
1423 for (uint32_t submit = 0; submit < submitCount; submit++) {
1424 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1425 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1426 }
ziga-lunargc77f0c02022-04-18 00:15:16 +02001427 if (pSubmits[submit].signalSemaphoreCount == 0 && pSubmits[submit].pSignalSemaphores != nullptr) {
1428 skip |=
1429 LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1430 "pSubmits[%" PRIu32 "].pSignalSemaphores is set, but pSubmits[%" PRIu32 "].signalSemaphoreCount is 0.",
1431 submit, submit);
1432 }
1433 if (pSubmits[submit].waitSemaphoreCount == 0 && pSubmits[submit].pWaitSemaphores != nullptr) {
1434 skip |= LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1435 "pSubmits[%" PRIu32 "].pWaitSemaphores is set, but pSubmits[%" PRIu32 "].waitSemaphoreCount is 0.",
1436 submit, submit);
1437 }
Camden5b184be2019-08-13 07:50:19 -06001438 }
1439
1440 return skip;
1441}
1442
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001443bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1444 VkFence fence) const {
1445 bool skip = false;
1446
1447 for (uint32_t submit = 0; submit < submitCount; submit++) {
1448 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1449 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1450 }
1451 }
1452
1453 return skip;
1454}
1455
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001456bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1457 VkFence fence) const {
1458 bool skip = false;
1459
1460 for (uint32_t submit = 0; submit < submitCount; submit++) {
1461 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1462 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1463 }
1464 }
1465
1466 return skip;
1467}
1468
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001469bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1470 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1471 bool skip = false;
1472
1473 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1474 skip |= LogPerformanceWarning(
1475 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1476 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1477 "pool instead.");
1478 }
1479
1480 return skip;
1481}
1482
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001483void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer,
1484 const VkCommandBufferBeginInfo* pBeginInfo) {
1485 StateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
1486
1487 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
paul-lunarg093c1762022-08-23 18:52:10 +02001488 if (!cb) return;
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001489
1490 cb->num_submits = 0;
1491 cb->is_one_time_submit = (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) != 0;
1492}
1493
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001494bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1495 const VkCommandBufferBeginInfo* pBeginInfo) const {
1496 bool skip = false;
1497
1498 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1499 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1500 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1501 }
1502
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001503 if (VendorCheckEnabled(kBPVendorArm)) {
Rodrigo Locattife5172b2022-03-22 18:49:29 -03001504 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1505 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001506 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1507 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1508 VendorSpecificTag(kBPVendorArm));
1509 }
1510 }
1511 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1512 auto cb = GetRead<bp_state::CommandBuffer>(commandBuffer);
1513 if (cb->num_submits == 1 && !cb->is_one_time_submit) {
1514 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1515 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT was not set "
1516 "and the command buffer has only been submitted once. "
1517 "For best performance on NVIDIA GPUs, use ONE_TIME_SUBMIT.",
1518 VendorSpecificTag(kBPVendorNVIDIA));
Rodrigo Locattife5172b2022-03-22 18:49:29 -03001519 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001520 }
1521
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001522 return skip;
1523}
1524
Jeff Bolz5c801d12019-10-09 10:38:45 -05001525bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001526 bool skip = false;
1527
1528 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1529
1530 return skip;
1531}
1532
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001533bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1534 const VkDependencyInfoKHR* pDependencyInfo) const {
1535 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1536}
1537
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001538bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1539 const VkDependencyInfo* pDependencyInfo) const {
1540 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1541}
1542
Jeff Bolz5c801d12019-10-09 10:38:45 -05001543bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1544 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001545 bool skip = false;
1546
1547 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1548
1549 return skip;
1550}
1551
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001552bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1553 VkPipelineStageFlags2KHR stageMask) const {
1554 bool skip = false;
1555
1556 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1557
1558 return skip;
1559}
1560
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001561bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1562 VkPipelineStageFlags2 stageMask) const {
1563 bool skip = false;
1564
1565 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1566
1567 return skip;
1568}
1569
Camden5b184be2019-08-13 07:50:19 -06001570bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1571 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1572 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1573 uint32_t bufferMemoryBarrierCount,
1574 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1575 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001576 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001577 bool skip = false;
1578
1579 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1580 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1581
1582 return skip;
1583}
1584
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001585bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1586 const VkDependencyInfoKHR* pDependencyInfos) const {
1587 bool skip = false;
1588 for (uint32_t i = 0; i < eventCount; i++) {
1589 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1590 }
1591
1592 return skip;
1593}
1594
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001595bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1596 const VkDependencyInfo* pDependencyInfos) const {
1597 bool skip = false;
1598 for (uint32_t i = 0; i < eventCount; i++) {
1599 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1600 }
1601
1602 return skip;
1603}
1604
Camden5b184be2019-08-13 07:50:19 -06001605bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1606 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1607 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1608 uint32_t bufferMemoryBarrierCount,
1609 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1610 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001611 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001612 bool skip = false;
1613
1614 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1615 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1616
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001617 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1618 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1619 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1620 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1621 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1622 "may be discarded, but the newLayout is %s, which is read only.",
1623 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1624 }
1625 }
1626
Nadav Gevaf0808442021-05-21 13:51:25 -04001627 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001628 auto num = num_barriers_objects_.load();
1629 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001630 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001631 "%s Performance warning: In this frame, %" PRIu32
1632 " barriers were already submitted. Barriers have a high cost and can "
1633 "stall the GPU. "
1634 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1635 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001636 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001637 }
1638 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
1639 static constexpr std::array<VkImageLayout, 3> read_layouts = {
Nadav Gevaf0808442021-05-21 13:51:25 -04001640 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1641 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1642 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1643 };
1644
1645 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1646 // read to read barriers
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001647 const auto &image_barrier = pImageMemoryBarriers[i];
1648 bool old_is_read_layout = std::find(read_layouts.begin(), read_layouts.end(), image_barrier.oldLayout) != read_layouts.end();
1649 bool new_is_read_layout = std::find(read_layouts.begin(), read_layouts.end(), image_barrier.newLayout) != read_layouts.end();
1650
Nadav Gevaf0808442021-05-21 13:51:25 -04001651 if (old_is_read_layout && new_is_read_layout) {
1652 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001653 "%s %s Performance warning: Don't issue read-to-read barriers. "
1654 "Get the resource in the right state the first time you use it.",
1655 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04001656 }
1657
1658 // general with no storage
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001659 if (VendorCheckEnabled(kBPVendorAMD) && image_barrier.newLayout == VK_IMAGE_LAYOUT_GENERAL) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001660 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1661 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1662 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1663 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1664 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1665 VendorSpecificTag(kBPVendorAMD));
1666 }
1667 }
1668 }
1669 }
1670
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001671 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1672 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pImageMemoryBarriers[i]);
1673 }
1674
Camden5b184be2019-08-13 07:50:19 -06001675 return skip;
1676}
1677
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001678bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1679 const VkDependencyInfoKHR* pDependencyInfo) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001680 bool skip = false;
1681
1682 skip |= CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1683
1684 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
1685 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
1686 }
1687
1688 return skip;
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001689}
1690
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001691bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1692 const VkDependencyInfo* pDependencyInfo) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001693 bool skip = false;
1694
1695 skip |= CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1696
1697 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
1698 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
1699 }
1700
1701 return skip;
1702}
1703
1704template <typename ImageMemoryBarrier>
1705bool BestPractices::ValidateCmdPipelineBarrierImageBarrier(VkCommandBuffer commandBuffer,
1706 const ImageMemoryBarrier& barrier) const {
1707
1708 bool skip = false;
1709
Mark Young0a6b48f2022-08-18 11:17:02 -06001710 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
1711 assert(cmd_state);
1712
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001713 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1714 if (barrier.oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && barrier.newLayout != VK_IMAGE_LAYOUT_UNDEFINED) {
Mark Young0a6b48f2022-08-18 11:17:02 -06001715 skip |= ValidateZcull(*cmd_state, barrier.image, barrier.subresourceRange);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001716 }
1717 }
1718
1719 return skip;
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001720}
1721
Camden5b184be2019-08-13 07:50:19 -06001722bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001723 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001724 bool skip = false;
1725
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001726 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1727
1728 return skip;
1729}
1730
1731bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1732 VkQueryPool queryPool, uint32_t query) const {
1733 bool skip = false;
1734
1735 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001736
1737 return skip;
1738}
1739
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001740bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1741 VkQueryPool queryPool, uint32_t query) const {
1742 bool skip = false;
1743
1744 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1745
1746 return skip;
1747}
1748
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001749void BestPractices::PreCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1750 VkPipeline pipeline) {
1751 StateTracker::PreCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1752
1753 auto pipeline_info = Get<PIPELINE_STATE>(pipeline);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001754 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001755
1756 assert(pipeline_info);
1757 assert(cb);
1758
1759 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS && VendorCheckEnabled(kBPVendorNVIDIA)) {
1760 using TessGeometryMeshState = bp_state::CommandBufferStateNV::TessGeometryMesh::State;
1761 auto& tgm = cb->nv.tess_geometry_mesh;
1762
1763 // Make sure the message is only signaled once per command buffer
1764 tgm.threshold_signaled = tgm.num_switches >= kNumBindPipelineTessGeometryMeshSwitchesThresholdNVIDIA;
1765
1766 // Track pipeline switches with tessellation, geometry, and/or mesh shaders enabled, and disabled
1767 auto tgm_stages = VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT |
1768 VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_TASK_BIT_NV | VK_SHADER_STAGE_MESH_BIT_NV;
1769 auto new_tgm_state = (pipeline_info->active_shaders & tgm_stages) != 0
1770 ? TessGeometryMeshState::Enabled
1771 : TessGeometryMeshState::Disabled;
1772 if (tgm.state != new_tgm_state && tgm.state != TessGeometryMeshState::Unknown) {
1773 tgm.num_switches++;
1774 }
1775 tgm.state = new_tgm_state;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001776
1777 // Track depthTestEnable and depthCompareOp
1778 auto &pipeline_create_info = pipeline_info->GetCreateInfo<VkGraphicsPipelineCreateInfo>();
1779 auto depth_stencil_state = pipeline_create_info.pDepthStencilState;
1780 auto dynamic_state = pipeline_create_info.pDynamicState;
1781 if (depth_stencil_state && dynamic_state) {
1782 auto dynamic_state_begin = dynamic_state->pDynamicStates;
1783 auto dynamic_state_end = dynamic_state->pDynamicStates + dynamic_state->dynamicStateCount;
1784
1785 bool dynamic_depth_test_enable = std::find(dynamic_state_begin, dynamic_state_end, VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE) != dynamic_state_end;
1786 bool dynamic_depth_func = std::find(dynamic_state_begin, dynamic_state_end, VK_DYNAMIC_STATE_DEPTH_COMPARE_OP) != dynamic_state_end;
1787
1788 if (!dynamic_depth_test_enable) {
1789 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depth_stencil_state->depthTestEnable != VK_FALSE);
1790 }
1791 if (!dynamic_depth_func) {
1792 RecordSetDepthTestState(*cb, depth_stencil_state->depthCompareOp, cb->nv.depth_test_enable);
1793 }
1794 }
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001795 }
1796}
1797
Sam Walls0961ec02020-03-31 16:39:15 +01001798void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1799 VkPipeline pipeline) {
1800 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1801
Nadav Gevaf0808442021-05-21 13:51:25 -04001802 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001803 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001804
Sam Walls0961ec02020-03-31 16:39:15 +01001805 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001806 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001807 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001808 if (pipeline_state) {
1809 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001810 assert(cb_node);
1811 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001812
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001813 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001814 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001815
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001816 const auto* blend_state = pipeline_state->ColorBlendState();
1817 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001818
1819 if (blend_state) {
1820 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001821 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001822 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1823 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001824 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001825 }
1826 }
1827 }
1828
1829 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001830 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001831
1832 if (stencil_state && stencil_state->depthTestEnable) {
1833 switch (stencil_state->depthCompareOp) {
1834 case VK_COMPARE_OP_EQUAL:
1835 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1836 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001837 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001838 break;
1839 default:
1840 break;
1841 }
1842 }
Sam Walls0961ec02020-03-31 16:39:15 +01001843 }
1844 }
1845}
1846
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001847void BestPractices::PreCallRecordCmdSetDepthCompareOp(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) {
1848 StateTracker::PreCallRecordCmdSetDepthCompareOp(commandBuffer, depthCompareOp);
1849
1850 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1851 assert(cb);
1852
1853 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1854 RecordSetDepthTestState(*cb, depthCompareOp, cb->nv.depth_test_enable);
1855 }
1856}
1857
1858void BestPractices::PreCallRecordCmdSetDepthCompareOpEXT(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) {
1859 StateTracker::PreCallRecordCmdSetDepthCompareOpEXT(commandBuffer, depthCompareOp);
1860
1861 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1862 assert(cb);
1863
1864 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1865 RecordSetDepthTestState(*cb, depthCompareOp, cb->nv.depth_test_enable);
1866 }
1867}
1868
1869void BestPractices::PreCallRecordCmdSetDepthTestEnable(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) {
1870 StateTracker::PreCallRecordCmdSetDepthTestEnable(commandBuffer, depthTestEnable);
1871
1872 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1873 assert(cb);
1874
1875 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1876 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depthTestEnable != VK_FALSE);
1877 }
1878}
1879
1880void BestPractices::PreCallRecordCmdSetDepthTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) {
1881 StateTracker::PreCallRecordCmdSetDepthTestEnableEXT(commandBuffer, depthTestEnable);
1882
1883 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1884 assert(cb);
1885
1886 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1887 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depthTestEnable != VK_FALSE);
1888 }
1889}
1890
1891void BestPractices::RecordSetDepthTestState(bp_state::CommandBuffer& cmd_state, VkCompareOp new_depth_compare_op, bool new_depth_test_enable) {
1892 assert(VendorCheckEnabled(kBPVendorNVIDIA));
1893
1894 if (cmd_state.nv.depth_compare_op != new_depth_compare_op) {
1895 switch (new_depth_compare_op) {
1896 case VK_COMPARE_OP_LESS:
1897 case VK_COMPARE_OP_LESS_OR_EQUAL:
1898 cmd_state.nv.zcull_direction = bp_state::CommandBufferStateNV::ZcullDirection::Less;
1899 break;
1900 case VK_COMPARE_OP_GREATER:
1901 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1902 cmd_state.nv.zcull_direction = bp_state::CommandBufferStateNV::ZcullDirection::Greater;
1903 break;
1904 default:
1905 // The other ops carry over the previous state.
1906 break;
1907 }
1908 }
1909 cmd_state.nv.depth_compare_op = new_depth_compare_op;
1910 cmd_state.nv.depth_test_enable = new_depth_test_enable;
1911}
1912
1913void BestPractices::RecordCmdBeginRenderingCommon(VkCommandBuffer commandBuffer) {
1914 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1915 assert(cmd_state);
1916
1917 auto rp = cmd_state->activeRenderPass.get();
1918 assert(rp);
1919
1920 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1921 std::shared_ptr<IMAGE_VIEW_STATE> depth_image_view_shared_ptr;
1922 IMAGE_VIEW_STATE* depth_image_view = nullptr;
1923 layer_data::optional<VkAttachmentLoadOp> load_op;
1924
1925 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
1926 const auto depth_attachment = rp->dynamic_rendering_begin_rendering_info.pDepthAttachment;
1927 if (depth_attachment) {
1928 load_op.emplace(depth_attachment->loadOp);
1929 depth_image_view_shared_ptr = Get<IMAGE_VIEW_STATE>(depth_attachment->imageView);
1930 depth_image_view = depth_image_view_shared_ptr.get();
1931 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03001932
1933 for (uint32_t i = 0; i < rp->dynamic_rendering_begin_rendering_info.colorAttachmentCount; ++i) {
1934 const auto& color_attachment = rp->dynamic_rendering_begin_rendering_info.pColorAttachments[i];
1935 if (color_attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1936 const VkFormat format = Get<IMAGE_VIEW_STATE>(color_attachment.imageView)->create_info.format;
1937 RecordClearColor(format, color_attachment.clearValue.color);
1938 }
1939 }
1940
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001941 } else {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03001942 if (rp->createInfo.pAttachments) {
1943 if (rp->createInfo.subpassCount > 0) {
1944 const auto depth_attachment = rp->createInfo.pSubpasses[0].pDepthStencilAttachment;
1945 if (depth_attachment) {
1946 const uint32_t attachment_index = depth_attachment->attachment;
1947 if (attachment_index != VK_ATTACHMENT_UNUSED) {
1948 load_op.emplace(rp->createInfo.pAttachments[attachment_index].loadOp);
1949 depth_image_view = (*cmd_state->active_attachments)[attachment_index];
1950 }
1951 }
1952 }
1953 for (uint32_t i = 0; i < cmd_state->activeRenderPassBeginInfo.clearValueCount; ++i) {
1954 const auto& attachment = rp->createInfo.pAttachments[i];
1955 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1956 const auto& clear_color = cmd_state->activeRenderPassBeginInfo.pClearValues[i].color;
1957 RecordClearColor(attachment.format, clear_color);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001958 }
1959 }
1960 }
1961 }
1962 if (depth_image_view && (depth_image_view->create_info.subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U) {
1963 const VkImage depth_image = depth_image_view->image_state->image();
1964 const VkImageSubresourceRange& subresource_range = depth_image_view->create_info.subresourceRange;
1965 RecordBindZcullScope(*cmd_state, depth_image, subresource_range);
1966 } else {
1967 RecordUnbindZcullScope(*cmd_state);
1968 }
1969 if (load_op) {
1970 if (*load_op == VK_ATTACHMENT_LOAD_OP_CLEAR || *load_op == VK_ATTACHMENT_LOAD_OP_DONT_CARE) {
1971 RecordResetScopeZcullDirection(*cmd_state);
1972 }
1973 }
1974 }
1975}
1976
1977void BestPractices::RecordCmdEndRenderingCommon(VkCommandBuffer commandBuffer) {
1978 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1979 assert(cmd_state);
1980
1981 auto rp = cmd_state->activeRenderPass.get();
1982 assert(rp);
1983
1984 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1985 layer_data::optional<VkAttachmentStoreOp> store_op;
1986
1987 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
1988 const auto depth_attachment = rp->dynamic_rendering_begin_rendering_info.pDepthAttachment;
1989 if (depth_attachment) {
1990 store_op.emplace(depth_attachment->storeOp);
1991 }
1992 } else {
1993 if (rp->createInfo.subpassCount > 0) {
1994 const uint32_t last_subpass = rp->createInfo.subpassCount - 1;
1995 const auto depth_attachment = rp->createInfo.pSubpasses[last_subpass].pDepthStencilAttachment;
1996 if (depth_attachment) {
1997 const uint32_t attachment = depth_attachment->attachment;
1998 if (attachment != VK_ATTACHMENT_UNUSED) {
1999 store_op.emplace(rp->createInfo.pAttachments[attachment].storeOp);
2000 }
2001 }
2002 }
2003 }
2004
2005 if (store_op) {
2006 if (*store_op == VK_ATTACHMENT_STORE_OP_DONT_CARE || *store_op == VK_ATTACHMENT_STORE_OP_NONE) {
2007 RecordResetScopeZcullDirection(*cmd_state);
2008 }
2009 }
2010
2011 RecordUnbindZcullScope(*cmd_state);
2012 }
2013}
2014
2015void BestPractices::RecordBindZcullScope(bp_state::CommandBuffer& cmd_state, VkImage depth_attachment, const VkImageSubresourceRange& subresource_range) {
2016 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2017
2018 if (depth_attachment == VK_NULL_HANDLE) {
2019 cmd_state.nv.zcull_scope = {};
2020 return;
2021 }
2022
2023 assert((subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U);
2024
2025 auto image_state = Get<IMAGE_STATE>(depth_attachment);
2026 assert(image_state);
2027
2028 const uint32_t mip_levels = image_state->createInfo.mipLevels;
2029 const uint32_t array_layers = image_state->createInfo.arrayLayers;
2030
2031 auto& tree = cmd_state.nv.zcull_per_image[depth_attachment];
2032 if (tree.states.empty()) {
2033 tree.mip_levels = mip_levels;
2034 tree.array_layers = array_layers;
2035 tree.states.resize(array_layers * mip_levels);
2036 }
2037
2038 cmd_state.nv.zcull_scope.image = depth_attachment;
2039 cmd_state.nv.zcull_scope.range = subresource_range;
2040 cmd_state.nv.zcull_scope.tree = &tree;
2041}
2042
2043void BestPractices::RecordUnbindZcullScope(bp_state::CommandBuffer& cmd_state) {
2044 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2045
2046 RecordBindZcullScope(cmd_state, VK_NULL_HANDLE, VkImageSubresourceRange{});
2047}
2048
2049void BestPractices::RecordResetScopeZcullDirection(bp_state::CommandBuffer& cmd_state) {
2050 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2051
2052 auto& scope = cmd_state.nv.zcull_scope;
2053 RecordResetZcullDirection(cmd_state, scope.image, scope.range);
2054}
2055
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002056template <typename Func>
2057static void ForEachSubresource(const IMAGE_STATE& image, const VkImageSubresourceRange& range, Func&& func)
2058{
2059 const uint32_t layerCount = (range.layerCount == VK_REMAINING_ARRAY_LAYERS) ? image.full_range.layerCount : range.layerCount;
2060 const uint32_t levelCount = (range.levelCount == VK_REMAINING_MIP_LEVELS) ? image.full_range.levelCount : range.levelCount;
2061
2062 for (uint32_t i = 0; i < layerCount; ++i) {
2063 const uint32_t layer = range.baseArrayLayer + i;
2064 for (uint32_t j = 0; j < levelCount; ++j) {
2065 const uint32_t level = range.baseMipLevel + j;
2066 func(layer, level);
2067 }
2068 }
2069}
2070
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002071void BestPractices::RecordResetZcullDirection(bp_state::CommandBuffer& cmd_state, VkImage depth_image,
2072 const VkImageSubresourceRange& subresource_range) {
2073 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2074
2075 RecordSetZcullDirection(cmd_state, depth_image, subresource_range, bp_state::CommandBufferStateNV::ZcullDirection::Unknown);
2076
2077 const auto image_it = cmd_state.nv.zcull_per_image.find(depth_image);
2078 if (image_it == cmd_state.nv.zcull_per_image.end()) {
2079 return;
2080 }
2081 auto& tree = image_it->second;
2082
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002083 auto image = Get<IMAGE_STATE>(depth_image);
2084 if (!image) return;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002085
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002086 ForEachSubresource(*image, subresource_range, [&tree](uint32_t layer, uint32_t level) {
2087 auto& subresource = tree.GetState(layer, level);
2088 subresource.num_less_draws = 0;
2089 subresource.num_greater_draws = 0;
2090 });
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002091}
2092
2093void BestPractices::RecordSetScopeZcullDirection(bp_state::CommandBuffer& cmd_state, bp_state::CommandBufferStateNV::ZcullDirection mode) {
2094 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2095
2096 auto& scope = cmd_state.nv.zcull_scope;
2097 RecordSetZcullDirection(cmd_state, scope.image, scope.range, mode);
2098}
2099
2100void BestPractices::RecordSetZcullDirection(bp_state::CommandBuffer& cmd_state, VkImage depth_image,
2101 const VkImageSubresourceRange& subresource_range,
2102 bp_state::CommandBufferStateNV::ZcullDirection mode) {
2103 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2104
2105 const auto image_it = cmd_state.nv.zcull_per_image.find(depth_image);
2106 if (image_it == cmd_state.nv.zcull_per_image.end()) {
2107 return;
2108 }
2109 auto& tree = image_it->second;
2110
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002111 auto image = Get<IMAGE_STATE>(depth_image);
2112 if (!image) return;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002113
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002114 ForEachSubresource(*image, subresource_range, [&tree, &cmd_state](uint32_t layer, uint32_t level) {
2115 tree.GetState(layer, level).direction = cmd_state.nv.zcull_direction;
2116 });
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002117}
2118
2119void BestPractices::RecordZcullDraw(bp_state::CommandBuffer& cmd_state) {
2120 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2121
2122 // Add one draw to each subresource depending on the current Z-cull direction
2123 auto& scope = cmd_state.nv.zcull_scope;
2124
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002125 auto image = Get<IMAGE_STATE>(scope.image);
2126 if (!image) return;
2127
2128 ForEachSubresource(*image, scope.range, [&scope](uint32_t layer, uint32_t level) {
2129 auto& subresource = scope.tree->GetState(layer, level);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002130
2131 switch (subresource.direction) {
2132 case bp_state::CommandBufferStateNV::ZcullDirection::Unknown:
2133 // Unreachable
2134 assert(0);
2135 break;
2136 case bp_state::CommandBufferStateNV::ZcullDirection::Less:
2137 ++subresource.num_less_draws;
2138 break;
2139 case bp_state::CommandBufferStateNV::ZcullDirection::Greater:
2140 ++subresource.num_greater_draws;
2141 break;
2142 }
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002143 });
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002144}
2145
Mark Young0a6b48f2022-08-18 11:17:02 -06002146bool BestPractices::ValidateZcullScope(const bp_state::CommandBuffer& cmd_state) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002147 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2148
2149 bool skip = false;
2150
Mark Young0a6b48f2022-08-18 11:17:02 -06002151 if (cmd_state.nv.depth_test_enable) {
2152 auto& scope = cmd_state.nv.zcull_scope;
2153 skip |= ValidateZcull(cmd_state, scope.image, scope.range);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002154 }
2155
2156 return skip;
2157}
2158
Mark Young0a6b48f2022-08-18 11:17:02 -06002159bool BestPractices::ValidateZcull(const bp_state::CommandBuffer& cmd_state, VkImage image,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002160 const VkImageSubresourceRange& subresource_range) const {
2161 bool skip = false;
2162
2163 const char* good_mode = nullptr;
2164 const char* bad_mode = nullptr;
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002165 bool is_balanced = false;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002166
Mark Young0a6b48f2022-08-18 11:17:02 -06002167 const auto image_it = cmd_state.nv.zcull_per_image.find(image);
2168 if (image_it == cmd_state.nv.zcull_per_image.end()) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002169 return skip;
2170 }
2171 const auto& tree = image_it->second;
2172
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002173 auto image_state = Get<IMAGE_STATE>(image);
2174 if (!image_state) {
2175 return skip;
2176 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002177
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002178 ForEachSubresource(*image_state, subresource_range, [&](uint32_t layer, uint32_t level) {
2179 if (is_balanced) {
2180 return;
2181 }
2182 const auto& resource = tree.GetState(layer, level);
2183 const uint64_t num_draws = resource.num_less_draws + resource.num_greater_draws;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002184
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002185 if (num_draws == 0) {
2186 return;
2187 }
2188 const uint64_t less_ratio = (resource.num_less_draws * 100) / num_draws;
2189 const uint64_t greater_ratio = (resource.num_greater_draws * 100) / num_draws;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002190
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002191 if ((less_ratio > kZcullDirectionBalanceRatioNVIDIA) && (greater_ratio > kZcullDirectionBalanceRatioNVIDIA)) {
2192 is_balanced = true;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002193
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002194 if (greater_ratio > less_ratio) {
2195 good_mode = "GREATER";
2196 bad_mode = "LESS";
2197 } else {
2198 good_mode = "LESS";
2199 bad_mode = "GREATER";
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002200 }
2201 }
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002202 });
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002203
2204 if (is_balanced) {
2205 skip |= LogPerformanceWarning(
Mark Young0a6b48f2022-08-18 11:17:02 -06002206 cmd_state.commandBuffer(), kVUID_BestPractices_Zcull_LessGreaterRatio,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002207 "%s Depth attachment %s is primarily rendered with depth compare op %s, but some draws use %s. "
2208 "Z-cull is disabled for the least used direction, which harms depth testing performance. "
2209 "The Z-cull direction can be reset by clearing the depth attachment, transitioning from VK_IMAGE_LAYOUT_UNDEFINED, "
2210 "using VK_ATTACHMENT_LOAD_OP_DONT_CARE, or using VK_ATTACHMENT_STORE_OP_DONT_CARE.",
Mark Young0a6b48f2022-08-18 11:17:02 -06002211 VendorSpecificTag(kBPVendorNVIDIA), report_data->FormatHandle(cmd_state.nv.zcull_scope.image).c_str(), good_mode,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002212 bad_mode);
2213 }
2214
2215 return skip;
2216}
2217
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002218static std::array<uint32_t, 4> GetRawClearColor(VkFormat format, const VkClearColorValue& clear_value) {
2219 std::array<uint32_t, 4> raw_color{};
2220 std::copy_n(clear_value.uint32, raw_color.size(), raw_color.data());
2221
2222 // Zero out unused components to avoid polluting the cache with garbage
2223 if (!FormatHasRed(format)) raw_color[0] = 0;
2224 if (!FormatHasGreen(format)) raw_color[1] = 0;
2225 if (!FormatHasBlue(format)) raw_color[2] = 0;
2226 if (!FormatHasAlpha(format)) raw_color[3] = 0;
2227
2228 return raw_color;
2229}
2230
2231static bool IsClearColorZeroOrOne(VkFormat format, const std::array<uint32_t, 4> clear_color) {
2232 static_assert(sizeof(float) == sizeof(uint32_t), "Mismatching float <-> uint32 sizes");
2233 const float one = 1.0f;
2234 const float zero = 0.0f;
2235 uint32_t raw_one{};
2236 uint32_t raw_zero{};
2237 memcpy(&raw_one, &one, sizeof(one));
2238 memcpy(&raw_zero, &zero, sizeof(zero));
2239
2240 const bool is_one = (!FormatHasRed(format) || (clear_color[0] == raw_one)) &&
2241 (!FormatHasGreen(format) || (clear_color[1] == raw_one)) &&
2242 (!FormatHasBlue(format) || (clear_color[2] == raw_one)) &&
2243 (!FormatHasAlpha(format) || (clear_color[3] == raw_one));
2244 const bool is_zero = (!FormatHasRed(format) || (clear_color[0] == raw_zero)) &&
2245 (!FormatHasGreen(format) || (clear_color[1] == raw_zero)) &&
2246 (!FormatHasBlue(format) || (clear_color[2] == raw_zero)) &&
2247 (!FormatHasAlpha(format) || (clear_color[3] == raw_zero));
2248 return is_one || is_zero;
2249}
2250
2251static std::string MakeCompressedFormatListNVIDIA() {
2252 std::string format_list;
2253 for (VkFormat compressed_format : kCustomClearColorCompressedFormatsNVIDIA) {
2254 if (compressed_format == kCustomClearColorCompressedFormatsNVIDIA.back()) {
2255 format_list += "or ";
2256 }
2257 format_list += string_VkFormat(compressed_format);
2258 if (compressed_format != kCustomClearColorCompressedFormatsNVIDIA.back()) {
2259 format_list += ", ";
2260 }
2261 }
2262 return format_list;
2263}
2264
2265void BestPractices::RecordClearColor(VkFormat format, const VkClearColorValue& clear_value) {
2266 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2267
2268 const std::array<uint32_t, 4> raw_color = GetRawClearColor(format, clear_value);
2269 if (IsClearColorZeroOrOne(format, raw_color)) {
2270 // These colors are always compressed
2271 return;
2272 }
2273
2274 const auto it = std::find(kCustomClearColorCompressedFormatsNVIDIA.begin(), kCustomClearColorCompressedFormatsNVIDIA.end(), format);
2275 if (it == kCustomClearColorCompressedFormatsNVIDIA.end()) {
2276 // The format cannot be compressed with a custom color
2277 return;
2278 }
2279
2280 // Record custom clear color
2281 WriteLockGuard guard{clear_colors_lock_};
2282 if (clear_colors_.size() < kMaxRecommendedNumberOfClearColorsNVIDIA) {
2283 clear_colors_.insert(raw_color);
2284 }
2285}
2286
2287bool BestPractices::ValidateClearColor(VkCommandBuffer commandBuffer, VkFormat format, const VkClearColorValue& clear_value) const {
2288 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2289
2290 bool skip = false;
2291
2292 const std::array<uint32_t, 4> raw_color = GetRawClearColor(format, clear_value);
2293 if (IsClearColorZeroOrOne(format, raw_color)) {
2294 return skip;
2295 }
2296
2297 const auto it = std::find(kCustomClearColorCompressedFormatsNVIDIA.begin(), kCustomClearColorCompressedFormatsNVIDIA.end(), format);
2298 if (it == kCustomClearColorCompressedFormatsNVIDIA.end()) {
2299 // The format is not compressible
2300 static const std::string format_list = MakeCompressedFormatListNVIDIA();
2301
2302 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_ClearColor_NotCompressed,
2303 "%s Clearing image with format %s without a 1.0f or 0.0f clear color. "
2304 "The clear will not get compressed in the GPU, harming performance. "
2305 "This can be fixed using a clear color of VkClearColorValue{0.0f, 0.0f, 0.0f, 0.0f}, or "
2306 "VkClearColorValue{1.0f, 1.0f, 1.0f, 1.0f}. Alternatively, use %s.",
2307 VendorSpecificTag(kBPVendorNVIDIA), string_VkFormat(format), format_list.c_str());
2308 } else {
2309 // The format is compressible
2310 bool registered = false;
2311 {
2312 ReadLockGuard guard{clear_colors_lock_};
2313 registered = clear_colors_.find(raw_color) != clear_colors_.end();
2314
2315 if (!registered) {
2316 // If it's not in the list, it might be new. Check if there's still space for new entries.
2317 registered = clear_colors_.size() < kMaxRecommendedNumberOfClearColorsNVIDIA;
2318 }
2319 }
2320 if (!registered) {
2321 std::string clear_color_str;
2322
2323 if (FormatIsUINT(format)) {
2324 clear_color_str = std::to_string(clear_value.uint32[0]) + ", " + std::to_string(clear_value.uint32[1]) + ", " +
2325 std::to_string(clear_value.uint32[2]) + ", " + std::to_string(clear_value.uint32[3]);
2326 } else if (FormatIsSINT(format)) {
2327 clear_color_str = std::to_string(clear_value.int32[0]) + ", " + std::to_string(clear_value.int32[1]) + ", " +
2328 std::to_string(clear_value.int32[2]) + ", " + std::to_string(clear_value.int32[3]);
2329 } else {
2330 clear_color_str = std::to_string(clear_value.float32[0]) + ", " + std::to_string(clear_value.float32[1]) + ", " +
2331 std::to_string(clear_value.float32[2]) + ", " + std::to_string(clear_value.float32[3]);
2332 }
2333
2334 skip |= LogPerformanceWarning(
2335 commandBuffer, kVUID_BestPractices_ClearColor_NotCompressed,
2336 "%s Clearing image with unregistered VkClearColorValue{%s}. "
2337 "This clear will not get compressed in the GPU, harming performance. "
2338 "The clear color is not registered because too many unique colors have been used. "
2339 "Select a discrete set of clear colors and stick to those. "
2340 "VkClearColorValue{0, 0, 0, 0} and VkClearColorValue{1.0f, 1.0f, 1.0f, 1.0f} are always registered.",
2341 VendorSpecificTag(kBPVendorNVIDIA), clear_color_str.c_str());
2342 }
2343 }
2344
2345 return skip;
2346}
2347
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002348static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2349 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
2350 const auto& subpass_info = createInfo.pSubpasses[subpass];
2351 if (subpass_info.pResolveAttachments) {
2352 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2353 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
2354 }
2355 }
2356 }
2357
2358 return false;
2359}
2360
Attilio Provenzano02859b22020-02-27 14:17:28 +00002361static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2362 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002363 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00002364
2365 // If an attachment is ever used as a color attachment,
2366 // resolve attachment or depth stencil attachment,
2367 // it needs to exist on tile at some point.
2368
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002369 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2370 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002371 }
2372
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002373 if (subpass_info.pResolveAttachments) {
2374 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2375 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
2376 }
2377 }
2378
2379 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002380 }
2381
2382 return false;
2383}
2384
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002385static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2386 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
2387 return false;
2388 }
2389
2390 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002391 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002392
2393 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
2394 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
2395 return true;
2396 }
2397 }
2398 }
2399
2400 return false;
2401}
2402
Attilio Provenzano02859b22020-02-27 14:17:28 +00002403bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2404 const VkRenderPassBeginInfo* pRenderPassBegin) const {
2405 bool skip = false;
2406
2407 if (!pRenderPassBegin) {
2408 return skip;
2409 }
2410
Gareth Webbdc6549a2021-06-16 03:52:24 +01002411 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
2412 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
2413 "This render pass has a zero-size render area. It cannot write to any attachments, "
2414 "and can only be used for side effects such as layout transitions.");
2415 }
2416
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002417 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002418 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002419 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07002420 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06002421 if (rpabi) {
2422 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
2423 }
2424 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00002425 // Check if any attachments have LOAD operation on them
2426 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002427 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00002428
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002429 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02002430 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002431 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002432 }
2433
2434 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002435 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002436 }
2437
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002438 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002439
2440 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002441 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2442 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002443 }
2444
2445 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00002446 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
2447 skip |=
2448 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00002449 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00002450 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04002451 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00002452 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
2453 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
2454 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
2455 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
2456 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002457 }
2458 }
paul-lunarg7089e272022-06-20 22:19:37 +02002459
2460 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
2461
2462 bool clearing = false;
2463
2464 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
2465 const auto& attachment = rp_state->createInfo.pAttachments[att];
2466
2467 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2468 clearing = true;
2469 break;
2470 }
2471 }
2472
2473 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
2474 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
2475 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
2476 skip |= LogWarning(
2477 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
2478 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
2479 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02002480 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02002481 }
paul-lunarga0a149c2022-06-23 16:18:51 +02002482
2483 // Check if there are more clearValues than attachments
2484 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
2485 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
2486 // This could signal a bug and there seems to be no reason for this to happen on purpose.
2487 skip |= LogWarning(
2488 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
2489 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
2490 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
2491 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
2492 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002493
2494 if (VendorCheckEnabled(kBPVendorNVIDIA) && rp_state->createInfo.pAttachments) {
2495 for (uint32_t i = 0; i < pRenderPassBegin->clearValueCount; ++i) {
2496 const auto& attachment = rp_state->createInfo.pAttachments[i];
2497 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2498 const auto& clear_color = pRenderPassBegin->pClearValues[i].color;
2499 skip |= ValidateClearColor(commandBuffer, attachment.format, clear_color);
2500 }
2501 }
2502 }
2503 }
2504
2505 return skip;
2506}
2507
2508bool BestPractices::ValidateCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2509 bool skip = false;
2510
2511 auto cmd_state = Get<bp_state::CommandBuffer>(commandBuffer);
2512 assert(cmd_state);
2513
2514 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2515 for (uint32_t i = 0; i < pRenderingInfo->colorAttachmentCount; ++i) {
2516 const auto& color_attachment = pRenderingInfo->pColorAttachments[i];
2517 if (color_attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2518 const VkFormat format = Get<IMAGE_VIEW_STATE>(color_attachment.imageView)->create_info.format;
2519 skip |= ValidateClearColor(commandBuffer, format, color_attachment.clearValue.color);
2520 }
2521 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00002522 }
2523
2524 return skip;
2525}
2526
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002527void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
2528 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002529 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002530 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
2531 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002532 }
2533}
2534
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002535void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2536 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002537 // If we're viewing a 3D slice, ignore base array layer.
2538 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002539 const uint32_t base_array_layer = state->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002540
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002541 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002542 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002543 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
2544 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002545
2546 for (uint32_t layer = 0; layer < array_layers; layer++) {
2547 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002548 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
2549 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002550 }
2551 }
2552}
2553
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002554void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2555 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
2556 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002557 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002558
2559 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002560 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002561 }
2562}
2563
paul-lunarg5eb52062022-06-27 18:57:15 +02002564void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2565 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
2566 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
2567 const CMD_BUFFER_STATE&) -> bool {
2568 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
2569 return false;
2570 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002571}
2572
LawG44d414ba2022-02-23 15:35:41 +00002573void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002574 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002575 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002576 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002577 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002578 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002579 LogPerformanceWarning(
2580 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00002581 "%s %s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002582 "image was used, it was written to with STORE_OP_STORE. "
2583 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
2584 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00002585 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002586 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002587 LogPerformanceWarning(
2588 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00002589 "%s %s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002590 "image was used, it was written to with vkCmdClear*Image(). "
2591 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00002592 "tile-based architectures.",
2593 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002594 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002595 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
2596 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002597 const char *last_cmd = nullptr;
2598 const char *vuid = nullptr;
2599 const char *suggestion = nullptr;
2600
2601 switch (last_usage) {
2602 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
2603 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
2604 last_cmd = "vkCmdBlitImage";
2605 suggestion =
2606 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
2607 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
2608 "which avoids the memory roundtrip.";
2609 break;
2610 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
2611 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
2612 last_cmd = "vkCmdClear*Image";
2613 suggestion =
2614 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
2615 "tile-based architectures. "
2616 "Use LOAD_OP_CLEAR instead to clear the image for free.";
2617 break;
2618 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
2619 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
2620 last_cmd = "vkCmdCopy*Image";
2621 suggestion =
2622 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
2623 "Rather than copying, just render the source image in a fragment shader in this render pass, "
2624 "which avoids the memory roundtrip.";
2625 break;
2626 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
2627 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
2628 last_cmd = "vkCmdResolveImage";
2629 suggestion =
2630 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
2631 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
2632 "which avoids the memory roundtrip.";
2633 break;
2634 default:
2635 break;
2636 }
2637
2638 LogPerformanceWarning(
2639 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00002640 "%s %s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was loaded to tile as part of LOAD_OP_LOAD, but last "
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002641 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00002642 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
2643 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002644 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002645}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002646
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002647void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
2648 uint32_t array_layer, uint32_t mip_level) {
2649 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02002650
2651 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
2652 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
2653 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
2654 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
2655 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
2656 "result in undefined behaviour.");
2657 }
2658
LawG44d414ba2022-02-23 15:35:41 +00002659 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
2660 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002661 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002662}
2663
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002664void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
2665 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
2666 cb.queue_submit_functions_after_render_pass.end());
2667 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002668}
2669
2670void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002671 RecordCmdEndRenderingCommon(commandBuffer);
2672
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002673 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002674 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2675 if (cb_node) {
2676 AddDeferredQueueOperations(*cb_node);
2677 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002678}
2679
2680void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002681 RecordCmdEndRenderingCommon(commandBuffer);
2682
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002683 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002684 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2685 if (cb_node) {
2686 AddDeferredQueueOperations(*cb_node);
2687 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002688}
2689
2690void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002691 RecordCmdEndRenderingCommon(commandBuffer);
2692
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002693 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002694 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2695 if (cb_node) {
2696 AddDeferredQueueOperations(*cb_node);
2697 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002698}
2699
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002700void BestPractices::PreCallRecordCmdEndRendering(VkCommandBuffer commandBuffer) {
2701 RecordCmdEndRenderingCommon(commandBuffer);
2702
2703 ValidationStateTracker::PreCallRecordCmdEndRendering(commandBuffer);
2704}
2705
2706void BestPractices::PreCallRecordCmdEndRenderingKHR(VkCommandBuffer commandBuffer) {
2707 RecordCmdEndRenderingCommon(commandBuffer);
2708
2709 ValidationStateTracker::PreCallRecordCmdEndRenderingKHR(commandBuffer);
2710}
2711
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002712void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
2713 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002714 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002715 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002716 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002717 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2718}
2719
2720void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
2721 const VkRenderPassBeginInfo* pRenderPassBegin,
2722 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2723 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002724 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002725 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2726}
2727
2728void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2729 const VkRenderPassBeginInfo* pRenderPassBegin,
2730 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2731 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002732 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002733 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2734}
2735
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002736void BestPractices::PreCallRecordCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) {
2737 ValidationStateTracker::PreCallRecordCmdBeginRendering(commandBuffer, pRenderingInfo);
2738 RecordCmdBeginRenderingCommon(commandBuffer);
2739}
2740
2741void BestPractices::PreCallRecordCmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) {
2742 ValidationStateTracker::PreCallRecordCmdBeginRenderingKHR(commandBuffer, pRenderingInfo);
2743 RecordCmdBeginRenderingCommon(commandBuffer);
2744}
2745
2746void BestPractices::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
2747 ValidationStateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
2748
2749 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2750 auto rp = cmd_state->activeRenderPass.get();
2751 assert(rp);
2752
2753 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2754 IMAGE_VIEW_STATE* depth_image_view = nullptr;
2755
2756 const auto depth_attachment = rp->createInfo.pSubpasses[cmd_state->activeSubpass].pDepthStencilAttachment;
2757 if (depth_attachment) {
2758 const uint32_t attachment_index = depth_attachment->attachment;
2759 if (attachment_index != VK_ATTACHMENT_UNUSED) {
2760 depth_image_view = (*cmd_state->active_attachments)[attachment_index];
2761 }
2762 }
2763 if (depth_image_view && (depth_image_view->create_info.subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U) {
2764 const VkImage depth_image = depth_image_view->image_state->image();
2765 const VkImageSubresourceRange& subresource_range = depth_image_view->create_info.subresourceRange;
2766 RecordBindZcullScope(*cmd_state, depth_image, subresource_range);
2767 } else {
2768 RecordUnbindZcullScope(*cmd_state);
2769 }
2770 }
2771}
2772
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002773void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002774
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002775 if (!pRenderPassBegin) {
2776 return;
2777 }
2778
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002779 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002780
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002781 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002782 if (rp_state) {
2783 // Check load ops
2784 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002785 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002786
2787 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
2788 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2789 continue;
2790 }
2791
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002792 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002793
2794 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
2795 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002796 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002797 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
2798 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002799 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002800 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002801 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002802 }
2803
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002804 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06002805 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002806
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002807 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002808 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2809 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002810 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002811 }
2812 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002813 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002814 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002815
Jeremy Gebben9f537102021-10-05 16:37:12 -06002816 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002817 }
2818
2819 // Check store ops
2820 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002821 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002822
2823 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2824 continue;
2825 }
2826
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002827 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002828
2829 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
2830 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002831 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002832 }
2833
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002834 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002835
Jeremy Gebben9f537102021-10-05 16:37:12 -06002836 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002837 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002838 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2839 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002840 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002841 }
2842 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002843 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002844 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002845
Jeremy Gebben9f537102021-10-05 16:37:12 -06002846 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002847 }
2848 }
2849}
2850
Attilio Provenzano02859b22020-02-27 14:17:28 +00002851bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2852 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002853 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2854 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002855 return skip;
2856}
2857
2858bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2859 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002860 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002861 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2862 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002863 return skip;
2864}
2865
2866bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002867 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002868 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2869 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002870 return skip;
2871}
2872
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002873bool BestPractices::PreCallValidateCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2874 bool skip = StateTracker::PreCallValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2875 skip |= ValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2876 return skip;
2877}
2878
2879bool BestPractices::PreCallValidateCmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2880 bool skip = StateTracker::PreCallValidateCmdBeginRenderingKHR(commandBuffer, pRenderingInfo);
2881 skip |= ValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2882 return skip;
2883}
2884
Sam Walls0961ec02020-03-31 16:39:15 +01002885void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2886 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002887 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002888 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
sjfricke52defd42022-08-08 16:37:46 +09002889 // TODO - move this logic to the Render Pass state as cb->has_draw_cmd should stay true for lifetime of command buffer
2890 cb->has_draw_cmd = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002891 assert(cb);
2892 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002893 render_pass_state.touchesAttachments.clear();
2894 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002895 render_pass_state.numDrawCallsDepthOnly = 0;
2896 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2897 render_pass_state.colorAttachment = false;
2898 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002899 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002900 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002901
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03002902 // Reset NV state
2903 cb->nv = {};
2904
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002905 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002906
2907 // track depth / color attachment usage within the renderpass
2908 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2909 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002910 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002911
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002912 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002913 }
2914}
2915
2916void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2917 VkSubpassContents contents) {
2918 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2919 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2920}
2921
2922void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2923 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2924 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2925 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2926}
2927
2928void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2929 const VkRenderPassBeginInfo* pRenderPassBegin,
2930 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2931 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2932 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2933}
2934
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002935// Generic function to handle validation for all CmdDraw* type functions
2936bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2937 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002938 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002939 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002940 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2941 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002942 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002943
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002944 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002945 if (pipeline_state && pipeline_state->vertex_input_state &&
2946 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002947 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002948 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002949 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002950 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2951 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002952 }
2953 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002954
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002955 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002956 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002957 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002958 if (rp_state) {
2959 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2960 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002961 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002962 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002963 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2964 const auto* raster_state = pipe->RasterizationState();
2965 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2966 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002967 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2968 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2969 }
2970 }
2971 }
2972 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002973 }
2974 return skip;
2975}
2976
Sam Walls0961ec02020-03-31 16:39:15 +01002977void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002978 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002979 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002980 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002981 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002982 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002983 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2984 RecordCmdDrawTypeNVIDIA(*cb_node);
2985 }
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002986
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002987 if (cb_node->render_pass_state.drawTouchAttachments) {
2988 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2989 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002990 }
2991 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002992 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002993 }
2994}
2995
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002996void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2997 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002998 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2999 // depth prepass warnings First find the lowest enabled draw count
3000 uint32_t lowestEnabledMinDrawCount = 0;
3001 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
3002 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
3003 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
3004
3005 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02003006 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
3007 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01003008 }
3009}
3010
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003011void BestPractices::RecordCmdDrawTypeNVIDIA(bp_state::CommandBuffer& cmd_state) {
3012 assert(VendorCheckEnabled(kBPVendorNVIDIA));
3013
3014 if (cmd_state.nv.depth_test_enable && cmd_state.nv.zcull_direction != bp_state::CommandBufferStateNV::ZcullDirection::Unknown) {
3015 RecordSetScopeZcullDirection(cmd_state, cmd_state.nv.zcull_direction);
3016 RecordZcullDraw(cmd_state);
3017 }
3018}
3019
Camden5b184be2019-08-13 07:50:19 -06003020bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003021 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06003022 bool skip = false;
3023
3024 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003025 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
3026 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003027 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06003028 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06003029
3030 return skip;
3031}
3032
Sam Walls0961ec02020-03-31 16:39:15 +01003033void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
3034 uint32_t firstVertex, uint32_t firstInstance) {
3035 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
3036 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
3037}
3038
Camden5b184be2019-08-13 07:50:19 -06003039bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003040 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06003041 bool skip = false;
3042
3043 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003044 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
3045 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003046 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07003047 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
3048
Attilio Provenzano02859b22020-02-27 14:17:28 +00003049 // Check if we reached the limit for small indexed draw calls.
3050 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003051 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003052 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003053 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00003054 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003055 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00003056 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00003057 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
3058 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00003059 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
3060 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003061 }
3062
Sam Walls8e77e4f2020-03-16 20:47:40 +00003063 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003064 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003065 }
3066
3067 return skip;
3068}
3069
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003070bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00003071 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
3072 bool skip = false;
3073
3074 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00003075
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003076 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
3077 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003078
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003079 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003080 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00003081 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
3082 const void* ib_mem = ib_mem_state.p_driver_data;
3083 bool primitive_restart_enable = false;
3084
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003085 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003086 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003087 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003088
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07003089 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
3090 if (ia_state) {
3091 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003092 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00003093
3094 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003095 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00003096 uint32_t scan_stride;
3097 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3098 scan_stride = sizeof(uint8_t);
3099 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3100 scan_stride = sizeof(uint16_t);
3101 } else {
3102 scan_stride = sizeof(uint32_t);
3103 }
3104
3105 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
3106 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
3107
3108 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
3109 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
3110 // irrespective of whether or not they're part of the draw call.
3111
3112 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
3113 uint32_t min_index = ~0u;
3114 // start with maximum as 0 and adjust to indices in the buffer
3115 uint32_t max_index = 0u;
3116
3117 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
3118 // for the given index buffer
3119 uint32_t vertex_shade_count = 0;
3120
3121 PostTransformLRUCacheModel post_transform_cache;
3122
3123 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
3124 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
3125 // target architecture.
3126 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
3127 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
3128 post_transform_cache.resize(32);
3129
3130 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
3131 uint32_t scan_index;
3132 uint32_t primitive_restart_value;
3133 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3134 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
3135 primitive_restart_value = 0xFF;
3136 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3137 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
3138 primitive_restart_value = 0xFFFF;
3139 } else {
3140 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
3141 primitive_restart_value = 0xFFFFFFFF;
3142 }
3143
3144 max_index = std::max(max_index, scan_index);
3145 min_index = std::min(min_index, scan_index);
3146
3147 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
3148 bool in_cache = post_transform_cache.query_cache(scan_index);
3149 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
3150 if (!in_cache) vertex_shade_count++;
3151 }
3152 }
3153
3154 // if the max and min values were not set, then we either have no indices, or all primitive restarts, exit...
Sam Walls61b06892020-07-23 16:20:50 +01003155 // if the max and min are the same, then it implies all the indices are the same, then we don't need to do anything
3156 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003157
3158 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07003159 skip |=
3160 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
3161 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
3162 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
3163 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
3164 "maximum would be loaded, and possibly shaded, whether or not they are used.",
3165 VendorSpecificTag(kBPVendorArm),
3166 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003167 return skip;
3168 }
3169
3170 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
3171 // each bit of the n-th bucket contains the inclusion information for indices (n*n_buckets) to ((n+1)*n_buckets)
Sam Walls61b06892020-07-23 16:20:50 +01003172 const size_t refs_per_bucket = 64;
3173 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
3174
3175 const uint32_t n_indices = max_index - min_index + 1;
3176 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
3177 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
3178
3179 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
3180 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00003181
3182 // To avoid using too much memory, we run over the indices again.
3183 // Knowing the size from the last scan allows us to record index usage with bitsets
3184 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
3185 uint32_t scan_index;
3186 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3187 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
3188 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3189 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
3190 } else {
3191 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
3192 }
3193 // keep track of the set of all indices used to reference vertices in the draw call
3194 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01003195 size_t bitset_bucket_index = index_offset / refs_per_bucket;
3196 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003197 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
3198 }
3199
3200 uint32_t vertex_reference_count = 0;
3201 for (const auto& bitset : vertex_reference_buckets) {
3202 vertex_reference_count += static_cast<uint32_t>(bitset.count());
3203 }
3204
3205 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
Mark Young0ec6b062020-11-19 15:32:17 -07003206 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003207 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
Mark Young0ec6b062020-11-19 15:32:17 -07003208 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003209
3210 if (utilization < 0.5f) {
3211 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
3212 "%s The indices which were specified for the draw call only utilise approximately "
3213 "%.02f%% of the bound vertex buffer.",
3214 VendorSpecificTag(kBPVendorArm), utilization);
3215 }
3216
3217 if (cache_hit_rate <= 0.5f) {
3218 skip |=
3219 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
3220 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
3221 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
3222 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
3223 "recently shaded vertices.",
3224 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
3225 }
3226 }
3227
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07003228 return skip;
3229}
3230
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003231bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
3232 const VkCommandBuffer* pCommandBuffers) const {
3233 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003234 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003235 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003236 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003237 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003238 continue;
3239 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003240 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003241 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003242 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
3243 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003244 }
3245 }
3246 }
Nadav Gevaf0808442021-05-21 13:51:25 -04003247
3248 if (VendorCheckEnabled(kBPVendorAMD)) {
3249 if (commandBufferCount > 0) {
3250 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
3251 "%s Performance warning: Use of secondary command buffers is not recommended. ",
3252 VendorSpecificTag(kBPVendorAMD));
3253 }
3254 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003255 return skip;
3256}
3257
3258void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
3259 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003260 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
3261
3262 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3263 if (!primary) {
3264 return;
3265 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003266
3267 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003268 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
3269 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003270 continue;
3271 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003272
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003273 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
3274 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
3275 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
3276 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003277 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003278 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003279 }
3280 }
3281
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003282 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
3283 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003284 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02003285
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003286 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
3287 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003288 }
3289
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003290}
3291
Rodrigo Locatti7d716e12022-03-09 19:15:17 -03003292bool BestPractices::PreCallValidateCmdBuildAccelerationStructureNV(VkCommandBuffer commandBuffer,
3293 const VkAccelerationStructureInfoNV* pInfo,
3294 VkBuffer instanceData, VkDeviceSize instanceOffset,
3295 VkBool32 update, VkAccelerationStructureNV dst,
3296 VkAccelerationStructureNV src, VkBuffer scratch,
3297 VkDeviceSize scratchOffset) const {
3298 return ValidateBuildAccelerationStructure(commandBuffer);
3299}
3300
3301bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresIndirectKHR(
3302 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
3303 const VkDeviceAddress* pIndirectDeviceAddresses, const uint32_t* pIndirectStrides,
3304 const uint32_t* const* ppMaxPrimitiveCounts) const {
3305 return ValidateBuildAccelerationStructure(commandBuffer);
3306}
3307
3308bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresKHR(
3309 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
3310 const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) const {
3311 return ValidateBuildAccelerationStructure(commandBuffer);
3312}
3313
3314bool BestPractices::ValidateBuildAccelerationStructure(VkCommandBuffer commandBuffer) const {
3315 bool skip = false;
3316 auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
3317 assert(cb_node);
3318
3319 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3320 if ((cb_node->GetQueueFlags() & VK_QUEUE_GRAPHICS_BIT) != 0) {
3321 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_AccelerationStructure_NotAsync,
3322 "%s Performance warning: Prefer building acceleration structures on an asynchronous "
3323 "compute queue, instead of using the universal graphics queue.",
3324 VendorSpecificTag(kBPVendorNVIDIA));
3325 }
3326 }
3327
3328 return skip;
3329}
3330
Rodrigo Locatti66b23352022-03-15 17:28:32 -03003331bool BestPractices::ValidateBindMemory(VkDevice device, VkDeviceMemory memory) const {
3332 bool skip = false;
3333
3334 if (VendorCheckEnabled(kBPVendorNVIDIA) && device_extensions.vk_ext_pageable_device_local_memory) {
3335 auto mem_info = std::static_pointer_cast<const bp_state::DeviceMemory>(Get<DEVICE_MEMORY_STATE>(memory));
3336 if (!mem_info->dynamic_priority) {
3337 skip |=
3338 LogPerformanceWarning(device, kVUID_BestPractices_BindMemory_NoPriority,
3339 "%s Use vkSetDeviceMemoryPriorityEXT to provide the OS with information on which allocations "
3340 "should stay in memory and which should be demoted first when video memory is limited. The "
3341 "highest priority should be given to GPU-written resources like color attachments, depth "
3342 "attachments, storage images, and buffers written from the GPU.",
3343 VendorSpecificTag(kBPVendorNVIDIA));
3344 }
3345 }
3346
3347 return skip;
3348}
3349
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003350void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
3351 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003352 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003353 auto itr =
3354 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
3355 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003356
3357 if (itr != state.touchesAttachments.end()) {
3358 itr->aspects |= aspects;
3359 } else {
3360 state.touchesAttachments.push_back({ fb_attachment, aspects });
3361 }
3362}
3363
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003364void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003365 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
3366 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003367 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003368 // If we observe a full clear before any other access to a frame buffer attachment,
3369 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003370 auto itr =
3371 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
3372 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003373
3374 uint32_t new_aspects = aspects;
3375 if (itr != state.touchesAttachments.end()) {
3376 new_aspects = aspects & ~itr->aspects;
3377 itr->aspects |= aspects;
3378 } else {
3379 state.touchesAttachments.push_back({ fb_attachment, aspects });
3380 }
3381
3382 if (new_aspects == 0) {
3383 return;
3384 }
3385
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003386 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003387 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
3388 // CmdExecuteCommands.
3389 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
3390 std::vector<VkClearRect>{pRects, pRects + rectCount} });
3391 }
3392}
3393
3394void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
3395 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
3396 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003397 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
3398
3399 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3400 auto* rp_state = cmd_state->activeRenderPass.get();
3401 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003402 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
3403
3404 if (rectCount == 0 || !rp_state) {
3405 return;
3406 }
3407
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003408 if (!is_secondary && !fb_state && !rp_state->use_dynamic_rendering && !rp_state->use_dynamic_rendering_inherited) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003409 return;
3410 }
3411
3412 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003413 const bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003414
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003415 if (rp_state->UsesDynamicRendering()) {
3416 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003417 auto pColorAttachments = rp_state->dynamic_rendering_begin_rendering_info.pColorAttachments;
3418
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003419 for (uint32_t i = 0; i < attachmentCount; i++) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003420 auto& clear_attachment = pClearAttachments[i];
3421
3422 if (clear_attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003423 RecordResetScopeZcullDirection(*cmd_state);
3424 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003425 if ((clear_attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) &&
3426 clear_attachment.colorAttachment != VK_ATTACHMENT_UNUSED &&
3427 pColorAttachments) {
3428 const auto& attachment = pColorAttachments[clear_attachment.colorAttachment];
3429 if (attachment.imageView) {
3430 auto image_view_state = Get<IMAGE_VIEW_STATE>(attachment.imageView);
3431 const VkFormat format = image_view_state->create_info.format;
3432 RecordClearColor(format, clear_attachment.clearValue.color);
3433 }
3434 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003435 }
3436 }
3437
3438 // TODO: Implement other best practices for dynamic rendering
3439
3440 } else {
ziga-lunarg885c6542022-03-07 01:08:25 +01003441 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
3442 for (uint32_t i = 0; i < attachmentCount; i++) {
3443 auto& attachment = pClearAttachments[i];
3444 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
3445 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003446
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003447 if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
3448 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3449 RecordResetScopeZcullDirection(*cmd_state);
3450 }
3451 }
ziga-lunarg885c6542022-03-07 01:08:25 +01003452 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
3453 if (subpass.pDepthStencilAttachment) {
3454 fb_attachment = subpass.pDepthStencilAttachment->attachment;
3455 }
3456 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
3457 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003458 }
ziga-lunarg885c6542022-03-07 01:08:25 +01003459 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
3460 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003461 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01003462 aspects, rectCount, pRects);
3463 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003464 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01003465 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003466 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3467 const VkFormat format = rp_state->createInfo.pAttachments[fb_attachment].format;
3468 RecordClearColor(format, attachment.clearValue.color);
3469 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003470 }
3471 }
3472 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003473}
3474
Attilio Provenzano02859b22020-02-27 14:17:28 +00003475void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
3476 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
3477 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
3478 firstInstance);
3479
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003480 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003481 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
3482 cmd_state->small_indexed_draw_call_count++;
3483 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003484
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003485 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00003486}
3487
Sam Walls0961ec02020-03-31 16:39:15 +01003488void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
3489 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
3490 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
3491 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
3492}
3493
Camden5b184be2019-08-13 07:50:19 -06003494bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003495 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06003496 bool skip = false;
3497
3498 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003499 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
3500 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003501 }
3502
Rodrigo Locatti8419cde2022-03-30 18:45:13 -03003503 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
3504
Camden5b184be2019-08-13 07:50:19 -06003505 return skip;
3506}
3507
Sam Walls0961ec02020-03-31 16:39:15 +01003508void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3509 uint32_t count, uint32_t stride) {
3510 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
3511 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
3512}
3513
Camden5b184be2019-08-13 07:50:19 -06003514bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003515 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06003516 bool skip = false;
3517
3518 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003519 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
3520 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003521 }
3522
Rodrigo Locatti8419cde2022-03-30 18:45:13 -03003523 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
3524
Camden5b184be2019-08-13 07:50:19 -06003525 return skip;
3526}
3527
Sam Walls0961ec02020-03-31 16:39:15 +01003528void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3529 uint32_t count, uint32_t stride) {
3530 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
3531 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
3532}
3533
Rodrigo Locatti467344a2022-03-30 18:48:13 -03003534bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3535 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3536 uint32_t maxDrawCount, uint32_t stride) const {
3537 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
3538
3539 return skip;
3540}
3541
3542void BestPractices::PostCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3543 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3544 uint32_t maxDrawCount, uint32_t stride) {
3545 StateTracker::PostCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3546 maxDrawCount, stride);
3547 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCount()");
3548}
3549
3550bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
3551 VkDeviceSize offset, VkBuffer countBuffer,
3552 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3553 uint32_t stride) const {
3554 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountAMD");
3555
3556 return skip;
3557}
3558
3559void BestPractices::PostCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
3560 VkDeviceSize offset, VkBuffer countBuffer,
3561 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3562 uint32_t stride) {
3563 StateTracker::PostCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3564 maxDrawCount, stride);
3565 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCountAMD()");
3566}
3567
3568bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
3569 VkDeviceSize offset, VkBuffer countBuffer,
3570 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3571 uint32_t stride) const {
3572 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR");
3573
3574 return skip;
3575}
3576
3577void BestPractices::PostCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
3578 VkDeviceSize offset, VkBuffer countBuffer,
3579 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3580 uint32_t stride) {
3581 StateTracker::PostCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3582 maxDrawCount, stride);
3583 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCountKHR()");
3584}
3585
3586bool BestPractices::PreCallValidateCmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount,
3587 uint32_t firstInstance, VkBuffer counterBuffer,
3588 VkDeviceSize counterBufferOffset, uint32_t counterOffset,
3589 uint32_t vertexStride) const {
3590 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectByteCountEXT");
3591
3592 return skip;
3593}
3594
3595void BestPractices::PostCallRecordCmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount,
3596 uint32_t firstInstance, VkBuffer counterBuffer,
3597 VkDeviceSize counterBufferOffset, uint32_t counterOffset,
3598 uint32_t vertexStride) {
3599 StateTracker::PostCallRecordCmdDrawIndirectByteCountEXT(commandBuffer, instanceCount, firstInstance, counterBuffer,
3600 counterBufferOffset, counterOffset, vertexStride);
3601 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectByteCountEXT()");
3602}
3603
3604bool BestPractices::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3605 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3606 uint32_t stride) const {
3607 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCount");
3608
3609 return skip;
3610}
3611
3612void BestPractices::PostCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3613 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3614 uint32_t stride) {
3615 StateTracker::PostCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3616 stride);
3617 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCount()");
3618}
3619
3620bool BestPractices::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3621 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3622 uint32_t maxDrawCount, uint32_t stride) const {
3623 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCountAMD");
3624
3625 return skip;
3626}
3627
3628void BestPractices::PostCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3629 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3630 uint32_t maxDrawCount, uint32_t stride) {
3631 StateTracker::PostCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3632 stride);
3633 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCountAMD()");
3634}
3635
3636bool BestPractices::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3637 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3638 uint32_t maxDrawCount, uint32_t stride) const {
3639 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCountKHR");
3640
3641 return skip;
3642}
3643
3644void BestPractices::PostCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3645 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3646 uint32_t maxDrawCount, uint32_t stride) {
3647 StateTracker::PostCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3648 stride);
3649 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCountKHR()");
3650}
3651
3652bool BestPractices::PreCallValidateCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
3653 VkDeviceSize offset, VkBuffer countBuffer,
3654 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3655 uint32_t stride) const {
3656 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksIndirectCountNV");
3657
3658 return skip;
3659}
3660
3661void BestPractices::PostCallRecordCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
3662 VkDeviceSize offset, VkBuffer countBuffer,
3663 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3664 uint32_t stride) {
3665 StateTracker::PostCallRecordCmdDrawMeshTasksIndirectCountNV(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3666 maxDrawCount, stride);
3667 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksIndirectCountNV()");
3668}
3669
3670bool BestPractices::PreCallValidateCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3671 uint32_t drawCount, uint32_t stride) const {
3672 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksIndirectNV");
3673
3674 return skip;
3675}
3676
3677void BestPractices::PostCallRecordCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3678 uint32_t drawCount, uint32_t stride) {
3679 StateTracker::PostCallRecordCmdDrawMeshTasksIndirectNV(commandBuffer, buffer, offset, drawCount, stride);
3680 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksIndirectNV()");
3681}
3682
3683bool BestPractices::PreCallValidateCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) const {
3684 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksNV");
3685
3686 return skip;
3687}
3688
3689void BestPractices::PostCallRecordCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) {
3690 StateTracker::PostCallRecordCmdDrawMeshTasksNV(commandBuffer, taskCount, firstTask);
3691 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksNV()");
3692}
3693
3694bool BestPractices::PreCallValidateCmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3695 const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount,
3696 uint32_t firstInstance, uint32_t stride,
3697 const int32_t* pVertexOffset) const {
3698 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMultiIndexedEXT");
3699
3700 return skip;
3701}
3702
3703void BestPractices::PostCallRecordCmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3704 const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount,
3705 uint32_t firstInstance, uint32_t stride, const int32_t* pVertexOffset) {
3706 StateTracker::PostCallRecordCmdDrawMultiIndexedEXT(commandBuffer, drawCount, pIndexInfo, instanceCount, firstInstance, stride,
3707 pVertexOffset);
3708 uint32_t count = 0;
3709 for (uint32_t i = 0; i < drawCount; ++i) {
3710 count += pIndexInfo[i].indexCount;
3711 }
3712 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawMultiIndexedEXT()");
3713}
3714
3715bool BestPractices::PreCallValidateCmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount, const VkMultiDrawInfoEXT* pVertexInfo,
3716 uint32_t instanceCount, uint32_t firstInstance, uint32_t stride) const {
3717 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMultiEXT");
3718
3719 return skip;
3720}
3721
3722void BestPractices::PostCallRecordCmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3723 const VkMultiDrawInfoEXT* pVertexInfo, uint32_t instanceCount,
3724 uint32_t firstInstance, uint32_t stride) {
3725 StateTracker::PostCallRecordCmdDrawMultiEXT(commandBuffer, drawCount, pVertexInfo, instanceCount, firstInstance, stride);
3726 uint32_t count = 0;
3727 for (uint32_t i = 0; i < drawCount; ++i) {
3728 count += pVertexInfo[i].vertexCount;
3729 }
3730 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawMultiEXT()");
3731}
3732
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003733void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
3734 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003735 for (const auto& binding : *descriptor_set) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003736 // For bindless scenarios, we should not attempt to track descriptor set state.
3737 // It is highly uncertain which resources are actually bound.
3738 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003739 if (binding->binding_flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
3740 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003741 continue;
3742 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01003743
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003744 for (uint32_t i = 0; i < binding->count; ++i) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003745 VkImageView image_view{VK_NULL_HANDLE};
3746
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003747 auto descriptor = binding->GetDescriptor(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02003748 if (!descriptor) {
3749 continue;
3750 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003751 switch (descriptor->GetClass()) {
3752 case cvdescriptorset::DescriptorClass::Image: {
3753 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
3754 image_view = image_descriptor->GetImageView();
3755 }
3756 break;
3757 }
3758 case cvdescriptorset::DescriptorClass::ImageSampler: {
3759 if (const auto image_sampler_descriptor =
3760 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
3761 image_view = image_sampler_descriptor->GetImageView();
3762 }
3763 break;
3764 }
3765 default:
3766 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01003767 }
3768
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003769 if (image_view) {
3770 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
3771 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
3772 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003773 }
3774 }
3775 }
3776 }
3777}
3778
3779void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
3780 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003781 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3782 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003783}
3784
3785void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3786 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003787 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3788 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003789}
3790
3791void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3792 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003793 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3794 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003795}
3796
Camden5b184be2019-08-13 07:50:19 -06003797bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003798 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06003799 bool skip = false;
3800
3801 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003802 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
3803 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
3804 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
3805 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06003806 }
3807
3808 return skip;
3809}
Camden83a9c372019-08-14 11:41:38 -06003810
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003811bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
3812 bool skip = false;
3813 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3814 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003815 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003816 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3817 assert(cmd_state);
3818 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003819 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003820 return skip;
3821}
3822
3823bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
3824 bool skip = false;
3825 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
3826 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003827 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003828 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3829 assert(cmd_state);
3830 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003831 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003832 return skip;
3833}
3834
Sam Walls0961ec02020-03-31 16:39:15 +01003835bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3836 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01003837 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003838 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003839 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003840 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3841 assert(cmd_state);
3842 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003843 }
3844 return skip;
3845}
3846
3847bool BestPractices::PreCallValidateCmdEndRendering(VkCommandBuffer commandBuffer) const {
3848 bool skip = false;
3849 skip |= StateTracker::PreCallValidateCmdEndRendering(commandBuffer);
3850 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003851 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3852 assert(cmd_state);
3853 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003854 }
3855 return skip;
3856}
3857
3858bool BestPractices::PreCallValidateCmdEndRenderingKHR(VkCommandBuffer commandBuffer) const {
3859 bool skip = false;
3860 skip |= StateTracker::PreCallValidateCmdEndRenderingKHR(commandBuffer);
3861 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003862 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3863 assert(cmd_state);
3864 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003865 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003866 return skip;
3867}
3868
3869bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3870 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003871 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01003872
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003873 if (cmd == nullptr) return skip;
3874 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01003875
LawG4b21485c2022-02-28 13:46:48 +00003876 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
3877 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
3878 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
3879 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
3880 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
3881
3882 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01003883 bool uses_depth =
3884 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01003885 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00003886
Sam Walls0961ec02020-03-31 16:39:15 +01003887 if (uses_depth) {
3888 skip |= LogPerformanceWarning(
3889 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00003890 "%s %s: Depth pre-passes may be in use. In general, this is not recommended in tile-based deferred "
LawG4b21485c2022-02-28 13:46:48 +00003891 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
3892 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
3893 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
3894 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01003895 }
3896
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003897 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
3898
LawG40da9c3d2022-03-01 09:51:01 +00003899 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003900 // If we use an attachment on-tile, we should access it in some way. Otherwise,
3901 // it is redundant to have it be part of the render pass.
3902 // Only consider it redundant if it will actually consume bandwidth, i.e.
3903 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
3904 // as is using pure input attachments.
3905 // CLEAR -> STORE might be considered a "useful" thing to do, but
3906 // the optimal thing to do is to defer the clear until you're actually
3907 // going to render to the image.
3908
3909 uint32_t num_attachments = rp->createInfo.attachmentCount;
3910 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02003911 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
3912 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003913 continue;
3914 }
3915
3916 auto& attachment = rp->createInfo.pAttachments[i];
3917
3918 VkImageAspectFlags bandwidth_aspects = 0;
3919
3920 if (!FormatIsStencilOnly(attachment.format) &&
3921 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
3922 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
3923 if (FormatHasDepth(attachment.format)) {
3924 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
3925 } else {
3926 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
3927 }
3928 }
3929
3930 if (FormatHasStencil(attachment.format) &&
3931 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
3932 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
3933 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
3934 }
3935
3936 if (!bandwidth_aspects) {
3937 continue;
3938 }
3939
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003940 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003941 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003942 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003943 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003944 untouched_aspects &= ~itr->aspects;
3945 }
3946
3947 if (untouched_aspects) {
3948 skip |= LogPerformanceWarning(
3949 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00003950 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003951 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00003952 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the "
LawG4015be1c2022-03-01 10:37:52 +00003953 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00003954 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003955 }
3956 }
3957 }
3958
Sam Walls0961ec02020-03-31 16:39:15 +01003959 return skip;
3960}
3961
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003962void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003963 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3964 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003965}
3966
3967void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003968 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3969 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003970}
3971
Camden Stocker9c051442019-11-06 14:28:43 -08003972bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
3973 const char* api_name) const {
3974 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003975 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08003976
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003977 if (bp_pd_state) {
3978 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
3979 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
3980 "Potential problem with calling %s() without first retrieving properties from "
3981 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
3982 api_name);
3983 }
Camden Stocker9c051442019-11-06 14:28:43 -08003984 }
3985
3986 return skip;
3987}
3988
Camden83a9c372019-08-14 11:41:38 -06003989bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003990 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06003991 bool skip = false;
3992
Camden Stocker9c051442019-11-06 14:28:43 -08003993 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06003994
Camden Stocker9c051442019-11-06 14:28:43 -08003995 return skip;
3996}
3997
3998bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
3999 uint32_t planeIndex,
4000 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
4001 bool skip = false;
4002
4003 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
4004
4005 return skip;
4006}
4007
4008bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
4009 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
4010 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
4011 bool skip = false;
4012
4013 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06004014
4015 return skip;
4016}
Camden05de2d42019-08-19 10:23:56 -06004017
4018bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004019 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06004020 bool skip = false;
4021
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004022 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06004023
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004024 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06004025 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004026 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004027 skip |=
4028 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
4029 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
4030 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06004031 }
Camden05de2d42019-08-19 10:23:56 -06004032
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06004033 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
4034 skip |= LogWarning(
4035 device, kVUID_BestPractices_Swapchain_InvalidCount,
4036 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04004037 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06004038 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
4039 }
4040 }
4041
Camden05de2d42019-08-19 10:23:56 -06004042 return skip;
4043}
4044
4045// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004046bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004047 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004048 const CALL_STATE call_state,
4049 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06004050 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004051 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
4052 if (UNCALLED == call_state) {
4053 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004054 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004055 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
4056 "recommended "
4057 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
4058 caller_name, caller_name);
4059 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004060 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
4061 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004062 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
4063 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
4064 ". It is recommended to instead receive all the properties by calling %s with "
4065 "pQueueFamilyPropertyCount that was "
4066 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004067 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004068 caller_name);
Camden05de2d42019-08-19 10:23:56 -06004069 }
4070
4071 return skip;
4072}
4073
Jeff Bolz5c801d12019-10-09 10:38:45 -05004074bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
4075 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06004076 bool skip = false;
4077
4078 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004079 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06004080 if (!as_state->memory_requirements_checked) {
4081 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
4082 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
4083 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004084 skip |= LogWarning(
4085 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06004086 "vkBindAccelerationStructureMemoryNV(): "
4087 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
4088 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
4089 }
4090 }
4091
4092 return skip;
4093}
4094
Camden05de2d42019-08-19 10:23:56 -06004095bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
4096 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004097 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004098 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004099 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004100 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004101 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
4102 "vkGetPhysicalDeviceQueueFamilyProperties()");
4103 }
4104 return false;
Camden05de2d42019-08-19 10:23:56 -06004105}
4106
Mike Schuchardt2df08912020-12-15 16:28:09 -08004107bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
4108 uint32_t* pQueueFamilyPropertyCount,
4109 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004110 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004111 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004112 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004113 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
4114 "vkGetPhysicalDeviceQueueFamilyProperties2()");
4115 }
4116 return false;
Camden05de2d42019-08-19 10:23:56 -06004117}
4118
Jeff Bolz5c801d12019-10-09 10:38:45 -05004119bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08004120 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004121 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004122 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004123 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004124 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
4125 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
4126 }
4127 return false;
Camden05de2d42019-08-19 10:23:56 -06004128}
4129
4130bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
4131 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004132 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06004133 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004134 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06004135 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06004136 bool skip = false;
4137 if (call_state == UNCALLED) {
4138 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
4139 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004140 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
4141 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
4142 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06004143 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06004144 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004145 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
4146 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
4147 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
4148 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06004149 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06004150 }
4151 }
4152 return skip;
4153}
Camden Stocker23cc47d2019-09-03 14:53:57 -06004154
4155bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004156 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004157 bool skip = false;
4158
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004159 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
4160 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06004161 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeremy Gebbencbf22862021-03-03 12:01:22 -07004162 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004163 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
4164 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07004165 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06004166 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004167 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
4168 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004169 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004170 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004171 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004172 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06004173 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004174 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
4175 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
4176 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004177 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004178 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
4179 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004180 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004181 }
4182 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004183 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004184 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004185 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004186 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
4187 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004188 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004189 }
4190 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004191 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
4192 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004193 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004194 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004195 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004196 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06004197 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004198 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
4199 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
4200 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004201 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004202 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
4203 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004204 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004205 }
4206 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004207 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004208 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004209 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004210 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
4211 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004212 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004213 }
4214 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
4215 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004216 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004217 }
4218 }
4219 }
4220 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004221 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
4222 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004223 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004224 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004225 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
4226 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004227 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004228 }
4229 }
4230 }
4231
Rodrigo Locatti7ab778d2022-03-09 18:57:15 -03004232 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4233 auto queue_state = Get<QUEUE_STATE>(queue);
4234 if (queue_state && queue_state->queueFamilyProperties.queueFlags != (VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT)) {
4235 skip |= LogPerformanceWarning(queue, kVUID_BestPractices_QueueBindSparse_NotAsync,
4236 "vkQueueBindSparse() issued on queue %s. All binds should happen on an asynchronous copy "
4237 "queue to hide the OS scheduling and submit costs.",
4238 report_data->FormatHandle(queue).c_str());
4239 }
4240 }
4241
Camden Stocker23cc47d2019-09-03 14:53:57 -06004242 return skip;
4243}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004244
Mark Lobodzinski84101d72020-04-24 09:43:48 -06004245void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
4246 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07004247 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07004248 return;
4249 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004250
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004251 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
4252 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
4253 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
4254 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004255 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004256 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004257 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004258 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004259 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
4260 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
4261 image_state->sparse_metadata_bound = true;
4262 }
4263 }
4264 }
4265 }
4266}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004267
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004268bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06004269 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004270 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004271 // We don't know the accurate render area in a secondary,
4272 // so assume we clear the entire frame buffer.
4273 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
4274 return true;
4275 }
4276
4277 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
4278 for (uint32_t i = 0; i < rectCount; i++) {
4279 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004280 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004281 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
4282 return true;
4283 }
4284 }
4285
4286 return false;
4287}
4288
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004289bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
4290 VkImageAspectFlags aspects, bool secondary) const {
4291 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004292 bool skip = false;
4293
4294 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
4295 return skip;
4296 }
4297
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004298 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004299
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004300 auto attachment_itr =
4301 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
4302 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004303
4304 // Only report aspects which haven't been touched yet.
4305 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06004306 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004307 new_aspects &= ~attachment_itr->aspects;
4308 }
4309
4310 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
sjfricke52defd42022-08-08 16:37:46 +09004311 if (!cmd.has_draw_cmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004312 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004313 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02004314 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
4315 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004316 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004317 }
4318
4319 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
4320 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
4321 skip |= LogPerformanceWarning(
4322 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4323 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
4324 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4325 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004326 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004327 }
4328
4329 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
4330 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004331 skip |=
4332 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4333 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
4334 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4335 "it is more efficient.",
4336 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004337
4338 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004339 const auto cmd_state = GetRead<bp_state::CommandBuffer>(cmd.commandBuffer());
4340 assert(cmd_state);
4341 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004342 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004343 }
4344
4345 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
4346 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004347 skip |=
4348 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4349 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
4350 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4351 "it is more efficient.",
4352 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004353 }
4354
4355 return skip;
4356}
4357
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004358bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06004359 const VkClearAttachment* pAttachments, uint32_t rectCount,
4360 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004361 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004362 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004363 if (!cb_node) return skip;
4364
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004365 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
4366 // Defer checks to ExecuteCommands.
4367 return skip;
4368 }
4369
4370 // Only care about full clears, partial clears might have legitimate uses.
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004371 const bool is_full_clear = ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004372
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004373 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
4374 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06004375 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004376 if (rp) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004377 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004378 const auto pColorAttachments = rp->dynamic_rendering_begin_rendering_info.pColorAttachments;
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004379
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004380 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4381 for (uint32_t i = 0; i < attachmentCount; i++) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004382 const auto& attachment = pAttachments[i];
4383 if (attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004384 skip |= ValidateZcullScope(*cb_node);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004385 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004386 if ((attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) && attachment.colorAttachment != VK_ATTACHMENT_UNUSED) {
4387 const auto& color_attachment = pColorAttachments[attachment.colorAttachment];
4388 if (color_attachment.imageView) {
4389 auto image_view_state = Get<IMAGE_VIEW_STATE>(color_attachment.imageView);
4390 const VkFormat format = image_view_state->create_info.format;
4391 skip |= ValidateClearColor(commandBuffer, format, attachment.clearValue.color);
4392 }
4393 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004394 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004395 }
4396
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004397 if (is_full_clear) {
4398 // TODO: Implement ValidateClearAttachment for dynamic rendering
4399 }
4400
4401 } else {
4402 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
4403
4404 if (is_full_clear) {
4405 for (uint32_t i = 0; i < attachmentCount; i++) {
4406 const auto& attachment = pAttachments[i];
4407
4408 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
4409 uint32_t color_attachment = attachment.colorAttachment;
4410 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
4411 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
4412 }
4413
4414 if (subpass.pDepthStencilAttachment &&
4415 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
4416 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
4417 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
4418 }
4419 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004420 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004421 if (VendorCheckEnabled(kBPVendorNVIDIA) && rp->createInfo.pAttachments) {
4422 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; ++attachment_idx) {
4423 const auto& attachment = pAttachments[attachment_idx];
4424
4425 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
4426 const uint32_t fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
4427 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
4428 const VkFormat format = rp->createInfo.pAttachments[fb_attachment].format;
4429 skip |= ValidateClearColor(commandBuffer, format, attachment.clearValue.color);
4430 }
4431 }
4432 }
4433 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004434 }
4435 }
4436
Nadav Gevaf0808442021-05-21 13:51:25 -04004437 if (VendorCheckEnabled(kBPVendorAMD)) {
4438 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
4439 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
4440 bool black_check = false;
4441 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
4442 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
4443 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
4444 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
4445 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
4446
4447 bool white_check = false;
4448 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
4449 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
4450 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
4451 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
4452 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
4453
4454 if (black_check && white_check) {
4455 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
4456 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
4457 "Consider changing to one of the following:"
4458 "RGBA(0, 0, 0, 0) "
4459 "RGBA(0, 0, 0, 1) "
4460 "RGBA(1, 1, 1, 0) "
4461 "RGBA(1, 1, 1, 1)",
4462 VendorSpecificTag(kBPVendorAMD), attachment_idx);
4463 }
4464 } else {
4465 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
4466 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
4467 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
4468 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
4469 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
4470 "attachment %" PRId32 " is not a fast clear value."
4471 "Consider changing to one of the following:"
4472 "D=0.0f, S=0"
4473 "D=1.0f, S=0",
4474 VendorSpecificTag(kBPVendorAMD), attachment_idx);
4475 }
4476 }
4477 }
4478 }
4479
Camden Stockerf55721f2019-09-09 11:04:49 -06004480 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004481}
Attilio Provenzano02859b22020-02-27 14:17:28 +00004482
4483bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4484 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4485 const VkImageResolve* pRegions) const {
4486 bool skip = false;
4487
4488 skip |= VendorCheckEnabled(kBPVendorArm) &&
4489 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
4490 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
4491 "This is a very slow and extremely bandwidth intensive path. "
4492 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4493 VendorSpecificTag(kBPVendorArm));
4494
4495 return skip;
4496}
4497
Jeff Leger178b1e52020-10-05 12:22:23 -04004498bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4499 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
4500 bool skip = false;
4501
4502 skip |= VendorCheckEnabled(kBPVendorArm) &&
4503 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
4504 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
4505 "This is a very slow and extremely bandwidth intensive path. "
4506 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4507 VendorSpecificTag(kBPVendorArm));
4508
4509 return skip;
4510}
4511
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004512bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
4513 const VkResolveImageInfo2* pResolveImageInfo) const {
4514 bool skip = false;
4515
4516 skip |= VendorCheckEnabled(kBPVendorArm) &&
4517 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
4518 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
4519 "This is a very slow and extremely bandwidth intensive path. "
4520 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4521 VendorSpecificTag(kBPVendorArm));
4522
4523 return skip;
4524}
4525
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004526void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4527 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4528 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004529 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004530 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004531 auto src = Get<bp_state::Image>(srcImage);
4532 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004533
4534 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004535 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
4536 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004537 }
4538}
4539
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004540void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4541 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004542 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004543 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004544 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
4545 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004546 uint32_t regionCount = pResolveImageInfo->regionCount;
4547
4548 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004549 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
4550 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004551 }
4552}
4553
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004554void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
4555 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004556 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004557 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004558 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
4559 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004560 uint32_t regionCount = pResolveImageInfo->regionCount;
4561
4562 for (uint32_t i = 0; i < regionCount; i++) {
4563 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
4564 pResolveImageInfo->pRegions[i].srcSubresource);
4565 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
4566 pResolveImageInfo->pRegions[i].dstSubresource);
4567 }
4568}
4569
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004570void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4571 const VkClearColorValue* pColor, uint32_t rangeCount,
4572 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004573 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004574 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004575 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004576
4577 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004578 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004579 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004580
4581 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4582 RecordClearColor(dst->createInfo.format, *pColor);
4583 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004584}
4585
4586void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4587 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
4588 const VkImageSubresourceRange* pRanges) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004589 ValidationStateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount,
4590 pRanges);
4591
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004592 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004593 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004594 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004595
4596 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004597 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004598 }
Rodrigo Locatti6c4c2662022-08-18 14:20:04 -03004599 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4600 for (uint32_t i = 0; i < rangeCount; i++) {
4601 RecordResetZcullDirection(*cb, image, pRanges[i]);
4602 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004603 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004604}
4605
4606void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4607 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4608 const VkImageCopy* pRegions) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004609 ValidationStateTracker::PreCallRecordCmdCopyImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout,
4610 regionCount, pRegions);
4611
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004612 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004613 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004614 auto src = Get<bp_state::Image>(srcImage);
4615 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004616
4617 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004618 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
4619 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004620 }
4621}
4622
4623void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4624 VkImageLayout dstImageLayout, uint32_t regionCount,
4625 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004626 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004627 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004628 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004629
4630 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004631 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004632 }
4633}
4634
4635void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4636 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004637 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004638 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004639 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004640
4641 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004642 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004643 }
4644}
4645
4646void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4647 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4648 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004649 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004650 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004651 auto src = Get<bp_state::Image>(srcImage);
4652 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004653
4654 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004655 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
4656 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004657 }
4658}
4659
Attilio Provenzano02859b22020-02-27 14:17:28 +00004660bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
4661 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
4662 bool skip = false;
4663
4664 if (VendorCheckEnabled(kBPVendorArm)) {
4665 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
4666 skip |= LogPerformanceWarning(
4667 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
4668 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
4669 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
4670 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06004671 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00004672 }
4673
4674 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
4675 skip |= LogPerformanceWarning(
4676 device, kVUID_BestPractices_CreateSampler_LodClamping,
4677 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
4678 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
4679 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
4680 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
4681 }
4682
4683 if (pCreateInfo->mipLodBias != 0.0f) {
4684 skip |=
4685 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
4686 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
4687 "descriptors being created and may cause reduced performance.",
4688 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
4689 }
4690
4691 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
4692 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
4693 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
4694 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
4695 skip |= LogPerformanceWarning(
4696 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
4697 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
4698 "This will lead to less efficient descriptors being created and may cause reduced performance. "
4699 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
4700 VendorSpecificTag(kBPVendorArm));
4701 }
4702
4703 if (pCreateInfo->unnormalizedCoordinates) {
4704 skip |= LogPerformanceWarning(
4705 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
4706 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
4707 "descriptors being created and may cause reduced performance.",
4708 VendorSpecificTag(kBPVendorArm));
4709 }
4710
4711 if (pCreateInfo->anisotropyEnable) {
4712 skip |= LogPerformanceWarning(
4713 device, kVUID_BestPractices_CreateSampler_Anisotropy,
4714 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
4715 "and may cause reduced performance.",
4716 VendorSpecificTag(kBPVendorArm));
4717 }
4718 }
4719
4720 return skip;
4721}
Sam Walls8e77e4f2020-03-16 20:47:40 +00004722
Nadav Gevaf0808442021-05-21 13:51:25 -04004723void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
4724 const VkGraphicsPipelineCreateInfo* pCreateInfos,
4725 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
4726 void* cgpl_state) {
4727 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
4728 pPipelines);
4729 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004730 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04004731}
4732
4733bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
4734 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
4735 const VkCopyDescriptorSet* pDescriptorCopies) const {
4736 bool skip = false;
4737 if (VendorCheckEnabled(kBPVendorAMD)) {
4738 if (descriptorCopyCount > 0) {
4739 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
4740 "%s Performance warning: copying descriptor sets is not recommended",
4741 VendorSpecificTag(kBPVendorAMD));
4742 }
4743 }
4744
4745 return skip;
4746}
4747
4748bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
4749 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
4750 const VkAllocationCallbacks* pAllocator,
4751 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
4752 bool skip = false;
4753 if (VendorCheckEnabled(kBPVendorAMD)) {
4754 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
4755 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
4756 "vkUpdateDescriptorSet instead",
4757 VendorSpecificTag(kBPVendorAMD));
4758 }
4759
4760 return skip;
4761}
4762
4763bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4764 const VkClearColorValue* pColor, uint32_t rangeCount,
4765 const VkImageSubresourceRange* pRanges) const {
4766 bool skip = false;
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004767
4768 auto dst = Get<bp_state::Image>(image);
4769
Nadav Gevaf0808442021-05-21 13:51:25 -04004770 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08004771 skip |= LogPerformanceWarning(
4772 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04004773 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
4774 "vkCmdClearAttachments instead",
4775 VendorSpecificTag(kBPVendorAMD));
4776 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004777 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4778 skip |= ValidateClearColor(commandBuffer, dst->createInfo.format, *pColor);
4779 }
Nadav Gevaf0808442021-05-21 13:51:25 -04004780
4781 return skip;
4782}
4783
4784bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4785 VkImageLayout imageLayout,
4786 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
4787 const VkImageSubresourceRange* pRanges) const {
4788 bool skip = false;
4789 if (VendorCheckEnabled(kBPVendorAMD)) {
4790 skip |= LogPerformanceWarning(
4791 device, kVUID_BestPractices_ClearAttachment_ClearImage,
4792 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
4793 "vkCmdClearAttachments instead",
4794 VendorSpecificTag(kBPVendorAMD));
4795 }
Mark Young0a6b48f2022-08-18 11:17:02 -06004796 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
4797 assert(cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004798 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4799 for (uint32_t i = 0; i < rangeCount; i++) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004800 skip |= ValidateZcull(*cmd_state, image, pRanges[i]);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004801 }
4802 }
Nadav Gevaf0808442021-05-21 13:51:25 -04004803
4804 return skip;
4805}
4806
4807bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
4808 const VkAllocationCallbacks* pAllocator,
4809 VkPipelineLayout* pPipelineLayout) const {
4810 bool skip = false;
4811 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004812 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04004813 // Descriptor sets cost 1 DWORD each.
4814 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
4815 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
4816 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
4817 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
4818 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004819 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004820 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04004821 }
4822
4823 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
4824 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
4825 }
4826
4827 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
4828 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
4829 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
4830 "Descriptor sets cost 1 DWORD each. "
4831 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
4832 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
4833 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
4834 VendorSpecificTag(kBPVendorAMD));
4835 }
4836 }
4837
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004838 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4839 bool has_separate_sampler = false;
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004840 size_t fast_space_usage = 0;
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004841
4842 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) {
4843 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
4844 for (const auto& binding : descriptor_set_layout_state->GetBindings()) {
4845 if (binding.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) {
4846 has_separate_sampler = true;
4847 }
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004848
4849 if ((descriptor_set_layout_state->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) == 0U) {
4850 size_t descriptor_type_size = 0;
4851
4852 switch (binding.descriptorType) {
4853 case VK_DESCRIPTOR_TYPE_SAMPLER:
4854 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
4855 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
4856 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
4857 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
4858 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
4859 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
4860 descriptor_type_size = 4;
4861 break;
4862 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
4863 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
4864 case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR:
4865 case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV:
4866 descriptor_type_size = 8;
4867 break;
4868 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
4869 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
4870 case VK_DESCRIPTOR_TYPE_MUTABLE_VALVE:
4871 descriptor_type_size = 16;
4872 break;
4873 case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK:
4874 descriptor_type_size = 1;
4875 default:
4876 // Unknown type.
4877 break;
4878 }
4879
4880 size_t descriptor_size = descriptor_type_size * binding.descriptorCount;
4881 fast_space_usage += descriptor_size;
4882 }
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004883 }
4884 }
4885
4886 if (has_separate_sampler) {
4887 skip |= LogPerformanceWarning(
4888 device, kVUID_BestPractices_CreatePipelineLayout_SeparateSampler,
4889 "%s Consider using combined image samplers instead of separate samplers for marginally better performance.",
4890 VendorSpecificTag(kBPVendorNVIDIA));
4891 }
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004892
4893 if (fast_space_usage > kPipelineLayoutFastDescriptorSpaceNVIDIA) {
4894 skip |= LogPerformanceWarning(
4895 device, kVUID_BestPractices_CreatePipelinesLayout_LargePipelineLayout,
4896 "%s Pipeline layout size is too large, prefer using pipeline-specific descriptor set layouts. "
4897 "Aim for consuming less than %" PRIu32 " bytes to allow fast reads for all non-bindless descriptors. "
4898 "Samplers, textures, texel buffers, and combined image samplers consume 4 bytes each. "
4899 "Uniform buffers and acceleration structures consume 8 bytes. "
4900 "Storage buffers consume 16 bytes. "
4901 "Push constants do not consume space.",
4902 VendorSpecificTag(kBPVendorNVIDIA), kPipelineLayoutFastDescriptorSpaceNVIDIA);
4903 }
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004904 }
4905
Nadav Gevaf0808442021-05-21 13:51:25 -04004906 return skip;
4907}
4908
4909bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4910 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4911 const VkImageCopy* pRegions) const {
4912 bool skip = false;
4913 std::stringstream src_image_hex;
4914 std::stringstream dst_image_hex;
4915 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
4916 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
4917
4918 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004919 auto src_state = Get<IMAGE_STATE>(srcImage);
4920 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04004921
4922 if (src_state && dst_state) {
4923 VkImageTiling src_Tiling = src_state->createInfo.tiling;
4924 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
4925 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
4926 skip |=
4927 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
4928 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
4929 "image (vkCmdCopyImageToBuffer) "
4930 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
4931 "copies when converting between linear and optimal images",
4932 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
4933 }
4934 }
4935 }
4936
4937 return skip;
4938}
4939
4940bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
4941 VkPipeline pipeline) const {
4942 bool skip = false;
4943
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03004944 auto cb = Get<bp_state::CommandBuffer>(commandBuffer);
4945
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004946 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004947 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04004948 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004949 "%s %s Performance warning: Pipeline %s was bound twice in the frame. "
4950 "Keep pipeline state changes to a minimum, for example, by sorting draw calls by pipeline.",
4951 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA),
4952 report_data->FormatHandle(pipeline).c_str());
Nadav Gevaf0808442021-05-21 13:51:25 -04004953 }
4954 }
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03004955 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4956 const auto& tgm = cb->nv.tess_geometry_mesh;
4957 if (tgm.num_switches >= kNumBindPipelineTessGeometryMeshSwitchesThresholdNVIDIA && !tgm.threshold_signaled) {
4958 LogPerformanceWarning(commandBuffer, kVUID_BestPractices_BindPipeline_SwitchTessGeometryMesh,
4959 "%s Avoid switching between pipelines with and without tessellation, geometry, task, "
4960 "and/or mesh shaders. Group draw calls using these shader stages together.",
4961 VendorSpecificTag(kBPVendorNVIDIA));
4962 // Do not set 'skip' so the number of switches gets properly counted after the message.
4963 }
4964 }
4965
Nadav Gevaf0808442021-05-21 13:51:25 -04004966 return skip;
4967}
4968
4969void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
4970 VkFence fence, VkResult result) {
4971 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004972 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04004973}
4974
4975bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
4976 bool skip = false;
4977
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004978 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004979 auto num = num_queue_submissions_.load();
4980 if (num > kNumberOfSubmissionWarningLimitAMD) {
4981 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004982 "%s %s Performance warning: command buffers submitted %" PRId32
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004983 " times this frame. Submitting command buffers has a CPU "
4984 "and GPU overhead. Submit fewer times to incur less overhead.",
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004985 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04004986 }
4987 }
4988
4989 return skip;
4990}
4991
4992void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4993 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4994 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
4995 uint32_t bufferMemoryBarrierCount,
4996 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
4997 uint32_t imageMemoryBarrierCount,
4998 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004999 ValidationStateTracker::PostCallRecordCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags,
5000 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5001 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
5002
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005003 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03005004
5005 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
5006 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pImageMemoryBarriers[i]);
5007 }
5008}
5009
5010void BestPractices::PostCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
5011 ValidationStateTracker::PostCallRecordCmdPipelineBarrier2(commandBuffer, pDependencyInfo);
5012
5013 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
5014 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
5015 }
5016}
5017
5018void BestPractices::PostCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
5019 ValidationStateTracker::PostCallRecordCmdPipelineBarrier2KHR(commandBuffer, pDependencyInfo);
5020
5021 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
5022 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
5023 }
5024}
5025
5026template <typename ImageMemoryBarrier>
5027void BestPractices::RecordCmdPipelineBarrierImageBarrier(VkCommandBuffer commandBuffer, const ImageMemoryBarrier& barrier) {
5028 auto cb = Get<bp_state::CommandBuffer>(commandBuffer);
5029 assert(cb);
5030
5031 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
5032 RecordResetZcullDirection(*cb, barrier.image, barrier.subresourceRange);
5033 }
Nadav Gevaf0808442021-05-21 13:51:25 -04005034}
5035
5036bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
5037 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
5038 bool skip = false;
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005039 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005040 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04005041 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005042 "%s %s Performance warning: High number of vkSemaphore objects created. "
Nadav Gevaf0808442021-05-21 13:51:25 -04005043 "Minimize the amount of queue synchronization that is used. "
5044 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005045 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04005046 }
5047 }
5048
5049 return skip;
5050}
5051
5052bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
5053 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
5054 bool skip = false;
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005055 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005056 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04005057 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005058 "%s %s Performance warning: High number of VkFence objects created."
Nadav Gevaf0808442021-05-21 13:51:25 -04005059 "Minimize the amount of CPU-GPU synchronization that is used. "
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005060 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
5061 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04005062 }
5063 }
5064
5065 return skip;
5066}
5067
Sam Walls8e77e4f2020-03-16 20:47:40 +00005068void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
5069
5070bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
5071 // look for a cache hit
5072 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
5073 if (hit != _entries.end()) {
5074 // mark the cache hit as being most recently used
5075 hit->age = iteration++;
5076 return true;
5077 }
5078
5079 // if there's no cache hit, we need to model the entry being inserted into the cache
5080 CacheEntry new_entry = {value, iteration};
5081 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
5082 // if there is still space left in the cache, use the next available slot
5083 *(_entries.begin() + iteration) = new_entry;
5084 } else {
5085 // otherwise replace the least recently used cache entry
5086 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
5087 *lru = new_entry;
5088 }
5089 iteration++;
5090 return false;
5091}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005092
5093bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
5094 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005095 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005096 bool skip = false;
5097 if (swapchain_data && swapchain_data->images.size() == 0) {
5098 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
5099 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
5100 "vkGetSwapchainImagesKHR after swapchain creation.");
5101 }
5102 return skip;
5103}
5104
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005105void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
5106 if (no_pointer) {
5107 if (UNCALLED == call_state) {
5108 call_state = QUERY_COUNT;
5109 }
5110 } else { // Save queue family properties
5111 call_state = QUERY_DETAILS;
5112 }
5113}
5114
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005115void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
5116 uint32_t* pQueueFamilyPropertyCount,
5117 VkQueueFamilyProperties* pQueueFamilyProperties) {
5118 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
5119 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005120 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005121 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005122 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
5123 nullptr == pQueueFamilyProperties);
5124 }
5125}
5126
5127void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
5128 uint32_t* pQueueFamilyPropertyCount,
5129 VkQueueFamilyProperties2* pQueueFamilyProperties) {
5130 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
5131 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005132 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005133 if (bp_pd_state) {
5134 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
5135 nullptr == pQueueFamilyProperties);
5136 }
5137}
5138
5139void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
5140 uint32_t* pQueueFamilyPropertyCount,
5141 VkQueueFamilyProperties2* pQueueFamilyProperties) {
5142 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
5143 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005144 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005145 if (bp_pd_state) {
5146 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
5147 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005148 }
5149}
5150
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005151void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
5152 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005153 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005154 if (bp_pd_state) {
5155 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5156 }
5157}
5158
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005159void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
5160 VkPhysicalDeviceFeatures2* pFeatures) {
5161 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005162 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005163 if (bp_pd_state) {
5164 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5165 }
5166}
5167
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005168void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
5169 VkPhysicalDeviceFeatures2* pFeatures) {
5170 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005171 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005172 if (bp_pd_state) {
5173 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5174 }
5175}
5176
5177void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
5178 VkSurfaceKHR surface,
5179 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
5180 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005181 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005182 if (bp_pd_state) {
5183 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5184 }
5185}
5186
5187void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
5188 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
5189 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005190 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005191 if (bp_pd_state) {
5192 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5193 }
5194}
5195
5196void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
5197 VkSurfaceKHR surface,
5198 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
5199 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005200 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005201 if (bp_pd_state) {
5202 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5203 }
5204}
5205
5206void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
5207 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
5208 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005209 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005210 if (bp_pd_data) {
5211 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
5212
5213 if (*pPresentModeCount) {
5214 if (call_state < QUERY_COUNT) {
5215 call_state = QUERY_COUNT;
5216 }
5217 }
5218 if (pPresentModes) {
5219 if (call_state < QUERY_DETAILS) {
5220 call_state = QUERY_DETAILS;
5221 }
5222 }
5223 }
5224}
5225
5226void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
5227 uint32_t* pSurfaceFormatCount,
5228 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005229 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005230 if (bp_pd_data) {
5231 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
5232
5233 if (*pSurfaceFormatCount) {
5234 if (call_state < QUERY_COUNT) {
5235 call_state = QUERY_COUNT;
5236 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06005237 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005238 }
5239 if (pSurfaceFormats) {
5240 if (call_state < QUERY_DETAILS) {
5241 call_state = QUERY_DETAILS;
5242 }
5243 }
5244 }
5245}
5246
5247void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
5248 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
5249 uint32_t* pSurfaceFormatCount,
5250 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005251 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005252 if (bp_pd_data) {
5253 if (*pSurfaceFormatCount) {
5254 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
5255 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
5256 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06005257 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005258 }
5259 if (pSurfaceFormats) {
5260 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
5261 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
5262 }
5263 }
5264 }
5265}
5266
5267void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
5268 uint32_t* pPropertyCount,
5269 VkDisplayPlanePropertiesKHR* pProperties,
5270 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005271 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005272 if (bp_pd_data) {
5273 if (*pPropertyCount) {
5274 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
5275 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
5276 }
5277 }
5278 if (pProperties) {
5279 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
5280 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
5281 }
5282 }
5283 }
5284}
5285
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005286void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
5287 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
5288 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005289 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06005290 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
5291 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
5292 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005293 }
5294 }
5295}
5296
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005297void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
5298 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
5299
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06005300 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005301 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02005302 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005303 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005304 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005305 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07005306 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005307 }
Rodrigo Locattic789fe82022-07-06 17:42:19 -03005308 cb->num_submits++;
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005309 }
5310 }
5311}