blob: 0e82b0980b7f5b272abaed33bc730de49e3ddaa2 [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
Jeremy Gebben20da7a12022-02-25 14:07:46 -070061ReadLockGuard BestPractices::ReadLock() {
62 if (fine_grained_locking) {
63 return ReadLockGuard(validation_object_mutex, std::defer_lock);
64 } else {
65 return ReadLockGuard(validation_object_mutex);
66 }
67}
68
69WriteLockGuard BestPractices::WriteLock() {
70 if (fine_grained_locking) {
71 return WriteLockGuard(validation_object_mutex, std::defer_lock);
72 } else {
73 return WriteLockGuard(validation_object_mutex);
74 }
75}
76
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060077std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
78 const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060079 const COMMAND_POOL_STATE* pool) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -070080 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 -060081}
82
Jeremy Gebben20da7a12022-02-25 14:07:46 -070083bp_state::CommandBuffer::CommandBuffer(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
84 const COMMAND_POOL_STATE* pool)
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060085 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
86
Attilio Provenzano19d6a982020-02-27 12:41:41 +000087bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070088 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060089 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000090 return true;
91 }
92 }
93 return false;
94}
95
96const char* VendorSpecificTag(BPVendorFlags vendors) {
97 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070098 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000099
100 auto res = tag_map.find(vendors);
101 if (res == tag_map.end()) {
102 // Build the vendor tag string
103 std::stringstream vendor_tag;
104
105 vendor_tag << "[";
106 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700107 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +0000108 if (vendors & vendor.first) {
109 if (!first_vendor) {
110 vendor_tag << ", ";
111 }
112 vendor_tag << vendor.second.name;
113 first_vendor = false;
114 }
115 }
116 vendor_tag << "]";
117
118 tag_map[vendors] = vendor_tag.str();
119 res = tag_map.find(vendors);
120 }
121
122 return res->second.c_str();
123}
124
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700125const char* DepReasonToString(ExtDeprecationReason reason) {
126 switch (reason) {
127 case kExtPromoted:
128 return "promoted to";
129 break;
130 case kExtObsoleted:
131 return "obsoleted by";
132 break;
133 case kExtDeprecated:
134 return "deprecated by";
135 break;
136 default:
137 return "";
138 break;
139 }
140}
141
142bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
143 const char* vuid) const {
144 bool skip = false;
145 auto dep_info_it = deprecated_extensions.find(extension_name);
146 if (dep_info_it != deprecated_extensions.end()) {
147 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600148 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
Tony-LunarGc30b59f2022-02-15 11:02:36 -0700149 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2)) ||
150 ((dep_info.target.compare("VK_VERSION_1_3") == 0) && (version >= VK_API_VERSION_1_3))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700151 skip |=
152 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
153 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600154 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700155 if (dep_info.target.length() == 0) {
156 skip |= LogWarning(instance, vuid,
157 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
158 "without replacement.",
159 api_name, extension_name);
160 } else {
161 skip |= LogWarning(instance, vuid,
162 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
163 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
164 }
165 }
166 }
167 return skip;
168}
169
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200170bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
171{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700172 bool skip = false;
173 auto dep_info_it = special_use_extensions.find(extension_name);
174
175 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200176 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
177 "and it is strongly recommended that it be otherwise avoided.";
178 auto& special_uses = dep_info_it->second;
sfricke-samsungef15e482022-01-26 11:32:49 -0800179
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700180 if (special_uses.find("cadsupport") != std::string::npos) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800181 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
182 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700183 }
184 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200185 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
186 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700187 }
188 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200189 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
190 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700191 }
192 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200193 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
194 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700195 }
196 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200197 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700198 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200199 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700200 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700201 }
202 return skip;
203}
204
Camden5b184be2019-08-13 07:50:19 -0600205bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500206 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600207 bool skip = false;
208
209 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
210 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800211 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700212 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
213 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600214 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600215 uint32_t specified_version =
216 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
217 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700218 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200219 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600220 }
221
222 return skip;
223}
224
Camden5b184be2019-08-13 07:50:19 -0600225bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500226 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600227 bool skip = false;
228
229 // get API version of physical device passed when creating device.
230 VkPhysicalDeviceProperties physical_device_properties{};
231 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500232 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600233
234 // check api versions and warn if instance api Version is higher than version on device.
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600235 if (api_version > device_api_version) {
236 std::string inst_api_name = StringAPIVersion(api_version);
Mark Lobodzinski60880782020-08-11 08:02:07 -0600237 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600238
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700239 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
240 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
241 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600242 }
243
Rodrigo Locattic2d5cf42022-03-01 18:05:26 -0300244 std::vector<std::string> extensions;
245 {
246 uint32_t property_count = 0;
247 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, nullptr) == VK_SUCCESS) {
248 std::vector<VkExtensionProperties> property_list(property_count);
249 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, property_list.data()) == VK_SUCCESS) {
250 extensions.reserve(property_list.size());
251 for (const VkExtensionProperties& properties : property_list) {
252 extensions.push_back(properties.extensionName);
253 }
254 }
255 }
256 }
257
Camden5b184be2019-08-13 07:50:19 -0600258 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
259 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800260 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700261 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
262 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600263 }
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600264 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700265 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200266 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600267 }
268
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700269 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600270 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700271 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
272 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600273 }
274
LawG43f848c72022-02-23 09:35:21 +0000275 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorIMG)) &&
276 (pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
Szilard Papp7d2c7952020-06-22 14:38:13 +0100277 skip |= LogPerformanceWarning(
278 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
LawG4015be1c2022-03-01 10:37:52 +0000279 "%s %s %s: vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100280 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
281 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
282 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
LawG43f848c72022-02-23 09:35:21 +0000283 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorIMG));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100284 }
285
Camden5b184be2019-08-13 07:50:19 -0600286 return skip;
287}
288
289bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500290 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600291 bool skip = false;
292
293 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700294 std::stringstream buffer_hex;
295 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600296
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700297 skip |= LogWarning(
298 device, kVUID_BestPractices_SharingModeExclusive,
299 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
300 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700301 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600302 }
303
304 return skip;
305}
306
307bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500308 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600309 bool skip = false;
310
311 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700312 std::stringstream image_hex;
313 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600314
315 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700316 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
317 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
318 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700319 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600320 }
321
ziga-lunarg6df3d102022-03-18 17:02:14 +0100322 if ((pCreateInfo->flags & VK_IMAGE_CREATE_EXTENDED_USAGE_BIT) && !(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
323 skip |= LogWarning(device, kVUID_BestPractices_ImageCreateFlags,
324 "vkCreateImage(): pCreateInfo->flags has VK_IMAGE_CREATE_EXTENDED_USAGE_BIT set, but not "
325 "VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, therefore image views created from this image will have to use the "
326 "same format and VK_IMAGE_CREATE_EXTENDED_USAGE_BIT will not have any effect.");
327 }
328
LawG4655f59c2022-02-23 13:55:55 +0000329 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000330 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
331 skip |= LogPerformanceWarning(
332 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
LawG4655f59c2022-02-23 13:55:55 +0000333 "%s %s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
Attilio Provenzano02859b22020-02-27 14:17:28 +0000334 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
335 "and do not need to be backed by physical storage. "
336 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
LawG4655f59c2022-02-23 13:55:55 +0000337 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Attilio Provenzano02859b22020-02-27 14:17:28 +0000338 }
339 }
340
LawG4ba113892022-02-23 14:39:02 +0000341 if (VendorCheckEnabled(kBPVendorArm) && pCreateInfo->samples > kMaxEfficientSamplesArm) {
342 skip |= LogPerformanceWarning(
343 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
344 "%s vkCreateImage(): Trying to create an image with %u samples. "
345 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
346 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
347 }
348
349 if (VendorCheckEnabled(kBPVendorIMG) && pCreateInfo->samples > kMaxEfficientSamplesImg) {
350 skip |= LogPerformanceWarning(
351 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
352 "%s vkCreateImage(): Trying to create an image with %u samples. "
353 "The device may not have full support for true multisampling for images with more than %u samples. "
354 "XT devices support up to 8 samples, XE up to 4 samples.",
355 VendorSpecificTag(kBPVendorIMG), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesImg);
356 }
357
LawG4db16f802022-03-21 17:33:39 +0000358 if (VendorCheckEnabled(kBPVendorIMG) && (pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ||
359 pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ||
360 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ||
361 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ||
362 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG ||
363 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG ||
364 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG ||
365 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG)) {
366 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Texture_Format_PVRTC_Outdated,
367 "%s vkCreateImage(): Trying to create an image with a PVRTC format. Both PVRTC1 and PVRTC2 "
368 "are slower than standard image formats on PowerVR GPUs, prefer ETC, BC, ASTC, etc.",
369 VendorSpecificTag(kBPVendorIMG));
370 }
371
Nadav Gevaf0808442021-05-21 13:51:25 -0400372 if (VendorCheckEnabled(kBPVendorAMD)) {
373 std::stringstream image_hex;
374 image_hex << "0x" << std::hex << HandleToUint64(pImage);
375
376 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
377 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
378 skip |= LogPerformanceWarning(device,
379 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
380 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
381 "Using a SHARING_MODE_CONCURRENT "
382 "is not recommended with color and depth targets",
383 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
384 }
385
386 if ((pCreateInfo->usage &
387 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
388 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
389 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
390 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
391 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
392 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
393 }
394
395 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
396 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
397 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
398 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
399 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
400 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
401 }
402 }
403
Camden5b184be2019-08-13 07:50:19 -0600404 return skip;
405}
406
407bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500408 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600409 bool skip = false;
410
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600411 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600412 if (bp_pd_state) {
413 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
414 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
415 "vkCreateSwapchainKHR() called before getting surface capabilities from "
416 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
417 }
Camden83a9c372019-08-14 11:41:38 -0600418
Shannon McPherson73e58c82021-03-05 17:14:26 -0700419 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
420 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600421 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
422 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
423 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
424 }
Camden83a9c372019-08-14 11:41:38 -0600425
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600426 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
427 skip |= LogWarning(
428 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
429 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
430 }
Camden83a9c372019-08-14 11:41:38 -0600431 }
432
Camden5b184be2019-08-13 07:50:19 -0600433 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700434 skip |=
435 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600436 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700437 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
438 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600439 }
440
ziga-lunarg79beba62022-03-30 01:17:30 +0200441 const auto present_mode = pCreateInfo->presentMode;
442 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
443 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100444 skip |= LogPerformanceWarning(
445 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
446 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
447 ", which means double buffering is going "
448 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
449 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
450 "3 to use triple buffering to maximize performance in such cases.",
451 pCreateInfo->minImageCount);
452 }
453
Szilard Pappd5f0f812020-06-22 09:01:29 +0100454 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
455 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
456 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
457 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
458 "Presentation modes which are not FIFO will present the latest available frame and discard other "
459 "frame(s) if any.",
460 VendorSpecificTag(kBPVendorArm));
461 }
462
Camden5b184be2019-08-13 07:50:19 -0600463 return skip;
464}
465
466bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
467 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500468 const VkAllocationCallbacks* pAllocator,
469 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600470 bool skip = false;
471
472 for (uint32_t i = 0; i < swapchainCount; i++) {
473 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700474 skip |= LogWarning(
475 device, kVUID_BestPractices_SharingModeExclusive,
476 "Warning: A shared swapchain (index %" PRIu32
477 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
478 "queues (queueFamilyIndexCount of %" PRIu32 ").",
479 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600480 }
481 }
482
483 return skip;
484}
485
486bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500487 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600488 bool skip = false;
489
490 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
491 VkFormat format = pCreateInfo->pAttachments[i].format;
492 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
493 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
494 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700495 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
496 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
497 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
498 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
499 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600500 }
501 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700502 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
503 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
504 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
505 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
506 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600507 }
508 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000509
510 const auto& attachment = pCreateInfo->pAttachments[i];
511 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
512 bool access_requires_memory =
513 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
514
515 if (FormatHasStencil(format)) {
516 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
517 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
518 }
519
520 if (access_requires_memory) {
521 skip |= LogPerformanceWarning(
522 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
523 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
524 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
525 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
526 i, static_cast<uint32_t>(attachment.samples));
527 }
528 }
Camden5b184be2019-08-13 07:50:19 -0600529 }
530
531 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
532 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
533 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
534 }
535
536 return skip;
537}
538
Tony-LunarG767180f2020-04-23 14:03:59 -0600539bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
540 const VkImageView* image_views) const {
541 bool skip = false;
542
543 // Check for non-transient attachments that should be transient and vice versa
544 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200545 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600546 bool attachment_should_be_transient =
547 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
548
549 if (FormatHasStencil(attachment.format)) {
550 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
551 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
552 }
553
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600554 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600555 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600556 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600557
558 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
559
560 // The check for an image that should not be transient applies to all GPUs
561 if (!attachment_should_be_transient && image_is_transient) {
562 skip |= LogPerformanceWarning(
563 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
564 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
565 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
566 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
567 i);
568 }
569
570 bool supports_lazy = false;
571 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
572 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
573 supports_lazy = true;
574 }
575 }
576
577 // The check for an image that should be transient only applies to GPUs supporting
578 // lazily allocated memory
579 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
580 skip |= LogPerformanceWarning(
581 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
582 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
583 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
584 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
585 i);
586 }
587 }
588 }
589 return skip;
590}
591
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000592bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
593 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
594 bool skip = false;
595
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600596 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800597 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600598 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000599 }
600
601 return skip;
602}
603
Sam Wallse746d522020-03-16 21:20:23 +0000604bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
605 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
606 bool skip = false;
607 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
608
609 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700610 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000611 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
612 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700613 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000614 skip |= LogPerformanceWarning(
615 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
616 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
617 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
618 VendorSpecificTag(kBPVendorArm));
619 }
ziga-lunarg5a76c442022-04-17 18:04:08 +0200620
621 if (IsExtEnabled(device_extensions.vk_khr_maintenance1)) {
622 // Track number of descriptorSets allowable in this pool
623 if (pool_state->GetAvailableSets() < pAllocateInfo->descriptorSetCount) {
624 skip |= LogWarning(pool_state->Handle(), kVUID_BestPractices_EmptyDescriptorPool,
625 "vkAllocateDescriptorSets(): Unable to allocate %" PRIu32 " descriptorSets from %s"
626 ". This pool only has %" PRIu32 " descriptorSets remaining.",
627 pAllocateInfo->descriptorSetCount, report_data->FormatHandle(pool_state->Handle()).c_str(),
628 pool_state->GetAvailableSets());
629 }
630 }
Sam Wallse746d522020-03-16 21:20:23 +0000631 }
632
633 return skip;
634}
635
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600636void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
637 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000638 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700639 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
640 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000641 // we record successful allocations by subtracting the allocation count from the last recorded free count
642 const auto alloc_count = pAllocateInfo->descriptorSetCount;
643 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700644 if (pool_state->freed_count > alloc_count) {
645 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700646 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700647 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700648 }
Sam Wallse746d522020-03-16 21:20:23 +0000649 }
650 }
651}
652
653void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
654 const VkDescriptorSet* pDescriptorSets, VkResult result) {
655 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
656 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700657 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000658 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700659 if (pool_state) {
660 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000661 }
662 }
663}
664
Camden5b184be2019-08-13 07:50:19 -0600665bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500666 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600667 bool skip = false;
668
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700669 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700670 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
671 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600672 }
673
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000674 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
675 skip |= LogPerformanceWarning(
676 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600677 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
678 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000679 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
680 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
681 }
682
Camden83a9c372019-08-14 11:41:38 -0600683 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
684
685 return skip;
686}
687
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600688void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
689 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
690 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700691 if (result != VK_SUCCESS) {
692 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
693 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800694 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700695 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600696 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700697 return;
698 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700699}
Camden Stocker9738af92019-10-16 13:54:03 -0700700
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600701void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
702 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700703 auto error = std::find(error_codes.begin(), error_codes.end(), result);
704 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000705 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
706 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
707
708 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
709 if (common_failure != common_failure_codes.end()) {
710 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
711 } else {
712 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
713 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700714 return;
715 }
716 auto success = std::find(success_codes.begin(), success_codes.end(), result);
717 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600718 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
719 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500720 }
721}
722
Jeff Bolz5c801d12019-10-09 10:38:45 -0500723bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
724 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700725 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600726 bool skip = false;
727
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700728 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600729
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700730 for (const auto& item : mem_info->ObjectBindings()) {
731 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600732 LogObjectList objlist(device);
733 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600734 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600735 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 -0600736 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600737 }
738
Camden5b184be2019-08-13 07:50:19 -0600739 return skip;
740}
741
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000742bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600743 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700744 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600745
sfricke-samsunge2441192019-11-06 14:07:57 -0800746 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700747 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
748 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
749 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600750 }
751
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700752 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000753
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300754 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000755 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
756 skip |= LogPerformanceWarning(
757 device, kVUID_BestPractices_SmallDedicatedAllocation,
758 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600759 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
760 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000761 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
762 }
763
Camden Stockerb603cc82019-09-03 10:09:02 -0600764 return skip;
765}
766
767bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500768 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600769 bool skip = false;
770 const char* api_name = "BindBufferMemory()";
771
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000772 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600773
774 return skip;
775}
776
777bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500778 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600779 char api_name[64];
780 bool skip = false;
781
782 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200783 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000784 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600785 }
786
787 return skip;
788}
Camden Stockerb603cc82019-09-03 10:09:02 -0600789
790bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500791 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600792 char api_name[64];
793 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600794
Camden Stocker8b798ab2019-09-03 10:33:28 -0600795 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200796 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000797 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600798 }
799
800 return skip;
801}
802
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000803bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600804 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700805 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600806
sfricke-samsung71bc6572020-04-29 15:49:43 -0700807 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600808 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700809 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
810 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
811 api_name, report_data->FormatHandle(image).c_str());
812 }
813 } else {
814 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
815 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600816 }
817
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700818 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000819
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600820 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000821 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
822 skip |= LogPerformanceWarning(
823 device, kVUID_BestPractices_SmallDedicatedAllocation,
824 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600825 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
826 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000827 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
828 }
829
830 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
831 // make sure this type is actually used.
832 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
833 // (i.e.most tile - based renderers)
834 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
835 bool supports_lazy = false;
836 uint32_t suggested_type = 0;
837
838 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600839 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000840 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
841 supports_lazy = true;
842 suggested_type = i;
843 break;
844 }
845 }
846 }
847
848 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
849
850 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
851 skip |= LogPerformanceWarning(
852 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600853 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000854 "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 -0600855 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600856 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000857 }
858 }
859
Camden Stocker8b798ab2019-09-03 10:33:28 -0600860 return skip;
861}
862
863bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500864 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600865 bool skip = false;
866 const char* api_name = "vkBindImageMemory()";
867
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000868 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600869
870 return skip;
871}
872
873bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500874 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600875 char api_name[64];
876 bool skip = false;
877
878 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200879 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700880 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600881 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
882 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600883 }
884
885 return skip;
886}
887
888bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500889 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600890 char api_name[64];
891 bool skip = false;
892
893 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200894 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000895 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600896 }
897
898 return skip;
899}
Camden83a9c372019-08-14 11:41:38 -0600900
Attilio Provenzano02859b22020-02-27 14:17:28 +0000901static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
902 switch (format) {
903 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
904 case VK_FORMAT_R16_SFLOAT:
905 case VK_FORMAT_R16G16_SFLOAT:
906 case VK_FORMAT_R16G16B16_SFLOAT:
907 case VK_FORMAT_R16G16B16A16_SFLOAT:
908 case VK_FORMAT_R32_SFLOAT:
909 case VK_FORMAT_R32G32_SFLOAT:
910 case VK_FORMAT_R32G32B32_SFLOAT:
911 case VK_FORMAT_R32G32B32A32_SFLOAT:
912 return false;
913
914 default:
915 return true;
916 }
917}
918
919bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
920 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
921 bool skip = false;
922
923 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700924 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000925
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700926 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
927 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
928 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000929 return skip;
930 }
931
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600932 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200933 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000934
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200935 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
936 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
937
938 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200939 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000940 uint32_t att = subpass.pColorAttachments[j].attachment;
941
942 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
943 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
944 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
945 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
946 "color attachment #%u makes use "
947 "of a format which cannot be blended at full throughput when using MSAA.",
948 VendorSpecificTag(kBPVendorArm), i, j);
949 }
950 }
951 }
952 }
953
954 return skip;
955}
956
Nadav Gevaf0808442021-05-21 13:51:25 -0400957void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
958 const VkComputePipelineCreateInfo* pCreateInfos,
959 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
960 VkResult result, void* pipe_state) {
961 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700962 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -0400963}
964
Camden5b184be2019-08-13 07:50:19 -0600965bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
966 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600967 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500968 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600969 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
970 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +0100971 if (skip) {
972 return skip;
973 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600974 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600975
976 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700977 skip |= LogPerformanceWarning(
978 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
979 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
980 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600981 }
982
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000983 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200984 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000985
Tony-LunarGb6a2daf2022-07-29 11:30:55 -0600986 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 +0200987 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600988 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700989 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
990 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600991 count++;
992 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000993 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600994 if (count > kMaxInstancedVertexBuffers) {
995 skip |= LogPerformanceWarning(
996 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
997 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
998 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
999 count, kMaxInstancedVertexBuffers);
1000 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001001 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001002
Szilard Pappaaf2da32020-06-22 10:37:35 +01001003 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
1004 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001005 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1006 VendorCheckEnabled(kBPVendorArm)) {
1007 skip |= LogPerformanceWarning(
1008 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1009 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1010 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1011 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1012 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1013 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001014 }
1015
Attilio Provenzano02859b22020-02-27 14:17:28 +00001016 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001017 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001018 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001019 auto prev_pipeline = pipeline_cache_.load();
1020 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001021 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
1022 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1023 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
1024 }
1025
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001026 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001027 skip |=
1028 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1029 "%s Performance warning: Too many pipelines created, consider consolidation",
1030 VendorSpecificTag(kBPVendorAMD));
1031 }
1032
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001033 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001034 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1035 "%s Performance warning: Use of primitive restart is not recommended",
1036 VendorSpecificTag(kBPVendorAMD));
1037 }
1038
1039 // TODO: this might be too aggressive of a check
1040 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1041 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1042 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1043 VendorSpecificTag(kBPVendorAMD));
1044 }
1045 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001046
Camden5b184be2019-08-13 07:50:19 -06001047 return skip;
1048}
1049
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001050static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1051 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1052 std::vector<bp_state::AttachmentInfo> result;
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06001053 if (!rp || rp->UsesDynamicRendering()) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001054 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001055 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001056
1057 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1058
1059 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1060 // are only non-null if they are enabled.
1061 if (create_info.pColorBlendState) {
1062 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1063 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1064 for (uint32_t j = 0; j < num_color_attachments; j++) {
1065 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1066 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1067 if (attachment != VK_ATTACHMENT_UNUSED) {
1068 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1069 }
1070 }
1071 }
1072 }
1073
1074 if (create_info.pDepthStencilState &&
1075 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1076 create_info.pDepthStencilState->stencilTestEnable)) {
1077 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1078 if (attachment != VK_ATTACHMENT_UNUSED) {
1079 VkImageAspectFlags aspects = 0;
1080 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1081 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1082 }
1083 if (create_info.pDepthStencilState->stencilTestEnable) {
1084 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1085 }
1086 result.push_back({attachment, aspects});
1087 }
1088 }
1089 return result;
1090}
1091
1092bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1093 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1094 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1095 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1096 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1097
1098std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1099 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1100 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1101 return std::static_pointer_cast<PIPELINE_STATE>(
1102 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001103}
1104
Sam Walls0961ec02020-03-31 16:39:15 +01001105void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1106 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1107 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1108 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001109 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001110 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001111}
1112
Camden5b184be2019-08-13 07:50:19 -06001113bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1114 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001115 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001116 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001117 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1118 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001119
1120 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001121 skip |= LogPerformanceWarning(
1122 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1123 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1124 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001125 }
1126
Nadav Gevaf0808442021-05-21 13:51:25 -04001127 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001128 auto prev_pipeline = pipeline_cache_.load();
1129 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1130 skip |= LogPerformanceWarning(
1131 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1132 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001133 "improve cache hit rate",
1134 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001135 }
1136 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001137
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001138 for (uint32_t i = 0; i < createInfoCount; i++) {
1139 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1140 if (VendorCheckEnabled(kBPVendorArm)) {
1141 skip |= ValidateCreateComputePipelineArm(createInfo);
1142 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001143
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001144 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1145 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1146 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1147 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1148 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1149 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1150 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1151 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1152 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001153 }
1154 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001155 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001156 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001157
1158 return skip;
1159}
1160
1161bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1162 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001163 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001164 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001165 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1166 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001167
1168 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001169 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001170
1171 uint32_t thread_count = x * y * z;
1172
1173 // Generate a priori warnings about work group sizes.
1174 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1175 skip |= LogPerformanceWarning(
1176 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1177 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1178 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1179 "groups with less than %u threads, especially when using barrier() or shared memory.",
1180 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1181 }
1182
1183 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1184 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1185 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1186 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1187 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1188 "%u, %u) is not aligned to %u "
1189 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1190 "leave threads idle on the shader "
1191 "core.",
1192 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1193 kThreadGroupDispatchCountAlignmentArm);
1194 }
1195
sfricke-samsungef15e482022-01-26 11:32:49 -08001196 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1197 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001198
1199 unsigned dimensions = 0;
1200 if (x > 1) dimensions++;
1201 if (y > 1) dimensions++;
1202 if (z > 1) dimensions++;
1203 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1204 dimensions = std::max(dimensions, 1u);
1205
1206 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1207 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1208 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1209 bool accesses_2d = false;
1210 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001211 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001212 if (dim < 0) continue;
1213 auto spvdim = spv::Dim(dim);
1214 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1215 }
1216
1217 if (accesses_2d && dimensions < 2) {
1218 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1219 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1220 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1221 "exhibiting poor spatial locality with respect to one or more shader resources.",
1222 VendorSpecificTag(kBPVendorArm), x, y, z);
1223 }
1224
Camden5b184be2019-08-13 07:50:19 -06001225 return skip;
1226}
1227
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001228bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001229 bool skip = false;
1230
1231 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001232 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1233 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001234 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001235 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1236 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001237 }
1238
1239 return skip;
1240}
1241
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001242bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1243 bool skip = false;
1244
1245 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1246 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1247 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1248 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1249 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1250 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1251 }
1252
1253 return skip;
1254}
1255
1256bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1257 bool skip = false;
1258 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1259
1260 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1261 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1262
1263 return skip;
1264}
1265
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001266void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001267 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1268 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1269 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1270 LogPerformanceWarning(
1271 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1272 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1273 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1274 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1275 "convenient opportunity.",
1276 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1277 }
1278 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001279
1280 // AMD best practice
1281 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001282 num_queue_submissions_ = 0;
1283 num_barriers_objects_ = 0;
1284 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001285}
1286
Jeff Bolz5c801d12019-10-09 10:38:45 -05001287bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1288 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001289 bool skip = false;
1290
1291 for (uint32_t submit = 0; submit < submitCount; submit++) {
1292 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1293 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1294 }
ziga-lunargc77f0c02022-04-18 00:15:16 +02001295 if (pSubmits[submit].signalSemaphoreCount == 0 && pSubmits[submit].pSignalSemaphores != nullptr) {
1296 skip |=
1297 LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1298 "pSubmits[%" PRIu32 "].pSignalSemaphores is set, but pSubmits[%" PRIu32 "].signalSemaphoreCount is 0.",
1299 submit, submit);
1300 }
1301 if (pSubmits[submit].waitSemaphoreCount == 0 && pSubmits[submit].pWaitSemaphores != nullptr) {
1302 skip |= LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1303 "pSubmits[%" PRIu32 "].pWaitSemaphores is set, but pSubmits[%" PRIu32 "].waitSemaphoreCount is 0.",
1304 submit, submit);
1305 }
Camden5b184be2019-08-13 07:50:19 -06001306 }
1307
1308 return skip;
1309}
1310
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001311bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1312 VkFence fence) const {
1313 bool skip = false;
1314
1315 for (uint32_t submit = 0; submit < submitCount; submit++) {
1316 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1317 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1318 }
1319 }
1320
1321 return skip;
1322}
1323
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001324bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1325 VkFence fence) const {
1326 bool skip = false;
1327
1328 for (uint32_t submit = 0; submit < submitCount; submit++) {
1329 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1330 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1331 }
1332 }
1333
1334 return skip;
1335}
1336
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001337bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1338 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1339 bool skip = false;
1340
1341 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1342 skip |= LogPerformanceWarning(
1343 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1344 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1345 "pool instead.");
1346 }
1347
1348 return skip;
1349}
1350
1351bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1352 const VkCommandBufferBeginInfo* pBeginInfo) const {
1353 bool skip = false;
1354
1355 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1356 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1357 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1358 }
1359
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001360 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1361 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001362 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1363 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1364 VendorSpecificTag(kBPVendorArm));
1365 }
1366
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001367 return skip;
1368}
1369
Jeff Bolz5c801d12019-10-09 10:38:45 -05001370bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001371 bool skip = false;
1372
1373 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1374
1375 return skip;
1376}
1377
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001378bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1379 const VkDependencyInfoKHR* pDependencyInfo) const {
1380 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1381}
1382
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001383bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1384 const VkDependencyInfo* pDependencyInfo) const {
1385 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1386}
1387
Jeff Bolz5c801d12019-10-09 10:38:45 -05001388bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1389 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001390 bool skip = false;
1391
1392 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1393
1394 return skip;
1395}
1396
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001397bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1398 VkPipelineStageFlags2KHR stageMask) const {
1399 bool skip = false;
1400
1401 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1402
1403 return skip;
1404}
1405
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001406bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1407 VkPipelineStageFlags2 stageMask) const {
1408 bool skip = false;
1409
1410 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1411
1412 return skip;
1413}
1414
Camden5b184be2019-08-13 07:50:19 -06001415bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1416 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1417 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1418 uint32_t bufferMemoryBarrierCount,
1419 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1420 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001421 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001422 bool skip = false;
1423
1424 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1425 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1426
1427 return skip;
1428}
1429
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001430bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1431 const VkDependencyInfoKHR* pDependencyInfos) const {
1432 bool skip = false;
1433 for (uint32_t i = 0; i < eventCount; i++) {
1434 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1435 }
1436
1437 return skip;
1438}
1439
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001440bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1441 const VkDependencyInfo* pDependencyInfos) const {
1442 bool skip = false;
1443 for (uint32_t i = 0; i < eventCount; i++) {
1444 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1445 }
1446
1447 return skip;
1448}
1449
Camden5b184be2019-08-13 07:50:19 -06001450bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1451 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1452 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1453 uint32_t bufferMemoryBarrierCount,
1454 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1455 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001456 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001457 bool skip = false;
1458
1459 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1460 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1461
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001462 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1463 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1464 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1465 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1466 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1467 "may be discarded, but the newLayout is %s, which is read only.",
1468 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1469 }
1470 }
1471
Nadav Gevaf0808442021-05-21 13:51:25 -04001472 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001473 auto num = num_barriers_objects_.load();
1474 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001475 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001476 "%s Performance warning: In this frame, %" PRIu32
1477 " barriers were already submitted. Barriers have a high cost and can "
1478 "stall the GPU. "
1479 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1480 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001481 }
1482
1483 std::array<VkImageLayout, 3> read_layouts = {
1484 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1485 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1486 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1487 };
1488
1489 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1490 // read to read barriers
1491 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1492 bool old_is_read_layout = found != read_layouts.end();
1493 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1494 bool new_is_read_layout = found != read_layouts.end();
1495 if (old_is_read_layout && new_is_read_layout) {
1496 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1497 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1498 "time you use it.",
1499 VendorSpecificTag(kBPVendorAMD));
1500 }
1501
1502 // general with no storage
1503 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1504 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1505 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1506 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1507 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1508 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1509 VendorSpecificTag(kBPVendorAMD));
1510 }
1511 }
1512 }
1513 }
1514
Camden5b184be2019-08-13 07:50:19 -06001515 return skip;
1516}
1517
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001518bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1519 const VkDependencyInfoKHR* pDependencyInfo) const {
1520 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1521}
1522
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001523bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1524 const VkDependencyInfo* pDependencyInfo) const {
1525 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1526}
1527
Camden5b184be2019-08-13 07:50:19 -06001528bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001529 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001530 bool skip = false;
1531
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001532 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1533
1534 return skip;
1535}
1536
1537bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1538 VkQueryPool queryPool, uint32_t query) const {
1539 bool skip = false;
1540
1541 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001542
1543 return skip;
1544}
1545
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001546bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1547 VkQueryPool queryPool, uint32_t query) const {
1548 bool skip = false;
1549
1550 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1551
1552 return skip;
1553}
1554
Sam Walls0961ec02020-03-31 16:39:15 +01001555void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1556 VkPipeline pipeline) {
1557 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1558
Nadav Gevaf0808442021-05-21 13:51:25 -04001559 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001560 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001561
Sam Walls0961ec02020-03-31 16:39:15 +01001562 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001563 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001564 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001565 if (pipeline_state) {
1566 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001567 assert(cb_node);
1568 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001569
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001570 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001571 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001572
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001573 const auto* blend_state = pipeline_state->ColorBlendState();
1574 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001575
1576 if (blend_state) {
1577 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001578 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001579 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1580 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001581 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001582 }
1583 }
1584 }
1585
1586 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001587 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001588
1589 if (stencil_state && stencil_state->depthTestEnable) {
1590 switch (stencil_state->depthCompareOp) {
1591 case VK_COMPARE_OP_EQUAL:
1592 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1593 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001594 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001595 break;
1596 default:
1597 break;
1598 }
1599 }
Sam Walls0961ec02020-03-31 16:39:15 +01001600 }
1601 }
1602}
1603
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001604static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1605 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1606 const auto& subpass_info = createInfo.pSubpasses[subpass];
1607 if (subpass_info.pResolveAttachments) {
1608 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1609 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1610 }
1611 }
1612 }
1613
1614 return false;
1615}
1616
Attilio Provenzano02859b22020-02-27 14:17:28 +00001617static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1618 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001619 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001620
1621 // If an attachment is ever used as a color attachment,
1622 // resolve attachment or depth stencil attachment,
1623 // it needs to exist on tile at some point.
1624
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001625 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1626 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001627 }
1628
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001629 if (subpass_info.pResolveAttachments) {
1630 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1631 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1632 }
1633 }
1634
1635 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001636 }
1637
1638 return false;
1639}
1640
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001641static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1642 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1643 return false;
1644 }
1645
1646 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001647 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001648
1649 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1650 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1651 return true;
1652 }
1653 }
1654 }
1655
1656 return false;
1657}
1658
Attilio Provenzano02859b22020-02-27 14:17:28 +00001659bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1660 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1661 bool skip = false;
1662
1663 if (!pRenderPassBegin) {
1664 return skip;
1665 }
1666
Gareth Webbdc6549a2021-06-16 03:52:24 +01001667 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1668 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1669 "This render pass has a zero-size render area. It cannot write to any attachments, "
1670 "and can only be used for side effects such as layout transitions.");
1671 }
1672
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001673 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001674 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001675 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001676 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001677 if (rpabi) {
1678 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1679 }
1680 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001681 // Check if any attachments have LOAD operation on them
1682 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001683 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001684
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001685 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001686 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001687 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001688 }
1689
1690 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001691 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001692 }
1693
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001694 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001695
1696 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001697 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1698 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001699 }
1700
1701 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00001702 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
1703 skip |=
1704 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00001705 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00001706 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001707 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00001708 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
1709 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
1710 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1711 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1712 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001713 }
1714 }
paul-lunarg7089e272022-06-20 22:19:37 +02001715
1716 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
1717
1718 bool clearing = false;
1719
1720 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1721 const auto& attachment = rp_state->createInfo.pAttachments[att];
1722
1723 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1724 clearing = true;
1725 break;
1726 }
1727 }
1728
1729 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
1730 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
1731 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
1732 skip |= LogWarning(
1733 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
1734 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
1735 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02001736 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02001737 }
paul-lunarga0a149c2022-06-23 16:18:51 +02001738
1739 // Check if there are more clearValues than attachments
1740 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
1741 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
1742 // This could signal a bug and there seems to be no reason for this to happen on purpose.
1743 skip |= LogWarning(
1744 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
1745 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
1746 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
1747 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
1748 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001749 }
1750
1751 return skip;
1752}
1753
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001754void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1755 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001756 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001757 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
1758 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001759 }
1760}
1761
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001762void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1763 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001764 // If we're viewing a 3D slice, ignore base array layer.
1765 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001766 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 +02001767
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001768 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001769 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001770 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
1771 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001772
1773 for (uint32_t layer = 0; layer < array_layers; layer++) {
1774 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001775 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1776 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001777 }
1778 }
1779}
1780
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001781void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1782 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
1783 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001784 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001785
1786 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001787 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001788 }
1789}
1790
paul-lunarg5eb52062022-06-27 18:57:15 +02001791void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1792 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
1793 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
1794 const CMD_BUFFER_STATE&) -> bool {
1795 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
1796 return false;
1797 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001798}
1799
LawG44d414ba2022-02-23 15:35:41 +00001800void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001801 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001802 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001803 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001804 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 -07001805 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001806 LogPerformanceWarning(
1807 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00001808 "%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 +02001809 "image was used, it was written to with STORE_OP_STORE. "
1810 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1811 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00001812 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001813 } 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 +02001814 LogPerformanceWarning(
1815 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00001816 "%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 +02001817 "image was used, it was written to with vkCmdClear*Image(). "
1818 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00001819 "tile-based architectures.",
1820 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001821 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001822 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1823 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001824 const char *last_cmd = nullptr;
1825 const char *vuid = nullptr;
1826 const char *suggestion = nullptr;
1827
1828 switch (last_usage) {
1829 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1830 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1831 last_cmd = "vkCmdBlitImage";
1832 suggestion =
1833 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1834 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1835 "which avoids the memory roundtrip.";
1836 break;
1837 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1838 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1839 last_cmd = "vkCmdClear*Image";
1840 suggestion =
1841 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1842 "tile-based architectures. "
1843 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1844 break;
1845 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1846 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1847 last_cmd = "vkCmdCopy*Image";
1848 suggestion =
1849 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1850 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1851 "which avoids the memory roundtrip.";
1852 break;
1853 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1854 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1855 last_cmd = "vkCmdResolveImage";
1856 suggestion =
1857 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1858 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1859 "which avoids the memory roundtrip.";
1860 break;
1861 default:
1862 break;
1863 }
1864
1865 LogPerformanceWarning(
1866 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00001867 "%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 +01001868 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00001869 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
1870 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001871 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001872}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001873
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001874void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
1875 uint32_t array_layer, uint32_t mip_level) {
1876 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02001877
1878 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
1879 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
1880 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
1881 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
1882 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
1883 "result in undefined behaviour.");
1884 }
1885
LawG44d414ba2022-02-23 15:35:41 +00001886 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
1887 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001888 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001889}
1890
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001891void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
1892 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
1893 cb.queue_submit_functions_after_render_pass.end());
1894 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001895}
1896
1897void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1898 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001899 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1900 if (cb_node) {
1901 AddDeferredQueueOperations(*cb_node);
1902 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001903}
1904
1905void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1906 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001907 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1908 if (cb_node) {
1909 AddDeferredQueueOperations(*cb_node);
1910 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001911}
1912
1913void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1914 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001915 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1916 if (cb_node) {
1917 AddDeferredQueueOperations(*cb_node);
1918 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001919}
1920
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001921void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1922 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001923 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001924 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001925 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1926}
1927
1928void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1929 const VkRenderPassBeginInfo* pRenderPassBegin,
1930 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1931 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1932 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1933}
1934
1935void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1936 const VkRenderPassBeginInfo* pRenderPassBegin,
1937 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1938 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1939 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1940}
1941
1942void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001943
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001944 if (!pRenderPassBegin) {
1945 return;
1946 }
1947
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001948 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001949
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001950 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001951 if (rp_state) {
1952 // Check load ops
1953 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001954 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001955
1956 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1957 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1958 continue;
1959 }
1960
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001961 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001962
1963 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1964 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001965 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001966 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1967 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001968 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001969 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001970 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001971 }
1972
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001973 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001974 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001975
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001976 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001977 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1978 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001979 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001980 }
1981 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001982 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001983 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001984
Jeremy Gebben9f537102021-10-05 16:37:12 -06001985 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001986 }
1987
1988 // Check store ops
1989 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001990 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001991
1992 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1993 continue;
1994 }
1995
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001996 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001997
1998 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1999 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002000 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002001 }
2002
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002003 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002004
Jeremy Gebben9f537102021-10-05 16:37:12 -06002005 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002006 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002007 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2008 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002009 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002010 }
2011 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002012 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002013 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002014
Jeremy Gebben9f537102021-10-05 16:37:12 -06002015 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002016 }
2017 }
2018}
2019
Attilio Provenzano02859b22020-02-27 14:17:28 +00002020bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2021 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002022 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2023 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002024 return skip;
2025}
2026
2027bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2028 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002029 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002030 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2031 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002032 return skip;
2033}
2034
2035bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002036 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002037 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2038 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002039 return skip;
2040}
2041
Sam Walls0961ec02020-03-31 16:39:15 +01002042void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2043 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002044 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002045 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
sjfricke52defd42022-08-08 16:37:46 +09002046 // TODO - move this logic to the Render Pass state as cb->has_draw_cmd should stay true for lifetime of command buffer
2047 cb->has_draw_cmd = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002048 assert(cb);
2049 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002050 render_pass_state.touchesAttachments.clear();
2051 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002052 render_pass_state.numDrawCallsDepthOnly = 0;
2053 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2054 render_pass_state.colorAttachment = false;
2055 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002056 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002057 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002058
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002059 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002060
2061 // track depth / color attachment usage within the renderpass
2062 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2063 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002064 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002065
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002066 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002067 }
2068}
2069
2070void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2071 VkSubpassContents contents) {
2072 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2073 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2074}
2075
2076void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2077 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2078 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2079 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2080}
2081
2082void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2083 const VkRenderPassBeginInfo* pRenderPassBegin,
2084 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2085 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2086 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2087}
2088
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002089// Generic function to handle validation for all CmdDraw* type functions
2090bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2091 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002092 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002093 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002094 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2095 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002096 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002097
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002098 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002099 if (pipeline_state && pipeline_state->vertex_input_state &&
2100 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002101 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002102 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002103 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002104 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2105 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002106 }
2107 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002108
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002109 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002110 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002111 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002112 if (rp_state) {
2113 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2114 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002115 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002116 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002117 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2118 const auto* raster_state = pipe->RasterizationState();
2119 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2120 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002121 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2122 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2123 }
2124 }
2125 }
2126 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002127 }
2128 return skip;
2129}
2130
Sam Walls0961ec02020-03-31 16:39:15 +01002131void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002132 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002133 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002134 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002135 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002136 }
2137
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002138 if (cb_node->render_pass_state.drawTouchAttachments) {
2139 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2140 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002141 }
2142 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002143 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002144 }
2145}
2146
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002147void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2148 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002149 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2150 // depth prepass warnings First find the lowest enabled draw count
2151 uint32_t lowestEnabledMinDrawCount = 0;
2152 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
2153 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
2154 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
2155
2156 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002157 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2158 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002159 }
2160}
2161
Camden5b184be2019-08-13 07:50:19 -06002162bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002163 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002164 bool skip = false;
2165
2166 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002167 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2168 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002169 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002170 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002171
2172 return skip;
2173}
2174
Sam Walls0961ec02020-03-31 16:39:15 +01002175void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2176 uint32_t firstVertex, uint32_t firstInstance) {
2177 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2178 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2179}
2180
Camden5b184be2019-08-13 07:50:19 -06002181bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002182 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002183 bool skip = false;
2184
2185 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002186 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2187 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002188 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002189 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2190
Attilio Provenzano02859b22020-02-27 14:17:28 +00002191 // Check if we reached the limit for small indexed draw calls.
2192 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002193 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002194 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002195 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00002196 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002197 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00002198 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002199 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2200 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00002201 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
2202 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002203 }
2204
Sam Walls8e77e4f2020-03-16 20:47:40 +00002205 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002206 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002207 }
2208
2209 return skip;
2210}
2211
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002212bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00002213 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2214 bool skip = false;
2215
2216 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00002217
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002218 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
2219 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002220
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002221 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002222 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002223 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2224 const void* ib_mem = ib_mem_state.p_driver_data;
2225 bool primitive_restart_enable = false;
2226
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002227 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002228 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002229 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002230
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002231 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
2232 if (ia_state) {
2233 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002234 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002235
2236 // 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 -06002237 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002238 uint32_t scan_stride;
2239 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2240 scan_stride = sizeof(uint8_t);
2241 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2242 scan_stride = sizeof(uint16_t);
2243 } else {
2244 scan_stride = sizeof(uint32_t);
2245 }
2246
2247 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2248 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2249
2250 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2251 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2252 // irrespective of whether or not they're part of the draw call.
2253
2254 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2255 uint32_t min_index = ~0u;
2256 // start with maximum as 0 and adjust to indices in the buffer
2257 uint32_t max_index = 0u;
2258
2259 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2260 // for the given index buffer
2261 uint32_t vertex_shade_count = 0;
2262
2263 PostTransformLRUCacheModel post_transform_cache;
2264
2265 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2266 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2267 // target architecture.
2268 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2269 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2270 post_transform_cache.resize(32);
2271
2272 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2273 uint32_t scan_index;
2274 uint32_t primitive_restart_value;
2275 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2276 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2277 primitive_restart_value = 0xFF;
2278 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2279 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2280 primitive_restart_value = 0xFFFF;
2281 } else {
2282 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2283 primitive_restart_value = 0xFFFFFFFF;
2284 }
2285
2286 max_index = std::max(max_index, scan_index);
2287 min_index = std::min(min_index, scan_index);
2288
2289 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2290 bool in_cache = post_transform_cache.query_cache(scan_index);
2291 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2292 if (!in_cache) vertex_shade_count++;
2293 }
2294 }
2295
2296 // 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 +01002297 // 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
2298 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002299
2300 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002301 skip |=
2302 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2303 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2304 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2305 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2306 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2307 VendorSpecificTag(kBPVendorArm),
2308 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002309 return skip;
2310 }
2311
2312 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2313 // 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 +01002314 const size_t refs_per_bucket = 64;
2315 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2316
2317 const uint32_t n_indices = max_index - min_index + 1;
2318 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2319 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2320
2321 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2322 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002323
2324 // To avoid using too much memory, we run over the indices again.
2325 // Knowing the size from the last scan allows us to record index usage with bitsets
2326 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2327 uint32_t scan_index;
2328 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2329 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2330 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2331 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2332 } else {
2333 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2334 }
2335 // keep track of the set of all indices used to reference vertices in the draw call
2336 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002337 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2338 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002339 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2340 }
2341
2342 uint32_t vertex_reference_count = 0;
2343 for (const auto& bitset : vertex_reference_buckets) {
2344 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2345 }
2346
2347 // 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 -07002348 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002349 // 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 -07002350 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002351
2352 if (utilization < 0.5f) {
2353 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2354 "%s The indices which were specified for the draw call only utilise approximately "
2355 "%.02f%% of the bound vertex buffer.",
2356 VendorSpecificTag(kBPVendorArm), utilization);
2357 }
2358
2359 if (cache_hit_rate <= 0.5f) {
2360 skip |=
2361 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2362 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2363 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2364 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2365 "recently shaded vertices.",
2366 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2367 }
2368 }
2369
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002370 return skip;
2371}
2372
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002373bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2374 const VkCommandBuffer* pCommandBuffers) const {
2375 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002376 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002377 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002378 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002379 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002380 continue;
2381 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002382 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002383 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002384 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
2385 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002386 }
2387 }
2388 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002389
2390 if (VendorCheckEnabled(kBPVendorAMD)) {
2391 if (commandBufferCount > 0) {
2392 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2393 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2394 VendorSpecificTag(kBPVendorAMD));
2395 }
2396 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002397 return skip;
2398}
2399
2400void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2401 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002402 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2403
2404 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2405 if (!primary) {
2406 return;
2407 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002408
2409 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002410 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
2411 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002412 continue;
2413 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002414
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002415 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
2416 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2417 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
2418 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002419 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002420 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002421 }
2422 }
2423
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002424 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
2425 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002426 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002427
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002428 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
2429 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002430 }
2431
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002432}
2433
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002434void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2435 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002436 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002437 auto itr =
2438 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2439 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002440
2441 if (itr != state.touchesAttachments.end()) {
2442 itr->aspects |= aspects;
2443 } else {
2444 state.touchesAttachments.push_back({ fb_attachment, aspects });
2445 }
2446}
2447
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002448void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002449 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2450 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002451 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002452 // If we observe a full clear before any other access to a frame buffer attachment,
2453 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002454 auto itr =
2455 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2456 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002457
2458 uint32_t new_aspects = aspects;
2459 if (itr != state.touchesAttachments.end()) {
2460 new_aspects = aspects & ~itr->aspects;
2461 itr->aspects |= aspects;
2462 } else {
2463 state.touchesAttachments.push_back({ fb_attachment, aspects });
2464 }
2465
2466 if (new_aspects == 0) {
2467 return;
2468 }
2469
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002470 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002471 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2472 // CmdExecuteCommands.
2473 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2474 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2475 }
2476}
2477
2478void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2479 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2480 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002481 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
2482
2483 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2484 auto* rp_state = cmd_state->activeRenderPass.get();
2485 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002486 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2487
2488 if (rectCount == 0 || !rp_state) {
2489 return;
2490 }
2491
2492 if (!is_secondary && !fb_state) {
2493 return;
2494 }
2495
2496 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002497 bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002498
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06002499 if (!rp_state->UsesDynamicRendering()) {
ziga-lunarg885c6542022-03-07 01:08:25 +01002500 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2501 for (uint32_t i = 0; i < attachmentCount; i++) {
2502 auto& attachment = pClearAttachments[i];
2503 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2504 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002505
ziga-lunarg885c6542022-03-07 01:08:25 +01002506 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2507 if (subpass.pDepthStencilAttachment) {
2508 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2509 }
2510 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2511 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002512 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002513
ziga-lunarg885c6542022-03-07 01:08:25 +01002514 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2515 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002516 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01002517 aspects, rectCount, pRects);
2518 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002519 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01002520 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002521 }
2522 }
2523 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002524}
2525
Attilio Provenzano02859b22020-02-27 14:17:28 +00002526void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2527 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2528 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2529 firstInstance);
2530
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002531 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002532 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2533 cmd_state->small_indexed_draw_call_count++;
2534 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002535
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002536 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002537}
2538
Sam Walls0961ec02020-03-31 16:39:15 +01002539void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2540 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2541 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2542 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2543}
2544
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002545bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2546 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2547 uint32_t maxDrawCount, uint32_t stride) const {
2548 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2549
2550 return skip;
2551}
2552
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002553bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2554 VkDeviceSize offset, VkBuffer countBuffer,
2555 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2556 uint32_t stride) const {
2557 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002558
2559 return skip;
2560}
2561
2562bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002563 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002564 bool skip = false;
2565
2566 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002567 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2568 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002569 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002570 }
2571
2572 return skip;
2573}
2574
Sam Walls0961ec02020-03-31 16:39:15 +01002575void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2576 uint32_t count, uint32_t stride) {
2577 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2578 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2579}
2580
Camden5b184be2019-08-13 07:50:19 -06002581bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002582 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002583 bool skip = false;
2584
2585 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002586 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2587 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002588 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002589 }
2590
2591 return skip;
2592}
2593
Sam Walls0961ec02020-03-31 16:39:15 +01002594void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2595 uint32_t count, uint32_t stride) {
2596 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2597 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2598}
2599
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002600void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
2601 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002602 for (const auto& binding : *descriptor_set) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002603 // For bindless scenarios, we should not attempt to track descriptor set state.
2604 // It is highly uncertain which resources are actually bound.
2605 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002606 if (binding->binding_flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2607 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002608 continue;
2609 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002610
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002611 for (uint32_t i = 0; i < binding->count; ++i) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002612 VkImageView image_view{VK_NULL_HANDLE};
2613
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002614 auto descriptor = binding->GetDescriptor(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02002615 if (!descriptor) {
2616 continue;
2617 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002618 switch (descriptor->GetClass()) {
2619 case cvdescriptorset::DescriptorClass::Image: {
2620 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2621 image_view = image_descriptor->GetImageView();
2622 }
2623 break;
2624 }
2625 case cvdescriptorset::DescriptorClass::ImageSampler: {
2626 if (const auto image_sampler_descriptor =
2627 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2628 image_view = image_sampler_descriptor->GetImageView();
2629 }
2630 break;
2631 }
2632 default:
2633 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002634 }
2635
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002636 if (image_view) {
2637 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
2638 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
2639 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002640 }
2641 }
2642 }
2643 }
2644}
2645
2646void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2647 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002648 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2649 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002650}
2651
2652void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2653 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002654 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2655 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002656}
2657
2658void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2659 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002660 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2661 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002662}
2663
Camden5b184be2019-08-13 07:50:19 -06002664bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002665 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002666 bool skip = false;
2667
2668 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002669 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2670 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2671 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2672 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002673 }
2674
2675 return skip;
2676}
Camden83a9c372019-08-14 11:41:38 -06002677
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002678bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2679 bool skip = false;
2680 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2681 skip |= ValidateCmdEndRenderPass(commandBuffer);
2682 return skip;
2683}
2684
2685bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2686 bool skip = false;
2687 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2688 skip |= ValidateCmdEndRenderPass(commandBuffer);
2689 return skip;
2690}
2691
Sam Walls0961ec02020-03-31 16:39:15 +01002692bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2693 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002694 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002695 skip |= ValidateCmdEndRenderPass(commandBuffer);
2696 return skip;
2697}
2698
2699bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2700 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002701 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002702
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002703 if (cmd == nullptr) return skip;
2704 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002705
LawG4b21485c2022-02-28 13:46:48 +00002706 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
2707 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2708 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2709 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
2710 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
2711
2712 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01002713 bool uses_depth =
2714 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01002715 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00002716
Sam Walls0961ec02020-03-31 16:39:15 +01002717 if (uses_depth) {
2718 skip |= LogPerformanceWarning(
2719 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00002720 "%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 +00002721 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
2722 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
2723 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
2724 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01002725 }
2726
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002727 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2728
LawG40da9c3d2022-03-01 09:51:01 +00002729 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002730 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2731 // it is redundant to have it be part of the render pass.
2732 // Only consider it redundant if it will actually consume bandwidth, i.e.
2733 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2734 // as is using pure input attachments.
2735 // CLEAR -> STORE might be considered a "useful" thing to do, but
2736 // the optimal thing to do is to defer the clear until you're actually
2737 // going to render to the image.
2738
2739 uint32_t num_attachments = rp->createInfo.attachmentCount;
2740 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002741 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2742 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002743 continue;
2744 }
2745
2746 auto& attachment = rp->createInfo.pAttachments[i];
2747
2748 VkImageAspectFlags bandwidth_aspects = 0;
2749
2750 if (!FormatIsStencilOnly(attachment.format) &&
2751 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2752 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2753 if (FormatHasDepth(attachment.format)) {
2754 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2755 } else {
2756 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2757 }
2758 }
2759
2760 if (FormatHasStencil(attachment.format) &&
2761 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2762 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2763 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2764 }
2765
2766 if (!bandwidth_aspects) {
2767 continue;
2768 }
2769
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002770 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002771 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002772 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002773 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002774 untouched_aspects &= ~itr->aspects;
2775 }
2776
2777 if (untouched_aspects) {
2778 skip |= LogPerformanceWarning(
2779 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00002780 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002781 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00002782 "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 +00002783 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00002784 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002785 }
2786 }
2787 }
2788
Sam Walls0961ec02020-03-31 16:39:15 +01002789 return skip;
2790}
2791
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002792void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002793 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2794 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002795}
2796
2797void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002798 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2799 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002800}
2801
Camden Stocker9c051442019-11-06 14:28:43 -08002802bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2803 const char* api_name) const {
2804 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002805 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002806
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002807 if (bp_pd_state) {
2808 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2809 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2810 "Potential problem with calling %s() without first retrieving properties from "
2811 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2812 api_name);
2813 }
Camden Stocker9c051442019-11-06 14:28:43 -08002814 }
2815
2816 return skip;
2817}
2818
Camden83a9c372019-08-14 11:41:38 -06002819bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002820 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002821 bool skip = false;
2822
Camden Stocker9c051442019-11-06 14:28:43 -08002823 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002824
Camden Stocker9c051442019-11-06 14:28:43 -08002825 return skip;
2826}
2827
2828bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2829 uint32_t planeIndex,
2830 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2831 bool skip = false;
2832
2833 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2834
2835 return skip;
2836}
2837
2838bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2839 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2840 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2841 bool skip = false;
2842
2843 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002844
2845 return skip;
2846}
Camden05de2d42019-08-19 10:23:56 -06002847
2848bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002849 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002850 bool skip = false;
2851
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002852 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002853
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002854 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002855 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002856 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002857 skip |=
2858 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2859 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2860 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002861 }
Camden05de2d42019-08-19 10:23:56 -06002862
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002863 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2864 skip |= LogWarning(
2865 device, kVUID_BestPractices_Swapchain_InvalidCount,
2866 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002867 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002868 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2869 }
2870 }
2871
Camden05de2d42019-08-19 10:23:56 -06002872 return skip;
2873}
2874
2875// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002876bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002877 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002878 const CALL_STATE call_state,
2879 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002880 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002881 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2882 if (UNCALLED == call_state) {
2883 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002884 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002885 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2886 "recommended "
2887 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2888 caller_name, caller_name);
2889 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002890 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2891 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002892 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2893 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2894 ". It is recommended to instead receive all the properties by calling %s with "
2895 "pQueueFamilyPropertyCount that was "
2896 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002897 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002898 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002899 }
2900
2901 return skip;
2902}
2903
Jeff Bolz5c801d12019-10-09 10:38:45 -05002904bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2905 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002906 bool skip = false;
2907
2908 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002909 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002910 if (!as_state->memory_requirements_checked) {
2911 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2912 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2913 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002914 skip |= LogWarning(
2915 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002916 "vkBindAccelerationStructureMemoryNV(): "
2917 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2918 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2919 }
2920 }
2921
2922 return skip;
2923}
2924
Camden05de2d42019-08-19 10:23:56 -06002925bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2926 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002927 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002928 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002929 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002930 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002931 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2932 "vkGetPhysicalDeviceQueueFamilyProperties()");
2933 }
2934 return false;
Camden05de2d42019-08-19 10:23:56 -06002935}
2936
Mike Schuchardt2df08912020-12-15 16:28:09 -08002937bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2938 uint32_t* pQueueFamilyPropertyCount,
2939 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002940 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002941 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002942 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002943 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2944 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2945 }
2946 return false;
Camden05de2d42019-08-19 10:23:56 -06002947}
2948
Jeff Bolz5c801d12019-10-09 10:38:45 -05002949bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002950 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002951 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002952 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002953 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002954 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2955 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2956 }
2957 return false;
Camden05de2d42019-08-19 10:23:56 -06002958}
2959
2960bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2961 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002962 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002963 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002964 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002965 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002966 bool skip = false;
2967 if (call_state == UNCALLED) {
2968 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2969 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002970 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2971 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2972 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002973 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002974 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002975 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2976 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2977 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2978 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002979 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06002980 }
2981 }
2982 return skip;
2983}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002984
2985bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002986 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002987 bool skip = false;
2988
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002989 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2990 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002991 // 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 -07002992 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002993 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2994 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002995 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002996 // 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 -07002997 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2998 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002999 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003000 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003001 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003002 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003003 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003004 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3005 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3006 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003007 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003008 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3009 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003010 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003011 }
3012 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003013 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003014 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003015 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003016 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3017 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003018 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003019 }
3020 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003021 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3022 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003023 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003024 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003025 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003026 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003027 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003028 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3029 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3030 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003031 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003032 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3033 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003034 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003035 }
3036 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003037 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003038 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003039 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003040 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3041 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003042 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003043 }
3044 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3045 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003046 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003047 }
3048 }
3049 }
3050 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003051 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
3052 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003053 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003054 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003055 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
3056 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003057 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003058 }
3059 }
3060 }
3061
3062 return skip;
3063}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003064
Mark Lobodzinski84101d72020-04-24 09:43:48 -06003065void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
3066 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003067 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003068 return;
3069 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003070
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003071 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3072 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
3073 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3074 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003075 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003076 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003077 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003078 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003079 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3080 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
3081 image_state->sparse_metadata_bound = true;
3082 }
3083 }
3084 }
3085 }
3086}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003087
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003088bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003089 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003090 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003091 // We don't know the accurate render area in a secondary,
3092 // so assume we clear the entire frame buffer.
3093 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
3094 return true;
3095 }
3096
3097 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
3098 for (uint32_t i = 0; i < rectCount; i++) {
3099 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003100 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003101 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
3102 return true;
3103 }
3104 }
3105
3106 return false;
3107}
3108
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003109bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
3110 VkImageAspectFlags aspects, bool secondary) const {
3111 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003112 bool skip = false;
3113
3114 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3115 return skip;
3116 }
3117
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003118 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003119
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003120 auto attachment_itr =
3121 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
3122 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003123
3124 // Only report aspects which haven't been touched yet.
3125 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003126 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003127 new_aspects &= ~attachment_itr->aspects;
3128 }
3129
3130 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
sjfricke52defd42022-08-08 16:37:46 +09003131 if (!cmd.has_draw_cmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003132 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003133 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003134 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3135 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003136 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003137 }
3138
3139 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3140 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3141 skip |= LogPerformanceWarning(
3142 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3143 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3144 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3145 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003146 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003147 }
3148
3149 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3150 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003151 skip |=
3152 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3153 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3154 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3155 "it is more efficient.",
3156 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003157 }
3158
3159 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3160 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003161 skip |=
3162 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3163 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3164 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3165 "it is more efficient.",
3166 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003167 }
3168
3169 return skip;
3170}
3171
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003172bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003173 const VkClearAttachment* pAttachments, uint32_t rectCount,
3174 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003175 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003176 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003177 if (!cb_node) return skip;
3178
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003179 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3180 // Defer checks to ExecuteCommands.
3181 return skip;
3182 }
3183
3184 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003185 if (!ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003186 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003187 }
3188
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003189 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3190 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003191 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003192 if (rp) {
3193 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3194
3195 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003196 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003197
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003198 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3199 uint32_t color_attachment = attachment.colorAttachment;
3200 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003201 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003202 }
3203
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003204 if (subpass.pDepthStencilAttachment &&
3205 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003206 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003207 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003208 }
3209 }
3210 }
3211
Nadav Gevaf0808442021-05-21 13:51:25 -04003212 if (VendorCheckEnabled(kBPVendorAMD)) {
3213 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3214 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3215 bool black_check = false;
3216 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3217 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3218 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3219 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3220 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3221
3222 bool white_check = false;
3223 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3224 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3225 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3226 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3227 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3228
3229 if (black_check && white_check) {
3230 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3231 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3232 "Consider changing to one of the following:"
3233 "RGBA(0, 0, 0, 0) "
3234 "RGBA(0, 0, 0, 1) "
3235 "RGBA(1, 1, 1, 0) "
3236 "RGBA(1, 1, 1, 1)",
3237 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3238 }
3239 } else {
3240 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3241 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3242 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3243 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3244 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3245 "attachment %" PRId32 " is not a fast clear value."
3246 "Consider changing to one of the following:"
3247 "D=0.0f, S=0"
3248 "D=1.0f, S=0",
3249 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3250 }
3251 }
3252 }
3253 }
3254
Camden Stockerf55721f2019-09-09 11:04:49 -06003255 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003256}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003257
3258bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3259 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3260 const VkImageResolve* pRegions) const {
3261 bool skip = false;
3262
3263 skip |= VendorCheckEnabled(kBPVendorArm) &&
3264 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3265 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3266 "This is a very slow and extremely bandwidth intensive path. "
3267 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3268 VendorSpecificTag(kBPVendorArm));
3269
3270 return skip;
3271}
3272
Jeff Leger178b1e52020-10-05 12:22:23 -04003273bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3274 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3275 bool skip = false;
3276
3277 skip |= VendorCheckEnabled(kBPVendorArm) &&
3278 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3279 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3280 "This is a very slow and extremely bandwidth intensive path. "
3281 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3282 VendorSpecificTag(kBPVendorArm));
3283
3284 return skip;
3285}
3286
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003287bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3288 const VkResolveImageInfo2* pResolveImageInfo) const {
3289 bool skip = false;
3290
3291 skip |= VendorCheckEnabled(kBPVendorArm) &&
3292 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3293 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3294 "This is a very slow and extremely bandwidth intensive path. "
3295 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3296 VendorSpecificTag(kBPVendorArm));
3297
3298 return skip;
3299}
3300
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003301void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3302 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3303 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003304 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003305 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003306 auto src = Get<bp_state::Image>(srcImage);
3307 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003308
3309 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003310 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3311 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003312 }
3313}
3314
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003315void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3316 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003317 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003318 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003319 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3320 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003321 uint32_t regionCount = pResolveImageInfo->regionCount;
3322
3323 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003324 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3325 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003326 }
3327}
3328
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003329void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3330 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003331 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003332 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003333 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3334 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003335 uint32_t regionCount = pResolveImageInfo->regionCount;
3336
3337 for (uint32_t i = 0; i < regionCount; i++) {
3338 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3339 pResolveImageInfo->pRegions[i].srcSubresource);
3340 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3341 pResolveImageInfo->pRegions[i].dstSubresource);
3342 }
3343}
3344
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003345void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3346 const VkClearColorValue* pColor, uint32_t rangeCount,
3347 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003348 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003349 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003350 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003351
3352 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003353 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003354 }
3355}
3356
3357void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3358 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3359 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003360 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003361 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003362 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003363
3364 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003365 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003366 }
3367}
3368
3369void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3370 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3371 const VkImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003372 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003373 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003374 auto src = Get<bp_state::Image>(srcImage);
3375 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003376
3377 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003378 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3379 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003380 }
3381}
3382
3383void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3384 VkImageLayout dstImageLayout, uint32_t regionCount,
3385 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003386 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003387 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003388 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003389
3390 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003391 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003392 }
3393}
3394
3395void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3396 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003397 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003398 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003399 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003400
3401 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003402 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003403 }
3404}
3405
3406void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3407 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3408 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003409 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003410 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003411 auto src = Get<bp_state::Image>(srcImage);
3412 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003413
3414 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003415 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3416 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003417 }
3418}
3419
Attilio Provenzano02859b22020-02-27 14:17:28 +00003420bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3421 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3422 bool skip = false;
3423
3424 if (VendorCheckEnabled(kBPVendorArm)) {
3425 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3426 skip |= LogPerformanceWarning(
3427 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3428 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3429 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3430 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003431 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003432 }
3433
3434 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3435 skip |= LogPerformanceWarning(
3436 device, kVUID_BestPractices_CreateSampler_LodClamping,
3437 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3438 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3439 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3440 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3441 }
3442
3443 if (pCreateInfo->mipLodBias != 0.0f) {
3444 skip |=
3445 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3446 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3447 "descriptors being created and may cause reduced performance.",
3448 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3449 }
3450
3451 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3452 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3453 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3454 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3455 skip |= LogPerformanceWarning(
3456 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3457 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3458 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3459 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3460 VendorSpecificTag(kBPVendorArm));
3461 }
3462
3463 if (pCreateInfo->unnormalizedCoordinates) {
3464 skip |= LogPerformanceWarning(
3465 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3466 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3467 "descriptors being created and may cause reduced performance.",
3468 VendorSpecificTag(kBPVendorArm));
3469 }
3470
3471 if (pCreateInfo->anisotropyEnable) {
3472 skip |= LogPerformanceWarning(
3473 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3474 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3475 "and may cause reduced performance.",
3476 VendorSpecificTag(kBPVendorArm));
3477 }
3478 }
3479
3480 return skip;
3481}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003482
Nadav Gevaf0808442021-05-21 13:51:25 -04003483void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3484 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3485 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3486 void* cgpl_state) {
3487 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3488 pPipelines);
3489 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003490 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003491}
3492
3493bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3494 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3495 const VkCopyDescriptorSet* pDescriptorCopies) const {
3496 bool skip = false;
3497 if (VendorCheckEnabled(kBPVendorAMD)) {
3498 if (descriptorCopyCount > 0) {
3499 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3500 "%s Performance warning: copying descriptor sets is not recommended",
3501 VendorSpecificTag(kBPVendorAMD));
3502 }
3503 }
3504
3505 return skip;
3506}
3507
3508bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3509 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3510 const VkAllocationCallbacks* pAllocator,
3511 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3512 bool skip = false;
3513 if (VendorCheckEnabled(kBPVendorAMD)) {
3514 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3515 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3516 "vkUpdateDescriptorSet instead",
3517 VendorSpecificTag(kBPVendorAMD));
3518 }
3519
3520 return skip;
3521}
3522
3523bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3524 const VkClearColorValue* pColor, uint32_t rangeCount,
3525 const VkImageSubresourceRange* pRanges) const {
3526 bool skip = false;
3527 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003528 skip |= LogPerformanceWarning(
3529 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003530 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3531 "vkCmdClearAttachments instead",
3532 VendorSpecificTag(kBPVendorAMD));
3533 }
3534
3535 return skip;
3536}
3537
3538bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3539 VkImageLayout imageLayout,
3540 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3541 const VkImageSubresourceRange* pRanges) const {
3542 bool skip = false;
3543 if (VendorCheckEnabled(kBPVendorAMD)) {
3544 skip |= LogPerformanceWarning(
3545 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3546 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3547 "vkCmdClearAttachments instead",
3548 VendorSpecificTag(kBPVendorAMD));
3549 }
3550
3551 return skip;
3552}
3553
3554bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3555 const VkAllocationCallbacks* pAllocator,
3556 VkPipelineLayout* pPipelineLayout) const {
3557 bool skip = false;
3558 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003559 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04003560 // Descriptor sets cost 1 DWORD each.
3561 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3562 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3563 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3564 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3565 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003566 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003567 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04003568 }
3569
3570 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3571 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3572 }
3573
3574 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3575 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3576 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3577 "Descriptor sets cost 1 DWORD each. "
3578 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3579 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3580 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3581 VendorSpecificTag(kBPVendorAMD));
3582 }
3583 }
3584
3585 return skip;
3586}
3587
3588bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3589 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3590 const VkImageCopy* pRegions) const {
3591 bool skip = false;
3592 std::stringstream src_image_hex;
3593 std::stringstream dst_image_hex;
3594 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3595 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3596
3597 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003598 auto src_state = Get<IMAGE_STATE>(srcImage);
3599 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003600
3601 if (src_state && dst_state) {
3602 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3603 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3604 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3605 skip |=
3606 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3607 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3608 "image (vkCmdCopyImageToBuffer) "
3609 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3610 "copies when converting between linear and optimal images",
3611 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3612 }
3613 }
3614 }
3615
3616 return skip;
3617}
3618
3619bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3620 VkPipeline pipeline) const {
3621 bool skip = false;
3622
3623 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003624 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003625 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3626 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3627 "for example, by sorting draw calls by pipeline.",
3628 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3629 }
3630 }
3631
3632 return skip;
3633}
3634
3635void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3636 VkFence fence, VkResult result) {
3637 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003638 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003639}
3640
3641bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3642 bool skip = false;
3643
3644 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003645 auto num = num_queue_submissions_.load();
3646 if (num > kNumberOfSubmissionWarningLimitAMD) {
3647 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3648 "%s Performance warning: command buffers submitted %" PRId32
3649 " times this frame. Submitting command buffers has a CPU "
3650 "and GPU overhead. Submit fewer times to incur less overhead.",
3651 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04003652 }
3653 }
3654
3655 return skip;
3656}
3657
3658void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3659 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3660 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3661 uint32_t bufferMemoryBarrierCount,
3662 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3663 uint32_t imageMemoryBarrierCount,
3664 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003665 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Nadav Gevaf0808442021-05-21 13:51:25 -04003666}
3667
3668bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3669 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3670 bool skip = false;
3671 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003672 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003673 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3674 "%s Performance warning: High number of vkSemaphore objects created."
3675 "Minimize the amount of queue synchronization that is used. "
3676 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3677 VendorSpecificTag(kBPVendorAMD));
3678 }
3679 }
3680
3681 return skip;
3682}
3683
3684bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3685 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3686 bool skip = false;
3687 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003688 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003689 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3690 "%s Performance warning: High number of VkFence objects created."
3691 "Minimize the amount of CPU-GPU synchronization that is used. "
3692 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3693 VendorSpecificTag(kBPVendorAMD));
3694 }
3695 }
3696
3697 return skip;
3698}
3699
Sam Walls8e77e4f2020-03-16 20:47:40 +00003700void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3701
3702bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3703 // look for a cache hit
3704 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3705 if (hit != _entries.end()) {
3706 // mark the cache hit as being most recently used
3707 hit->age = iteration++;
3708 return true;
3709 }
3710
3711 // if there's no cache hit, we need to model the entry being inserted into the cache
3712 CacheEntry new_entry = {value, iteration};
3713 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3714 // if there is still space left in the cache, use the next available slot
3715 *(_entries.begin() + iteration) = new_entry;
3716 } else {
3717 // otherwise replace the least recently used cache entry
3718 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3719 *lru = new_entry;
3720 }
3721 iteration++;
3722 return false;
3723}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003724
3725bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3726 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003727 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003728 bool skip = false;
3729 if (swapchain_data && swapchain_data->images.size() == 0) {
3730 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3731 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3732 "vkGetSwapchainImagesKHR after swapchain creation.");
3733 }
3734 return skip;
3735}
3736
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003737void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3738 if (no_pointer) {
3739 if (UNCALLED == call_state) {
3740 call_state = QUERY_COUNT;
3741 }
3742 } else { // Save queue family properties
3743 call_state = QUERY_DETAILS;
3744 }
3745}
3746
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003747void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3748 uint32_t* pQueueFamilyPropertyCount,
3749 VkQueueFamilyProperties* pQueueFamilyProperties) {
3750 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3751 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003752 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003753 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003754 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3755 nullptr == pQueueFamilyProperties);
3756 }
3757}
3758
3759void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3760 uint32_t* pQueueFamilyPropertyCount,
3761 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3762 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3763 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003764 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003765 if (bp_pd_state) {
3766 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3767 nullptr == pQueueFamilyProperties);
3768 }
3769}
3770
3771void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3772 uint32_t* pQueueFamilyPropertyCount,
3773 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3774 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3775 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003776 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003777 if (bp_pd_state) {
3778 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3779 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003780 }
3781}
3782
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003783void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3784 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003785 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003786 if (bp_pd_state) {
3787 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3788 }
3789}
3790
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003791void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3792 VkPhysicalDeviceFeatures2* pFeatures) {
3793 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003794 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003795 if (bp_pd_state) {
3796 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3797 }
3798}
3799
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003800void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3801 VkPhysicalDeviceFeatures2* pFeatures) {
3802 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003803 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003804 if (bp_pd_state) {
3805 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3806 }
3807}
3808
3809void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3810 VkSurfaceKHR surface,
3811 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3812 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003813 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003814 if (bp_pd_state) {
3815 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3816 }
3817}
3818
3819void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3820 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3821 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003822 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003823 if (bp_pd_state) {
3824 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3825 }
3826}
3827
3828void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3829 VkSurfaceKHR surface,
3830 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3831 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003832 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003833 if (bp_pd_state) {
3834 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3835 }
3836}
3837
3838void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3839 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3840 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003841 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003842 if (bp_pd_data) {
3843 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3844
3845 if (*pPresentModeCount) {
3846 if (call_state < QUERY_COUNT) {
3847 call_state = QUERY_COUNT;
3848 }
3849 }
3850 if (pPresentModes) {
3851 if (call_state < QUERY_DETAILS) {
3852 call_state = QUERY_DETAILS;
3853 }
3854 }
3855 }
3856}
3857
3858void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3859 uint32_t* pSurfaceFormatCount,
3860 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003861 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003862 if (bp_pd_data) {
3863 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3864
3865 if (*pSurfaceFormatCount) {
3866 if (call_state < QUERY_COUNT) {
3867 call_state = QUERY_COUNT;
3868 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003869 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003870 }
3871 if (pSurfaceFormats) {
3872 if (call_state < QUERY_DETAILS) {
3873 call_state = QUERY_DETAILS;
3874 }
3875 }
3876 }
3877}
3878
3879void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3880 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3881 uint32_t* pSurfaceFormatCount,
3882 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003883 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003884 if (bp_pd_data) {
3885 if (*pSurfaceFormatCount) {
3886 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3887 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3888 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003889 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003890 }
3891 if (pSurfaceFormats) {
3892 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3893 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3894 }
3895 }
3896 }
3897}
3898
3899void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3900 uint32_t* pPropertyCount,
3901 VkDisplayPlanePropertiesKHR* pProperties,
3902 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003903 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003904 if (bp_pd_data) {
3905 if (*pPropertyCount) {
3906 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3907 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3908 }
3909 }
3910 if (pProperties) {
3911 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3912 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3913 }
3914 }
3915 }
3916}
3917
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003918void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3919 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3920 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003921 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003922 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3923 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3924 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003925 }
3926 }
3927}
3928
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003929void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3930 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3931
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06003932 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003933 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003934 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003935 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003936 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003937 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07003938 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003939 }
3940 }
3941 }
3942}